first commit
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
||||
## Laravel Boost
|
||||
- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.
|
||||
|
||||
## Artisan
|
||||
- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.
|
||||
|
||||
## URLs
|
||||
- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.
|
||||
|
||||
## Tinker / Debugging
|
||||
- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.
|
||||
- Use the `database-query` tool when you only need to read from the database.
|
||||
|
||||
@if (config('boost.browser_logs', true) !== false || config('boost.browser_logs_watcher', true) !== false)
|
||||
## Reading Browser Logs With the `browser-logs` Tool
|
||||
- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.
|
||||
- Only recent browser logs will be useful - ignore old logs.
|
||||
@endif
|
||||
|
||||
## Searching Documentation (Critically Important)
|
||||
- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.
|
||||
- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.
|
||||
- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches.
|
||||
- Search the documentation before making code changes to ensure we are taking the correct approach.
|
||||
- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.
|
||||
- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.
|
||||
|
||||
### Available Search Syntax
|
||||
- You can and should pass multiple queries at once. The most relevant results will be returned first.
|
||||
|
||||
1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.
|
||||
2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".
|
||||
3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order.
|
||||
4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit".
|
||||
5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms.
|
||||
@@ -0,0 +1,7 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## 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 `{{ $assist->artisanCommand('test --compact') }}` with a specific filename or filter.
|
||||
@@ -0,0 +1,20 @@
|
||||
## Flux UI Free
|
||||
|
||||
- This project is using the free edition of Flux UI. It has full access to the free components and variants, but does not have access to the Pro components.
|
||||
- Flux UI is a component library for Livewire. Flux is a robust, hand-crafted UI component library for your Livewire applications. It's built using Tailwind CSS and provides a set of components that are easy to use and customize.
|
||||
- You should use Flux UI components when available.
|
||||
- Fallback to standard Blade components if Flux is unavailable.
|
||||
- If available, use the `search-docs` tool to get the exact documentation and code snippets available for this project.
|
||||
- Flux UI components look like this:
|
||||
@verbatim
|
||||
<code-snippet name="Flux UI Component Example" lang="blade">
|
||||
<flux:button variant="primary"/>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
### Available Components
|
||||
This is correct as of Boost installation, but there may be additional components within the codebase.
|
||||
|
||||
<available-flux-components>
|
||||
avatar, badge, brand, breadcrumbs, button, callout, checkbox, dropdown, field, heading, icon, input, modal, navbar, otp-input, profile, radio, select, separator, skeleton, switch, text, textarea, tooltip
|
||||
</available-flux-components>
|
||||
@@ -0,0 +1,20 @@
|
||||
## Flux UI Pro
|
||||
|
||||
- This project is using the Pro version of Flux UI. It has full access to the free components and variants, as well as full access to the Pro components and variants.
|
||||
- Flux UI is a component library for Livewire. Flux is a robust, hand-crafted UI component library for your Livewire applications. It's built using Tailwind CSS and provides a set of components that are easy to use and customize.
|
||||
- You should use Flux UI components when available.
|
||||
- Fallback to standard Blade components if Flux is unavailable.
|
||||
- If available, use the `search-docs` tool to get the exact documentation and code snippets available for this project.
|
||||
- Flux UI components look like this:
|
||||
@verbatim
|
||||
<code-snippet name="Flux UI Component Example" lang="blade">
|
||||
<flux:button variant="primary"/>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
### Available Components
|
||||
This is correct as of Boost installation, but there may be additional components within the codebase.
|
||||
|
||||
<available-flux-components>
|
||||
accordion, autocomplete, avatar, badge, brand, breadcrumbs, button, calendar, callout, card, chart, checkbox, command, composer, context, date-picker, dropdown, editor, field, file-upload, heading, icon, input, kanban, modal, navbar, otp-input, pagination, pillbox, popover, profile, radio, select, separator, skeleton, slider, switch, table, tabs, text, textarea, time-picker, toast, tooltip
|
||||
</available-flux-components>
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Laravel Folio
|
||||
|
||||
- Laravel Folio is a file-based router. With Laravel Folio, a new route is created for every Blade file within the configured Folio directory. For example, pages are usually in `resources/views/pages/` and the file structure determines routes:
|
||||
- `pages/index.blade.php` → `/`
|
||||
- `pages/profile/index.blade.php` → `/profile`
|
||||
- `pages/auth/login.blade.php` → `/auth/login`
|
||||
- You may list available Folio routes using `{{ $assist->artisanCommand('folio:list') }}` or using the `list-routes` tool.
|
||||
|
||||
### New Pages & Routes
|
||||
- Always create new `folio` pages and routes using `{{ $assist->artisanCommand('folio:page [name]') }}` following existing naming conventions.
|
||||
|
||||
<code-snippet name="Example folio:page Commands for Automatic Routing" lang="shell">
|
||||
// Creates: resources/views/pages/products.blade.php → /products
|
||||
{!! $assist->artisanCommand('folio:page "products"') !!}
|
||||
|
||||
// Creates: resources/views/pages/products/[id].blade.php → /products/{id}
|
||||
{!! $assist->artisanCommand('folio:page "products/[id]"') !!}
|
||||
</code-snippet>
|
||||
|
||||
- Add a 'name' to each new Folio page at the very top of the file so it has a named route available for other parts of the codebase to use.
|
||||
@verbatim
|
||||
<code-snippet name="Adding Named Route to Folio Page" lang="php">
|
||||
use function Laravel\Folio\name;
|
||||
|
||||
name('products.index');
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
### Support & Documentation
|
||||
- Folio supports: middleware, serving pages from multiple paths, subdomain routing, named routes, nested routes, index routes, route parameters, and route model binding.
|
||||
- If available, use the `search-docs` tool to use Folio to its full potential and help the user effectively.
|
||||
@verbatim
|
||||
<code-snippet name="Folio Middleware Example" lang="php">
|
||||
use function Laravel\Folio\{name, middleware};
|
||||
|
||||
name('admin.products');
|
||||
middleware(['auth', 'verified', 'can:manage-products']);
|
||||
?>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
# Laravel Boost Guidelines
|
||||
|
||||
The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction 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 - {{ PHP_VERSION }}
|
||||
@foreach (app(\Laravel\Roster\Roster::class)->packages()->unique(fn ($package) => $package->rawName()) as $package)
|
||||
- {{ $package->rawName() }} ({{ $package->name() }}) - v{{ $package->majorVersion() }}
|
||||
@endforeach
|
||||
|
||||
@if (! empty(config('boost.purpose')))
|
||||
Application purpose: {!! config('boost.purpose') !!}
|
||||
|
||||
@endif
|
||||
## 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 it works. 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 `{{ $assist->nodePackageManagerCommand('run build') }}`, `{{ $assist->nodePackageManagerCommand('run dev') }}`, or `{{ $assist->composerCommand('run dev') }}`. Ask them.
|
||||
|
||||
## Replies
|
||||
- Be concise in your explanations - focus on what's important rather than explaining obvious details.
|
||||
|
||||
## Documentation Files
|
||||
- You must only create documentation files if explicitly requested by the user.
|
||||
@@ -0,0 +1,4 @@
|
||||
## Laravel Herd
|
||||
|
||||
- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs.
|
||||
- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd.
|
||||
@@ -0,0 +1,8 @@
|
||||
## Inertia v1
|
||||
|
||||
- Inertia v1 does not come with these features. Do not recommend using these Inertia v2 features directly:
|
||||
- Deferred props.
|
||||
- Infinite scrolling using merging props and `WhenVisible`.
|
||||
- Lazy loading data on scroll.
|
||||
- Polling.
|
||||
- Prefetching.
|
||||
@@ -0,0 +1,26 @@
|
||||
## Inertia v2
|
||||
|
||||
- Make use of all Inertia features from v1 and v2. Check the documentation before making any changes to ensure we are taking the correct approach.
|
||||
|
||||
### Inertia v2 New Features
|
||||
- Deferred props.
|
||||
- Infinite scrolling using merging props and `WhenVisible`.
|
||||
- Lazy loading data on scroll.
|
||||
- Polling.
|
||||
- Prefetching.
|
||||
|
||||
### Deferred Props & Empty States
|
||||
- When using deferred props on the frontend, you should add a nice empty state with pulsing/animated skeleton.
|
||||
|
||||
### Inertia Form General Guidance
|
||||
@if ($assist->inertia()->hasFormComponent())
|
||||
- The recommended way to build forms when using Inertia is with the `<Form>` component - a useful example is below. Use the `search-docs` tool with a query of `form component` for guidance.
|
||||
- Forms can also be built using the `useForm` helper for more programmatic control, or to follow existing conventions. Use the `search-docs` tool with a query of `useForm helper` for guidance.
|
||||
@if ($assist->inertia()->hasFormComponentResets())
|
||||
- `resetOnError`, `resetOnSuccess`, and `setDefaultsOnSuccess` are available on the `<Form>` component. Use the `search-docs` tool with a query of `form component resetting` for guidance.
|
||||
@else
|
||||
- This version of Inertia does not support `resetOnError`, `resetOnSuccess`, or `setDefaultsOnSuccess` on the `<Form>` component. Using these will cause errors.
|
||||
@endif
|
||||
@else
|
||||
- Build forms using the `useForm` helper. Use the code examples and the `search-docs` tool with a query of `useForm helper` for guidance.
|
||||
@endif
|
||||
@@ -0,0 +1,14 @@
|
||||
## Inertia
|
||||
|
||||
- Inertia.js components should be placed in the `{{ $assist->inertia()->pagesDirectory() }}` directory unless specified differently in the JS bundler (`vite.config.js`).
|
||||
- Use `Inertia::render()` for server-side routing instead of traditional Blade views.
|
||||
- Use the `search-docs` tool for accurate guidance on all things Inertia.
|
||||
|
||||
<code-snippet name="Inertia Render Example" lang="php">
|
||||
// routes/web.php example
|
||||
Route::get('/users', function () {
|
||||
return Inertia::render('Users/Index', [
|
||||
'users' => User::all()
|
||||
]);
|
||||
});
|
||||
</code-snippet>
|
||||
@@ -0,0 +1,45 @@
|
||||
## Inertia v1 + React Forms
|
||||
|
||||
- For form handling in Inertia pages, use `router.post` and related methods. Do not use regular forms.
|
||||
@verbatim
|
||||
<code-snippet name="Inertia React Form Example" lang="react">
|
||||
import { useState } from 'react'
|
||||
import { router } from '@inertiajs/react'
|
||||
|
||||
export default function Edit() {
|
||||
const [values, setValues] = useState({
|
||||
first_name: "",
|
||||
last_name: "",
|
||||
email: "",
|
||||
})
|
||||
|
||||
function handleChange(e) {
|
||||
const key = e.target.id;
|
||||
const value = e.target.value
|
||||
|
||||
setValues(values => ({
|
||||
...values,
|
||||
[key]: value,
|
||||
}))
|
||||
}
|
||||
|
||||
function handleSubmit(e) {
|
||||
e.preventDefault()
|
||||
|
||||
router.post('/users', values)
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label htmlFor="first_name">First name:</label>
|
||||
<input id="first_name" value={values.first_name} onChange={handleChange} />
|
||||
<label htmlFor="last_name">Last name:</label>
|
||||
<input id="last_name" value={values.last_name} onChange={handleChange} />
|
||||
<label htmlFor="email">Email:</label>
|
||||
<input id="email" value={values.email} onChange={handleChange} />
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,66 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Inertia v2 + React Forms
|
||||
|
||||
@if($assist->inertia()->hasFormComponent())
|
||||
@boostsnippet("`<Form>` Component Example", "react")
|
||||
import { Form } from '@inertiajs/react'
|
||||
|
||||
export default () => (
|
||||
<Form action="/users" method="post">
|
||||
{({
|
||||
errors,
|
||||
hasErrors,
|
||||
processing,
|
||||
wasSuccessful,
|
||||
recentlySuccessful,
|
||||
clearErrors,
|
||||
resetAndClearErrors,
|
||||
defaults
|
||||
}) => (
|
||||
<>
|
||||
<input type="text" name="name" />
|
||||
|
||||
{errors.name && <div>{errors.name}</div>}
|
||||
|
||||
<button type="submit" disabled={processing}>
|
||||
{processing ? 'Creating...' : 'Create User'}
|
||||
</button>
|
||||
|
||||
{wasSuccessful && <div>User created successfully!</div>}
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
)
|
||||
@endboostsnippet
|
||||
@endif
|
||||
|
||||
@if($assist->inertia()->hasFormComponent() === false)
|
||||
{{-- Inertia 2.0.x, not 2.1.0 or higher. So still need to use 'useForm' --}}
|
||||
@boostsnippet("Inertia React useForm Example", "react")
|
||||
import { useForm } from '@inertiajs/react'
|
||||
|
||||
const { data, setData, post, processing, errors } = useForm({
|
||||
email: '',
|
||||
password: '',
|
||||
remember: false,
|
||||
})
|
||||
|
||||
function submit(e) {
|
||||
e.preventDefault()
|
||||
post('/login')
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={submit}>
|
||||
<input type="text" value={data.email} onChange={e => setData('email', e.target.value)} />
|
||||
{errors.email && <div>{errors.email}</div>}
|
||||
<input type="password" value={data.password} onChange={e => setData('password', e.target.value)} />
|
||||
{errors.password && <div>{errors.password}</div>}
|
||||
<input type="checkbox" checked={data.remember} onChange={e => setData('remember', e.target.checked)} /> Remember Me
|
||||
<button type="submit" disabled={processing}>Login</button>
|
||||
</form>
|
||||
)
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@@ -0,0 +1,8 @@
|
||||
## Inertia + React
|
||||
|
||||
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
|
||||
|
||||
@boostsnippet("Inertia Client Navigation", "react")
|
||||
import { Link } from '@inertiajs/react'
|
||||
<Link href="/">Home</Link>
|
||||
@endboostsnippet
|
||||
@@ -0,0 +1,33 @@
|
||||
## Inertia v1 + Svelte Forms
|
||||
|
||||
- For form handling, use `router.post` and related methods. Do not use regular forms.
|
||||
@verbatim
|
||||
<code-snippet name="Inertia Svelte Form Example" lang="svelte">
|
||||
<script>
|
||||
import { router } from '@inertiajs/svelte'
|
||||
|
||||
let values = {
|
||||
first_name: null,
|
||||
last_name: null,
|
||||
email: null,
|
||||
}
|
||||
|
||||
function handleSubmit() {
|
||||
router.post('/users', values)
|
||||
}
|
||||
</script>
|
||||
|
||||
<form on:submit|preventDefault={handleSubmit}>
|
||||
<label for="first_name">First name:</label>
|
||||
<input id="first_name" bind:value={values.first_name}>
|
||||
|
||||
<label for="last_name">Last name:</label>
|
||||
<input id="last_name" bind:value={values.last_name}>
|
||||
|
||||
<label for="email">Email:</label>
|
||||
<input id="email" bind:value={values.email}>
|
||||
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,75 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Inertia v2 + Svelte Forms
|
||||
|
||||
- There are critical differences between Svelte 4 and 5; use the `search-docs` tool for up-to-date guidance.
|
||||
|
||||
@if($assist->inertia()->hasFormComponent())
|
||||
@boostsnippet("`<Form>` Component Example", "svelte5")
|
||||
<Form action="/users" method="post">
|
||||
{#snippet children({
|
||||
errors,
|
||||
hasErrors,
|
||||
processing,
|
||||
progress,
|
||||
wasSuccessful,
|
||||
recentlySuccessful,
|
||||
setError,
|
||||
clearErrors,
|
||||
resetAndClearErrors,
|
||||
defaults,
|
||||
isDirty,
|
||||
reset,
|
||||
submit,
|
||||
})}
|
||||
<input type="text" name="name" />
|
||||
|
||||
{#if errors.name}
|
||||
<div>{errors.name}</div>
|
||||
{/if}
|
||||
|
||||
<button type="submit" disabled={processing}>
|
||||
{processing ? 'Creating...' : 'Create User'}
|
||||
</button>
|
||||
|
||||
{#if wasSuccessful}
|
||||
<div>User created successfully!</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
|
||||
@if($assist->inertia()->hasFormComponent() === false)
|
||||
{{-- Inertia 2.0.x, not 2.1.0 or higher. So they still need to use 'useForm' --}}
|
||||
@boostsnippet("Inertia Svelte useForm Example", "svelte")
|
||||
<script>
|
||||
import { useForm } from '@inertiajs/svelte'
|
||||
|
||||
const form = useForm({
|
||||
email: null,
|
||||
password: null,
|
||||
remember: false,
|
||||
})
|
||||
|
||||
function submit(e) {
|
||||
e.preventDefault() /* Only required with Svelte 5 */
|
||||
$form.post('/login')
|
||||
}
|
||||
</script>
|
||||
|
||||
<form onsubmit={submit}>
|
||||
<input type="text" bind:value={$form.email} />
|
||||
{#if $form.errors.email}
|
||||
<div class="form-error">{$form.errors.email}</div>
|
||||
{/if}
|
||||
<input type="password" bind:value={$form.password} />
|
||||
{#if $form.errors.password}
|
||||
<div class="form-error">{$form.errors.password}</div>
|
||||
{/if}
|
||||
<input type="checkbox" bind:checked={$form.remember} /> Remember Me
|
||||
<button type="submit" disabled={$form.processing}>Submit</button>
|
||||
</form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@@ -0,0 +1,10 @@
|
||||
## Inertia + Svelte
|
||||
|
||||
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
|
||||
|
||||
@boostsnippet("Inertia Client Navigation", "svelte")
|
||||
import { inertia, Link } from '@inertiajs/svelte'
|
||||
|
||||
<a href="/" use:inertia>Home</a>
|
||||
<Link href="/">Home</Link>
|
||||
@endboostsnippet
|
||||
@@ -0,0 +1,37 @@
|
||||
## Inertia v1 + Vue Forms
|
||||
|
||||
- For form handling in Inertia pages, use `router.post` and related methods. Do not use regular forms.
|
||||
@verbatim
|
||||
<code-snippet name="Inertia Vue Form Example" lang="vue">
|
||||
<script setup>
|
||||
import { reactive } from 'vue'
|
||||
import { router } from '@inertiajs/vue3'
|
||||
import { usePage } from '@inertiajs/vue3'
|
||||
|
||||
const page = usePage()
|
||||
|
||||
const form = reactive({
|
||||
first_name: null,
|
||||
last_name: null,
|
||||
email: null,
|
||||
})
|
||||
|
||||
function submit() {
|
||||
router.post('/users', form)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>Create {{ page.modelName }}</h1>
|
||||
<form @submit.prevent="submit">
|
||||
<label for="first_name">First name:</label>
|
||||
<input id="first_name" v-model="form.first_name" />
|
||||
<label for="last_name">Last name:</label>
|
||||
<input id="last_name" v-model="form.last_name" />
|
||||
<label for="email">Email:</label>
|
||||
<input id="email" v-model="form.email" />
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</template>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,70 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Inertia v2 + Vue Forms
|
||||
|
||||
@if($assist->inertia()->hasFormComponent())
|
||||
@boostsnippet("`<Form>` Component Example", "vue")
|
||||
<Form
|
||||
action="/users"
|
||||
method="post"
|
||||
#default="{
|
||||
errors,
|
||||
hasErrors,
|
||||
processing,
|
||||
progress,
|
||||
wasSuccessful,
|
||||
recentlySuccessful,
|
||||
setError,
|
||||
clearErrors,
|
||||
resetAndClearErrors,
|
||||
defaults,
|
||||
isDirty,
|
||||
reset,
|
||||
submit,
|
||||
}"
|
||||
>
|
||||
<input type="text" name="name" />
|
||||
|
||||
<div v-if="errors.name">
|
||||
{{ errors.name }}
|
||||
</div>
|
||||
|
||||
<button type="submit" :disabled="processing">
|
||||
{{ processing ? 'Creating...' : 'Create User' }}
|
||||
</button>
|
||||
|
||||
<div v-if="wasSuccessful">User created successfully!</div>
|
||||
</Form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
|
||||
@if($assist->inertia()->hasFormComponent() === false)
|
||||
{{-- Inertia 2.0.x, not 2.1.0 or higher. So still need to use 'useForm' --}}
|
||||
@boostsnippet("Inertia Vue useForm example", "vue")
|
||||
<script setup>
|
||||
import { useForm } from '@inertiajs/vue3'
|
||||
|
||||
const form = useForm({
|
||||
email: null,
|
||||
password: null,
|
||||
remember: false,
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit.prevent="form.post('/login')">
|
||||
<!-- email -->
|
||||
<input type="text" v-model="form.email">
|
||||
<div v-if="form.errors.email">{{ form.errors.email }}</div>
|
||||
<!-- password -->
|
||||
<input type="password" v-model="form.password">
|
||||
<div v-if="form.errors.password">{{ form.errors.password }}</div>
|
||||
<!-- remember me -->
|
||||
<input type="checkbox" v-model="form.remember"> Remember Me
|
||||
<!-- submit -->
|
||||
<button type="submit" :disabled="form.processing">Login</button>
|
||||
</form>
|
||||
</template>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@@ -0,0 +1,9 @@
|
||||
## Inertia + Vue
|
||||
|
||||
- Vue components must have a single root element.
|
||||
- Use `router.visit()` or `<Link>` for navigation instead of traditional links.
|
||||
|
||||
@boostsnippet("Inertia Client Navigation", "vue")
|
||||
import { Link } from '@inertiajs/vue3'
|
||||
<Link href="/">Home</Link>
|
||||
@endboostsnippet
|
||||
@@ -0,0 +1,10 @@
|
||||
## Laravel 10
|
||||
|
||||
- Use the `search-docs` tool to get version-specific documentation.
|
||||
- Middleware typically live in `app/Http/Middleware/` and service providers in `app/Providers/`.
|
||||
- Laravel 10 has a `bootstrap/app.php` file that creates the application instance and binds kernel contracts, but does not use it for application configuration like Laravel 11:
|
||||
- Middleware registration is in `app/Http/Kernel.php`
|
||||
- Exception handling is in `app/Exceptions/Handler.php`
|
||||
- Console commands and schedule registration is in `app/Console/Kernel.php`
|
||||
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
|
||||
- When using Eloquent model casts, you must use `protected $casts = [];` and not the `casts()` method. The `casts()` method isn't available on models in Laravel 10.
|
||||
@@ -0,0 +1,41 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Laravel 11
|
||||
|
||||
- Use the `search-docs` tool to get version-specific documentation.
|
||||
@if (file_exists(base_path('app/Http/Kernel.php')))
|
||||
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel 11 file structure.
|
||||
- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the Laravel 11 structure unless the user explicitly requests it.
|
||||
|
||||
### Laravel 10 Structure
|
||||
- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`.
|
||||
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
|
||||
- Middleware registration is in `app/Http/Kernel.php`
|
||||
- Exception handling is in `app/Exceptions/Handler.php`
|
||||
- Console commands and schedule registration is in `app/Console/Kernel.php`
|
||||
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
|
||||
@else
|
||||
- Laravel 11 brought a new streamlined file structure which this project now uses.
|
||||
|
||||
### Laravel 11 Structure
|
||||
- In Laravel 11, middleware are no longer registered in `app/Http/Kernel.php`.
|
||||
- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`.
|
||||
- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.
|
||||
- `bootstrap/providers.php` contains application specific service providers.
|
||||
- **No app\Console\Kernel.php** - use `bootstrap/app.php` or `routes/console.php` for console configuration.
|
||||
- **Commands auto-register** - files in `app/Console/Commands/` are automatically available and do not require manual registration.
|
||||
@endif
|
||||
|
||||
### Database
|
||||
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
|
||||
- Laravel 11 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
|
||||
|
||||
### Models
|
||||
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
|
||||
|
||||
### New Artisan Commands
|
||||
- List Artisan commands using Boost's MCP tool, if available. New commands available in Laravel 11:
|
||||
- `{{ $assist->artisanCommand('make:enum') }}`
|
||||
- `{{ $assist->artisanCommand('make:class') }}`
|
||||
- `{{ $assist->artisanCommand('make:interface') }}`
|
||||
@@ -0,0 +1,32 @@
|
||||
## Laravel 12
|
||||
|
||||
- Use the `search-docs` tool to get version-specific documentation.
|
||||
@if (file_exists(base_path('app/Http/Kernel.php')))
|
||||
- This project upgraded from Laravel 10 without migrating to the new streamlined Laravel file structure.
|
||||
- This is **perfectly fine** and recommended by Laravel. Follow the existing structure from Laravel 10. We do not need to migrate to the new Laravel structure unless the user explicitly requests it.
|
||||
|
||||
### Laravel 10 Structure
|
||||
- Middleware typically lives in `app/Http/Middleware/` and service providers in `app/Providers/`.
|
||||
- There is no `bootstrap/app.php` application configuration in a Laravel 10 structure:
|
||||
- Middleware registration happens in `app/Http/Kernel.php`
|
||||
- Exception handling is in `app/Exceptions/Handler.php`
|
||||
- Console commands and schedule register in `app/Console/Kernel.php`
|
||||
- Rate limits likely exist in `RouteServiceProvider` or `app/Http/Kernel.php`
|
||||
@else
|
||||
- Since Laravel 11, Laravel has a new streamlined file structure which this project uses.
|
||||
|
||||
### Laravel 12 Structure
|
||||
- In Laravel 12, middleware are no longer registered in `app/Http/Kernel.php`.
|
||||
- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`.
|
||||
- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.
|
||||
- `bootstrap/providers.php` contains application specific service providers.
|
||||
- The `app\Console\Kernel.php` file no longer exists; use `bootstrap/app.php` or `routes/console.php` for console configuration.
|
||||
- Console commands in `app/Console/Commands/` are automatically available and do not require manual registration.
|
||||
@endif
|
||||
|
||||
### Database
|
||||
- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.
|
||||
- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.
|
||||
|
||||
### Models
|
||||
- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Do Things the Laravel Way
|
||||
|
||||
- Use `{{ $assist->artisanCommand('make:') }}` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.
|
||||
- If you're creating a generic PHP class, use `{{ $assist->artisanCommand('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.
|
||||
|
||||
### Database
|
||||
- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.
|
||||
- Use Eloquent models and relationships before suggesting raw database queries.
|
||||
- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.
|
||||
- Generate code that prevents N+1 query problems by using eager loading.
|
||||
- Use Laravel's query builder for very complex database operations.
|
||||
|
||||
### Model Creation
|
||||
- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `{{ $assist->artisanCommand('make:model') }}`.
|
||||
|
||||
### 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.
|
||||
|
||||
### Controllers & Validation
|
||||
- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.
|
||||
- Check sibling Form Requests to see if the application uses array or string based validation rules.
|
||||
|
||||
### Queues
|
||||
- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.
|
||||
|
||||
### Authentication & Authorization
|
||||
- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).
|
||||
|
||||
### URL Generation
|
||||
- When generating links to other pages, prefer named routes and the `route()` function.
|
||||
|
||||
### Configuration
|
||||
- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.
|
||||
|
||||
### 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 `{{ $assist->artisanCommand('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 `{{ $assist->nodePackageManagerCommand('run build') }}` or ask the user to run `{{ $assist->nodePackageManagerCommand('run dev') }}` or `{{ $assist->composerCommand('run dev') }}`.
|
||||
@@ -0,0 +1,18 @@
|
||||
## Livewire 2
|
||||
|
||||
- `wire:model` is live by default.
|
||||
- Components typically exist in the `App\Http\Livewire` namespace.
|
||||
- Use `emit()`, `emitTo()`, `emitSelf()`, and `dispatchBrowserEvent()` for events.
|
||||
- Alpine is included separately from Livewire.
|
||||
- You can listen for `livewire:load` to hook into Livewire initialization, and `Livewire.onPageExpired` for when the page expires:
|
||||
@verbatim
|
||||
<code-snippet name="Livewire Load Hook Example" lang="js">
|
||||
document.addEventListener('livewire:load', function () {
|
||||
Livewire.onPageExpired(() => {
|
||||
alert('Your session expired');
|
||||
});
|
||||
|
||||
Livewire.onError(status => console.error(status));
|
||||
});
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,33 @@
|
||||
## Livewire 3
|
||||
|
||||
### Key Changes From Livewire 2
|
||||
- These things changed in Livewire 3, but may not have been updated in this application. Verify this application's setup to ensure you conform with application conventions.
|
||||
- Use `wire:model.live` for real-time updates, `wire:model` is now deferred by default.
|
||||
- Components now use the `App\Livewire` namespace (not `App\Http\Livewire`).
|
||||
- Use `$this->dispatch()` to dispatch events (not `emit` or `dispatchBrowserEvent`).
|
||||
- Use the `components.layouts.app` view as the typical layout path (not `layouts.app`).
|
||||
|
||||
### New Directives
|
||||
- `wire:show`, `wire:transition`, `wire:cloak`, `wire:offline`, `wire:target` are available for use. Use the documentation to find usage examples.
|
||||
|
||||
### Alpine
|
||||
- Alpine is now included with Livewire; don't manually include Alpine.js.
|
||||
- Plugins included with Alpine: persist, intersect, collapse, and focus.
|
||||
|
||||
### Lifecycle Hooks
|
||||
- You can listen for `livewire:init` to hook into Livewire initialization, and `fail.status === 419` for the page expiring:
|
||||
@verbatim
|
||||
<code-snippet name="Livewire Init Hook Example" lang="js">
|
||||
document.addEventListener('livewire:init', function () {
|
||||
Livewire.hook('request', ({ fail }) => {
|
||||
if (fail && fail.status === 419) {
|
||||
alert('Your session expired');
|
||||
}
|
||||
});
|
||||
|
||||
Livewire.hook('message.failed', (message, component) => {
|
||||
console.error(message);
|
||||
});
|
||||
});
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,48 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Livewire
|
||||
|
||||
- Use the `search-docs` tool to find exact version-specific documentation for how to write Livewire and Livewire tests.
|
||||
- Use the `{{ $assist->artisanCommand('make:livewire [Posts\\CreatePost]') }}` Artisan command to create new components.
|
||||
- State should live on the server, with the UI reflecting it.
|
||||
- All Livewire requests hit the Laravel backend; they're like regular HTTP requests. Always validate form data and run authorization checks in Livewire actions.
|
||||
|
||||
## Livewire Best Practices
|
||||
- Livewire components require a single root element.
|
||||
- Use `wire:loading` and `wire:dirty` for delightful loading states.
|
||||
- Add `wire:key` in loops:
|
||||
@verbatim
|
||||
```blade
|
||||
@foreach ($items as $item)
|
||||
<div wire:key="item-{{ $item->id }}">
|
||||
{{ $item->name }}
|
||||
</div>
|
||||
@endforeach
|
||||
```
|
||||
@endverbatim
|
||||
- Prefer lifecycle hooks like `mount()`, `updatedFoo()` for initialization and reactive side effects:
|
||||
@verbatim
|
||||
<code-snippet name="Lifecycle Hook Examples" lang="php">
|
||||
public function mount(User $user) { $this->user = $user; }
|
||||
public function updatedSearch() { $this->resetPage(); }
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
## Testing Livewire
|
||||
@verbatim
|
||||
<code-snippet name="Example Livewire Component Test" lang="php">
|
||||
Livewire::test(Counter::class)
|
||||
->assertSet('count', 0)
|
||||
->call('increment')
|
||||
->assertSet('count', 1)
|
||||
->assertSee(1)
|
||||
->assertStatus(200);
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@verbatim
|
||||
<code-snippet name="Testing Livewire Component Exists on Page" lang="php">
|
||||
$this->get('/posts/create')
|
||||
->assertSeeLivewire(CreatePost::class);
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
## Laravel MCP
|
||||
|
||||
- MCP (Model Context Protocol) is very new. You must use the `search-docs` tool to get documentation for how to write and test Laravel MCP servers, tools, resources, and prompts effectively.
|
||||
- MCP servers need to be registered with a route or handle in `routes/ai.php`. Typically, they will be registered using `Mcp::web()` to register an HTTP streaming MCP server.
|
||||
- Servers are very testable; use the `search-docs` tool to find testing instructions.
|
||||
- Do not run `mcp:start`. This command hangs waiting for JSON-RPC MCP requests.
|
||||
- Some MCP clients use Node, which has its own certificate store. If a user tries to connect to their web MCP server locally using HTTPS, it could fail due to this reason. They will need to switch to HTTP during local development.
|
||||
@@ -0,0 +1,4 @@
|
||||
## Laravel Pennant
|
||||
|
||||
- This application uses Laravel Pennant for feature flag management, providing a flexible system for controlling feature availability across different organizations and user types.
|
||||
- Use the `search-docs` tool, in combination with existing codebase conventions, to assist the user effectively with feature flags.
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
## Pest 4
|
||||
|
||||
- Pest 4 is a huge upgrade to Pest and offers: browser testing, smoke testing, visual regression testing, test sharding, and faster type coverage.
|
||||
- Browser testing is incredibly powerful and useful for this project.
|
||||
- Browser tests should live in `tests/Browser/`.
|
||||
- Use the `search-docs` tool for detailed guidance on utilizing these features.
|
||||
|
||||
### Browser Testing
|
||||
- You can use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories within Pest 4 browser tests, as well as `RefreshDatabase` (when needed) to ensure a clean state for each test.
|
||||
- Interact with the page (click, type, scroll, select, submit, drag-and-drop, touch gestures, etc.) when appropriate to complete the test.
|
||||
- If requested, test on multiple browsers (Chrome, Firefox, Safari).
|
||||
- If requested, test on different devices and viewports (like iPhone 14 Pro, tablets, or custom breakpoints).
|
||||
- Switch color schemes (light/dark mode) when appropriate.
|
||||
- Take screenshots or pause tests for debugging when appropriate.
|
||||
|
||||
### Example Tests
|
||||
@verbatim
|
||||
<code-snippet name="Pest Browser Test Example" lang="php">
|
||||
it('may reset the password', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$page = visit('/sign-in'); // Visit on a real browser...
|
||||
|
||||
$page->assertSee('Sign In')
|
||||
->assertNoJavascriptErrors() // or ->assertNoConsoleLogs()
|
||||
->click('Forgot Password?')
|
||||
->fill('email', 'nuno@laravel.com')
|
||||
->click('Send Reset Link')
|
||||
->assertSee('We have emailed your password reset link!')
|
||||
|
||||
Notification::assertSent(ResetPassword::class);
|
||||
});
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
@verbatim
|
||||
<code-snippet name="Pest Smoke Testing Example" lang="php">
|
||||
$pages = visit(['/', '/about', '/contact']);
|
||||
|
||||
$pages->assertNoJavascriptErrors()->assertNoConsoleLogs();
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
## Pest
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
### Testing
|
||||
- If you need to verify a feature is working, write or update a Unit / Feature test.
|
||||
|
||||
### Pest Tests
|
||||
- All tests must be written using Pest. Use `{{ $assist->artisanCommand('make:test --pest {name}') }}`.
|
||||
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.
|
||||
- Tests should test all of the happy paths, failure paths, and weird paths.
|
||||
- Tests live in the `tests/Feature` and `tests/Unit` directories.
|
||||
- Pest tests look and behave like this:
|
||||
<code-snippet name="Basic Pest Test Example" lang="php">
|
||||
it('is true', function () {
|
||||
expect(true)->toBeTrue();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Running Tests
|
||||
- Run the minimal number of tests using an appropriate filter before finalizing code edits.
|
||||
- To run all tests: `{{ $assist->artisanCommand('test --compact') }}`.
|
||||
- To run all tests in a file: `{{ $assist->artisanCommand('test --compact tests/Feature/ExampleTest.php') }}`.
|
||||
- To filter on a particular test name: `{{ $assist->artisanCommand('test --compact --filter=testName') }}` (recommended after making a change to a related file).
|
||||
- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.
|
||||
|
||||
### Pest Assertions
|
||||
- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:
|
||||
<code-snippet name="Pest Example Asserting postJson Response" lang="php">
|
||||
it('returns all', function () {
|
||||
$response = $this->postJson('/api/docs', []);
|
||||
|
||||
$response->assertSuccessful();
|
||||
});
|
||||
</code-snippet>
|
||||
|
||||
### Mocking
|
||||
- Mocking can be very helpful when appropriate.
|
||||
- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.
|
||||
- You can also create partial mocks using the same import or self method.
|
||||
|
||||
### Datasets
|
||||
- Use datasets in Pest to simplify tests that have a lot of duplicated data. This is often the case when testing validation rules, so consider this solution when writing tests for validation rules.
|
||||
|
||||
<code-snippet name="Pest Dataset Example" lang="php">
|
||||
it('has emails', function (string $email) {
|
||||
expect($email)->not->toBeEmpty();
|
||||
})->with([
|
||||
'james' => 'james@laravel.com',
|
||||
'taylor' => 'taylor@laravel.com',
|
||||
]);
|
||||
</code-snippet>
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
## PHP 8.4
|
||||
|
||||
- PHP 8.4 has new array functions that will make code simpler whenever we don't use Laravel's collections:
|
||||
- `array_find(array $array, callable $callback): mixed` - Find first matching element.
|
||||
- `array_find_key(array $array, callable $callback): int|string|null` - Find first matching key.
|
||||
- `array_any(array $array, callable $callback): bool` - Check if any element satisfies a callback function.
|
||||
- `array_all(array $array, callable $callback): bool` - Check if all elements satisfy a callback function.
|
||||
|
||||
### Cleaner Chaining on New Instances
|
||||
- No extra parentheses are needed when chaining on new object instances:
|
||||
|
||||
<code-snippet name="New Object Chaining Example" lang="php">
|
||||
// Before PHP 8.4
|
||||
$response = (new JsonResponse(['data' => $data]))->setStatusCode(201);
|
||||
|
||||
// After PHP 8.4
|
||||
$response = new JsonResponse(['data' => $data])->setStatusCode(201);
|
||||
</code-snippet>
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
## PHP 8.5
|
||||
|
||||
- PHP 8.5 has new array functions that will make code simpler whenever we don't use Laravel's collections:
|
||||
- `array_first(array $array): mixed` - Get first value (or `null` if empty).
|
||||
- `array_last(array $array): mixed` - Get last value (or `null` if empty).
|
||||
|
||||
- Use `clone($object, ['property' => $value])` to modify properties during cloning; this is ideal for readonly classes.
|
||||
|
||||
### Pipe Operator
|
||||
- The pipe operator (`|>`) chains function calls left-to-right, replacing nested calls:
|
||||
<code-snippet name="Pipe Operator Example" lang="php">
|
||||
// Before PHP 8.5
|
||||
$slug = strtolower(str_replace(' ', '-', trim($title)));
|
||||
|
||||
// After PHP 8.5
|
||||
$slug = $title |> trim(...) |> (fn($s) => str_replace(' ', '-', $s)) |> strtolower(...);
|
||||
</code-snippet>
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
## PHP
|
||||
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
@if($assist->shouldEnforceStrictTypes())
|
||||
- Always use strict typing at the head of a `.php` file: `declare(strict_types=1);`.
|
||||
@endif
|
||||
- Always use curly braces for control structures, even if it has one line.
|
||||
|
||||
### Constructors
|
||||
- Use PHP 8 constructor property promotion in `__construct()`.
|
||||
- <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>
|
||||
- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.
|
||||
|
||||
### Type Declarations
|
||||
- Always use explicit return type declarations for methods and functions.
|
||||
- Use appropriate PHP type hints for method parameters.
|
||||
|
||||
<code-snippet name="Explicit Return Types and Method Params" lang="php">
|
||||
protected function isAccessible(User $user, ?string $path = null): bool
|
||||
{
|
||||
...
|
||||
}
|
||||
</code-snippet>
|
||||
|
||||
## Comments
|
||||
- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on.
|
||||
|
||||
## PHPDoc Blocks
|
||||
- Add useful array shape type definitions for arrays when appropriate.
|
||||
|
||||
## Enums
|
||||
@if(empty($assist->enums()) || preg_match('/[A-Z]{3,8}/', $assist->enumContents()))
|
||||
- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.
|
||||
@else
|
||||
- That being said, keys in an Enum should follow existing application Enum conventions.
|
||||
@endif
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## PHPUnit
|
||||
|
||||
- This application uses PHPUnit for testing. All tests must be written as PHPUnit classes. Use `{{ $assist->artisanCommand('make:test --phpunit {name}') }}` to create a new test.
|
||||
- If you see a test using "Pest", convert it to PHPUnit.
|
||||
- Every time a test has been updated, run that singular test.
|
||||
- When the tests relating to your feature are passing, ask the user if they would like to also run the entire test suite to make sure everything is still passing.
|
||||
- Tests should test all of the happy paths, failure paths, and weird paths.
|
||||
- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files; these are core to the application.
|
||||
|
||||
### Running Tests
|
||||
- Run the minimal number of tests, using an appropriate filter, before finalizing.
|
||||
- To run all tests: `{{ $assist->artisanCommand('test --compact') }}`.
|
||||
- To run all tests in a file: `{{ $assist->artisanCommand('test --compact tests/Feature/ExampleTest.php') }}`.
|
||||
- To filter on a particular test name: `{{ $assist->artisanCommand('test --compact --filter=testName') }}` (recommended after making a change to a related file).
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Laravel Pint Code Formatter
|
||||
|
||||
@if($assist->supportsPintAgentFormatter())
|
||||
- You must run `{{ $assist->binCommand('pint') }} --dirty --format agent` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `{{ $assist->binCommand('pint') }} --test --format agent`, simply run `{{ $assist->binCommand('pint') }} --format agent` to fix any formatting issues.
|
||||
@else
|
||||
- You must run `{{ $assist->binCommand('pint') }} --dirty` before finalizing changes to ensure your code matches the project's expected style.
|
||||
- Do not run `{{ $assist->binCommand('pint') }} --test`, simply run `{{ $assist->binCommand('pint') }}` to fix any formatting issues.
|
||||
@endif
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Laravel Sail
|
||||
|
||||
- This project runs inside Laravel Sail's Docker containers. You MUST execute all commands through Sail.
|
||||
- Start services using `{{ $assist->sailBinaryPath() }} up -d` and stop them with `{{ $assist->sailBinaryPath() }} stop`.
|
||||
- Open the application in the browser by running `{{ $assist->sailBinaryPath() }} open`.
|
||||
- Always prefix PHP, Artisan, Composer, and Node commands with `{{ $assist->sailBinaryPath() }}`. Examples:
|
||||
- Run Artisan Commands: `{{ $assist->artisanCommand('migrate') }}`
|
||||
- Install Composer packages: `{{ $assist->composerCommand('install') }}`
|
||||
- Execute Node commands: `{{ $assist->nodePackageManagerCommand('run dev') }}`
|
||||
- Execute PHP scripts: `{{ $assist->sailBinaryPath() }} php [script]`
|
||||
- View all available Sail commands by running `{{ $assist->sailBinaryPath() }}` without arguments.
|
||||
@@ -0,0 +1,3 @@
|
||||
## Tailwind CSS 3
|
||||
|
||||
- Always use Tailwind CSS v3; verify you're using only classes supported by this version.
|
||||
@@ -0,0 +1,39 @@
|
||||
## Tailwind CSS 4
|
||||
|
||||
- Always use Tailwind CSS v4; do not use the deprecated utilities.
|
||||
- `corePlugins` is not supported in Tailwind v4.
|
||||
- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed.
|
||||
@verbatim
|
||||
<code-snippet name="Extending Theme in CSS" lang="css">
|
||||
@theme {
|
||||
--color-brand: oklch(0.72 0.11 178);
|
||||
}
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
- In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3:
|
||||
@verbatim
|
||||
<code-snippet name="Tailwind v4 Import Tailwind Diff" lang="diff">
|
||||
- @tailwind base;
|
||||
- @tailwind components;
|
||||
- @tailwind utilities;
|
||||
+ @import "tailwindcss";
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
### Replaced Utilities
|
||||
- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement.
|
||||
- Opacity values are still 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 |
|
||||
@@ -0,0 +1,21 @@
|
||||
## Tailwind CSS
|
||||
|
||||
- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own.
|
||||
- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.).
|
||||
- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically.
|
||||
- You can use the `search-docs` tool to get exact examples from the official documentation when needed.
|
||||
|
||||
### Spacing
|
||||
- When listing items, use gap utilities for spacing; don't use margins.
|
||||
@verbatim
|
||||
<code-snippet name="Valid Flex Gap Spacing Example" lang="html">
|
||||
<div class="flex gap-8">
|
||||
<div>Superior</div>
|
||||
<div>Michigan</div>
|
||||
<div>Erie</div>
|
||||
</div>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
### Dark Mode
|
||||
- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Livewire Volt
|
||||
|
||||
- This project uses Livewire Volt for interactivity within its pages. New pages requiring interactivity must also use Livewire Volt.
|
||||
- Make new Volt components using `{{ $assist->artisanCommand('make:volt [name] [--test] [--pest]') }}`.
|
||||
- Volt is a class-based and functional API for Livewire that supports single-file components, allowing a component's PHP logic and Blade templates to coexist in the same file.
|
||||
- Livewire Volt allows PHP logic and Blade templates in one file. Components use the @verbatim`@volt`@endverbatim directive.
|
||||
- You must check existing Volt components to determine if they're functional or class-based. If you can't detect that, ask the user which they prefer before writing a Volt component.
|
||||
|
||||
### Volt Functional Component Example
|
||||
@verbatim
|
||||
<code-snippet name="Volt Functional Component Example" lang="php">
|
||||
@volt
|
||||
<?php
|
||||
use function Livewire\Volt\{state, computed};
|
||||
|
||||
state(['count' => 0]);
|
||||
|
||||
$increment = fn () => $this->count++;
|
||||
$decrement = fn () => $this->count--;
|
||||
|
||||
$double = computed(fn () => $this->count * 2);
|
||||
?>
|
||||
|
||||
<div>
|
||||
<h1>Count: {{ $count }}</h1>
|
||||
<h2>Double: {{ $this->double }}</h2>
|
||||
<button wire:click="increment">+</button>
|
||||
<button wire:click="decrement">-</button>
|
||||
</div>
|
||||
@endvolt
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
### Volt Class Based Component Example
|
||||
To get started, define an anonymous class that extends Livewire\Volt\Component. Within the class, you may utilize all of the features of Livewire using traditional Livewire syntax:
|
||||
@verbatim
|
||||
<code-snippet name="Volt Class-based Volt Component Example" lang="php">
|
||||
use Livewire\Volt\Component;
|
||||
|
||||
new class extends Component {
|
||||
public $count = 0;
|
||||
|
||||
public function increment()
|
||||
{
|
||||
$this->count++;
|
||||
}
|
||||
} ?>
|
||||
|
||||
<div>
|
||||
<h1>{{ $count }}</h1>
|
||||
<button wire:click="increment">+</button>
|
||||
</div>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
### Testing Volt & Volt Components
|
||||
- Use the existing directory for tests if it already exists. Otherwise, fallback to `tests/Feature/Volt`.
|
||||
|
||||
<code-snippet name="Livewire Test Example" lang="php">
|
||||
use Livewire\Volt\Volt;
|
||||
|
||||
test('counter increments', function () {
|
||||
Volt::test('counter')
|
||||
->assertSee('Count: 0')
|
||||
->call('increment')
|
||||
->assertSee('Count: 1');
|
||||
});
|
||||
</code-snippet>
|
||||
@verbatim
|
||||
<code-snippet name="Volt Component Test Using Pest" lang="php">
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\{User, Product};
|
||||
use Livewire\Volt\Volt;
|
||||
|
||||
test('product form creates product', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
Volt::test('pages.products.create')
|
||||
->actingAs($user)
|
||||
->set('form.name', 'Test Product')
|
||||
->set('form.description', 'Test Description')
|
||||
->set('form.price', 99.99)
|
||||
->call('create')
|
||||
->assertHasNoErrors();
|
||||
|
||||
expect(Product::where('name', 'Test Product')->exists())->toBeTrue();
|
||||
});
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
### Common Patterns
|
||||
@verbatim
|
||||
<code-snippet name="CRUD With Volt" lang="php">
|
||||
<?php
|
||||
|
||||
use App\Models\Product;
|
||||
use function Livewire\Volt\{state, computed};
|
||||
|
||||
state(['editing' => null, 'search' => '']);
|
||||
|
||||
$products = computed(fn() => Product::when($this->search,
|
||||
fn($q) => $q->where('name', 'like', "%{$this->search}%")
|
||||
)->get());
|
||||
|
||||
$edit = fn(Product $product) => $this->editing = $product->id;
|
||||
$delete = fn(Product $product) => $product->delete();
|
||||
|
||||
?>
|
||||
|
||||
<!-- HTML / UI Here -->
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@verbatim
|
||||
<code-snippet name="Real-Time Search With Volt" lang="php">
|
||||
<flux:input
|
||||
wire:model.live.debounce.300ms="search"
|
||||
placeholder="Search..."
|
||||
/>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@verbatim
|
||||
<code-snippet name="Loading States With Volt" lang="php">
|
||||
<flux:button wire:click="save" wire:loading.attr="disabled">
|
||||
<span wire:loading.remove>Save</span>
|
||||
<span wire:loading>Saving...</span>
|
||||
</flux:button>
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
@@ -0,0 +1,79 @@
|
||||
@php
|
||||
/** @var \Laravel\Boost\Install\GuidelineAssist $assist */
|
||||
@endphp
|
||||
## Laravel Wayfinder
|
||||
|
||||
Wayfinder generates TypeScript functions and types for Laravel controllers and routes which you can import into your client-side code. It provides type safety and automatic synchronization between backend routes and frontend code.
|
||||
|
||||
### Development Guidelines
|
||||
- Always use the `search-docs` tool to check Wayfinder correct usage before implementing any features.
|
||||
- Always prefer named imports for tree-shaking (e.g., `import { show } from '@/actions/...'`).
|
||||
- Avoid default controller imports (prevents tree-shaking).
|
||||
- Run `{{ $assist->artisanCommand('wayfinder:generate') }}` after route changes if Vite plugin isn't installed.
|
||||
|
||||
### Feature Overview
|
||||
- Form Support: Use `.form()` with `--with-form` flag for HTML form attributes — `<form {...store.form()}>` → `action="/posts" method="post"`.
|
||||
- HTTP Methods: Call `.get()`, `.post()`, `.patch()`, `.put()`, `.delete()` for specific methods — `show.head(1)` → `{ url: "/posts/1", method: "head" }`.
|
||||
- Invokable Controllers: Import and invoke directly as functions. For example, `import StorePost from '@/actions/.../StorePostController'; StorePost()`.
|
||||
- Named Routes: Import from `@/routes/` for non-controller routes. For example, `import { show } from '@/routes/post'; show(1)` for route name `post.show`.
|
||||
- Parameter Binding: Detects route keys (e.g., `{post:slug}`) and accepts matching object properties — `show("my-post")` or `show({ slug: "my-post" })`.
|
||||
- Query Merging: Use `mergeQuery` to merge with `window.location.search`, set values to `null` to remove — `show(1, { mergeQuery: { page: 2, sort: null } })`.
|
||||
- Query Parameters: Pass `{ query: {...} }` in options to append params — `show(1, { query: { page: 1 } })` → `"/posts/1?page=1"`.
|
||||
- Route Objects: Functions return `{ url, method }` shaped objects — `show(1)` → `{ url: "/posts/1", method: "get" }`.
|
||||
- URL Extraction: Use `.url()` to get URL string — `show.url(1)` → `"/posts/1"`.
|
||||
|
||||
### Example Usage
|
||||
@verbatim
|
||||
<code-snippet name="Wayfinder Basic Usage" lang="typescript">
|
||||
// Import controller methods (tree-shakable)...
|
||||
import { show, store, update } from '@/actions/App/Http/Controllers/PostController'
|
||||
|
||||
// Get route object with URL and method...
|
||||
show(1) // { url: "/posts/1", method: "get" }
|
||||
|
||||
// Get just the URL...
|
||||
show.url(1) // "/posts/1"
|
||||
|
||||
// Use specific HTTP methods...
|
||||
show.get(1) // { url: "/posts/1", method: "get" }
|
||||
show.head(1) // { url: "/posts/1", method: "head" }
|
||||
|
||||
// Import named routes...
|
||||
import { show as postShow } from '@/routes/post' // For route name 'post.show'
|
||||
postShow(1) // { url: "/posts/1", method: "get" }
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
|
||||
@if($assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_LARAVEL) || $assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_REACT) || $assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_VUE) || $assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_SVELTE))
|
||||
### Wayfinder + Inertia
|
||||
@if($assist->inertia()->hasFormComponent())
|
||||
If your application uses the `<Form>` component from Inertia, you can use Wayfinder to generate form action and method automatically.
|
||||
@if($assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_REACT))
|
||||
@boostsnippet("Wayfinder Form Component (React)", "typescript")
|
||||
<Form {...store.form()}><input name="title" /></Form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@if($assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_VUE))
|
||||
@boostsnippet("Wayfinder Form Component (Vue)", "vue")
|
||||
<Form v-bind="store.form()"><input name="title" /></Form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@if($assist->roster->uses(\Laravel\Roster\Enums\Packages::INERTIA_SVELTE))
|
||||
@boostsnippet("Wayfinder Form Component (Svelte)", "svelte")
|
||||
<Form {...store.form()}><input name="title" /></Form>
|
||||
@endboostsnippet
|
||||
@endif
|
||||
@else
|
||||
If your application uses the `useForm` component from Inertia, you can directly submit to the Wayfinder generated functions.
|
||||
|
||||
<code-snippet name="Wayfinder useForm Example" lang="typescript">
|
||||
import { store } from "@/actions/App/Http/Controllers/ExampleController";
|
||||
|
||||
const form = useForm({
|
||||
name: "My Big Post",
|
||||
});
|
||||
|
||||
form.submit(store());
|
||||
</code-snippet>
|
||||
@endif
|
||||
@endif
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) Taylor Otwell
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+270
@@ -0,0 +1,270 @@
|
||||
<p align="center">
|
||||
<img alt="Boost Logo Dark Mode" src="/art/boost-light-mode.svg#gh-light-mode-only"/>
|
||||
<img alt="Boost Logo Dark Mode" src="/art/boost-dark-mode.svg#gh-dark-mode-only"/>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/laravel/boost/actions"><img src="https://github.com/laravel/boost/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||
<a href="https://packagist.org/packages/laravel/boost"><img src="https://img.shields.io/packagist/dt/laravel/boost?v=1" alt="Total Downloads"></a>
|
||||
<a href="https://packagist.org/packages/laravel/boost"><img src="https://img.shields.io/packagist/v/laravel/boost?v=1" alt="Latest Stable Version"></a>
|
||||
<a href="https://packagist.org/packages/laravel/boost"><img src="https://img.shields.io/packagist/l/laravel/boost?v=1" alt="License"></a>
|
||||
</p>
|
||||
|
||||
## Introduction
|
||||
|
||||
Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.
|
||||
|
||||
At its foundation, Laravel Boost is an MCP server equipped with over 15 specialized tools designed to streamline AI-assisted coding workflows. The package includes composable AI guidelines specifically crafted for Laravel ecosystem packages, ensuring consistent and framework-appropriate code generation.
|
||||
|
||||
Boost also features a powerful Documentation API that combines a built-in MCP tool with an extensive knowledge base containing over 17,000 pieces of Laravel-specific information, all enhanced by semantic search capabilities using embeddings for precise, context-aware results.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Laravel Boost is currently in beta and receives frequent updates as we refine features and expand capabilities.
|
||||
|
||||
## Installation
|
||||
|
||||
Laravel Boost can be installed via Composer:
|
||||
|
||||
```bash
|
||||
composer require laravel/boost -w --dev
|
||||
```
|
||||
|
||||
Next, install the MCP server and coding guidelines:
|
||||
|
||||
```bash
|
||||
php artisan boost:install
|
||||
```
|
||||
|
||||
Feel free to add the generated MCP configuration file, guideline files (`.mcp.json`, `CLAUDE.md`, `AGENTS.md`, `junie/`, etc.) and `boost.json` configuration file to your application's `.gitignore` as these files are automatically re-generated when running `boost:install` and `boost:update`.
|
||||
|
||||
Once Laravel Boost has been installed, you're ready to start coding with Cursor, Claude Code, or your AI agent of choice.
|
||||
|
||||
### Set up Your Code Editors
|
||||
|
||||
#### PhpStorm
|
||||
|
||||
1. Press `shift` twice to open the command palette
|
||||
2. Search "MCP Settings" and press `enter`
|
||||
3. Check the box next to `laravel-boost`
|
||||
4. Click "Apply" at the bottom right
|
||||
|
||||
#### VS Code
|
||||
|
||||
1. Open the command palette (`Cmd+Shift+P` or `Ctrl+Shift+P`)
|
||||
2. Press `enter` on "MCP: List Servers"
|
||||
3. Arrow to `laravel-boost` and press `enter`
|
||||
4. Choose "Start server"
|
||||
|
||||
#### Cursor
|
||||
|
||||
1. Open the command palette (`Cmd+Shift+P` or `Ctrl+Shift+P`)
|
||||
2. Press `enter` on "/open MCP Settings"
|
||||
3. Turn the toggle on for `laravel-boost`
|
||||
|
||||
#### Claude Code
|
||||
|
||||
1. Claude support is typically enabled automatically, but if you find it isn't
|
||||
2. Open a shell in the project's directory
|
||||
3. Run `claude mcp add -s local -t stdio laravel-boost php artisan boost:mcp`
|
||||
|
||||
#### Codex
|
||||
|
||||
1. Codex support is typically enabled automatically, but if you find it isn't
|
||||
2. Open a shell in the project's directory
|
||||
3. Run `codex mcp add -- php artisan boost:mcp`
|
||||
|
||||
#### Gemini
|
||||
|
||||
1. Gemini support is typically enabled automatically, but if you find it isn't
|
||||
2. Open a shell in the project's directory
|
||||
3. Run `gemini mcp add -s project -t stdio laravel-boost php artisan boost:mcp`
|
||||
|
||||
## Available MCP Tools
|
||||
|
||||
| Name | Notes |
|
||||
| -------------------------- |----------------------------------------------------------------------------------------------------------------|
|
||||
| Application Info | Read PHP & Laravel versions, database engine, list of ecosystem packages with versions, and Eloquent models |
|
||||
| Browser Logs | Read logs and errors from the browser |
|
||||
| Database Connections | Inspect available database connections, including the default connection |
|
||||
| Database Query | Execute a query against the database |
|
||||
| Database Schema | Read the database schema |
|
||||
| Get Absolute URL | Convert relative path URIs to absolute so agents generate valid URLs |
|
||||
| Get Config | Get a value from the configuration files using "dot" notation |
|
||||
| Last Error | Read the last error from the application's log files |
|
||||
| List Artisan Commands | Inspect the available Artisan commands |
|
||||
| List Available Config Keys | Inspect the available configuration keys |
|
||||
| List Available Env Vars | Inspect the available environment variable keys |
|
||||
| List Routes | Inspect the application's routes |
|
||||
| Read Log Entries | Read the last N log entries |
|
||||
| Search Docs | Query the Laravel hosted documentation API service to retrieve documentation based on installed packages |
|
||||
| Tinker | Execute arbitrary code within the context of the application |
|
||||
|
||||
## Available AI Guidelines
|
||||
|
||||
Laravel Boost includes AI guidelines for the following packages and frameworks. The `core` guidelines provide generic, generalized advice to the AI for the given package that is applicable across all versions.
|
||||
|
||||
| Package | Versions Supported |
|
||||
|---------|------------------------|
|
||||
| Core & Boost | core |
|
||||
| Laravel Framework | core, 10.x, 11.x, 12.x |
|
||||
| Livewire | core, 2.x, 3.x, 4.x |
|
||||
| Flux UI | core, free, pro |
|
||||
| Herd | core |
|
||||
| Inertia Laravel | core, 1.x, 2.x |
|
||||
| Inertia React | core, 1.x, 2.x |
|
||||
| Inertia Vue | core, 1.x, 2.x |
|
||||
| Pest | core, 4.x |
|
||||
| PHPUnit | core |
|
||||
| Pint | core |
|
||||
| Tailwind CSS | core, 3.x, 4.x |
|
||||
| Livewire Volt | core |
|
||||
| Laravel Folio | core |
|
||||
| Enforce Tests | conditional |
|
||||
|
||||
### Keeping Guidelines Up-to-Date
|
||||
|
||||
You may want to periodically update your local AI guidelines to ensure they reflect the latest versions of the Laravel ecosystem packages you have installed. To do so, you can use the `boost:update` Artisan command.
|
||||
|
||||
```bash
|
||||
php artisan boost:update
|
||||
```
|
||||
|
||||
You may also automate this process by adding it to your Composer "post-update-cmd" scripts:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"post-update-cmd": [
|
||||
"@php artisan boost:update --ansi"
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Available Documentation
|
||||
|
||||
| Package | Versions Supported |
|
||||
|---------|--------------------|
|
||||
| Laravel Framework | 10.x, 11.x, 12.x |
|
||||
| Filament | 2.x, 3.x, 4.x, 5.x |
|
||||
| Flux UI | 2.x Free, 2.x Pro |
|
||||
| Inertia | 1.x, 2.x |
|
||||
| Livewire | 1.x, 2.x, 3.x, 4.x |
|
||||
| Nova | 4.x, 5.x |
|
||||
| Pest | 3.x, 4.x |
|
||||
| Tailwind CSS | 3.x, 4.x |
|
||||
|
||||
|
||||
## Adding Custom AI Guidelines
|
||||
|
||||
To augment Laravel Boost with your own custom AI guidelines, add `.blade.php` or `.md` files to your application's `.ai/guidelines/*` directory. These files will automatically be included with Laravel Boost's guidelines when you run `boost:install`.
|
||||
|
||||
### Overriding Boost AI Guidelines
|
||||
|
||||
You can override Boost's built-in AI guidelines by creating your own custom guidelines with matching file paths. When you create a custom guideline that matches an existing Boost guideline path, Boost will use your custom version instead of the built-in one.
|
||||
|
||||
For example, to override Boost's "Inertia React v2 Form Guidance" guidelines, create a file at `.ai/guidelines/inertia-react/2/forms.blade.php`. When you run `boost:install`, Boost will include your custom guideline instead of the default one.
|
||||
|
||||
## Third-Party Package AI Guidelines
|
||||
|
||||
If you maintain a third-party package and would like Boost to include AI guidelines for it, you can do so by adding a `resources/boost/guidelines/core.blade.php` file to your package. When users of your package run `php artisan boost:install`, Boost will automatically load your guidelines.
|
||||
|
||||
AI guidelines should provide a short overview of what your package does, outline any required file structure or conventions, and explain how to create or use its main features (with example commands or code snippets). Keep them concise, actionable, and focused on best practices so AI can generate correct code for your users. Here is an example:
|
||||
|
||||
```php
|
||||
## Package Name
|
||||
|
||||
This package provides [brief description of functionality].
|
||||
|
||||
### Features
|
||||
|
||||
- Feature 1: [clear & short description].
|
||||
- Feature 2: [clear & short description]. Example usage:
|
||||
|
||||
@verbatim
|
||||
<code-snippet name="How to use Feature 2" lang="php">
|
||||
$result = PackageName::featureTwo($param1, $param2);
|
||||
</code-snippet>
|
||||
@endverbatim
|
||||
```
|
||||
|
||||
## Manually Registering the Boost MCP Server
|
||||
|
||||
Sometimes you may need to manually register the Laravel Boost MCP server with your editor of choice. You should register the MCP server using the following details:
|
||||
|
||||
<table>
|
||||
<tr><td><strong>Command</strong></td><td><code>php</code></td></tr>
|
||||
<tr><td><strong>Args</strong></td><td><code>artisan boost:mcp</code></td></tr>
|
||||
</table>
|
||||
|
||||
JSON Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"laravel-boost": {
|
||||
"command": "php",
|
||||
"args": ["artisan", "boost:mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding Support for Other IDEs / AI Agents
|
||||
|
||||
Boost works with many popular IDEs and AI agents out of the box. If your coding tool isn't supported yet, you can create your own code environment and integrate it with Boost. To do this, create a class that extends `Laravel\Boost\Install\CodeEnvironment\CodeEnvironment` and implement one or both of the following contracts depending on what you need:
|
||||
|
||||
- `Laravel\Boost\Contracts\Agent` - Adds support for AI guidelines.
|
||||
- `Laravel\Boost\Contracts\McpClient` - Adds support for MCP.
|
||||
|
||||
### Writing the Code Environment
|
||||
|
||||
```php
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
|
||||
|
||||
class OpenCode extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
// Your implementation...
|
||||
}
|
||||
```
|
||||
|
||||
For an example implementation, see [ClaudeCode.php](https://github.com/laravel/boost/blob/main/src/Install/CodeEnvironment/ClaudeCode.php).
|
||||
|
||||
### Registering the Code Environment
|
||||
|
||||
Register your custom code environment in the `boot` method of your application's `App\Providers\AppServiceProvider`:
|
||||
|
||||
```php
|
||||
use Laravel\Boost\Boost;
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
Boost::registerCodeEnvironment('opencode', OpenCode::class);
|
||||
}
|
||||
```
|
||||
|
||||
Once registered, your code environment will be available for selection when running `php artisan boost:install`.
|
||||
|
||||
## Contributing
|
||||
|
||||
Thank you for considering contributing to Boost! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
|
||||
|
||||
## Security Vulnerabilities
|
||||
|
||||
Please review [our security policy](https://github.com/laravel/boost/security/policy) on how to report security vulnerabilities.
|
||||
|
||||
## License
|
||||
|
||||
Laravel Boost is open-sourced software licensed under the [MIT license](LICENSE.md).
|
||||
Vendored
+79
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"name": "laravel/boost",
|
||||
"description": "Laravel Boost accelerates AI-assisted development by providing the essential context and structure that AI needs to generate high-quality, Laravel-specific code.",
|
||||
"keywords": [
|
||||
"dev",
|
||||
"laravel",
|
||||
"ai"
|
||||
],
|
||||
"homepage": "https://github.com/laravel/boost",
|
||||
"license": "MIT",
|
||||
"support": {
|
||||
"issues": "https://github.com/laravel/boost/issues",
|
||||
"source": "https://github.com/laravel/boost"
|
||||
},
|
||||
"require": {
|
||||
"php": "^8.1",
|
||||
"guzzlehttp/guzzle": "^7.9",
|
||||
"illuminate/console": "^10.49.0|^11.45.3|^12.41.1",
|
||||
"illuminate/contracts": "^10.49.0|^11.45.3|^12.41.1",
|
||||
"illuminate/routing": "^10.49.0|^11.45.3|^12.41.1",
|
||||
"illuminate/support": "^10.49.0|^11.45.3|^12.41.1",
|
||||
"laravel/mcp": "^0.5.1",
|
||||
"laravel/prompts": "0.1.25|^0.3.6",
|
||||
"laravel/roster": "^0.2.9"
|
||||
},
|
||||
"require-dev": {
|
||||
"laravel/pint": "^1.20.0",
|
||||
"mockery/mockery": "^1.6.12",
|
||||
"orchestra/testbench": "^8.36.0|^9.15.0|^10.6",
|
||||
"pestphp/pest": "^2.36.0|^3.8.4|^4.1.5",
|
||||
"phpstan/phpstan": "^2.1.27",
|
||||
"rector/rector": "^2.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Laravel\\Boost\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.x-dev"
|
||||
},
|
||||
"laravel": {
|
||||
"providers": [
|
||||
"Laravel\\Boost\\BoostServiceProvider"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"lint": [
|
||||
"pint",
|
||||
"phpstan --memory-limit=-1",
|
||||
"rector"
|
||||
],
|
||||
"test": "pest",
|
||||
"test:lint": [
|
||||
"pint --test",
|
||||
"rector --dry-run"
|
||||
],
|
||||
"test:types": "phpstan",
|
||||
"check": [
|
||||
"@composer lint",
|
||||
"@composer test"
|
||||
]
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"pestphp/pest-plugin": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"prefer-stable": true
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Boost Master Switch
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option may be used to disable all Boost functionality - which
|
||||
| will prevent Boost's routes from being registered and will also
|
||||
| disable Boost's browser logging functionality from operating.
|
||||
|
|
||||
*/
|
||||
|
||||
'enabled' => env('BOOST_ENABLED', true),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Boost Browser Logs Watcher
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The following option may be used to enable or disable the browser logs
|
||||
| watcher feature within Laravel Boost. The log watcher will read any
|
||||
| errors within the browser's console to give Boost better context.
|
||||
|
|
||||
*/
|
||||
|
||||
'browser_logs_watcher' => env('BOOST_BROWSER_LOGS_WATCHER', true),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Boost Executables Paths
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These options allow you to specify custom paths for the executables that
|
||||
| Boost uses. When configured, they take precedence over the automatic
|
||||
| discovery mechanism. Leave empty to use defaults from your $PATH.
|
||||
|
|
||||
*/
|
||||
|
||||
'executable_paths' => [
|
||||
'php' => env('BOOST_PHP_EXECUTABLE_PATH'),
|
||||
'composer' => env('BOOST_COMPOSER_EXECUTABLE_PATH'),
|
||||
'npm' => env('BOOST_NPM_EXECUTABLE_PATH'),
|
||||
'vendor_bin' => env('BOOST_VENDOR_BIN_EXECUTABLE_PATH'),
|
||||
],
|
||||
|
||||
];
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"preset": "laravel",
|
||||
"rules": {
|
||||
"global_namespace_import": {
|
||||
"import_classes": true,
|
||||
"import_constants": true
|
||||
},
|
||||
"phpdoc_types": false,
|
||||
"combine_consecutive_issets": true,
|
||||
"combine_consecutive_unsets": true,
|
||||
"explicit_string_variable": true,
|
||||
"method_chaining_indentation": true,
|
||||
"no_binary_string": false,
|
||||
"strict_comparison": true,
|
||||
"strict_param": true,
|
||||
"ternary_to_null_coalescing": true
|
||||
}
|
||||
}
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector;
|
||||
use Rector\Config\RectorConfig;
|
||||
use Rector\Php81\Rector\Property\ReadOnlyPropertyRector;
|
||||
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
|
||||
|
||||
return RectorConfig::configure()
|
||||
->withPaths([
|
||||
__DIR__.'/src',
|
||||
__DIR__.'/tests',
|
||||
])
|
||||
->withSkip([
|
||||
ReadOnlyPropertyRector::class,
|
||||
EncapsedStringsToSprintfRector::class,
|
||||
DisallowedEmptyRuleFixerRector::class,
|
||||
])
|
||||
->withPreparedSets(
|
||||
deadCode: true,
|
||||
codeQuality: true,
|
||||
codingStyle: true,
|
||||
typeDeclarations: true,
|
||||
earlyReturn: true,
|
||||
)->withPhpSets(php81: true);
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost;
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
|
||||
/**
|
||||
* @method static void registerCodeEnvironment(string $key, string $className)
|
||||
* @method static array getCodeEnvironments()
|
||||
*
|
||||
* @see BoostManager
|
||||
*/
|
||||
class Boost extends Facade
|
||||
{
|
||||
protected static function getFacadeAccessor(): string
|
||||
{
|
||||
return BoostManager::class;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Laravel\Boost\Install\CodeEnvironment\ClaudeCode;
|
||||
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
|
||||
use Laravel\Boost\Install\CodeEnvironment\Codex;
|
||||
use Laravel\Boost\Install\CodeEnvironment\Copilot;
|
||||
use Laravel\Boost\Install\CodeEnvironment\Cursor;
|
||||
use Laravel\Boost\Install\CodeEnvironment\Gemini;
|
||||
use Laravel\Boost\Install\CodeEnvironment\OpenCode;
|
||||
use Laravel\Boost\Install\CodeEnvironment\PhpStorm;
|
||||
use Laravel\Boost\Install\CodeEnvironment\VSCode;
|
||||
|
||||
class BoostManager
|
||||
{
|
||||
/** @var array<string, class-string<CodeEnvironment>> */
|
||||
private array $codeEnvironments = [
|
||||
'phpstorm' => PhpStorm::class,
|
||||
'vscode' => VSCode::class,
|
||||
'cursor' => Cursor::class,
|
||||
'claudecode' => ClaudeCode::class,
|
||||
'codex' => Codex::class,
|
||||
'copilot' => Copilot::class,
|
||||
'opencode' => OpenCode::class,
|
||||
'gemini' => Gemini::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* @param class-string<CodeEnvironment> $className
|
||||
*/
|
||||
public function registerCodeEnvironment(string $key, string $className): void
|
||||
{
|
||||
if (array_key_exists($key, $this->codeEnvironments)) {
|
||||
throw new InvalidArgumentException("Code environment '{$key}' is already registered");
|
||||
}
|
||||
|
||||
$this->codeEnvironments[$key] = $className;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, class-string<CodeEnvironment>>
|
||||
*/
|
||||
public function getCodeEnvironments(): array
|
||||
{
|
||||
return $this->codeEnvironments;
|
||||
}
|
||||
}
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Log\Logger;
|
||||
use Illuminate\Routing\Router;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\View\Compilers\BladeCompiler;
|
||||
use Laravel\Boost\Install\GuidelineAssist;
|
||||
use Laravel\Boost\Install\GuidelineConfig;
|
||||
use Laravel\Boost\Mcp\Boost;
|
||||
use Laravel\Boost\Middleware\InjectBoost;
|
||||
use Laravel\Boost\Services\BrowserLogger;
|
||||
use Laravel\Mcp\Facades\Mcp;
|
||||
use Laravel\Roster\Roster;
|
||||
|
||||
class BoostServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->mergeConfigFrom(
|
||||
__DIR__.'/../config/boost.php',
|
||||
'boost'
|
||||
);
|
||||
|
||||
if (! $this->shouldRun()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->app->singleton(BoostManager::class, fn (): BoostManager => new BoostManager);
|
||||
|
||||
$this->app->singleton(Roster::class, function () {
|
||||
$lockFiles = [
|
||||
base_path('composer.lock'),
|
||||
base_path('package-lock.json'),
|
||||
base_path('bun.lock'),
|
||||
base_path('bun.lockb'),
|
||||
base_path('pnpm-lock.yaml'),
|
||||
base_path('yarn.lock'),
|
||||
];
|
||||
|
||||
$cacheKey = 'boost.roster.scan';
|
||||
$lastModified = max(array_map(fn (string $path): int|false => file_exists($path) ? filemtime($path) : 0, $lockFiles));
|
||||
|
||||
$cached = cache()->get($cacheKey);
|
||||
if ($cached && isset($cached['timestamp']) && $cached['timestamp'] >= $lastModified) {
|
||||
return $cached['roster'];
|
||||
}
|
||||
|
||||
$roster = Roster::scan(base_path());
|
||||
cache()->put($cacheKey, [
|
||||
'roster' => $roster,
|
||||
'timestamp' => time(),
|
||||
], now()->addHours(24));
|
||||
|
||||
return $roster;
|
||||
});
|
||||
|
||||
$this->app->singleton(GuidelineConfig::class, fn (): GuidelineConfig => new GuidelineConfig);
|
||||
|
||||
$this->app->singleton(GuidelineAssist::class, fn ($app): GuidelineAssist => new GuidelineAssist(
|
||||
$app->make(Roster::class),
|
||||
$app->make(GuidelineConfig::class)
|
||||
));
|
||||
}
|
||||
|
||||
public function boot(Router $router): void
|
||||
{
|
||||
if (! $this->shouldRun()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Mcp::local('laravel-boost', Boost::class);
|
||||
|
||||
$this->registerPublishing();
|
||||
$this->registerCommands();
|
||||
$this->registerRoutes();
|
||||
|
||||
if (config('boost.browser_logs_watcher', true)) {
|
||||
$this->registerBrowserLogger();
|
||||
$this->callAfterResolving('blade.compiler', $this->registerBladeDirectives(...));
|
||||
$this->hookIntoResponses($router);
|
||||
}
|
||||
}
|
||||
|
||||
protected function registerPublishing(): void
|
||||
{
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->publishes([
|
||||
__DIR__.'/../config/boost.php' => config_path('boost.php'),
|
||||
], 'boost-config');
|
||||
}
|
||||
}
|
||||
|
||||
protected function registerCommands(): void
|
||||
{
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([
|
||||
Console\StartCommand::class,
|
||||
Console\InstallCommand::class,
|
||||
Console\UpdateCommand::class,
|
||||
Console\ExecuteToolCommand::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
protected function registerRoutes(): void
|
||||
{
|
||||
Route::post('/_boost/browser-logs', function (Request $request) {
|
||||
$logs = $request->input('logs', []);
|
||||
/** @var Logger $logger */
|
||||
$logger = Log::channel('browser');
|
||||
|
||||
/**
|
||||
* @var array{
|
||||
* type: 'error'|'warn'|'info'|'log'|'table'|'window_error'|'uncaught_error'|'unhandled_rejection',
|
||||
* timestamp: string,
|
||||
* data: array,
|
||||
* url:string,
|
||||
* userAgent:string
|
||||
* } $log */
|
||||
foreach ($logs as $log) {
|
||||
$logger->write(
|
||||
level: match ($log['type']) {
|
||||
'warn' => 'warning',
|
||||
'log', 'table' => 'debug',
|
||||
'window_error', 'uncaught_error', 'unhandled_rejection' => 'error',
|
||||
default => $log['type']
|
||||
},
|
||||
message: self::buildLogMessageFromData($log['data']),
|
||||
context: [
|
||||
'url' => $log['url'],
|
||||
'user_agent' => $log['userAgent'] ?: null,
|
||||
'timestamp' => $log['timestamp'] ?: now()->toIso8601String(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
return response()->json(['status' => 'logged']);
|
||||
})
|
||||
->name('boost.browser-logs')
|
||||
->withoutMiddleware(VerifyCsrfToken::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a string message for the log based on various input types. Single-dimensional, and multi:
|
||||
* "data": {"message":"Unhandled Promise Rejection","reason":{"name":"TypeError","message":"NetworkError when attempting to fetch resource.","stack":""}}]
|
||||
*/
|
||||
private static function buildLogMessageFromData(array $data): string
|
||||
{
|
||||
$messages = [];
|
||||
|
||||
foreach ($data as $value) {
|
||||
$messages[] = match (true) {
|
||||
is_array($value) => self::buildLogMessageFromData($value),
|
||||
is_string($value), is_numeric($value) => (string) $value,
|
||||
is_bool($value) => $value ? 'true' : 'false',
|
||||
is_null($value) => 'null',
|
||||
is_object($value) => json_encode($value),
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
|
||||
return implode(' ', $messages);
|
||||
}
|
||||
|
||||
protected function registerBrowserLogger(): void
|
||||
{
|
||||
if (config('logging.channels.browser') !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
config([
|
||||
'logging.channels.browser' => [
|
||||
'driver' => 'single',
|
||||
'path' => storage_path('logs/browser.log'),
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'days' => 14,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
protected function registerBladeDirectives(BladeCompiler $bladeCompiler): void
|
||||
{
|
||||
$bladeCompiler->directive('boostJs', fn (): string => '<?php echo '.BrowserLogger::class.'::getScript(); ?>');
|
||||
}
|
||||
|
||||
protected function hookIntoResponses(Router $router): void
|
||||
{
|
||||
$this->app->booted(function () use ($router): void {
|
||||
$router->pushMiddlewareToGroup('web', InjectBoost::class);
|
||||
});
|
||||
}
|
||||
|
||||
protected function shouldRun(): bool
|
||||
{
|
||||
if (! config('boost.enabled', true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (app()->runningUnitTests()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only enable Boost on local environments or when debug is true
|
||||
if (! app()->environment('local') && config('app.debug', false) !== true) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Concerns;
|
||||
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
trait MakesHttpRequests
|
||||
{
|
||||
public function client(): PendingRequest
|
||||
{
|
||||
$client = Http::withHeaders([
|
||||
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0 Laravel Boost',
|
||||
]);
|
||||
|
||||
// Disable SSL verification for local development URLs and testing
|
||||
if (app()->environment(['local', 'testing']) || str_contains((string) config('boost.hosted.api_url', ''), '.test')) {
|
||||
return $client->withoutVerifying();
|
||||
}
|
||||
|
||||
return $client;
|
||||
}
|
||||
|
||||
public function get(string $url): Response
|
||||
{
|
||||
return $this->client()->get($url);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $json
|
||||
*/
|
||||
public function json(string $url, array $json): Response
|
||||
{
|
||||
return $this->client()->asJson()->post($url, $json);
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Concerns;
|
||||
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
|
||||
trait ReadsLogs
|
||||
{
|
||||
/**
|
||||
* Regular expression fragments and default chunk-window sizes used when
|
||||
* scanning log files. Declaring them once keeps every consumer in sync.
|
||||
*/
|
||||
protected function getTimestampRegex(): string
|
||||
{
|
||||
return '\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\]';
|
||||
}
|
||||
|
||||
protected function getEntrySplitRegex(): string
|
||||
{
|
||||
return '/(?='.$this->getTimestampRegex().')/';
|
||||
}
|
||||
|
||||
protected function getErrorEntryRegex(): string
|
||||
{
|
||||
return '/^'.$this->getTimestampRegex().'.*\\.ERROR:/';
|
||||
}
|
||||
|
||||
protected function getChunkSizeStart(): int
|
||||
{
|
||||
return 64 * 1024; // 64 kB
|
||||
}
|
||||
|
||||
protected function getChunkSizeMax(): int
|
||||
{
|
||||
return 1024 * 1024; // 1 MB
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the current log file path based on Laravel's logging configuration.
|
||||
*/
|
||||
protected function resolveLogFilePath(): string
|
||||
{
|
||||
$channel = Config::get('logging.default');
|
||||
$channelConfig = Config::get("logging.channels.{$channel}");
|
||||
|
||||
$channelConfig = $this->resolveChannelWithPath($channelConfig);
|
||||
|
||||
$baseLogPath = Arr::get($channelConfig, 'path', storage_path('logs/laravel.log'));
|
||||
|
||||
if (Arr::get($channelConfig, 'driver') === 'daily') {
|
||||
return $this->resolveDailyLogFilePath($baseLogPath);
|
||||
}
|
||||
|
||||
return $baseLogPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $channelConfig
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
protected function resolveChannelWithPath(?array $channelConfig, int $depth = 0): ?array
|
||||
{
|
||||
if ($channelConfig === null || $depth > 2) {
|
||||
return $channelConfig;
|
||||
}
|
||||
|
||||
if (isset($channelConfig['path'])) {
|
||||
return $channelConfig;
|
||||
}
|
||||
|
||||
if (($channelConfig['driver'] ?? null) !== 'stack') {
|
||||
return $channelConfig;
|
||||
}
|
||||
|
||||
$firstValidLoggerConfig = collect($channelConfig['channels'] ?? [])
|
||||
->map(fn (string $name) => Config::get("logging.channels.{$name}"))
|
||||
->filter(fn ($config): bool => is_array($config))
|
||||
->map(fn (array $config) => $this->resolveChannelWithPath($config, $depth + 1))
|
||||
->first(fn (?array $config): bool => isset($config['path']));
|
||||
|
||||
return $firstValidLoggerConfig ?? $channelConfig;
|
||||
}
|
||||
|
||||
protected function resolveDailyLogFilePath(string $basePath): string
|
||||
{
|
||||
$pathInfo = pathinfo($basePath);
|
||||
$directory = $pathInfo['dirname'];
|
||||
$filename = $pathInfo['filename'];
|
||||
$extension = isset($pathInfo['extension']) ? '.'.$pathInfo['extension'] : '';
|
||||
|
||||
$todayLogFile = $directory.DIRECTORY_SEPARATOR.$filename.'-'.date('Y-m-d').$extension;
|
||||
|
||||
if (file_exists($todayLogFile)) {
|
||||
return $todayLogFile;
|
||||
}
|
||||
|
||||
$pattern = $directory.DIRECTORY_SEPARATOR.$filename.'-*'.$extension;
|
||||
$files = glob($pattern) ?: [];
|
||||
|
||||
$datePattern = '/^'.preg_quote($filename, '/').'-\d{4}-\d{2}-\d{2}'.preg_quote($extension, '/').'$/';
|
||||
$latestFile = collect($files)
|
||||
->filter(fn ($file): int|false => preg_match($datePattern, basename($file)))
|
||||
->sortDesc()
|
||||
->first();
|
||||
|
||||
return $latestFile ?? $todayLogFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the given line (or entry) is an ERROR log entry.
|
||||
*/
|
||||
protected function isErrorEntry(string $line): bool
|
||||
{
|
||||
return preg_match($this->getErrorEntryRegex(), $line) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the last $count complete PSR-3 log entries from the log file using
|
||||
* chunked reading instead of character-by-character reverse scanning.
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
protected function readLastLogEntries(string $logFile, int $count): array
|
||||
{
|
||||
$chunkSize = $this->getChunkSizeStart();
|
||||
|
||||
do {
|
||||
$entries = $this->scanLogChunkForEntries($logFile, $chunkSize);
|
||||
|
||||
if (count($entries) >= $count || $chunkSize >= $this->getChunkSizeMax()) {
|
||||
break;
|
||||
}
|
||||
|
||||
$chunkSize *= 2;
|
||||
} while (true);
|
||||
|
||||
return array_slice($entries, -$count);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the most recent ERROR log entry, or null if none exists within the
|
||||
* inspected window.
|
||||
*/
|
||||
protected function readLastErrorEntry(string $logFile): ?string
|
||||
{
|
||||
$chunkSize = $this->getChunkSizeStart();
|
||||
|
||||
do {
|
||||
$entries = $this->scanLogChunkForEntries($logFile, $chunkSize);
|
||||
|
||||
for ($i = count($entries) - 1; $i >= 0; $i--) {
|
||||
if ($this->isErrorEntry($entries[$i])) {
|
||||
return trim((string) $entries[$i]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($chunkSize >= $this->getChunkSizeMax()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$chunkSize *= 2;
|
||||
} while (true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan the last $chunkSize bytes of the log file and return an array of
|
||||
* complete log entries (oldest ➜ newest).
|
||||
*
|
||||
* @return string[]
|
||||
*/
|
||||
protected function scanLogChunkForEntries(string $logFile, int $chunkSize): array
|
||||
{
|
||||
$fileSize = filesize($logFile);
|
||||
if ($fileSize === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$handle = fopen($logFile, 'r');
|
||||
if (! $handle) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
$offset = max($fileSize - $chunkSize, 0);
|
||||
fseek($handle, $offset);
|
||||
|
||||
// If we started mid-line, discard the partial line to align to the next newline.
|
||||
if ($offset > 0) {
|
||||
fgets($handle);
|
||||
}
|
||||
|
||||
$content = stream_get_contents($handle);
|
||||
|
||||
// Split by beginning-of-entry look-ahead (PSR-3 timestamp pattern).
|
||||
$entries = preg_split($this->getEntrySplitRegex(), $content, -1, PREG_SPLIT_NO_EMPTY);
|
||||
if (! $entries) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $entries; // already in chronological order relative to chunk
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Laravel\Boost\Mcp\ToolRegistry;
|
||||
use Laravel\Mcp\Request;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
use Throwable;
|
||||
|
||||
class ExecuteToolCommand extends Command
|
||||
{
|
||||
protected $signature = 'boost:execute-tool {tool} {arguments}';
|
||||
|
||||
protected $description = 'Execute a Boost MCP tool in isolation (internal command)';
|
||||
|
||||
protected $hidden = true;
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$toolClass = $this->argument('tool');
|
||||
$argumentsEncoded = $this->argument('arguments');
|
||||
|
||||
// Validate the tool is registered
|
||||
if (! ToolRegistry::isToolAllowed($toolClass)) {
|
||||
$this->error("Tool not registered or not allowed: {$toolClass}");
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Decode arguments
|
||||
$arguments = json_decode(base64_decode($argumentsEncoded, true), true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
$this->error('Invalid arguments format: '.json_last_error_msg());
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/** @var Tool $tool */
|
||||
$tool = app($toolClass);
|
||||
|
||||
$request = new Request($arguments ?? []);
|
||||
|
||||
try {
|
||||
/** @var Response $response */
|
||||
$response = $tool->handle($request); // @phpstan-ignore-line
|
||||
} catch (Throwable $throwable) {
|
||||
$errorResult = Response::error("Tool execution failed (E_THROWABLE): {$throwable->getMessage()}");
|
||||
|
||||
$this->error(json_encode([
|
||||
'isError' => true,
|
||||
'content' => [
|
||||
$errorResult->content()->toTool($tool),
|
||||
],
|
||||
]));
|
||||
|
||||
return static::FAILURE;
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'isError' => $response->isError(),
|
||||
'content' => [
|
||||
$response->content()->toTool($tool),
|
||||
],
|
||||
]);
|
||||
|
||||
return static::SUCCESS;
|
||||
}
|
||||
}
|
||||
+680
@@ -0,0 +1,680 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Console;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Cli\DisplayHelper;
|
||||
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
|
||||
use Laravel\Boost\Install\CodeEnvironmentsDetector;
|
||||
use Laravel\Boost\Install\GuidelineComposer;
|
||||
use Laravel\Boost\Install\GuidelineConfig;
|
||||
use Laravel\Boost\Install\GuidelineWriter;
|
||||
use Laravel\Boost\Install\Herd;
|
||||
use Laravel\Boost\Install\Sail;
|
||||
use Laravel\Boost\Support\Config;
|
||||
use Laravel\Prompts\Concerns\Colors;
|
||||
use Laravel\Prompts\Terminal;
|
||||
use Symfony\Component\Finder\Finder;
|
||||
use Symfony\Component\Process\Process;
|
||||
|
||||
use function Laravel\Prompts\confirm;
|
||||
use function Laravel\Prompts\intro;
|
||||
use function Laravel\Prompts\multiselect;
|
||||
use function Laravel\Prompts\note;
|
||||
|
||||
class InstallCommand extends Command
|
||||
{
|
||||
use Colors;
|
||||
|
||||
protected $signature = 'boost:install {--ignore-guidelines : Skip installing AI guidelines} {--ignore-mcp : Skip installing MCP server configuration}';
|
||||
|
||||
private CodeEnvironmentsDetector $codeEnvironmentsDetector;
|
||||
|
||||
private Herd $herd;
|
||||
|
||||
private Sail $sail;
|
||||
|
||||
private Terminal $terminal;
|
||||
|
||||
/** @var Collection<int, Agent> */
|
||||
private Collection $selectedTargetAgents;
|
||||
|
||||
/** @var Collection<int, McpClient> */
|
||||
private Collection $selectedTargetMcpClient;
|
||||
|
||||
/** @var Collection<int, string> */
|
||||
private Collection $selectedBoostFeatures;
|
||||
|
||||
/** @var Collection<int, string> */
|
||||
private Collection $selectedAiGuidelines;
|
||||
|
||||
private string $projectName;
|
||||
|
||||
/** @var array<non-empty-string> */
|
||||
private array $systemInstalledCodeEnvironments = [];
|
||||
|
||||
private array $projectInstalledCodeEnvironments = [];
|
||||
|
||||
private bool $enforceTests = true;
|
||||
|
||||
const MIN_TEST_COUNT = 6;
|
||||
|
||||
private string $greenTick;
|
||||
|
||||
private string $redCross;
|
||||
|
||||
private bool $installGuidelines;
|
||||
|
||||
private bool $installMcpConfig;
|
||||
|
||||
public function __construct(protected Config $config)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle(
|
||||
CodeEnvironmentsDetector $codeEnvironmentsDetector,
|
||||
Herd $herd,
|
||||
Sail $sail,
|
||||
Terminal $terminal,
|
||||
): int {
|
||||
$this->installGuidelines = ! $this->option('ignore-guidelines');
|
||||
$this->installMcpConfig = ! $this->option('ignore-mcp');
|
||||
|
||||
if (! $this->installGuidelines && ! $this->installMcpConfig) {
|
||||
$this->error('You cannot ignore both guidelines and MCP config. Please select at least one option to proceed.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->bootstrap($codeEnvironmentsDetector, $herd, $sail, $terminal);
|
||||
$this->displayBoostHeader();
|
||||
$this->discoverEnvironment();
|
||||
$this->collectInstallationPreferences();
|
||||
$this->performInstallation();
|
||||
$this->outro();
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
protected function bootstrap(CodeEnvironmentsDetector $codeEnvironmentsDetector, Herd $herd, Sail $sail, Terminal $terminal): void
|
||||
{
|
||||
$this->codeEnvironmentsDetector = $codeEnvironmentsDetector;
|
||||
$this->herd = $herd;
|
||||
$this->sail = $sail;
|
||||
$this->terminal = $terminal;
|
||||
|
||||
$this->terminal->initDimensions();
|
||||
|
||||
$this->greenTick = $this->green('✓');
|
||||
$this->redCross = $this->red('✗');
|
||||
|
||||
$this->selectedTargetAgents = collect();
|
||||
$this->selectedTargetMcpClient = collect();
|
||||
|
||||
$this->projectName = config('app.name');
|
||||
}
|
||||
|
||||
protected function displayBoostHeader(): void
|
||||
{
|
||||
note($this->boostLogo());
|
||||
intro('✦ Laravel Boost :: Install :: We Must Ship ✦');
|
||||
note("Let's give {$this->bgYellow($this->black($this->bold($this->projectName)))} a Boost");
|
||||
}
|
||||
|
||||
protected function boostLogo(): string
|
||||
{
|
||||
return
|
||||
<<<'HEADER'
|
||||
██████╗ ██████╗ ██████╗ ███████╗ ████████╗
|
||||
██╔══██╗ ██╔═══██╗ ██╔═══██╗ ██╔════╝ ╚══██╔══╝
|
||||
██████╔╝ ██║ ██║ ██║ ██║ ███████╗ ██║
|
||||
██╔══██╗ ██║ ██║ ██║ ██║ ╚════██║ ██║
|
||||
██████╔╝ ╚██████╔╝ ╚██████╔╝ ███████║ ██║
|
||||
╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝
|
||||
HEADER;
|
||||
}
|
||||
|
||||
protected function discoverEnvironment(): void
|
||||
{
|
||||
$this->systemInstalledCodeEnvironments = $this->codeEnvironmentsDetector->discoverSystemInstalledCodeEnvironments();
|
||||
$this->projectInstalledCodeEnvironments = $this->codeEnvironmentsDetector->discoverProjectInstalledCodeEnvironments(base_path());
|
||||
}
|
||||
|
||||
protected function collectInstallationPreferences(): void
|
||||
{
|
||||
$this->selectedBoostFeatures = $this->selectBoostFeatures();
|
||||
$this->selectedAiGuidelines = $this->selectAiGuidelines();
|
||||
$this->selectedTargetMcpClient = $this->selectTargetMcpClients();
|
||||
$this->selectedTargetAgents = $this->selectTargetAgents();
|
||||
$this->enforceTests = $this->determineTestEnforcement();
|
||||
}
|
||||
|
||||
protected function performInstallation(): void
|
||||
{
|
||||
if ($this->installGuidelines) {
|
||||
$this->installGuidelines();
|
||||
}
|
||||
|
||||
usleep(750000);
|
||||
|
||||
if ($this->installMcpConfig && $this->selectedTargetMcpClient->isNotEmpty()) {
|
||||
$this->installMcpServerConfig();
|
||||
}
|
||||
}
|
||||
|
||||
protected function discoverTools(): array
|
||||
{
|
||||
$tools = [];
|
||||
$toolDir = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'Mcp', 'Tools']);
|
||||
$finder = Finder::create()
|
||||
->in($toolDir)
|
||||
->files()
|
||||
->name('*.php');
|
||||
|
||||
foreach ($finder as $toolFile) {
|
||||
$fullyClassifiedClassName = 'Laravel\\Boost\\Mcp\\Tools\\'.$toolFile->getBasename('.php');
|
||||
if (class_exists($fullyClassifiedClassName, false)) {
|
||||
$tools[$fullyClassifiedClassName] = Str::headline($toolFile->getBasename('.php'));
|
||||
}
|
||||
}
|
||||
|
||||
ksort($tools);
|
||||
|
||||
return $tools;
|
||||
}
|
||||
|
||||
protected function outro(): void
|
||||
{
|
||||
$label = 'https://boost.laravel.com/installed';
|
||||
|
||||
$ideNames = $this->selectedTargetMcpClient->map(fn (McpClient $mcpClient): string => 'i:'.$mcpClient->mcpClientName())
|
||||
->toArray();
|
||||
$agentNames = $this->selectedTargetAgents->map(fn (Agent $agent): string => 'a:'.$agent->agentName())->toArray();
|
||||
$boostFeatures = $this->selectedBoostFeatures->map(fn ($feature): string => 'b:'.$feature)->toArray();
|
||||
|
||||
$guidelines = [];
|
||||
|
||||
$guidelines[] = 'g:ai';
|
||||
|
||||
if ($this->shouldInstallStyleGuidelines()) {
|
||||
$guidelines[] = 'g:style';
|
||||
}
|
||||
|
||||
$allData = array_merge($ideNames, $agentNames, $boostFeatures, $guidelines);
|
||||
$installData = base64_encode(implode(',', $allData));
|
||||
|
||||
$link = $this->hyperlink($label, 'https://boost.laravel.com/installed/?d='.$installData);
|
||||
|
||||
$text = 'Enjoy the boost 🚀 Next steps: ';
|
||||
$paddingLength = (int) (floor(($this->terminal->cols() - mb_strlen($text.$label)) / 2)) - 2;
|
||||
|
||||
$this->output->write([
|
||||
"\033[42m\033[2K".str_repeat(' ', max(0, $paddingLength)),
|
||||
$this->black($this->bold($text.$link)).$this->reset(PHP_EOL).$this->reset(PHP_EOL),
|
||||
]);
|
||||
}
|
||||
|
||||
protected function hyperlink(string $label, string $url): string
|
||||
{
|
||||
return "\033]8;;{$url}\007{$label}\033]8;;\033\\";
|
||||
}
|
||||
|
||||
/**
|
||||
* We shouldn't add an AI guideline enforcing tests if they don't have a basic test setup.
|
||||
* This would likely just create headaches for them or be a waste of time as they
|
||||
* won't have the CI setup to make use of them anyway, so we're just wasting their
|
||||
* tokens/money by enforcing them.
|
||||
*/
|
||||
protected function determineTestEnforcement(): bool
|
||||
{
|
||||
if (! $this->installGuidelines) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hasMinimumTests = false;
|
||||
|
||||
if (file_exists(base_path('vendor/bin/phpunit'))) {
|
||||
$process = new Process([PHP_BINARY, 'artisan', 'test', '--list-tests'], base_path());
|
||||
$process->run();
|
||||
|
||||
/** Count the number of tests - they'll always have :: between the filename and test name */
|
||||
$hasMinimumTests = Str::of($process->getOutput())
|
||||
->trim()
|
||||
->explode("\n")
|
||||
->filter(fn ($line): bool => str_contains($line, '::'))
|
||||
->count() >= self::MIN_TEST_COUNT;
|
||||
}
|
||||
|
||||
return $hasMinimumTests;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, string>
|
||||
*/
|
||||
protected function selectBoostFeatures(): Collection
|
||||
{
|
||||
if (! $this->installMcpConfig) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$features = collect(['mcp_server', 'ai_guidelines']);
|
||||
|
||||
if ($this->herd->isMcpAvailable() && $this->shouldConfigureHerdMcp()) {
|
||||
$features->push('herd_mcp');
|
||||
}
|
||||
|
||||
if ($this->sail->isInstalled() && ($this->sail->isActive() || $this->shouldConfigureSail())) {
|
||||
$features->push('sail');
|
||||
}
|
||||
|
||||
return $features;
|
||||
}
|
||||
|
||||
protected function shouldConfigureSail(): bool
|
||||
{
|
||||
return confirm(
|
||||
label: 'Laravel Sail detected. Configure Boost MCP to use Sail?',
|
||||
default: $this->config->getSail(),
|
||||
hint: 'This will configure the MCP server to run through Sail. Note: Sail must be running to use Boost MCP',
|
||||
);
|
||||
}
|
||||
|
||||
protected function shouldConfigureHerdMcp(): bool
|
||||
{
|
||||
return confirm(
|
||||
label: 'Would you like to install Herd MCP alongside Boost MCP?',
|
||||
default: $this->config->getHerdMcp(),
|
||||
hint: 'The Herd MCP provides additional tools like browser logs, which can help AI understand issues better',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, string>
|
||||
*/
|
||||
protected function selectAiGuidelines(): Collection
|
||||
{
|
||||
if (! $this->installGuidelines) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$options = app(GuidelineComposer::class)->guidelines()
|
||||
->reject(fn (array $guideline): bool => $guideline['third_party'] === false);
|
||||
|
||||
if ($options->isEmpty()) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return collect(multiselect(
|
||||
label: 'Which third-party AI guidelines do you want to install?',
|
||||
// @phpstan-ignore-next-line
|
||||
options: $options->mapWithKeys(function (array $guideline, string $name): array {
|
||||
$humanName = str_replace('/core', '', $name);
|
||||
|
||||
return [$name => "{$humanName} (~{$guideline['tokens']} tokens) {$guideline['description']}"];
|
||||
}),
|
||||
default: collect($this->config->getGuidelines()),
|
||||
scroll: 10,
|
||||
hint: 'You can add or remove them later by running this command again',
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, CodeEnvironment>
|
||||
*/
|
||||
protected function selectTargetMcpClients(): Collection
|
||||
{
|
||||
if (! $this->installMcpConfig) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
return $this->selectCodeEnvironments(
|
||||
McpClient::class,
|
||||
sprintf('Which code editors do you use to work on %s?', $this->projectName),
|
||||
$this->config->getEditors(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, CodeEnvironment>
|
||||
*/
|
||||
protected function selectTargetAgents(): Collection
|
||||
{
|
||||
if (! $this->installGuidelines) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$defaults = $this->config->getAgents();
|
||||
|
||||
if ($this->selectedTargetMcpClient->isNotEmpty()) {
|
||||
$defaults = $this->selectedTargetMcpClient
|
||||
->filter(fn (McpClient $client): bool => $client instanceof Agent)
|
||||
->map(fn (McpClient $client): string => $client->name())
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
return $this->selectCodeEnvironments(
|
||||
Agent::class,
|
||||
sprintf('Which agents need AI guidelines for %s?', $this->projectName),
|
||||
$defaults,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get configuration settings for contract-specific selection behavior.
|
||||
*
|
||||
* @return array{required: bool, displayMethod: string}
|
||||
*/
|
||||
protected function getSelectionConfig(string $contractClass): array
|
||||
{
|
||||
return match ($contractClass) {
|
||||
Agent::class => ['required' => false, 'displayMethod' => 'agentName'],
|
||||
McpClient::class => ['required' => true, 'displayMethod' => 'displayName'],
|
||||
default => throw new InvalidArgumentException("Unsupported contract class: {$contractClass}"),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $defaults
|
||||
* @return Collection<int, CodeEnvironment>
|
||||
*/
|
||||
protected function selectCodeEnvironments(string $contractClass, string $label, array $defaults): Collection
|
||||
{
|
||||
$allEnvironments = $this->codeEnvironmentsDetector->getCodeEnvironments();
|
||||
$config = $this->getSelectionConfig($contractClass);
|
||||
|
||||
$availableEnvironments = $allEnvironments->filter(fn (CodeEnvironment $environment): bool => $environment instanceof $contractClass);
|
||||
|
||||
if ($availableEnvironments->isEmpty()) {
|
||||
return collect();
|
||||
}
|
||||
|
||||
$options = $availableEnvironments->mapWithKeys(function (CodeEnvironment $environment) use ($config): array {
|
||||
$displayMethod = $config['displayMethod'];
|
||||
$displayText = $environment->{$displayMethod}();
|
||||
|
||||
return [$environment->name() => $displayText];
|
||||
})->sort();
|
||||
|
||||
$installedEnvNames = array_unique(array_merge(
|
||||
$this->projectInstalledCodeEnvironments,
|
||||
$this->systemInstalledCodeEnvironments
|
||||
));
|
||||
|
||||
$detectedDefaults = [];
|
||||
|
||||
if ($defaults === []) {
|
||||
foreach ($installedEnvNames as $envKey) {
|
||||
$matchingEnv = $availableEnvironments->first(fn (CodeEnvironment $env): bool => strtolower((string) $envKey) === strtolower($env->name()));
|
||||
if ($matchingEnv) {
|
||||
$detectedDefaults[] = $matchingEnv->name();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$selectedCodeEnvironments = collect(multiselect(
|
||||
label: $label,
|
||||
options: $options->toArray(),
|
||||
default: $defaults === [] ? $detectedDefaults : $defaults,
|
||||
scroll: $options->count(),
|
||||
required: $config['required'],
|
||||
hint: $defaults === [] || $detectedDefaults === [] ? '' : sprintf('Auto-detected %s for you',
|
||||
Arr::join(array_map(function ($className) use ($availableEnvironments, $config) {
|
||||
$env = $availableEnvironments->first(fn ($env): bool => $env->name() === $className);
|
||||
$displayMethod = $config['displayMethod'];
|
||||
|
||||
return $env->{$displayMethod}();
|
||||
}, $detectedDefaults), ', ', ' & ')
|
||||
)
|
||||
))->sort();
|
||||
|
||||
return $selectedCodeEnvironments->map(
|
||||
fn (string $name) => $availableEnvironments->first(fn ($env): bool => $env->name() === $name),
|
||||
)->filter()->values();
|
||||
}
|
||||
|
||||
protected function installGuidelines(): void
|
||||
{
|
||||
if ($this->selectedTargetAgents->isEmpty()) {
|
||||
$this->info(' No agents selected for guideline installation.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$guidelineConfig = new GuidelineConfig;
|
||||
$guidelineConfig->enforceTests = $this->enforceTests;
|
||||
$guidelineConfig->laravelStyle = $this->shouldInstallStyleGuidelines();
|
||||
$guidelineConfig->caresAboutLocalization = $this->detectLocalization();
|
||||
$guidelineConfig->hasAnApi = false;
|
||||
$guidelineConfig->aiGuidelines = $this->selectedAiGuidelines->values()->toArray();
|
||||
$guidelineConfig->usesSail = $this->shouldUseSail();
|
||||
|
||||
$composer = app(GuidelineComposer::class)->config($guidelineConfig);
|
||||
$guidelines = $composer->guidelines();
|
||||
|
||||
$this->newLine();
|
||||
$this->info(sprintf(' Adding %d guidelines to your selected agents', $guidelines->count()));
|
||||
DisplayHelper::grid(
|
||||
$guidelines
|
||||
->map(fn ($guideline, string $key): string => $key.($guideline['custom'] ? '*' : ''))
|
||||
->values()
|
||||
->sort()
|
||||
->toArray(),
|
||||
$this->terminal->cols()
|
||||
);
|
||||
$this->newLine();
|
||||
usleep(750000);
|
||||
|
||||
$failed = [];
|
||||
$composedAiGuidelines = $composer->compose();
|
||||
|
||||
$longestAgentName = max(1, ...$this->selectedTargetAgents->map(fn ($agent) => Str::length($agent->agentName()))->toArray());
|
||||
/** @var CodeEnvironment $agent */
|
||||
foreach ($this->selectedTargetAgents as $agent) {
|
||||
$agentName = $agent->agentName();
|
||||
$displayAgentName = str_pad((string) $agentName, $longestAgentName);
|
||||
$this->output->write(" {$displayAgentName}... ");
|
||||
/** @var Agent $agent */
|
||||
try {
|
||||
(new GuidelineWriter($agent))
|
||||
->write($composedAiGuidelines);
|
||||
|
||||
$this->line($this->greenTick);
|
||||
} catch (Exception $e) {
|
||||
$failed[$agentName] = $e->getMessage();
|
||||
$this->line($this->redCross);
|
||||
}
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
if ($failed !== []) {
|
||||
$this->error(sprintf('✗ Failed to install guidelines to %d agent%s:',
|
||||
count($failed),
|
||||
count($failed) === 1 ? '' : 's'
|
||||
));
|
||||
foreach ($failed as $agentName => $error) {
|
||||
$this->line(" - {$agentName}: {$error}");
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->installMcpConfig) {
|
||||
$this->config->setSail(
|
||||
$this->shouldUseSail()
|
||||
);
|
||||
|
||||
$this->config->setHerdMcp(
|
||||
$this->shouldInstallHerdMcp()
|
||||
);
|
||||
|
||||
$this->config->setEditors(
|
||||
$this->selectedTargetMcpClient->map(fn (McpClient $mcpClient): string => $mcpClient->name())->values()->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
$this->config->setAgents(
|
||||
$this->selectedTargetAgents->map(fn (Agent $agent): string => $agent->name())->values()->toArray()
|
||||
);
|
||||
|
||||
$this->config->setGuidelines(
|
||||
$this->selectedAiGuidelines->values()->toArray()
|
||||
);
|
||||
}
|
||||
|
||||
protected function shouldInstallStyleGuidelines(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function shouldInstallHerdMcp(): bool
|
||||
{
|
||||
return $this->selectedBoostFeatures->contains('herd_mcp');
|
||||
}
|
||||
|
||||
protected function shouldUseSail(): bool
|
||||
{
|
||||
if ($this->selectedBoostFeatures->isEmpty()) {
|
||||
return $this->config->getSail();
|
||||
}
|
||||
|
||||
return $this->selectedBoostFeatures->contains('sail');
|
||||
}
|
||||
|
||||
protected function buildMcpCommand(McpClient $mcpClient): array
|
||||
{
|
||||
$serverName = 'laravel-boost';
|
||||
|
||||
if ($this->shouldUseSail()) {
|
||||
return $this->sail->buildMcpCommand($serverName);
|
||||
}
|
||||
|
||||
$inWsl = $this->isRunningInWsl();
|
||||
|
||||
return array_filter([
|
||||
$serverName,
|
||||
$inWsl ? 'wsl.exe' : false,
|
||||
$mcpClient->getPhpPath($inWsl),
|
||||
$mcpClient->getArtisanPath($inWsl),
|
||||
'boost:mcp',
|
||||
]);
|
||||
}
|
||||
|
||||
protected function installMcpServerConfig(): void
|
||||
{
|
||||
if ($this->selectedTargetMcpClient->isEmpty()) {
|
||||
$this->info('No agents selected for guideline installation.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->info(' Installing MCP servers to your selected IDEs');
|
||||
$this->newLine();
|
||||
|
||||
usleep(750000);
|
||||
|
||||
$failed = [];
|
||||
$longestIdeName = max(
|
||||
1,
|
||||
...$this->selectedTargetMcpClient->map(
|
||||
fn (McpClient $mcpClient) => Str::length($mcpClient->mcpClientName())
|
||||
)->toArray()
|
||||
);
|
||||
|
||||
foreach ($this->selectedTargetMcpClient as $mcpClient) {
|
||||
$ideName = $mcpClient->mcpClientName();
|
||||
$ideDisplay = str_pad((string) $ideName, $longestIdeName);
|
||||
$this->output->write(" {$ideDisplay}... ");
|
||||
$results = [];
|
||||
|
||||
$mcp = $this->buildMcpCommand($mcpClient);
|
||||
|
||||
try {
|
||||
$result = $mcpClient->installMcp(
|
||||
array_shift($mcp),
|
||||
array_shift($mcp),
|
||||
$mcp
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
$results[] = $this->greenTick.' Boost';
|
||||
} else {
|
||||
$results[] = $this->redCross.' Boost';
|
||||
$failed[$ideName]['boost'] = 'Failed to write configuration';
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$results[] = $this->redCross.' Boost';
|
||||
$failed[$ideName]['boost'] = $e->getMessage();
|
||||
}
|
||||
|
||||
// Install Herd MCP if enabled
|
||||
if ($this->shouldInstallHerdMcp()) {
|
||||
$php = $mcpClient->getPhpPath();
|
||||
|
||||
try {
|
||||
$result = $mcpClient->installMcp(
|
||||
key: 'herd',
|
||||
command: $php,
|
||||
args: [$this->herd->mcpPath()],
|
||||
env: ['SITE_PATH' => base_path()]
|
||||
);
|
||||
|
||||
if ($result) {
|
||||
$results[] = $this->greenTick.' Herd';
|
||||
} else {
|
||||
$results[] = $this->redCross.' Herd';
|
||||
$failed[$ideName]['herd'] = 'Failed to write configuration';
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
$results[] = $this->redCross.' Herd';
|
||||
$failed[$ideName]['herd'] = $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
$this->line(implode(' ', $results));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
|
||||
if ($failed !== []) {
|
||||
$this->error(sprintf('%s Some MCP servers failed to install:', $this->redCross));
|
||||
|
||||
foreach ($failed as $ideName => $errors) {
|
||||
foreach ($errors as $server => $error) {
|
||||
$this->line(" - {$ideName} ({$server}): {$error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the project actually using localization for their new features?
|
||||
*/
|
||||
protected function detectLocalization(): bool
|
||||
{
|
||||
$actuallyUsing = false;
|
||||
|
||||
/** @phpstan-ignore-next-line */
|
||||
return $actuallyUsing && is_dir(base_path('lang'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Are we running inside a Windows Subsystem for Linux (WSL) environment?
|
||||
* This differentiates between a regular Linux installation and a WSL.
|
||||
*/
|
||||
private function isRunningInWsl(): bool
|
||||
{
|
||||
// Check for WSL-specific environment variables.
|
||||
return ! empty(getenv('WSL_DISTRO_NAME')) || ! empty(getenv('IS_WSL'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand('boost:mcp', 'Starts Laravel Boost (usually from mcp.json)')]
|
||||
class StartCommand extends Command
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
return Artisan::call('mcp:start laravel-boost');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Console;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Symfony\Component\Console\Attribute\AsCommand;
|
||||
|
||||
#[AsCommand('boost:update', 'Update the Laravel Boost guidelines to the latest guidance')]
|
||||
class UpdateCommand extends Command
|
||||
{
|
||||
public function handle(): void
|
||||
{
|
||||
$this->callSilently(InstallCommand::class, [
|
||||
'--no-interaction' => true,
|
||||
'--ignore-mcp' => true,
|
||||
]);
|
||||
|
||||
$this->components->info('Boost guidelines updated successfully.');
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Contracts;
|
||||
|
||||
/**
|
||||
* Agent contract for AI coding assistants that receive guidelines.
|
||||
*/
|
||||
interface Agent
|
||||
{
|
||||
public function name(): string;
|
||||
|
||||
/**
|
||||
* Get the display name of the Agent.
|
||||
*/
|
||||
public function agentName(): ?string;
|
||||
|
||||
/**
|
||||
* Get the file path where AI guidelines should be written.
|
||||
*
|
||||
* @return string The relative or absolute path to the guideline file
|
||||
*/
|
||||
public function guidelinesPath(): string;
|
||||
|
||||
/**
|
||||
* Determine if the guideline file requires frontmatter.
|
||||
*/
|
||||
public function frontmatter(): bool;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Contracts;
|
||||
|
||||
/**
|
||||
* Contract for code editors that support MCP (Model Context Protocol).
|
||||
*/
|
||||
interface McpClient
|
||||
{
|
||||
public function name(): string;
|
||||
|
||||
/**
|
||||
* Get the display name of the MCP (Model Context Protocol) client.
|
||||
*/
|
||||
public function mcpClientName(): ?string;
|
||||
|
||||
/**
|
||||
* Whether to use absolute paths for MCP commands.
|
||||
*/
|
||||
public function useAbsolutePathForMcp(): bool;
|
||||
|
||||
/**
|
||||
* Get the PHP executable path for this MCP client.
|
||||
*/
|
||||
public function getPhpPath(bool $forceAbsolutePath = false): string;
|
||||
|
||||
/**
|
||||
* Get the artisan path for this MCP client.
|
||||
*/
|
||||
public function getArtisanPath(bool $forceAbsolutePath = false): string;
|
||||
|
||||
/**
|
||||
* Install an MCP server configuration in this IDE.
|
||||
*
|
||||
* @param string $key Server identifier/name
|
||||
* @param string $command Executable command to run the MCP server
|
||||
* @param array<int, string> $args Command line arguments
|
||||
* @param array<string, string> $env Environment variables
|
||||
* @return bool True if installation succeeded, false otherwise
|
||||
*/
|
||||
public function installMcp(string $key, string $command, array $args = [], array $env = []): bool;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Assists;
|
||||
|
||||
use Laravel\Roster\Enums\Packages;
|
||||
use Laravel\Roster\Roster;
|
||||
|
||||
class Inertia
|
||||
{
|
||||
public function __construct(private Roster $roster) {}
|
||||
|
||||
public function gte(string $version): bool
|
||||
{
|
||||
if ($this->roster->usesVersion(Packages::INERTIA_LARAVEL, $version, '>=')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->roster->usesVersion(Packages::INERTIA_REACT, $version, '>=')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->roster->usesVersion(Packages::INERTIA_SVELTE, $version, '>=')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->roster->usesVersion(Packages::INERTIA_VUE, $version, '>=');
|
||||
}
|
||||
|
||||
public function hasFormComponent(): bool
|
||||
{
|
||||
return $this->gte('2.1.0');
|
||||
}
|
||||
|
||||
public function hasFormComponentResets(): bool
|
||||
{
|
||||
return $this->gte('2.1.2');
|
||||
}
|
||||
|
||||
public function pagesDirectory(): string
|
||||
{
|
||||
$jsPath = base_path('resources/js');
|
||||
|
||||
if (is_dir($jsPath)) {
|
||||
$entries = @scandir($jsPath);
|
||||
|
||||
if ($entries !== false && in_array('pages', $entries, true)) {
|
||||
return 'resources/js/pages';
|
||||
}
|
||||
}
|
||||
|
||||
return 'resources/js/Pages';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Cli;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class DisplayHelper
|
||||
{
|
||||
private const UNICODE_TOP_LEFT = '╭';
|
||||
|
||||
private const UNICODE_TOP_RIGHT = '╮';
|
||||
|
||||
private const UNICODE_BOTTOM_LEFT = '╰';
|
||||
|
||||
private const UNICODE_BOTTOM_RIGHT = '╯';
|
||||
|
||||
private const UNICODE_HORIZONTAL = '─';
|
||||
|
||||
private const UNICODE_VERTICAL = '│';
|
||||
|
||||
private const UNICODE_CROSS = '┼';
|
||||
|
||||
private const UNICODE_TOP_T = '┬';
|
||||
|
||||
private const UNICODE_BOTTOM_T = '┴';
|
||||
|
||||
private const UNICODE_LEFT_T = '├';
|
||||
|
||||
private const UNICODE_RIGHT_T = '┤';
|
||||
|
||||
private const BORDER_TOP = 'top';
|
||||
|
||||
private const BORDER_MIDDLE = 'middle';
|
||||
|
||||
private const BORDER_BOTTOM = 'bottom';
|
||||
|
||||
private const CELL_PADDING = 2;
|
||||
|
||||
private const GRID_CELL_PADDING = 4;
|
||||
|
||||
private const ANSI_BOLD = "\e[1m";
|
||||
|
||||
private const ANSI_RESET = "\e[0m";
|
||||
|
||||
private const SPACE = ' ';
|
||||
|
||||
/**
|
||||
* @param array<int, array<int|string, mixed>> $data
|
||||
*/
|
||||
public static function datatable(array $data, int $maxWidth = 80): void
|
||||
{
|
||||
if ($data === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$columnWidths = self::calculateColumnWidths($data);
|
||||
$columnWidths = array_map(fn (int $width): int => $width + self::CELL_PADDING, $columnWidths);
|
||||
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_TOP);
|
||||
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
|
||||
$rowCount = 0;
|
||||
foreach ($data as $row) {
|
||||
echo self::buildDataRow($row, $columnWidths).PHP_EOL;
|
||||
|
||||
if ($rowCount < count($data) - 1) {
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_MIDDLE);
|
||||
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
}
|
||||
|
||||
$rowCount++;
|
||||
}
|
||||
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_BOTTOM);
|
||||
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $items
|
||||
*/
|
||||
public static function grid(array $items, int $maxWidth = 80): void
|
||||
{
|
||||
if ($items === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$maxWidth -= 2; // account for grid margins
|
||||
$maxItemLength = max(array_map(mb_strlen(...), $items));
|
||||
$cellWidth = $maxItemLength + self::GRID_CELL_PADDING;
|
||||
$cellsPerRow = max(1, (int) floor(($maxWidth - 1) / ($cellWidth + 1)));
|
||||
$rows = array_chunk($items, $cellsPerRow);
|
||||
|
||||
$cellWidths = array_fill(0, $cellsPerRow, $cellWidth);
|
||||
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_TOP);
|
||||
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
|
||||
$rowCount = 0;
|
||||
foreach ($rows as $row) {
|
||||
echo self::SPACE.self::buildGridRow($row, $cellWidth, $cellsPerRow).PHP_EOL;
|
||||
|
||||
if ($rowCount < count($rows) - 1) {
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_MIDDLE);
|
||||
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
}
|
||||
|
||||
$rowCount++;
|
||||
}
|
||||
|
||||
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_BOTTOM);
|
||||
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
|
||||
}
|
||||
|
||||
private static function getBorderChars(string $type): array
|
||||
{
|
||||
return match ($type) {
|
||||
self::BORDER_TOP => [self::UNICODE_TOP_LEFT, self::UNICODE_TOP_RIGHT, self::UNICODE_TOP_T],
|
||||
self::BORDER_MIDDLE => [self::UNICODE_LEFT_T, self::UNICODE_RIGHT_T, self::UNICODE_CROSS],
|
||||
self::BORDER_BOTTOM => [self::UNICODE_BOTTOM_LEFT, self::UNICODE_BOTTOM_RIGHT, self::UNICODE_BOTTOM_T],
|
||||
default => throw new InvalidArgumentException('Border type should be valid'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<int|string, mixed>> $data
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private static function calculateColumnWidths(array $data): array
|
||||
{
|
||||
$columnWidths = [];
|
||||
foreach ($data as $row) {
|
||||
foreach ($row as $colIndex => $cell) {
|
||||
$length = mb_strlen((string) $cell);
|
||||
$columnWidths[$colIndex] = max($columnWidths[$colIndex] ?? 0, $length);
|
||||
}
|
||||
}
|
||||
|
||||
return $columnWidths;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $widths
|
||||
*/
|
||||
private static function buildBorder(array $widths, string $leftChar, string $rightChar, string $joinChar): string
|
||||
{
|
||||
$border = $leftChar;
|
||||
foreach ($widths as $index => $width) {
|
||||
$border .= str_repeat(self::UNICODE_HORIZONTAL, $width);
|
||||
if ($index < count($widths) - 1) {
|
||||
$border .= $joinChar;
|
||||
}
|
||||
}
|
||||
|
||||
return $border.$rightChar;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int|string, mixed> $row
|
||||
* @param array<int, int> $columnWidths
|
||||
*/
|
||||
private static function buildDataRow(array $row, array $columnWidths): string
|
||||
{
|
||||
$line = self::UNICODE_VERTICAL;
|
||||
$colIndex = 0;
|
||||
foreach ($row as $cell) {
|
||||
$cellStr = ($colIndex === 0) ? self::ANSI_BOLD.$cell.self::ANSI_RESET : $cell;
|
||||
$padding = $columnWidths[$colIndex] - mb_strlen((string) $cell);
|
||||
$line .= self::SPACE.$cellStr.str_repeat(self::SPACE, $padding - 1).self::UNICODE_VERTICAL;
|
||||
$colIndex++;
|
||||
}
|
||||
|
||||
return $line;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $row
|
||||
*/
|
||||
private static function buildGridRow(array $row, int $cellWidth, int $cellsPerRow): string
|
||||
{
|
||||
$line = self::UNICODE_VERTICAL;
|
||||
|
||||
$cells = array_map(
|
||||
fn (int $index): string => self::formatGridCell($row[$index] ?? '', $cellWidth),
|
||||
range(0, $cellsPerRow - 1)
|
||||
);
|
||||
|
||||
return $line.(implode(self::UNICODE_VERTICAL, $cells).self::UNICODE_VERTICAL);
|
||||
}
|
||||
|
||||
private static function formatGridCell(string $item, int $cellWidth): string
|
||||
{
|
||||
if ($item === '' || $item === '0') {
|
||||
return str_repeat(self::SPACE, $cellWidth);
|
||||
}
|
||||
|
||||
$padding = $cellWidth - mb_strlen($item) - 2;
|
||||
|
||||
return self::SPACE.$item.str_repeat(self::SPACE, $padding + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class ClaudeCode extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'claude_code';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'Claude Code';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin, Platform::Linux => [
|
||||
'command' => 'command -v claude',
|
||||
],
|
||||
Platform::Windows => [
|
||||
'command' => 'where claude 2>nul',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.claude'],
|
||||
'files' => ['CLAUDE.md'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mcpInstallationStrategy(): McpInstallationStrategy
|
||||
{
|
||||
return McpInstallationStrategy::FILE;
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return '.mcp.json';
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.claude_code.guidelines_path', 'CLAUDE.md');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Laravel\Boost\BoostManager;
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Detection\DetectionStrategyFactory;
|
||||
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
use Laravel\Boost\Install\Mcp\FileWriter;
|
||||
|
||||
abstract class CodeEnvironment
|
||||
{
|
||||
public bool $useAbsolutePathForMcp = false;
|
||||
|
||||
public function __construct(protected readonly DetectionStrategyFactory $strategyFactory) {}
|
||||
|
||||
abstract public function name(): string;
|
||||
|
||||
abstract public function displayName(): string;
|
||||
|
||||
public function agentName(): ?string
|
||||
{
|
||||
return $this->displayName();
|
||||
}
|
||||
|
||||
public function mcpClientName(): ?string
|
||||
{
|
||||
return $this->displayName();
|
||||
}
|
||||
|
||||
public function useAbsolutePathForMcp(): bool
|
||||
{
|
||||
return $this->useAbsolutePathForMcp;
|
||||
}
|
||||
|
||||
public function getPhpPath(bool $forceAbsolutePath = false): string
|
||||
{
|
||||
$phpBinaryPath = config('boost.executable_paths.php') ?? 'php';
|
||||
|
||||
if ($phpBinaryPath === 'php' && ($this->useAbsolutePathForMcp() || $forceAbsolutePath)) {
|
||||
return PHP_BINARY;
|
||||
}
|
||||
|
||||
return $phpBinaryPath;
|
||||
}
|
||||
|
||||
public function getArtisanPath(bool $forceAbsolutePath = false): string
|
||||
{
|
||||
return ($this->useAbsolutePathForMcp() || $forceAbsolutePath) ? base_path('artisan') : 'artisan';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the detection configuration for system-wide installation detection.
|
||||
*
|
||||
* @return array{paths?: string[], command?: string, files?: string[]}
|
||||
*/
|
||||
abstract public function systemDetectionConfig(Platform $platform): array;
|
||||
|
||||
/**
|
||||
* Get the detection configuration for project-specific detection.
|
||||
*
|
||||
* @return array{paths?: string[], files?: string[]}
|
||||
*/
|
||||
abstract public function projectDetectionConfig(): array;
|
||||
|
||||
public function detectOnSystem(Platform $platform): bool
|
||||
{
|
||||
$config = $this->systemDetectionConfig($platform);
|
||||
$strategy = $this->strategyFactory->makeFromConfig($config);
|
||||
|
||||
return $strategy->detect($config, $platform);
|
||||
}
|
||||
|
||||
public function detectInProject(string $basePath): bool
|
||||
{
|
||||
$config = array_merge($this->projectDetectionConfig(), ['basePath' => $basePath]);
|
||||
$strategy = $this->strategyFactory->makeFromConfig($config);
|
||||
|
||||
return $strategy->detect($config);
|
||||
}
|
||||
|
||||
public function isAgent(): bool
|
||||
{
|
||||
return $this->agentName() && $this instanceof Agent;
|
||||
}
|
||||
|
||||
public function isMcpClient(): bool
|
||||
{
|
||||
return $this->mcpClientName() && $this instanceof McpClient;
|
||||
}
|
||||
|
||||
public function mcpInstallationStrategy(): McpInstallationStrategy
|
||||
{
|
||||
return McpInstallationStrategy::FILE;
|
||||
}
|
||||
|
||||
public static function fromName(string $name): ?CodeEnvironment
|
||||
{
|
||||
$detectionFactory = app(DetectionStrategyFactory::class);
|
||||
$boostManager = app(BoostManager::class);
|
||||
|
||||
foreach ($boostManager->getCodeEnvironments() as $class) {
|
||||
/** @var class-string<CodeEnvironment> $class */
|
||||
$instance = new $class($detectionFactory);
|
||||
if ($instance->name() === $name) {
|
||||
return $instance;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function shellMcpCommand(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function frontmatter(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function mcpConfigKey(): string
|
||||
{
|
||||
return 'mcpServers';
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function defaultMcpConfig(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Install MCP server using the appropriate strategy.
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @param array<string, string> $env
|
||||
*/
|
||||
public function installMcp(string $key, string $command, array $args = [], array $env = []): bool
|
||||
{
|
||||
return match ($this->mcpInstallationStrategy()) {
|
||||
McpInstallationStrategy::SHELL => $this->installShellMcp($key, $command, $args, $env),
|
||||
McpInstallationStrategy::FILE => $this->installFileMcp($key, $command, $args, $env),
|
||||
McpInstallationStrategy::NONE => false
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the MCP server configuration payload for file-based installation.
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @param array<string, string> $env
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function mcpServerConfig(string $command, array $args = [], array $env = []): array
|
||||
{
|
||||
return [
|
||||
'command' => $command,
|
||||
'args' => $args,
|
||||
'env' => $env,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Install MCP server using a shell command strategy.
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @param array<string, string> $env
|
||||
*/
|
||||
protected function installShellMcp(string $key, string $command, array $args = [], array $env = []): bool
|
||||
{
|
||||
$shellCommand = $this->shellMcpCommand();
|
||||
if ($shellCommand === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$normalized = $this->normalizeCommand($command, $args);
|
||||
|
||||
// Build environment string
|
||||
$envString = '';
|
||||
foreach ($env as $envKey => $value) {
|
||||
$envKey = strtoupper($envKey);
|
||||
$envString .= "-e {$envKey}=\"{$value}\" ";
|
||||
}
|
||||
|
||||
// Replace placeholders in shell command
|
||||
$command = str_replace([
|
||||
'{key}',
|
||||
'{command}',
|
||||
'{args}',
|
||||
'{env}',
|
||||
], [
|
||||
$key,
|
||||
$normalized['command'],
|
||||
implode(' ', array_map(fn (string $arg): string => '"'.$arg.'"', $normalized['args'])),
|
||||
trim($envString),
|
||||
], $shellCommand);
|
||||
|
||||
$result = Process::run($command);
|
||||
if ($result->successful()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return str_contains($result->errorOutput(), 'already exists');
|
||||
}
|
||||
|
||||
/**
|
||||
* Install MCP server using a file-based configuration strategy.
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @param array<string, string> $env
|
||||
*/
|
||||
protected function installFileMcp(string $key, string $command, array $args = [], array $env = []): bool
|
||||
{
|
||||
$path = $this->mcpConfigPath();
|
||||
if (! $path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$normalized = $this->normalizeCommand($command, $args);
|
||||
|
||||
return (new FileWriter($path, $this->defaultMcpConfig()))
|
||||
->configKey($this->mcpConfigKey())
|
||||
->addServerConfig($key, $this->mcpServerConfig($normalized['command'], $normalized['args'], $env))
|
||||
->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize command by splitting space-separated commands into command + args.
|
||||
*
|
||||
* Absolute paths (starting with / on Unix or a drive letter on Windows)
|
||||
* are never split, as they may contain spaces (e.g. macOS "Application Support").
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @return array{command: string, args: array<int, string>}
|
||||
*/
|
||||
protected function normalizeCommand(string $command, array $args = []): array
|
||||
{
|
||||
if (str_starts_with($command, '/') || preg_match('#^[a-zA-Z]:[/\\\\]#', $command)) {
|
||||
return [
|
||||
'command' => $command,
|
||||
'args' => $args,
|
||||
];
|
||||
}
|
||||
|
||||
$parts = str($command)->explode(' ');
|
||||
|
||||
return [
|
||||
'command' => $parts->first(),
|
||||
'args' => $parts->skip(1)->values()->merge($args)->all(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class Codex extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'codex';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'Codex';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin, Platform::Linux => [
|
||||
'command' => 'which codex',
|
||||
],
|
||||
Platform::Windows => [
|
||||
'command' => 'where codex 2>nul',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.codex'],
|
||||
'files' => ['AGENTS.md'],
|
||||
];
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.codex.guidelines_path', 'AGENTS.md');
|
||||
}
|
||||
|
||||
public function mcpInstallationStrategy(): McpInstallationStrategy
|
||||
{
|
||||
return McpInstallationStrategy::SHELL;
|
||||
}
|
||||
|
||||
public function shellMcpCommand(): string
|
||||
{
|
||||
return 'codex mcp add {key} -- {command} {args}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class Copilot extends CodeEnvironment implements Agent
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'copilot';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'GitHub Copilot';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
// Copilot doesn't have system-wide detection as it's an extension/feature
|
||||
return [
|
||||
'files' => [],
|
||||
];
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'files' => ['.github/copilot-instructions.md'],
|
||||
];
|
||||
}
|
||||
|
||||
public function detectOnSystem(Platform $platform): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function mcpClientName(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.copilot.guidelines_path', '.github/copilot-instructions.md');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class Cursor extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'cursor';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'Cursor';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin => [
|
||||
'paths' => ['/Applications/Cursor.app'],
|
||||
],
|
||||
Platform::Linux => [
|
||||
'paths' => [
|
||||
'/opt/cursor',
|
||||
'/usr/local/bin/cursor',
|
||||
'~/.local/bin/cursor',
|
||||
],
|
||||
],
|
||||
Platform::Windows => [
|
||||
'paths' => [
|
||||
'%ProgramFiles%\\Cursor',
|
||||
'%LOCALAPPDATA%\\Programs\\Cursor',
|
||||
],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.cursor'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return '.cursor/mcp.json';
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.cursor.guidelines_path', '.cursor/rules/laravel-boost.mdc');
|
||||
}
|
||||
|
||||
public function frontmatter(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class Gemini extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'gemini';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'Gemini';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin, Platform::Linux => [
|
||||
'command' => 'command -v gemini',
|
||||
],
|
||||
Platform::Windows => [
|
||||
'command' => 'where gemini 2>nul',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.gemini'],
|
||||
'files' => ['GEMINI.md'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return '.gemini/settings.json';
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.gemini.guidelines_path', 'GEMINI.md');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class OpenCode extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'opencode';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'OpenCode';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin, Platform::Linux => [
|
||||
'command' => 'command -v opencode',
|
||||
],
|
||||
Platform::Windows => [
|
||||
'command' => 'where opencode 2>nul',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'files' => ['AGENTS.md', 'opencode.json'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mcpInstallationStrategy(): McpInstallationStrategy
|
||||
{
|
||||
return McpInstallationStrategy::FILE;
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return 'opencode.json';
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.opencode.guidelines_path', 'AGENTS.md');
|
||||
}
|
||||
|
||||
public function mcpConfigKey(): string
|
||||
{
|
||||
return 'mcp';
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
public function defaultMcpConfig(): array
|
||||
{
|
||||
return [
|
||||
'$schema' => 'https://opencode.ai/config.json',
|
||||
];
|
||||
}
|
||||
|
||||
/** {@inheritDoc} */
|
||||
public function mcpServerConfig(string $command, array $args = [], array $env = []): array
|
||||
{
|
||||
return [
|
||||
'type' => 'local',
|
||||
'enabled' => true,
|
||||
'command' => [$command, ...$args],
|
||||
'environment' => $env,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class PhpStorm extends CodeEnvironment implements Agent, McpClient
|
||||
{
|
||||
public bool $useAbsolutePathForMcp = true;
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'phpstorm';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'PhpStorm';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin => [
|
||||
'paths' => ['/Applications/PhpStorm.app'],
|
||||
],
|
||||
Platform::Linux => [
|
||||
'paths' => [
|
||||
'/opt/phpstorm',
|
||||
'/opt/PhpStorm*',
|
||||
'/usr/local/bin/phpstorm',
|
||||
'~/.local/share/JetBrains/Toolbox/apps/PhpStorm/ch-*',
|
||||
],
|
||||
],
|
||||
Platform::Windows => [
|
||||
'paths' => [
|
||||
'%ProgramFiles%\\JetBrains\\PhpStorm*',
|
||||
'%LOCALAPPDATA%\\JetBrains\\Toolbox\\apps\\PhpStorm\\ch-*',
|
||||
'%LOCALAPPDATA%\\Programs\\PhpStorm',
|
||||
],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.idea', '.junie'],
|
||||
];
|
||||
}
|
||||
|
||||
public function agentName(): string
|
||||
{
|
||||
return 'Junie';
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return '.junie/mcp/mcp.json';
|
||||
}
|
||||
|
||||
public function guidelinesPath(): string
|
||||
{
|
||||
return config('boost.code_environments.phpstorm.guidelines_path', '.junie/guidelines.md');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\CodeEnvironment;
|
||||
|
||||
use Laravel\Boost\Contracts\McpClient;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class VSCode extends CodeEnvironment implements McpClient
|
||||
{
|
||||
public function name(): string
|
||||
{
|
||||
return 'vscode';
|
||||
}
|
||||
|
||||
public function displayName(): string
|
||||
{
|
||||
return 'VS Code';
|
||||
}
|
||||
|
||||
public function systemDetectionConfig(Platform $platform): array
|
||||
{
|
||||
return match ($platform) {
|
||||
Platform::Darwin => [
|
||||
'paths' => ['/Applications/Visual Studio Code.app'],
|
||||
],
|
||||
Platform::Linux => [
|
||||
'command' => 'command -v code',
|
||||
],
|
||||
Platform::Windows => [
|
||||
'paths' => [
|
||||
'%ProgramFiles%\\Microsoft VS Code',
|
||||
'%LOCALAPPDATA%\\Programs\\Microsoft VS Code',
|
||||
],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
public function projectDetectionConfig(): array
|
||||
{
|
||||
return [
|
||||
'paths' => ['.vscode'],
|
||||
];
|
||||
}
|
||||
|
||||
public function mcpConfigPath(): string
|
||||
{
|
||||
return '.vscode/mcp.json';
|
||||
}
|
||||
|
||||
public function mcpConfigKey(): string
|
||||
{
|
||||
return 'servers';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use Illuminate\Support\Collection;
|
||||
use Laravel\Boost\BoostManager;
|
||||
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class CodeEnvironmentsDetector
|
||||
{
|
||||
public function __construct(
|
||||
private readonly Container $container,
|
||||
private readonly BoostManager $boostManager
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Detect installed applications on the current platform.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public function discoverSystemInstalledCodeEnvironments(): array
|
||||
{
|
||||
$platform = Platform::current();
|
||||
|
||||
return $this->getCodeEnvironments()
|
||||
->filter(fn (CodeEnvironment $program): bool => $program->detectOnSystem($platform))
|
||||
->map(fn (CodeEnvironment $program): string => $program->name())
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect applications used in the current project.
|
||||
*
|
||||
* @return array<string>
|
||||
*/
|
||||
public function discoverProjectInstalledCodeEnvironments(string $basePath): array
|
||||
{
|
||||
return $this->getCodeEnvironments()
|
||||
->filter(fn (CodeEnvironment $program): bool => $program->detectInProject($basePath))
|
||||
->map(fn (CodeEnvironment $program): string => $program->name())
|
||||
->values()
|
||||
->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all registered code environments.
|
||||
*
|
||||
* @return Collection<string, CodeEnvironment>
|
||||
*/
|
||||
public function getCodeEnvironments(): Collection
|
||||
{
|
||||
return collect($this->boostManager->getCodeEnvironments())
|
||||
->map(fn (string $className) => $this->container->make($className));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Contracts;
|
||||
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
interface DetectionStrategy
|
||||
{
|
||||
/**
|
||||
* Detect if the application is installed on the machine.
|
||||
*
|
||||
* @param array{command?:string, basePath?:string, files?:array<string>, paths?:array<string>} $config
|
||||
*/
|
||||
public function detect(array $config, ?Platform $platform = null): bool;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Detection;
|
||||
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Laravel\Boost\Install\Contracts\DetectionStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class CommandDetectionStrategy implements DetectionStrategy
|
||||
{
|
||||
public function detect(array $config, ?Platform $platform = null): bool
|
||||
{
|
||||
if (! isset($config['command'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Process::run($config['command'])->successful();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Detection;
|
||||
|
||||
use Laravel\Boost\Install\Contracts\DetectionStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class CompositeDetectionStrategy implements DetectionStrategy
|
||||
{
|
||||
/**
|
||||
* @param DetectionStrategy[] $strategies
|
||||
*/
|
||||
public function __construct(private readonly array $strategies) {}
|
||||
|
||||
public function detect(array $config, ?Platform $platform = null): bool
|
||||
{
|
||||
foreach ($this->strategies as $strategy) {
|
||||
if ($strategy->detect($config, $platform)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Detection;
|
||||
|
||||
use Illuminate\Container\Container;
|
||||
use InvalidArgumentException;
|
||||
use Laravel\Boost\Install\Contracts\DetectionStrategy;
|
||||
|
||||
class DetectionStrategyFactory
|
||||
{
|
||||
private const TYPE_DIRECTORY = 'directory';
|
||||
|
||||
private const TYPE_COMMAND = 'command';
|
||||
|
||||
private const TYPE_FILE = 'file';
|
||||
|
||||
public function __construct(private readonly Container $container) {}
|
||||
|
||||
public function make(string|array $type, array $config = []): DetectionStrategy
|
||||
{
|
||||
if (is_array($type)) {
|
||||
return new CompositeDetectionStrategy(
|
||||
array_map(fn (string|array $singleType): DetectionStrategy => $this->make($singleType, $config), $type)
|
||||
);
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
self::TYPE_DIRECTORY => $this->container->make(DirectoryDetectionStrategy::class),
|
||||
self::TYPE_COMMAND => $this->container->make(CommandDetectionStrategy::class),
|
||||
self::TYPE_FILE => $this->container->make(FileDetectionStrategy::class),
|
||||
default => throw new InvalidArgumentException("Unknown detection type: {$type}"),
|
||||
};
|
||||
}
|
||||
|
||||
public function makeFromConfig(array $config): DetectionStrategy
|
||||
{
|
||||
$type = $this->inferTypeFromConfig($config);
|
||||
|
||||
return $this->make($type, $config);
|
||||
}
|
||||
|
||||
protected function inferTypeFromConfig(array $config): string|array
|
||||
{
|
||||
$typeMap = [
|
||||
'files' => self::TYPE_FILE,
|
||||
'paths' => self::TYPE_DIRECTORY,
|
||||
'command' => self::TYPE_COMMAND,
|
||||
];
|
||||
|
||||
$types = collect($typeMap)
|
||||
->only(array_keys($config))
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if (empty($types)) {
|
||||
throw new InvalidArgumentException(
|
||||
'Cannot infer detection type from config keys. Expected one of: '.collect($typeMap)->keys()->join(', ')
|
||||
);
|
||||
}
|
||||
|
||||
return count($types) > 1 ? $types : reset($types);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Detection;
|
||||
|
||||
use Laravel\Boost\Install\Contracts\DetectionStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class DirectoryDetectionStrategy implements DetectionStrategy
|
||||
{
|
||||
public function detect(array $config, ?Platform $platform = null): bool
|
||||
{
|
||||
if (! isset($config['paths'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$basePath = $config['basePath'] ?? '';
|
||||
|
||||
foreach ($config['paths'] as $path) {
|
||||
$expandedPath = $this->expandPath($path, $platform);
|
||||
|
||||
// If basePath is provided, prepend it to relative paths
|
||||
if ($basePath && ! $this->isAbsolutePath($expandedPath)) {
|
||||
$expandedPath = $basePath.DIRECTORY_SEPARATOR.$expandedPath;
|
||||
}
|
||||
|
||||
if (str_contains($expandedPath, '*')) {
|
||||
$matches = glob($expandedPath, GLOB_ONLYDIR);
|
||||
if (! empty($matches)) {
|
||||
return true;
|
||||
}
|
||||
} elseif (is_dir($expandedPath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function expandPath(string $path, ?Platform $platform = null): string
|
||||
{
|
||||
if ($platform === Platform::Windows) {
|
||||
return preg_replace_callback('/%([^%]+)%/', fn (array $matches) => getenv($matches[1]) ?: $matches[0], $path);
|
||||
}
|
||||
|
||||
if (str_starts_with($path, '~')) {
|
||||
$home = getenv('HOME');
|
||||
if ($home) {
|
||||
return str_replace('~', $home, $path);
|
||||
}
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
protected function isAbsolutePath(string $path): bool
|
||||
{
|
||||
return str_starts_with($path, '/') ||
|
||||
str_starts_with($path, '\\') ||
|
||||
(strlen($path) > 1 && $path[1] === ':'); // Windows C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Detection;
|
||||
|
||||
use Laravel\Boost\Install\Contracts\DetectionStrategy;
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class FileDetectionStrategy implements DetectionStrategy
|
||||
{
|
||||
public function detect(array $config, ?Platform $platform = null): bool
|
||||
{
|
||||
$basePath = $config['basePath'] ?? getcwd();
|
||||
|
||||
if (isset($config['files'])) {
|
||||
foreach ($config['files'] as $file) {
|
||||
if (file_exists($basePath.DIRECTORY_SEPARATOR.$file)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Enums;
|
||||
|
||||
enum McpInstallationStrategy: string
|
||||
{
|
||||
case SHELL = 'shell';
|
||||
case FILE = 'file';
|
||||
case NONE = 'none';
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Enums;
|
||||
|
||||
enum Platform: string
|
||||
{
|
||||
case Darwin = 'darwin';
|
||||
case Linux = 'linux';
|
||||
case Windows = 'windows';
|
||||
|
||||
public static function current(): self
|
||||
{
|
||||
return match (PHP_OS_FAMILY) {
|
||||
'Windows' => self::Windows,
|
||||
'Darwin' => self::Darwin,
|
||||
default => self::Linux,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Laravel\Boost\Install\Assists\Inertia;
|
||||
use Laravel\Roster\Enums\NodePackageManager;
|
||||
use Laravel\Roster\Enums\Packages;
|
||||
use Laravel\Roster\Roster;
|
||||
use ReflectionClass;
|
||||
use Symfony\Component\Finder\Finder;
|
||||
use Throwable;
|
||||
|
||||
class GuidelineAssist
|
||||
{
|
||||
/** @var array<string, string> */
|
||||
protected array $modelPaths = [];
|
||||
|
||||
protected array $controllerPaths = [];
|
||||
|
||||
protected array $enumPaths = [];
|
||||
|
||||
protected static array $classes = [];
|
||||
|
||||
public function __construct(public Roster $roster, public GuidelineConfig $config)
|
||||
{
|
||||
$this->modelPaths = $this->discover(fn ($reflection): bool => ($reflection->isSubclassOf(Model::class) && ! $reflection->isAbstract()));
|
||||
$this->controllerPaths = $this->discover(fn (ReflectionClass $reflection): bool => (stripos($reflection->getName(), 'controller') !== false || stripos($reflection->getNamespaceName(), 'controller') !== false));
|
||||
$this->enumPaths = $this->discover(fn ($reflection) => $reflection->isEnum());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> - className, absolutePath
|
||||
*/
|
||||
public function models(): array
|
||||
{
|
||||
return $this->modelPaths;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> - className, absolutePath
|
||||
*/
|
||||
public function controllers(): array
|
||||
{
|
||||
return $this->controllerPaths;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string> - className, absolutePath
|
||||
*/
|
||||
public function enums(): array
|
||||
{
|
||||
return $this->enumPaths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover all Eloquent models in the application.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function discover(callable $cb): array
|
||||
{
|
||||
$classes = [];
|
||||
$appPath = app_path();
|
||||
|
||||
if (! is_dir($appPath)) {
|
||||
return ['app-path-isnt-a-directory' => $appPath];
|
||||
}
|
||||
|
||||
if (self::$classes === []) {
|
||||
$finder = Finder::create()
|
||||
->in($appPath)
|
||||
->files()
|
||||
->name('/[A-Z].*\.php$/');
|
||||
|
||||
foreach ($finder as $file) {
|
||||
$relativePath = $file->getRelativePathname();
|
||||
$namespace = app()->getNamespace();
|
||||
$className = $namespace.str_replace(
|
||||
['/', '.php'],
|
||||
['\\', ''],
|
||||
$relativePath
|
||||
);
|
||||
|
||||
try {
|
||||
$path = $appPath.DIRECTORY_SEPARATOR.$relativePath;
|
||||
|
||||
if (! $this->fileHasClassLike($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (class_exists($className, false)) {
|
||||
self::$classes[$className] = $path;
|
||||
}
|
||||
} catch (Throwable) {
|
||||
// Ignore exceptions and errors from class loading/reflection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (self::$classes as $className => $path) {
|
||||
if ($cb(new ReflectionClass($className))) {
|
||||
$classes[$className] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
return $classes;
|
||||
}
|
||||
|
||||
public function fileHasClassLike(string $path): bool
|
||||
{
|
||||
static $cache = [];
|
||||
|
||||
if (isset($cache[$path])) {
|
||||
return $cache[$path];
|
||||
}
|
||||
|
||||
$code = file_get_contents($path);
|
||||
if ($code === false) {
|
||||
return $cache[$path] = false;
|
||||
}
|
||||
|
||||
if (stripos($code, 'class') === false
|
||||
&& stripos($code, 'interface') === false
|
||||
&& stripos($code, 'trait') === false
|
||||
&& stripos($code, 'enum') === false) {
|
||||
return $cache[$path] = false;
|
||||
}
|
||||
|
||||
$tokens = token_get_all($code);
|
||||
foreach ($tokens as $token) {
|
||||
if (is_array($token) && in_array($token[0], [T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], true)) {
|
||||
return $cache[$path] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $cache[$path] = false;
|
||||
}
|
||||
|
||||
public function shouldEnforceStrictTypes(): bool
|
||||
{
|
||||
if ($this->modelPaths === []) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return str_contains(
|
||||
file_get_contents(current($this->modelPaths)),
|
||||
'strict_types=1'
|
||||
);
|
||||
}
|
||||
|
||||
public function enumContents(): string
|
||||
{
|
||||
if ($this->enumPaths === []) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return file_get_contents(current($this->enumPaths));
|
||||
}
|
||||
|
||||
public function inertia(): Inertia
|
||||
{
|
||||
return new Inertia($this->roster);
|
||||
}
|
||||
|
||||
public function supportsPintAgentFormatter(): bool
|
||||
{
|
||||
return $this->roster->usesVersion(Packages::PINT, '1.27.0', '>=');
|
||||
}
|
||||
|
||||
protected function detectedNodePackageManager(): string
|
||||
{
|
||||
return ($this->roster->nodePackageManager() ?? NodePackageManager::NPM)->value;
|
||||
}
|
||||
|
||||
public function nodePackageManagerCommand(string $command): string
|
||||
{
|
||||
$npmExecutable = config('boost.executable_paths.npm');
|
||||
|
||||
if ($npmExecutable !== null) {
|
||||
return "{$npmExecutable} {$command}";
|
||||
}
|
||||
|
||||
if ($this->config->usesSail) {
|
||||
return Sail::nodePackageManagerCommand($this->detectedNodePackageManager())." {$command}";
|
||||
}
|
||||
|
||||
return "{$this->detectedNodePackageManager()} {$command}";
|
||||
}
|
||||
|
||||
public function artisanCommand(string $command): string
|
||||
{
|
||||
return "{$this->artisan()} {$command}";
|
||||
}
|
||||
|
||||
public function composerCommand(string $command): string
|
||||
{
|
||||
$composerExecutable = config('boost.executable_paths.composer');
|
||||
|
||||
if ($composerExecutable !== null) {
|
||||
return "{$composerExecutable} {$command}";
|
||||
}
|
||||
|
||||
if ($this->config->usesSail) {
|
||||
return Sail::composerCommand()." {$command}";
|
||||
}
|
||||
|
||||
return "composer {$command}";
|
||||
}
|
||||
|
||||
public function binCommand(string $command): string
|
||||
{
|
||||
$vendorBinPrefix = config('boost.executable_paths.vendor_bin');
|
||||
|
||||
if ($vendorBinPrefix !== null) {
|
||||
return "{$vendorBinPrefix}{$command}";
|
||||
}
|
||||
|
||||
if ($this->config->usesSail) {
|
||||
return Sail::binCommand().$command;
|
||||
}
|
||||
|
||||
return "vendor/bin/{$command}";
|
||||
}
|
||||
|
||||
public function artisan(): string
|
||||
{
|
||||
$phpExecutable = config('boost.executable_paths.php');
|
||||
|
||||
if ($phpExecutable !== null) {
|
||||
return "{$phpExecutable} artisan";
|
||||
}
|
||||
|
||||
return $this->config->usesSail
|
||||
? Sail::artisanCommand()
|
||||
: 'php artisan';
|
||||
}
|
||||
|
||||
public function sailBinaryPath(): string
|
||||
{
|
||||
return Sail::BINARY_PATH;
|
||||
}
|
||||
|
||||
public function hasPackage(Packages $package): bool
|
||||
{
|
||||
return $this->roster->packages()->contains(
|
||||
fn ($pkg): bool => $pkg->package() === $package
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
|
||||
use Laravel\Boost\Support\Composer;
|
||||
use Laravel\Roster\Enums\Packages;
|
||||
use Laravel\Roster\Package;
|
||||
use Laravel\Roster\PackageCollection;
|
||||
use Laravel\Roster\Roster;
|
||||
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
|
||||
use Symfony\Component\Finder\Finder;
|
||||
use Symfony\Component\Finder\SplFileInfo;
|
||||
|
||||
class GuidelineComposer
|
||||
{
|
||||
use RendersBladeGuidelines;
|
||||
|
||||
protected string $userGuidelineDir = '.ai/guidelines';
|
||||
|
||||
/** @var Collection<string, array> */
|
||||
protected Collection $guidelines;
|
||||
|
||||
protected GuidelineConfig $config;
|
||||
|
||||
/**
|
||||
* Package priority system to handle conflicts between packages.
|
||||
* When a higher-priority package is present, lower-priority packages are excluded from guidelines.
|
||||
*
|
||||
* @var array<string, string[]>
|
||||
*/
|
||||
protected array $packagePriorities;
|
||||
|
||||
/**
|
||||
* Only include guidelines for these package names if they're a direct requirement.
|
||||
* This fixes every Boost user getting the MCP guidelines due to indirect import.
|
||||
*
|
||||
* @var array<int, Packages>
|
||||
* */
|
||||
protected array $mustBeDirect = [
|
||||
Packages::MCP,
|
||||
];
|
||||
|
||||
/**
|
||||
* Packages that should be excluded from automatic guideline inclusion.
|
||||
* These packages require explicit configuration to be included.
|
||||
*
|
||||
* @var array<int, Packages>
|
||||
*/
|
||||
protected array $optInPackages = [
|
||||
Packages::SAIL,
|
||||
];
|
||||
|
||||
public function __construct(protected Roster $roster, protected Herd $herd)
|
||||
{
|
||||
$this->packagePriorities = [
|
||||
Packages::PEST->value => [Packages::PHPUNIT->value],
|
||||
Packages::FLUXUI_PRO->value => [Packages::FLUXUI_FREE->value],
|
||||
];
|
||||
$this->config = new GuidelineConfig;
|
||||
}
|
||||
|
||||
public function config(GuidelineConfig $config): self
|
||||
{
|
||||
$this->config = $config;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto discovers the guideline files and composes them into one string.
|
||||
*/
|
||||
public function compose(): string
|
||||
{
|
||||
return self::composeGuidelines($this->guidelines());
|
||||
}
|
||||
|
||||
public function customGuidelinePath(string $path = ''): string
|
||||
{
|
||||
return base_path($this->userGuidelineDir.'/'.ltrim($path, '/'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Static method to compose guidelines from a collection.
|
||||
* Can be used without Laravel dependencies.
|
||||
*
|
||||
* @param Collection<string, array{content: string, name: string, path: ?string, custom: bool}> $guidelines
|
||||
*/
|
||||
public static function composeGuidelines(Collection $guidelines): string
|
||||
{
|
||||
return str_replace("\n\n\n\n", "\n\n", trim($guidelines
|
||||
->filter(fn ($guideline): bool => ! empty(trim($guideline['content'])))
|
||||
->map(fn ($guideline, $key): string => "\n=== {$key} rules ===\n\n".trim($guideline['content']))
|
||||
->join("\n\n"))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function used(): array
|
||||
{
|
||||
return $this->guidelines()->keys()->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array>
|
||||
*/
|
||||
public function guidelines(): Collection
|
||||
{
|
||||
if (! empty($this->guidelines)) {
|
||||
return $this->guidelines;
|
||||
}
|
||||
|
||||
$base = collect()
|
||||
->merge($this->getCoreGuidelines())
|
||||
->merge($this->getConditionalGuidelines())
|
||||
->merge($this->getPackageGuidelines())
|
||||
->merge($this->getThirdPartyGuidelines());
|
||||
|
||||
$basePaths = $base->pluck('path')->filter()->values();
|
||||
|
||||
$customGuidelines = $this->getUserGuidelines()
|
||||
->reject(fn ($guideline): bool => $basePaths->contains($guideline['path']));
|
||||
|
||||
return $this->guidelines = $customGuidelines
|
||||
->merge($base)
|
||||
->filter(fn ($guideline): bool => filled($guideline['content']));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array>
|
||||
*/
|
||||
protected function getUserGuidelines(): Collection
|
||||
{
|
||||
return collect($this->guidelinesDir($this->customGuidelinePath()))
|
||||
->mapWithKeys(fn ($guideline): array => ['.ai/'.$guideline['name'] => $guideline]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array>
|
||||
*/
|
||||
protected function getCoreGuidelines(): Collection
|
||||
{
|
||||
return collect([
|
||||
'foundation' => $this->guideline('foundation'),
|
||||
'boost' => $this->guideline('boost/core'),
|
||||
'php' => $this->guideline('php/core'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array>
|
||||
*/
|
||||
protected function getConditionalGuidelines(): Collection
|
||||
{
|
||||
return collect([
|
||||
'herd' => [
|
||||
'condition' => str_contains((string) config('app.url'), '.test') && $this->herd->isInstalled() && ! $this->config->usesSail,
|
||||
'path' => 'herd/core',
|
||||
],
|
||||
'sail' => [
|
||||
'condition' => $this->config->usesSail,
|
||||
'path' => 'sail/core',
|
||||
],
|
||||
'laravel/style' => [
|
||||
'condition' => $this->config->laravelStyle,
|
||||
'path' => 'laravel/style',
|
||||
],
|
||||
'laravel/api' => [
|
||||
'condition' => $this->config->hasAnApi,
|
||||
'path' => 'laravel/api',
|
||||
],
|
||||
'laravel/localization' => [
|
||||
'condition' => $this->config->caresAboutLocalization,
|
||||
'path' => 'laravel/localization',
|
||||
],
|
||||
'tests' => [
|
||||
'condition' => $this->config->enforceTests,
|
||||
'path' => 'enforce-tests',
|
||||
],
|
||||
])
|
||||
->filter(fn ($config): bool => $config['condition'])
|
||||
->mapWithKeys(fn ($config, $key): array => [$key => $this->guideline($config['path'])]);
|
||||
}
|
||||
|
||||
protected function getPackageGuidelines(): PackageCollection
|
||||
{
|
||||
return $this->roster->packages()
|
||||
->reject(fn (Package $package): bool => $this->shouldExcludePackage($package))
|
||||
->flatMap(function ($package): Collection {
|
||||
$guidelineDir = str_replace('_', '-', strtolower($package->name()));
|
||||
$guidelines = collect([$guidelineDir.'/core' => $this->guideline($guidelineDir.'/core')]);
|
||||
$packageGuidelines = $this->guidelinesDir($guidelineDir.'/'.$package->majorVersion());
|
||||
|
||||
foreach ($packageGuidelines as $guideline) {
|
||||
$suffix = $guideline['name'] === 'core' ? '' : '/'.$guideline['name'];
|
||||
|
||||
$guidelines->put(
|
||||
$guidelineDir.'/v'.$package->majorVersion().$suffix,
|
||||
$guideline
|
||||
);
|
||||
}
|
||||
|
||||
return $guidelines;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<string, array>
|
||||
*/
|
||||
protected function getThirdPartyGuidelines(): Collection
|
||||
{
|
||||
$guidelines = collect();
|
||||
|
||||
collect(Composer::packagesDirectoriesWithBoostGuidelines())
|
||||
->each(function (string $path, string $package) use ($guidelines): void {
|
||||
$packageGuidelines = $this->guidelinesDir($path, true);
|
||||
|
||||
foreach ($packageGuidelines as $guideline) {
|
||||
$guidelines->put($package, $guideline);
|
||||
}
|
||||
});
|
||||
|
||||
return $guidelines->when(
|
||||
isset($this->config->aiGuidelines),
|
||||
fn (Collection $collection): Collection => $collection->filter(
|
||||
fn (mixed $guideline, string $name): bool => in_array($name, $this->config->aiGuidelines, true),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a package should be excluded from guidelines based on priority rules.
|
||||
*/
|
||||
protected function shouldExcludePackage(Package $package): bool
|
||||
{
|
||||
if (in_array($package->package(), $this->optInPackages, true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($this->packagePriorities as $priorityPackage => $excludedPackages) {
|
||||
$packageIsInExclusionList = in_array($package->package()->value, $excludedPackages, true);
|
||||
|
||||
if ($packageIsInExclusionList && $this->roster->uses(Packages::from($priorityPackage))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return $package->indirect() && in_array($package->package(), $this->mustBeDirect, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<array{content: string, name: string, description: string, path: ?string, custom: bool, third_party: bool}>
|
||||
*/
|
||||
protected function guidelinesDir(string $dirPath, bool $thirdParty = false): array
|
||||
{
|
||||
if (! is_dir($dirPath)) {
|
||||
$dirPath = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/../../.ai/'.$dirPath);
|
||||
}
|
||||
|
||||
try {
|
||||
$finder = Finder::create()
|
||||
->files()
|
||||
->in($dirPath)
|
||||
->name('*.blade.php')
|
||||
->name('*.md');
|
||||
} catch (DirectoryNotFoundException) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return collect($finder)
|
||||
->map(fn (SplFileInfo $file): array => $this->guideline($file->getRealPath(), $thirdParty))
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{content: string, name: string, description: string, path: ?string, custom: bool, third_party: bool}
|
||||
*/
|
||||
protected function guideline(string $path, bool $thirdParty = false): array
|
||||
{
|
||||
$path = $this->guidelinePath($path);
|
||||
if (is_null($path)) {
|
||||
return [
|
||||
'content' => '',
|
||||
'description' => '',
|
||||
'name' => '',
|
||||
'path' => null,
|
||||
'custom' => false,
|
||||
'third_party' => $thirdParty,
|
||||
];
|
||||
}
|
||||
|
||||
$content = file_get_contents($path);
|
||||
$content = $this->processBoostSnippets($content);
|
||||
|
||||
$rendered = $this->renderContent($content, $path);
|
||||
|
||||
$rendered = str_replace(array_keys($this->storedSnippets), array_values($this->storedSnippets), $rendered);
|
||||
|
||||
$this->storedSnippets = []; // Clear for next use
|
||||
|
||||
$description = Str::of($rendered)
|
||||
->after('# ')
|
||||
->before("\n")
|
||||
->trim()
|
||||
->limit(50)
|
||||
->whenEmpty(fn () => Str::of('No description provided'))
|
||||
->value();
|
||||
|
||||
return [
|
||||
'content' => trim($rendered),
|
||||
'name' => str_replace(['.blade.php', '.md'], '', basename($path)),
|
||||
'description' => $description,
|
||||
'path' => $path,
|
||||
'custom' => str_contains($path, $this->customGuidelinePath()),
|
||||
'third_party' => $thirdParty,
|
||||
'tokens' => round(str_word_count($rendered) * 1.3),
|
||||
];
|
||||
}
|
||||
|
||||
protected function getGuidelineAssist(): GuidelineAssist
|
||||
{
|
||||
return new GuidelineAssist($this->roster, $this->config);
|
||||
}
|
||||
|
||||
protected function prependPackageGuidelinePath(string $path): string
|
||||
{
|
||||
return $this->prependGuidelinePath($path, __DIR__.'/../../.ai/');
|
||||
}
|
||||
|
||||
protected function prependUserGuidelinePath(string $path): string
|
||||
{
|
||||
return $this->prependGuidelinePath($path, $this->customGuidelinePath());
|
||||
}
|
||||
|
||||
private function prependGuidelinePath(string $path, string $basePath): string
|
||||
{
|
||||
if (! str_ends_with($path, '.md') && ! str_ends_with($path, '.blade.php')) {
|
||||
$path .= '.blade.php';
|
||||
}
|
||||
|
||||
return str_replace('/', DIRECTORY_SEPARATOR, $basePath.$path);
|
||||
}
|
||||
|
||||
protected function guidelinePath(string $path): ?string
|
||||
{
|
||||
// Relative path, prepend our package path to it
|
||||
if (! file_exists($path)) {
|
||||
$path = $this->prependPackageGuidelinePath($path);
|
||||
if (! file_exists($path)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$path = realpath($path);
|
||||
|
||||
// If this is a custom guideline, return it unchanged
|
||||
if (str_contains($path, $this->customGuidelinePath())) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
// The path is not a custom guideline, check if the user has an override for this
|
||||
$basePath = realpath(__DIR__.'/../../');
|
||||
$relativePath = Str::of($path)
|
||||
->replace([$basePath, '.ai'.DIRECTORY_SEPARATOR, '.ai/'], '')
|
||||
->ltrim('/\\')
|
||||
->toString();
|
||||
|
||||
$customPath = $this->prependUserGuidelinePath($relativePath);
|
||||
|
||||
return file_exists($customPath) ? $customPath : $path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
class GuidelineConfig
|
||||
{
|
||||
public bool $enforceTests = false;
|
||||
|
||||
public bool $laravelStyle = false;
|
||||
|
||||
public bool $usesSail = false;
|
||||
|
||||
public bool $caresAboutLocalization = false;
|
||||
|
||||
public bool $hasAnApi = false;
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public array $aiGuidelines;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use Laravel\Boost\Contracts\Agent;
|
||||
use RuntimeException;
|
||||
|
||||
class GuidelineWriter
|
||||
{
|
||||
public const NEW = 0;
|
||||
|
||||
public const REPLACED = 1;
|
||||
|
||||
public const FAILED = 2;
|
||||
|
||||
public const NOOP = 3;
|
||||
|
||||
public function __construct(protected Agent $agent) {}
|
||||
|
||||
/**
|
||||
* @return GuidelineWriter::NEW|GuidelineWriter::REPLACED|GuidelineWriter::FAILED|GuidelineWriter::NOOP
|
||||
*/
|
||||
public function write(string $guidelines): int
|
||||
{
|
||||
if (empty($guidelines)) {
|
||||
return self::NOOP;
|
||||
}
|
||||
|
||||
$filePath = $this->agent->guidelinesPath();
|
||||
|
||||
$directory = dirname($filePath);
|
||||
if (! is_dir($directory) && ! @mkdir($directory, 0755, true)) {
|
||||
throw new RuntimeException("Failed to create directory: {$directory}");
|
||||
}
|
||||
|
||||
$handle = @fopen($filePath, 'c+');
|
||||
if (! $handle) {
|
||||
throw new RuntimeException("Failed to open file: {$filePath}");
|
||||
}
|
||||
|
||||
try {
|
||||
$this->acquireLockWithRetry($handle, $filePath);
|
||||
|
||||
$content = stream_get_contents($handle);
|
||||
|
||||
// Check if guidelines already exist
|
||||
$pattern = '/<laravel-boost-guidelines>.*?<\/laravel-boost-guidelines>/s';
|
||||
$replacement = "<laravel-boost-guidelines>\n".$guidelines."\n</laravel-boost-guidelines>";
|
||||
$replaced = false;
|
||||
|
||||
if (preg_match($pattern, $content)) {
|
||||
// Replace ALL existing boost guidelines blocks in-place
|
||||
// If the user added guidelines after ours then let's
|
||||
// make sure we keep the flow.
|
||||
$newContent = preg_replace($pattern, $replacement, $content, 1);
|
||||
$replaced = true;
|
||||
} else {
|
||||
// No existing Boost guidelines found, append to end of existing file
|
||||
$frontMatter = '';
|
||||
if ($this->agent->frontmatter() && ! str_contains($content, "\n---\n")) {
|
||||
$frontMatter = "---\nalwaysApply: true\n---\n";
|
||||
}
|
||||
|
||||
$existingContent = rtrim($content);
|
||||
$separatingNewlines = empty($existingContent) ? '' : "\n\n===\n\n";
|
||||
$newContent = $frontMatter.$existingContent.$separatingNewlines.$replacement;
|
||||
}
|
||||
|
||||
// Normalize multiple blank lines to single blank lines
|
||||
$newContent = preg_replace("/\n{3,}/", "\n\n", (string) $newContent);
|
||||
|
||||
// Ensure file content ends with a newline
|
||||
if (! str_ends_with((string) $newContent, "\n")) {
|
||||
$newContent .= "\n";
|
||||
}
|
||||
|
||||
if (ftruncate($handle, 0) === false || fseek($handle, 0) === -1) {
|
||||
throw new RuntimeException("Failed to reset file pointer: {$filePath}");
|
||||
}
|
||||
|
||||
if (fwrite($handle, (string) $newContent) === false) {
|
||||
throw new RuntimeException("Failed to write to file: {$filePath}");
|
||||
}
|
||||
|
||||
flock($handle, LOCK_UN);
|
||||
} finally {
|
||||
fclose($handle);
|
||||
}
|
||||
|
||||
return $replaced ? self::REPLACED : self::NEW;
|
||||
}
|
||||
|
||||
protected function acquireLockWithRetry(mixed $handle, string $filePath, int $maxRetries = 3): void
|
||||
{
|
||||
$attempts = 0;
|
||||
$delay = 100000; // Start with 100ms in microseconds
|
||||
|
||||
while ($attempts < $maxRetries) {
|
||||
if (flock($handle, LOCK_EX | LOCK_NB)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$attempts++;
|
||||
|
||||
if ($attempts >= $maxRetries) {
|
||||
throw new RuntimeException("Failed to acquire lock on file after {$maxRetries} attempts: {$filePath}");
|
||||
}
|
||||
|
||||
// Exponential backoff with jitter
|
||||
$jitter = random_int(0, (int) ($delay * 0.1));
|
||||
usleep($delay + $jitter);
|
||||
$delay *= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use Laravel\Boost\Install\Enums\Platform;
|
||||
|
||||
class Herd
|
||||
{
|
||||
public function isInstalled(): bool
|
||||
{
|
||||
if (! $this->isWindowsPlatform()) {
|
||||
return file_exists('/Applications/Herd.app/Contents/MacOS/Herd');
|
||||
}
|
||||
|
||||
return is_dir($this->getHomePath().'/.config/herd');
|
||||
}
|
||||
|
||||
public function isMcpAvailable(): bool
|
||||
{
|
||||
return file_exists($this->mcpPath());
|
||||
}
|
||||
|
||||
public function getHomePath(): string
|
||||
{
|
||||
if ($this->isWindowsPlatform()) {
|
||||
if (! isset($_SERVER['HOME'])) {
|
||||
$_SERVER['HOME'] = $_SERVER['USERPROFILE'];
|
||||
}
|
||||
|
||||
$_SERVER['HOME'] = str_replace('\\', '/', $_SERVER['HOME']);
|
||||
}
|
||||
|
||||
return $_SERVER['HOME'];
|
||||
}
|
||||
|
||||
public function mcpPath(): string
|
||||
{
|
||||
if ($this->isWindowsPlatform()) {
|
||||
return $this->getHomePath().'/.config/herd/bin/herd-mcp.phar';
|
||||
}
|
||||
|
||||
return '/Applications/Herd.app/Contents/Resources/herd-mcp.phar';
|
||||
}
|
||||
|
||||
public function isWindowsPlatform(): bool
|
||||
{
|
||||
return Platform::current() === Platform::Windows;
|
||||
}
|
||||
}
|
||||
+426
@@ -0,0 +1,426 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install\Mcp;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class FileWriter
|
||||
{
|
||||
protected string $configKey = 'mcpServers';
|
||||
|
||||
protected array $serversToAdd = [];
|
||||
|
||||
protected int $defaultIndentation = 8;
|
||||
|
||||
public function __construct(protected string $filePath, protected array $baseConfig = []) {}
|
||||
|
||||
public function configKey(string $key): self
|
||||
{
|
||||
$this->configKey = $key;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use addServerConfig() for array-based configuration.
|
||||
*
|
||||
* @param array<int, string> $args
|
||||
* @param array<string, string> $env
|
||||
*/
|
||||
public function addServer(string $key, string $command, array $args = [], array $env = []): self
|
||||
{
|
||||
return $this->addServerConfig($key, collect([
|
||||
'command' => $command,
|
||||
'args' => $args,
|
||||
'env' => $env,
|
||||
])->filter(fn ($value): bool => ! in_array($value, [[], null, ''], true))->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $config
|
||||
*/
|
||||
public function addServerConfig(string $key, array $config): self
|
||||
{
|
||||
$this->serversToAdd[$key] = collect($config)
|
||||
->filter(fn ($value): bool => ! in_array($value, [[], null, ''], true))
|
||||
->toArray();
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function save(): bool
|
||||
{
|
||||
$this->ensureDirectoryExists();
|
||||
|
||||
if ($this->shouldWriteNew()) {
|
||||
return $this->createNewFile();
|
||||
}
|
||||
|
||||
$content = $this->readFile();
|
||||
|
||||
if ($this->isPlainJson($content)) {
|
||||
return $this->updatePlainJsonFile($content);
|
||||
}
|
||||
|
||||
return $this->updateJson5File($content);
|
||||
}
|
||||
|
||||
protected function updatePlainJsonFile(string $content): bool
|
||||
{
|
||||
$config = json_decode($content, true);
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->addServersToConfig($config);
|
||||
|
||||
return $this->writeJsonConfig($config);
|
||||
}
|
||||
|
||||
protected function updateJson5File(string $content): bool
|
||||
{
|
||||
$configKeyPattern = '/["\']'.preg_quote($this->configKey, '/').'["\']\\s*:\\s*\\{/';
|
||||
|
||||
if (preg_match($configKeyPattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
|
||||
return $this->injectIntoExistingConfigKey($content, $matches);
|
||||
}
|
||||
|
||||
return $this->injectNewConfigKey($content);
|
||||
}
|
||||
|
||||
protected function injectIntoExistingConfigKey(string $content, array $matches): bool
|
||||
{
|
||||
// $matches[0][1] contains the position of the configKey pattern match
|
||||
$configKeyStart = $matches[0][1];
|
||||
|
||||
// Find the opening brace of the configKey object
|
||||
$openBracePos = strpos($content, '{', $configKeyStart);
|
||||
if ($openBracePos === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Find the matching closing brace for this configKey object
|
||||
$closeBracePos = $this->findMatchingClosingBrace($content, $openBracePos);
|
||||
if ($closeBracePos === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Filter out servers that already exist
|
||||
$serversToAdd = $this->filterExistingServers($content, $openBracePos, $closeBracePos);
|
||||
|
||||
if ($serversToAdd === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Detect indentation from surrounding content
|
||||
$indentLength = $this->detectIndentation($content, $closeBracePos);
|
||||
|
||||
$serverJsonParts = [];
|
||||
foreach ($serversToAdd as $key => $serverConfig) {
|
||||
$serverJsonParts[] = $this->generateServerJson($key, $serverConfig, $indentLength);
|
||||
}
|
||||
|
||||
$serversJson = implode(','."\n", $serverJsonParts);
|
||||
|
||||
// Check if we need a comma and add it to the preceding content
|
||||
$needsComma = $this->needsCommaBeforeClosingBrace($content, $openBracePos, $closeBracePos);
|
||||
if (! $needsComma) {
|
||||
$newContent = substr_replace($content, $serversJson, $closeBracePos, 0);
|
||||
|
||||
return $this->writeFile($newContent);
|
||||
}
|
||||
|
||||
// Find the position to add comma (after the last meaningful character)
|
||||
$commaPosition = $this->findCommaInsertionPoint($content, $openBracePos, $closeBracePos);
|
||||
if ($commaPosition !== -1) {
|
||||
$newContent = substr_replace($content, ',', $commaPosition, 0);
|
||||
$newContent = substr_replace($newContent, $serversJson, $commaPosition + 1, 0);
|
||||
} else {
|
||||
$newContent = substr_replace($content, $serversJson, $closeBracePos, 0);
|
||||
}
|
||||
|
||||
return $this->writeFile($newContent);
|
||||
}
|
||||
|
||||
protected function filterExistingServers(string $content, int $openBracePos, int $closeBracePos): array
|
||||
{
|
||||
$configContent = substr($content, $openBracePos + 1, $closeBracePos - $openBracePos - 1);
|
||||
$filteredServers = [];
|
||||
|
||||
foreach ($this->serversToAdd as $key => $serverConfig) {
|
||||
if (! $this->serverExistsInContent($configContent, $key)) {
|
||||
$filteredServers[$key] = $serverConfig;
|
||||
}
|
||||
}
|
||||
|
||||
return $filteredServers;
|
||||
}
|
||||
|
||||
protected function serverExistsInContent(string $content, string $serverKey): bool
|
||||
{
|
||||
$quotedPattern = '/["\']'.preg_quote($serverKey, '/').'["\']\\s*:/';
|
||||
$unquotedPattern = '/(?<=^|\\s|,|{)'.preg_quote($serverKey, '/').'\\s*:/m';
|
||||
|
||||
return preg_match($quotedPattern, $content) || preg_match($unquotedPattern, $content);
|
||||
}
|
||||
|
||||
protected function injectNewConfigKey(string $content): bool
|
||||
{
|
||||
$openBracePos = strpos($content, '{');
|
||||
if ($openBracePos === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$serverJsonParts = [];
|
||||
foreach ($this->serversToAdd as $key => $serverConfig) {
|
||||
$serverJsonParts[] = $this->generateServerJson($key, $serverConfig);
|
||||
}
|
||||
|
||||
$serversJson = implode(',', $serverJsonParts);
|
||||
$configKeySection = '"'.$this->configKey.'": {'.$serversJson.'}';
|
||||
|
||||
$needsComma = $this->needsCommaAfterBrace($content, $openBracePos);
|
||||
$injection = $configKeySection.($needsComma ? ',' : '');
|
||||
|
||||
$newContent = substr_replace($content, $injection, $openBracePos + 1, 0);
|
||||
|
||||
return $this->writeFile($newContent);
|
||||
}
|
||||
|
||||
protected function generateServerJson(string $key, array $serverConfig, int $baseIndent = 0): string
|
||||
{
|
||||
$json = json_encode($serverConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
// Normalize line endings to Unix style
|
||||
$json = str_replace("\r\n", "\n", $json);
|
||||
|
||||
// If no indentation needed, return as-is
|
||||
if (empty($baseIndent)) {
|
||||
return '"'.$key.'": '.$json;
|
||||
}
|
||||
|
||||
// Apply indentation to each line of the JSON
|
||||
$baseIndent = str_repeat(' ', $baseIndent);
|
||||
$lines = explode("\n", $json);
|
||||
$firstLine = array_shift($lines);
|
||||
$indentedLines = [
|
||||
"{$baseIndent}\"{$key}\": {$firstLine}",
|
||||
...array_map(fn (string $line): string => $baseIndent.$line, $lines),
|
||||
];
|
||||
|
||||
return "\n".implode("\n", $indentedLines);
|
||||
}
|
||||
|
||||
protected function needsCommaAfterBrace(string $content, int $bracePosition): bool
|
||||
{
|
||||
$afterBrace = substr($content, $bracePosition + 1);
|
||||
$trimmed = preg_replace('/^\s*(?:\/\/.*$)?/m', '', $afterBrace);
|
||||
|
||||
return filled($trimmed) && ! Str::startsWith($trimmed, '}');
|
||||
}
|
||||
|
||||
protected function findMatchingClosingBrace(string $content, int $openBracePos): int|false
|
||||
{
|
||||
$braceCount = 1;
|
||||
$length = strlen($content);
|
||||
$inString = false;
|
||||
$escaped = false;
|
||||
|
||||
for ($i = $openBracePos + 1; $i < $length; $i++) {
|
||||
$char = $content[$i];
|
||||
|
||||
if (! $inString) {
|
||||
if ($char === '{') {
|
||||
$braceCount++;
|
||||
} elseif ($char === '}') {
|
||||
$braceCount--;
|
||||
if ($braceCount === 0) {
|
||||
return $i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle string detection (similar to hasUnquotedComments logic)
|
||||
if ($char === '"' && ! $escaped) {
|
||||
$inString = ! $inString;
|
||||
}
|
||||
|
||||
$escaped = ($char === '\\' && ! $escaped);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function needsCommaBeforeClosingBrace(string $content, int $openBracePos, int $closeBracePos): bool
|
||||
{
|
||||
// Get content between opening and closing braces
|
||||
$innerContent = substr($content, $openBracePos + 1, $closeBracePos - $openBracePos - 1);
|
||||
|
||||
// Skip whitespace and comments to find last meaningful character
|
||||
$trimmed = preg_replace('/\s+|\/\/.*$/m', '', $innerContent);
|
||||
|
||||
// If empty or ends with opening brace, no comma needed
|
||||
if (blank($trimmed) || Str::endsWith($trimmed, '{')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If ends with comma, no additional comma needed
|
||||
return ! Str::endsWith($trimmed, ',');
|
||||
}
|
||||
|
||||
protected function findCommaInsertionPoint(string $content, int $openBracePos, int $closeBracePos): int
|
||||
{
|
||||
// Work backwards from closing brace to find last meaningful character
|
||||
for ($i = $closeBracePos - 1; $i > $openBracePos; $i--) {
|
||||
$char = $content[$i];
|
||||
|
||||
// Skip whitespace and newlines
|
||||
if (in_array($char, [' ', "\t", "\n", "\r"], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip comments (simple approach - if we hit //, skip to start of line)
|
||||
if ($i > 0 && $content[$i - 1] === '/' && $char === '/') {
|
||||
// Find start of this line
|
||||
$lineStart = strrpos($content, "\n", $i - strlen($content)) ?: 0;
|
||||
$i = $lineStart;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Found last meaningful character, comma goes after it
|
||||
if ($char !== ',') {
|
||||
return $i + 1;
|
||||
}
|
||||
|
||||
// Already has comma, no insertion needed
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Fallback - insert right after opening brace
|
||||
return $openBracePos + 1;
|
||||
}
|
||||
|
||||
public function detectIndentation(string $content, int $nearPosition): int
|
||||
{
|
||||
// Look backwards from the position to find server-level indentation
|
||||
// We want to find lines that look like: "server-name": {
|
||||
|
||||
$lines = explode("\n", substr($content, 0, $nearPosition));
|
||||
|
||||
// Look for the most recent server definition to match its indentation
|
||||
for ($i = count($lines) - 1; $i >= 0; $i--) {
|
||||
$line = $lines[$i];
|
||||
// Match server definitions: any amount of whitespace + "key": {
|
||||
if (preg_match('/^(\s*)"[^"]+"\s*:\s*\{/', $line, $matches)) {
|
||||
return strlen($matches[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: assume 8 spaces (2 levels of 4-space indentation typical for JSON)
|
||||
return $this->defaultIndentation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the file content plain JSON, without JSON5 features?
|
||||
*/
|
||||
protected function isPlainJson(string $content): bool
|
||||
{
|
||||
if ($this->hasUnquotedComments($content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Trailing commas (,] or ,}) - supported in JSON 5
|
||||
if (preg_match('/,\s*[\]}]/', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unquoted keys - supported in JSON 5
|
||||
if (preg_match('/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/m', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
json_decode($content);
|
||||
|
||||
return json_last_error() === JSON_ERROR_NONE;
|
||||
}
|
||||
|
||||
protected function hasUnquotedComments(string $content): bool
|
||||
{
|
||||
// Regex that matches both quoted strings and comments
|
||||
// Group 1: Double-quoted strings with escaped characters
|
||||
// Group 2: Line comments starting with //
|
||||
$pattern = '/"(\\\\.|[^"\\\\])*"|(\/\/.*)/';
|
||||
|
||||
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
|
||||
foreach ($matches as $match) {
|
||||
// If group 2 is set, we found a // comment outside strings
|
||||
if (! empty($match[2])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function createNewFile(): bool
|
||||
{
|
||||
$config = $this->baseConfig;
|
||||
$this->addServersToConfig($config);
|
||||
|
||||
return $this->writeJsonConfig($config);
|
||||
}
|
||||
|
||||
protected function addServersToConfig(array &$config): void
|
||||
{
|
||||
foreach ($this->serversToAdd as $key => $serverConfig) {
|
||||
data_set($config, $this->configKey.'.'.$key, $serverConfig);
|
||||
}
|
||||
}
|
||||
|
||||
protected function writeJsonConfig(array $config): bool
|
||||
{
|
||||
$json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
// Normalize line endings to Unix style
|
||||
if ($json) {
|
||||
$json = str_replace("\r\n", "\n", $json);
|
||||
}
|
||||
|
||||
return $json && $this->writeFile($json);
|
||||
}
|
||||
|
||||
protected function ensureDirectoryExists(): void
|
||||
{
|
||||
File::ensureDirectoryExists(dirname($this->filePath));
|
||||
}
|
||||
|
||||
protected function fileExists(): bool
|
||||
{
|
||||
return File::exists($this->filePath);
|
||||
}
|
||||
|
||||
protected function shouldWriteNew(): bool
|
||||
{
|
||||
if (! $this->fileExists()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return File::size($this->filePath) < 3;
|
||||
// To account for files that are just `{}`
|
||||
}
|
||||
|
||||
protected function readFile(): string
|
||||
{
|
||||
return File::get($this->filePath);
|
||||
}
|
||||
|
||||
protected function writeFile(string $content): bool
|
||||
{
|
||||
return File::put($this->filePath, $content) !== false;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Install;
|
||||
|
||||
use const DIRECTORY_SEPARATOR;
|
||||
|
||||
class Sail
|
||||
{
|
||||
public const BINARY_PATH = 'vendor'.DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'sail';
|
||||
|
||||
public static function artisanCommand(): string
|
||||
{
|
||||
return self::command('artisan');
|
||||
}
|
||||
|
||||
public static function binCommand(): string
|
||||
{
|
||||
return self::command('bin ');
|
||||
}
|
||||
|
||||
public static function composerCommand(): string
|
||||
{
|
||||
return self::command('composer');
|
||||
}
|
||||
|
||||
public static function nodePackageManagerCommand(string $manager): string
|
||||
{
|
||||
return self::command($manager);
|
||||
}
|
||||
|
||||
public static function command(string $command): string
|
||||
{
|
||||
return self::BINARY_PATH.' '.$command;
|
||||
}
|
||||
|
||||
public function isInstalled(): bool
|
||||
{
|
||||
return file_exists(base_path(self::BINARY_PATH)) &&
|
||||
(file_exists(base_path('docker-compose.yml')) || file_exists(base_path('compose.yaml')));
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return get_current_user() === 'sail' || getenv('LARAVEL_SAIL') === '1';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function buildMcpCommand(string $serverName): array
|
||||
{
|
||||
return [$serverName, self::BINARY_PATH, 'artisan', 'boost:mcp'];
|
||||
}
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Laravel\Boost\Mcp\Methods\CallToolWithExecutor;
|
||||
use Laravel\Boost\Mcp\Prompts\LaravelCodeSimplifier\LaravelCodeSimplifier;
|
||||
use Laravel\Boost\Mcp\Prompts\PackageGuidelinePrompt;
|
||||
use Laravel\Boost\Mcp\Prompts\UpgradeLivewirev4\UpgradeLivewireV4;
|
||||
use Laravel\Boost\Mcp\Resources\PackageGuidelineResource;
|
||||
use Laravel\Boost\Mcp\Tools\ApplicationInfo;
|
||||
use Laravel\Boost\Mcp\Tools\BrowserLogs;
|
||||
use Laravel\Boost\Mcp\Tools\DatabaseConnections;
|
||||
use Laravel\Boost\Mcp\Tools\DatabaseQuery;
|
||||
use Laravel\Boost\Mcp\Tools\DatabaseSchema;
|
||||
use Laravel\Boost\Mcp\Tools\GetAbsoluteUrl;
|
||||
use Laravel\Boost\Mcp\Tools\GetConfig;
|
||||
use Laravel\Boost\Mcp\Tools\LastError;
|
||||
use Laravel\Boost\Mcp\Tools\ListArtisanCommands;
|
||||
use Laravel\Boost\Mcp\Tools\ListAvailableConfigKeys;
|
||||
use Laravel\Boost\Mcp\Tools\ListAvailableEnvVars;
|
||||
use Laravel\Boost\Mcp\Tools\ListRoutes;
|
||||
use Laravel\Boost\Mcp\Tools\ReadLogEntries;
|
||||
use Laravel\Boost\Mcp\Tools\SearchDocs;
|
||||
use Laravel\Boost\Mcp\Tools\Tinker;
|
||||
use Laravel\Boost\Support\Composer;
|
||||
use Laravel\Mcp\Server;
|
||||
use Laravel\Mcp\Server\Prompt;
|
||||
use Laravel\Mcp\Server\Resource;
|
||||
use Laravel\Mcp\Server\Tool;
|
||||
|
||||
class Boost extends Server
|
||||
{
|
||||
/**
|
||||
* The MCP server's name.
|
||||
*/
|
||||
protected string $name = 'Laravel Boost';
|
||||
|
||||
/**
|
||||
* The MCP server's version.
|
||||
*/
|
||||
protected string $version = '0.0.1';
|
||||
|
||||
/**
|
||||
* The MCP server's instructions for the LLM.
|
||||
*/
|
||||
protected string $instructions = 'Laravel ecosystem MCP server offering database schema access, Artisan commands, error logs, Tinker execution, semantic documentation search and more. Boost helps with code generation.';
|
||||
|
||||
/**
|
||||
* The default pagination length for resources that support pagination.
|
||||
*/
|
||||
public int $defaultPaginationLength = 50;
|
||||
|
||||
/**
|
||||
* The tools registered with this MCP server.
|
||||
*
|
||||
* @var array<int, class-string<Tool>>
|
||||
*/
|
||||
protected array $tools = [];
|
||||
|
||||
/**
|
||||
* The resources registered with this MCP server.
|
||||
*
|
||||
* @var array<int, class-string<Resource>>
|
||||
*/
|
||||
protected array $resources = [];
|
||||
|
||||
/**
|
||||
* The prompts registered with this MCP server.
|
||||
*
|
||||
* @var array<int, class-string<Prompt>>
|
||||
*/
|
||||
protected array $prompts = [];
|
||||
|
||||
protected function boot(): void
|
||||
{
|
||||
$this->tools = $this->discoverTools();
|
||||
$this->resources = $this->discoverResources();
|
||||
$this->prompts = $this->discoverPrompts();
|
||||
|
||||
// Override the tools/call method to use our ToolExecutor
|
||||
$this->methods['tools/call'] = CallToolWithExecutor::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, class-string<Tool>>
|
||||
*/
|
||||
protected function discoverTools(): array
|
||||
{
|
||||
return $this->filterPrimitives([
|
||||
ApplicationInfo::class,
|
||||
BrowserLogs::class,
|
||||
DatabaseConnections::class,
|
||||
DatabaseQuery::class,
|
||||
DatabaseSchema::class,
|
||||
GetAbsoluteUrl::class,
|
||||
GetConfig::class,
|
||||
LastError::class,
|
||||
ListArtisanCommands::class,
|
||||
ListAvailableConfigKeys::class,
|
||||
ListAvailableEnvVars::class,
|
||||
ListRoutes::class,
|
||||
ReadLogEntries::class,
|
||||
SearchDocs::class,
|
||||
Tinker::class,
|
||||
], 'tools');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, class-string<Resource>>
|
||||
*/
|
||||
protected function discoverResources(): array
|
||||
{
|
||||
$availableResources = [
|
||||
Resources\ApplicationInfo::class,
|
||||
...$this->discoverThirdPartyPrimitives(Resource::class),
|
||||
];
|
||||
|
||||
return $this->filterPrimitives($availableResources, 'resources');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, class-string<Prompt>>
|
||||
*/
|
||||
protected function discoverPrompts(): array
|
||||
{
|
||||
$availablePrompts = [
|
||||
LaravelCodeSimplifier::class,
|
||||
UpgradeLivewireV4::class,
|
||||
...$this->discoverThirdPartyPrimitives(Prompt::class),
|
||||
];
|
||||
|
||||
return $this->filterPrimitives($availablePrompts, 'prompts');
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T of Prompt|Resource
|
||||
*
|
||||
* @param class-string<T> $primitiveType
|
||||
* @return array<int, T>
|
||||
*/
|
||||
private function discoverThirdPartyPrimitives(string $primitiveType): array
|
||||
{
|
||||
$primitiveClass = match ($primitiveType) {
|
||||
Prompt::class => PackageGuidelinePrompt::class,
|
||||
Resource::class => PackageGuidelineResource::class,
|
||||
default => throw new InvalidArgumentException('Invalid Primitive Type'),
|
||||
};
|
||||
|
||||
$primitives = [];
|
||||
|
||||
foreach (Composer::packagesDirectoriesWithBoostGuidelines() as $package => $path) {
|
||||
$corePath = $path.DIRECTORY_SEPARATOR.'core.blade.php';
|
||||
|
||||
if (file_exists($corePath)) {
|
||||
$primitives[] = new $primitiveClass($package, $corePath);
|
||||
}
|
||||
}
|
||||
|
||||
return $primitives;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, Tool|Resource|Prompt|class-string> $availablePrimitives
|
||||
* @return array<int, Tool|Resource|Prompt|class-string>
|
||||
*/
|
||||
private function filterPrimitives(array $availablePrimitives, string $type): array
|
||||
{
|
||||
$excludeList = config("boost.mcp.{$type}.exclude", []);
|
||||
$includeList = config("boost.mcp.{$type}.include", []);
|
||||
|
||||
$filtered = collect($availablePrimitives)->reject(function (string|object $item) use ($excludeList): bool {
|
||||
$className = is_string($item) ? $item : $item::class;
|
||||
|
||||
return in_array($className, $excludeList, true);
|
||||
});
|
||||
|
||||
$explicitlyIncluded = collect($includeList)
|
||||
->filter(fn (string $class): bool => class_exists($class));
|
||||
|
||||
return $filtered
|
||||
->merge($explicitlyIncluded)
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Methods;
|
||||
|
||||
use Laravel\Boost\Mcp\ToolExecutor;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Contracts\Errable;
|
||||
use Laravel\Mcp\Server\Contracts\Method;
|
||||
use Laravel\Mcp\Server\Exceptions\JsonRpcException;
|
||||
use Laravel\Mcp\Server\Methods\Concerns\InteractsWithResponses;
|
||||
use Laravel\Mcp\Server\ServerContext;
|
||||
use Laravel\Mcp\Server\Transport\JsonRpcRequest;
|
||||
use Laravel\Mcp\Server\Transport\JsonRpcResponse;
|
||||
use Throwable;
|
||||
|
||||
class CallToolWithExecutor implements Errable, Method
|
||||
{
|
||||
use InteractsWithResponses;
|
||||
|
||||
public function __construct(protected ToolExecutor $executor)
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the JSON-RPC tool/call request with process isolation.
|
||||
*/
|
||||
public function handle(JsonRpcRequest $request, ServerContext $context): JsonRpcResponse
|
||||
{
|
||||
if (is_null($request->get('name'))) {
|
||||
throw new JsonRpcException(
|
||||
'Missing [name] parameter.',
|
||||
-32602,
|
||||
$request->id,
|
||||
);
|
||||
}
|
||||
|
||||
$tool = $context
|
||||
->tools()
|
||||
->first(
|
||||
fn ($tool): bool => $tool->name() === $request->params['name'],
|
||||
fn () => throw new JsonRpcException(
|
||||
"Tool [{$request->params['name']}] not found.",
|
||||
-32602,
|
||||
$request->id,
|
||||
));
|
||||
|
||||
$arguments = [];
|
||||
if (isset($request->params['arguments']) && is_array($request->params['arguments'])) {
|
||||
$arguments = $request->params['arguments'];
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->executor->execute($tool::class, $arguments);
|
||||
} catch (Throwable $throwable) {
|
||||
$response = Response::error('Tool execution error: '.$throwable->getMessage());
|
||||
}
|
||||
|
||||
return $this->toJsonRpcResponse($request, $response, fn ($responseFactory): array => [
|
||||
'content' => $responseFactory->responses()->map(fn ($response) => $response->content()->toTool($tool))->all(),
|
||||
'isError' => $responseFactory->responses()->contains(fn ($response) => $response->isError()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Prompts\Concerns;
|
||||
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Laravel\Boost\Install\GuidelineAssist;
|
||||
|
||||
trait RendersBladeGuidelines
|
||||
{
|
||||
private array $storedSnippets = [];
|
||||
|
||||
protected function renderContent(string $content, string $path): string
|
||||
{
|
||||
$isBladeTemplate = str_ends_with($path, '.blade.php');
|
||||
|
||||
if (! $isBladeTemplate) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
// Temporarily replace backticks and PHP opening tags with placeholders before Blade processing
|
||||
// This prevents Blade from trying to execute PHP code examples and supports inline code
|
||||
$placeholders = [
|
||||
'`' => '___SINGLE_BACKTICK___',
|
||||
'<?php' => '___OPEN_PHP_TAG___',
|
||||
'@volt' => '___VOLT_DIRECTIVE___',
|
||||
'@endvolt' => '___ENDVOLT_DIRECTIVE___',
|
||||
];
|
||||
|
||||
$content = str_replace(array_keys($placeholders), array_values($placeholders), $content);
|
||||
$rendered = Blade::render($content, [
|
||||
'assist' => $this->getGuidelineAssist(),
|
||||
]);
|
||||
|
||||
return str_replace(array_values($placeholders), array_keys($placeholders), $rendered);
|
||||
}
|
||||
|
||||
protected function processBoostSnippets(string $content): string
|
||||
{
|
||||
return preg_replace_callback('/(?<!@)@boostsnippet\(\s*(?P<nameQuote>[\'"])(?P<name>[^\1]*?)\1(?:\s*,\s*(?P<langQuote>[\'"])(?P<lang>[^\3]*?)\3)?\s*\)(?P<content>.*?)@endboostsnippet/s', function (array $matches): string {
|
||||
$name = $matches['name'];
|
||||
$lang = empty($matches['lang']) ? 'html' : $matches['lang'];
|
||||
$snippetContent = $matches['content'];
|
||||
|
||||
$placeholder = '___BOOST_SNIPPET_'.count($this->storedSnippets).'___';
|
||||
|
||||
$this->storedSnippets[$placeholder] = '<code-snippet name="'.$name.'" lang="'.$lang.'">'."\n".$snippetContent."\n".'</code-snippet>'."\n\n";
|
||||
|
||||
return $placeholder;
|
||||
}, $content);
|
||||
}
|
||||
|
||||
protected function renderGuidelineFile(string $bladePath): string
|
||||
{
|
||||
if (! file_exists($bladePath)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$content = file_get_contents($bladePath);
|
||||
$content = $this->processBoostSnippets($content);
|
||||
|
||||
$rendered = $this->renderContent($content, $bladePath);
|
||||
|
||||
$rendered = str_replace(array_keys($this->storedSnippets), array_values($this->storedSnippets), $rendered);
|
||||
|
||||
$this->storedSnippets = [];
|
||||
|
||||
return $rendered;
|
||||
}
|
||||
|
||||
protected function getGuidelineAssist(): GuidelineAssist
|
||||
{
|
||||
return app(GuidelineAssist::class);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Prompts\LaravelCodeSimplifier;
|
||||
|
||||
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Prompt;
|
||||
|
||||
class LaravelCodeSimplifier extends Prompt
|
||||
{
|
||||
use RendersBladeGuidelines;
|
||||
|
||||
protected string $name = 'laravel-code-simplifier';
|
||||
|
||||
protected string $title = 'laravel_code_simplifier';
|
||||
|
||||
protected string $description = 'Simplifies and refines PHP/Laravel code for clarity, consistency, and maintainability while preserving all functionality. Focuses on recently modified code unless instructed otherwise.';
|
||||
|
||||
public function handle(): Response
|
||||
{
|
||||
$content = $this->renderGuidelineFile(__DIR__.'/laravel-code-simplifier.blade.php');
|
||||
|
||||
return Response::text($content);
|
||||
}
|
||||
}
|
||||
Vendored
+66
@@ -0,0 +1,66 @@
|
||||
# Laravel Code Simplifier
|
||||
|
||||
You are an expert PHP/Laravel code simplification specialist focused on enhancing code clarity, consistency, and maintainability while preserving exact functionality. Your expertise lies in applying Laravel best practices and standards to simplify and improve code without altering its behavior. You prioritize readable, explicit code over overly compact solutions. This is a balance that you have mastered as a result of your years as an expert PHP developer.
|
||||
|
||||
You will analyze recently modified code using git and apply refinements that:
|
||||
|
||||
## 1. Preserve Functionality
|
||||
|
||||
Never change what the code does - only how it does it. All original features, outputs, and behaviors must remain intact.
|
||||
|
||||
## 2. Apply Project Standards
|
||||
|
||||
Follow established project coding standards including:
|
||||
|
||||
- Use proper namespace declarations and organize imports logically
|
||||
- Prefer explicit return type declarations on methods
|
||||
- Follow Laravel conventions for controllers, models, and services
|
||||
- Use proper error handling patterns (exceptions, custom exception classes)
|
||||
- Maintain consistent naming conventions (PSR-12, Laravel standards)
|
||||
|
||||
## 3. Enhance Clarity
|
||||
|
||||
Simplify the code structure by:
|
||||
|
||||
- Reducing unnecessary complexity and nesting
|
||||
- Eliminating redundant code and abstractions
|
||||
- Improving readability through clear variable and function names
|
||||
- Consolidating related logic
|
||||
- Removing unnecessary comments that describe obvious code
|
||||
- **IMPORTANT**: Avoid nested ternary operators - prefer match expressions, switch statements, or if/else chains for multiple conditions
|
||||
- Choose clarity over brevity - explicit code is often better than overly compact code
|
||||
|
||||
## 4. Maintain Balance
|
||||
|
||||
Avoid oversimplification that could:
|
||||
|
||||
- Reduce code clarity or maintainability
|
||||
- Create overly clever solutions that are hard to understand
|
||||
- Combine too many concerns into single methods or classes
|
||||
- Remove helpful abstractions that improve code organization
|
||||
- Prioritize "fewer lines" over readability (e.g., nested ternaries, dense one-liners)
|
||||
- Make the code harder to debug or extend
|
||||
|
||||
## 5. Focus Scope
|
||||
|
||||
Only refine code that has been recently modified or touched in the current session, unless explicitly instructed to review a broader scope.
|
||||
|
||||
## Refinement Process
|
||||
|
||||
1. Identify the recently modified code sections
|
||||
2. Analyze for opportunities to improve elegance and consistency
|
||||
3. Apply project-specific best practices and coding standards
|
||||
4. Ensure all functionality remains unchanged
|
||||
5. Verify the refined code is simpler and more maintainable
|
||||
6. Document only significant changes that affect understanding
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
When multiple files need refinement, maximize efficiency by:
|
||||
|
||||
- **Spin up background agents in parallel** to process independent files simultaneously
|
||||
- Each agent should handle a separate file or logical unit of work
|
||||
- Coordinate results to ensure consistency across related files
|
||||
- Use as many concurrent agents as possible when files don't have dependencies on each other
|
||||
|
||||
You operate autonomously and proactively, refining code immediately after it's written or modified without requiring explicit requests. Your goal is to ensure all code meets the highest standards of elegance and maintainability while preserving its complete functionality.
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Prompts;
|
||||
|
||||
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Prompt;
|
||||
|
||||
class PackageGuidelinePrompt extends Prompt
|
||||
{
|
||||
use RendersBladeGuidelines;
|
||||
|
||||
public function __construct(
|
||||
protected string $packageName,
|
||||
protected string $bladePath,
|
||||
) {
|
||||
$this->name = $this->packageName;
|
||||
$this->title = $this->packageName;
|
||||
$this->description = "Guidelines for {$packageName}";
|
||||
}
|
||||
|
||||
public function handle(): Response
|
||||
{
|
||||
$content = $this->renderGuidelineFile($this->bladePath);
|
||||
|
||||
return Response::text($content);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Prompts\UpgradeLivewirev4;
|
||||
|
||||
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Prompt;
|
||||
use Laravel\Roster\Enums\Packages;
|
||||
use Laravel\Roster\Roster;
|
||||
|
||||
class UpgradeLivewireV4 extends Prompt
|
||||
{
|
||||
use RendersBladeGuidelines;
|
||||
|
||||
protected string $name = 'upgrade-livewire-v4';
|
||||
|
||||
protected string $title = 'upgrade_livewire_v4';
|
||||
|
||||
protected string $description = 'Provides step-by-step guidance for upgrading from Livewire v3 to v4.';
|
||||
|
||||
public function shouldRegister(Roster $roster): bool
|
||||
{
|
||||
return $roster->uses(Packages::LIVEWIRE);
|
||||
}
|
||||
|
||||
public function handle(): Response
|
||||
{
|
||||
$content = $this->renderGuidelineFile(__DIR__.'/upgrade-livewire-v4.blade.php');
|
||||
|
||||
return Response::text($content);
|
||||
}
|
||||
}
|
||||
+825
@@ -0,0 +1,825 @@
|
||||
# Livewire v3 to v4 Upgrade Specialist
|
||||
|
||||
You are an expert Livewire upgrade specialist with deep knowledge of both Livewire v3 and v4. Your task is to systematically upgrade the application from Livewire v3 to v4 while ensuring all functionality remains intact. You understand the nuances of breaking changes and can identify affected code patterns with precision.
|
||||
|
||||
## Core Principle: Documentation-First Approach
|
||||
|
||||
**IMPORTANT:** Always use the `search-docs` tool whenever you need:
|
||||
- Specific code examples for implementing Livewire v4 features
|
||||
- Clarification on breaking changes or new syntax
|
||||
- Verification of upgrade patterns before applying them
|
||||
- Examples of correct usage for new directives or methods
|
||||
|
||||
The official Livewire documentation is your primary source of truth. Consult it before making assumptions or implementing changes.
|
||||
|
||||
## Upgrade Process
|
||||
|
||||
Follow this systematic process to upgrade the application:
|
||||
|
||||
### 1. Assess Current State
|
||||
|
||||
Before making any changes:
|
||||
|
||||
- Check `composer.json` for the current Livewire version constraint
|
||||
- Run `{{ $assist->composerCommand('show livewire/livewire') }}` to confirm installed version
|
||||
- Identify all Livewire components in the application (search for `extends Component`)
|
||||
- Review `config/livewire.php` for current configuration
|
||||
|
||||
### 2. Create Safety Net
|
||||
|
||||
- Ensure you're working on a dedicated branch
|
||||
- Run the existing test suite to establish baseline
|
||||
- Note any components with complex JavaScript interactions
|
||||
|
||||
### 3. Analyze Codebase for Breaking Changes
|
||||
|
||||
Search the codebase for patterns affected by v4 changes:
|
||||
|
||||
**High Priority Searches:**
|
||||
- `config/livewire.php` - Configuration key renames needed
|
||||
- `Route::get` with Livewire components - May need `Route::livewire()`
|
||||
- `wire:model` on container elements (divs, modals) - Check for bubbling behavior
|
||||
- `wire:scroll` - Needs rename to `wire:navigate:scroll`
|
||||
- `<livewire:` tags - Must be properly closed (self-closing or with closing tag)
|
||||
|
||||
**Medium Priority Searches:**
|
||||
- `wire:transition` with modifiers (`.opacity`, `.scale`, `.duration`) - Modifiers removed
|
||||
- `$this->stream(` - Parameter order changed
|
||||
- Array property replacements from JavaScript - Hook behavior changed
|
||||
|
||||
**Low Priority Searches:**
|
||||
- `$wire.$js(` or `$js(` - Deprecated syntax
|
||||
- `Livewire.hook('commit'` or `Livewire.hook('request'` - Deprecated hooks
|
||||
|
||||
### 4. Apply Changes Systematically
|
||||
|
||||
For each category of changes:
|
||||
|
||||
1. **Search** for affected patterns using grep/search tools
|
||||
2. **Consult documentation** - Use `search-docs` tool to verify correct upgrade patterns and examples
|
||||
3. **List** all files that need modification
|
||||
4. **Apply** the fix consistently across all occurrences
|
||||
5. **Verify** each change doesn't break functionality
|
||||
|
||||
### 5. Update Dependencies
|
||||
|
||||
After code changes are complete:
|
||||
|
||||
```bash
|
||||
{{ $assist->composerCommand('require livewire/livewire:^4.0') }}
|
||||
{{ $assist->artisanCommand('optimize:clear') }}
|
||||
```
|
||||
|
||||
### 6. Test and Verify
|
||||
|
||||
- Run the full test suite
|
||||
- Manually test critical user flows
|
||||
- Check browser console for JavaScript errors
|
||||
- Verify all components render correctly
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
When upgrading, maximize efficiency by:
|
||||
|
||||
- **Batch similar changes** - Group all config updates, then all routing updates, etc.
|
||||
- **Use parallel agents** for independent file modifications
|
||||
- **Prioritize high-impact changes** that could cause immediate failures
|
||||
- **Test incrementally** - Verify after each category of changes
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Most applications can upgrade with minimal changes
|
||||
- The old syntax for deprecated features still works but should be migrated
|
||||
|
||||
---
|
||||
|
||||
# Upgrading from v3 to v4
|
||||
|
||||
Livewire v4 introduces several improvements and optimizations while maintaining backward compatibility wherever possible. This guide will help you upgrade from Livewire v3 to v4.
|
||||
|
||||
> [!tip] Smooth upgrade path
|
||||
> Most applications can upgrade to v4 with minimal changes. The breaking changes are primarily configuration updates and method signature changes that only affect advanced usage.
|
||||
|
||||
## Installation
|
||||
|
||||
Update your `composer.json` to require Livewire v4:
|
||||
|
||||
@boostsnippet('Installation', 'bash')
|
||||
composer require livewire/livewire:^4.0
|
||||
@endboostsnippet
|
||||
|
||||
After updating, clear your application's cache:
|
||||
|
||||
@boostsnippet('Clear Cache', 'bash')
|
||||
php artisan optimize:clear
|
||||
@endboostsnippet
|
||||
|
||||
> [!info] View all changes on GitHub
|
||||
> For a complete overview of all code changes between v3 and v4, you can review the full diff on GitHub: [Compare 3.x to main →](https://github.com/livewire/livewire/compare/3.x...main)
|
||||
|
||||
## High-impact changes
|
||||
|
||||
These changes are most likely to affect your application and should be reviewed carefully.
|
||||
|
||||
### Config file updates
|
||||
|
||||
Several configuration keys have been renamed, reorganized, or have new defaults. Update your `config/livewire.php` file:
|
||||
|
||||
> [!tip] View the full config file
|
||||
> For reference, you can view the complete v4 config file on GitHub: [livewire.php →](https://github.com/livewire/livewire/blob/main/config/livewire.php)
|
||||
|
||||
#### Renamed configuration keys
|
||||
|
||||
**Layout configuration:**
|
||||
|
||||
@boostsnippet('Layout Configuration', 'php')
|
||||
// Before (v3)
|
||||
'layout' => 'components.layouts.app',
|
||||
|
||||
// After (v4)
|
||||
'component_layout' => 'layouts::app',
|
||||
@endboostsnippet
|
||||
|
||||
The layout now uses the `layouts::` namespace by default, pointing to `resources/views/layouts/app.blade.php`.
|
||||
|
||||
**Placeholder configuration:**
|
||||
|
||||
@boostsnippet('Placeholder Configuration', 'php')
|
||||
// Before (v3)
|
||||
'lazy_placeholder' => 'livewire.placeholder',
|
||||
|
||||
// After (v4)
|
||||
'component_placeholder' => 'livewire.placeholder',
|
||||
@endboostsnippet
|
||||
|
||||
#### Changed defaults
|
||||
|
||||
**Smart wire:key behavior:**
|
||||
|
||||
@boostsnippet('Smart Wire Key', 'php')
|
||||
// Now defaults to true (was false in v3)
|
||||
'smart_wire_keys' => true,
|
||||
@endboostsnippet
|
||||
|
||||
This helps prevent wire:key issues on deeply nested components. Note: You still need to add `wire:key` manually in loops—this setting doesn't eliminate that requirement.
|
||||
|
||||
[Learn more about wire:key →](/docs/4.x/nesting#rendering-children-in-a-loop)
|
||||
|
||||
#### New configuration options
|
||||
|
||||
**Component locations:**
|
||||
|
||||
@boostsnippet('Component Locations', 'php')
|
||||
'component_locations' => [
|
||||
resource_path('views/components'),
|
||||
resource_path('views/livewire'),
|
||||
],
|
||||
@endboostsnippet
|
||||
|
||||
Defines where Livewire looks for single-file and multi-file (view-based) components.
|
||||
|
||||
**Component namespaces:**
|
||||
|
||||
@boostsnippet('Component Namespaces', 'php')
|
||||
'component_namespaces' => [
|
||||
'layouts' => resource_path('views/layouts'),
|
||||
'pages' => resource_path('views/pages'),
|
||||
],
|
||||
@endboostsnippet
|
||||
|
||||
Creates custom namespaces for organizing view-based components (e.g., `<livewire:pages::dashboard />`).
|
||||
|
||||
**Make command defaults:**
|
||||
|
||||
@boostsnippet('Make Command Defaults', 'php')
|
||||
'make_command' => [
|
||||
'type' => 'sfc', // Options: 'sfc', 'mfc', or 'class'
|
||||
'emoji' => true, // Whether to use ⚡ emoji prefix
|
||||
],
|
||||
@endboostsnippet
|
||||
|
||||
Configure default component format and emoji usage. Set `type` to `'class'` to match v3 behavior.
|
||||
|
||||
**CSP-safe mode:**
|
||||
|
||||
@boostsnippet('CSP Safe Mode', 'php')
|
||||
'csp_safe' => false,
|
||||
@endboostsnippet
|
||||
|
||||
Enable Content Security Policy mode to avoid `unsafe-eval` violations. When enabled, Livewire uses the [Alpine CSP build](https://alpinejs.dev/advanced/csp). Note: This mode restricts complex JavaScript expressions in directives like `wire:click="addToCart($event.detail.productId)"` or global references like `window.location`.
|
||||
|
||||
### Routing changes
|
||||
|
||||
For full-page components, the recommended routing approach has changed:
|
||||
|
||||
@boostsnippet('Routing Changes', 'php')
|
||||
// Before (v3) - still works but not recommended
|
||||
Route::get('/dashboard', Dashboard::class);
|
||||
|
||||
// After (v4) - recommended for all component types
|
||||
Route::livewire('/dashboard', Dashboard::class);
|
||||
|
||||
// For view-based components, you can use the component name
|
||||
Route::livewire('/dashboard', 'pages::dashboard');
|
||||
@endboostsnippet
|
||||
|
||||
Using `Route::livewire()` is now the preferred method and is required for single-file and multi-file components to work correctly as full-page components.
|
||||
|
||||
[Learn more about routing →](/docs/4.x/components#page-components)
|
||||
|
||||
### `wire:model` now ignores child events by default
|
||||
|
||||
In v3, `wire:model` would respond to input/change events that bubbled up from child elements. This caused unexpected behavior when using `wire:model` on container elements (like modals or accordions) that contained form inputs—clearing an input inside would bubble up and potentially close the modal.
|
||||
|
||||
In v4, `wire:model` now only listens for events originating directly on the element itself (equivalent to the `.self` modifier behavior).
|
||||
|
||||
If you have code that relies on capturing events from child elements, add the `.deep` modifier:
|
||||
|
||||
@boostsnippet('Wire Model Deep', 'blade')
|
||||
<!-- Before (v3) - listened to child events by default -->
|
||||
<div wire:model="value">
|
||||
<input type="text">
|
||||
</div>
|
||||
|
||||
<!-- After (v4) - add .deep to restore old behavior -->
|
||||
<div wire:model.deep="value">
|
||||
<input type="text">
|
||||
</div>
|
||||
@endboostsnippet
|
||||
|
||||
> [!tip] Most apps won't need changes
|
||||
> This change primarily affects non-standard uses of `wire:model` on container elements. Standard form input bindings (inputs, selects, textareas) are unaffected.
|
||||
|
||||
### Use `wire:navigate:scroll`
|
||||
|
||||
When using `wire:scroll` to preserve scroll in a scrollable container across `wire:navigate` requests in v3, you will need to instead use `wire:navigate:scroll` in v4:
|
||||
|
||||
@boostsnippet('Wire Navigate Scroll', 'blade')
|
||||
@@persist('sidebar')
|
||||
<div class="overflow-y-scroll" wire:scroll> <!-- [tl! remove] -->
|
||||
<div class="overflow-y-scroll" wire:navigate:scroll> <!-- [tl! add] -->
|
||||
<!-- ... -->
|
||||
</div>
|
||||
@@endpersist
|
||||
@endboostsnippet
|
||||
|
||||
### Component tags must be closed
|
||||
|
||||
In v3, Livewire component tags would render even without being properly closed. In v4, with the addition of slot support, component tags must be properly closed—otherwise Livewire interprets subsequent content as slot content and the component won't render:
|
||||
|
||||
@boostsnippet('Component Tags Closed', 'blade')
|
||||
<!-- Before (v3) - unclosed tag -->
|
||||
<livewire:component-name>
|
||||
|
||||
<!-- After (v4) - Self-closing tag -->
|
||||
<livewire:component-name />
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about rendering components →](/docs/4.x/components#rendering-components)
|
||||
|
||||
[Learn more about slots →](/docs/4.x/nesting#slots)
|
||||
|
||||
## Medium-impact changes
|
||||
|
||||
These changes may affect certain parts of your application depending on which features you use.
|
||||
|
||||
### `wire:transition` now uses View Transitions API
|
||||
|
||||
In v3, `wire:transition` was a wrapper around Alpine's `x-transition` directive, supporting modifiers like `.opacity`, `.scale`, `.duration.200ms`, and `.origin.top`.
|
||||
|
||||
In v4, `wire:transition` uses the browser's native [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) instead. Basic usage still works—elements will fade in and out smoothly—but all modifiers have been removed.
|
||||
|
||||
@boostsnippet('Wire Transition', 'blade')
|
||||
<!-- This still works in v4 -->
|
||||
<div wire:transition>...</div>
|
||||
|
||||
<!-- These modifiers are no longer supported -->
|
||||
<div wire:transition.opacity>...</div> <!-- [tl! remove] -->
|
||||
<div wire:transition.scale.origin.top>...</div> <!-- [tl! remove] -->
|
||||
<div wire:transition.duration.500ms>...</div> <!-- [tl! remove] -->
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about wire:transition →](/docs/4.x/wire-transition)
|
||||
|
||||
### Performance improvements
|
||||
|
||||
Livewire v4 includes significant performance improvements to the request handling system:
|
||||
|
||||
- **Non-blocking polling**: `wire:poll` no longer blocks other requests or is blocked by them
|
||||
- **Parallel live updates**: `wire:model.live` requests now run in parallel, allowing faster typing and quicker results
|
||||
|
||||
These improvements happen automatically—no changes needed to your code.
|
||||
|
||||
### Update hooks consolidate array/object changes
|
||||
|
||||
When replacing an entire array or object from the frontend (e.g., `$wire.items = ['new', 'values']`), Livewire now sends a single consolidated update instead of granular updates for each index.
|
||||
|
||||
**Before:** Setting `$wire.items = ['a', 'b']` on an array of 4 items would fire `updatingItems`/`updatedItems` hooks multiple times—once for each index change plus `__rm__` removals.
|
||||
|
||||
**After:** The same operation fires the hooks once with the full new array value, matching v2 behavior.
|
||||
|
||||
If your code relies on individual index hooks firing when replacing entire arrays, you may need to adjust. Single-item changes (like `wire:model="items.0"`) still fire granular hooks as expected.
|
||||
|
||||
### Method signature changes
|
||||
|
||||
If you're extending Livewire's core functionality or using these methods directly, note these signature changes:
|
||||
|
||||
**Streaming:**
|
||||
|
||||
The `stream()` method parameter order has changed:
|
||||
|
||||
@boostsnippet('Stream Method Signature', 'php')
|
||||
// Before (v3)
|
||||
$this->stream(to: '#container', content: 'Hello', replace: true);
|
||||
|
||||
// After (v4)
|
||||
$this->stream(content: 'Hello', replace: true, el: '#container');
|
||||
@endboostsnippet
|
||||
|
||||
If you're using named parameters (as shown above), note that `to:` has been renamed to `el:`. If you're using positional parameters, you'll need to update to the following:
|
||||
|
||||
@boostsnippet('Stream Positional Parameters', 'php')
|
||||
// Before (v3) - positional parameters
|
||||
$this->stream('#container', 'Hello');
|
||||
|
||||
// After (v4) - positional/named parameters
|
||||
$this->stream('Hello', el: '#container');
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about streaming →](/docs/4.x/wire-stream)
|
||||
|
||||
**Component mounting (internal):**
|
||||
|
||||
If you're extending `LivewireManager` or calling the `mount()` method directly:
|
||||
|
||||
@boostsnippet('Mount Method Signature', 'php')
|
||||
// Before (v3)
|
||||
public function mount($name, $params = [], $key = null)
|
||||
|
||||
// After (v4)
|
||||
public function mount($name, $params = [], $key = null, $slots = [])
|
||||
@endboostsnippet
|
||||
|
||||
This change adds support for passing slots when mounting components and generally won't affect most applications.
|
||||
|
||||
## Low-impact changes
|
||||
|
||||
These changes only affect applications using advanced features or customization.
|
||||
|
||||
### JavaScript deprecations
|
||||
|
||||
#### Deprecated: `$wire.$js()` method
|
||||
|
||||
The `$wire.$js()` method for defining JavaScript actions has been deprecated:
|
||||
|
||||
@boostsnippet('Wire JS Deprecation', 'js')
|
||||
// Deprecated (v3)
|
||||
$wire.$js('bookmark', () => {
|
||||
// Toggle bookmark...
|
||||
})
|
||||
|
||||
// New (v4)
|
||||
$wire.$js.bookmark = () => {
|
||||
// Toggle bookmark...
|
||||
}
|
||||
@endboostsnippet
|
||||
|
||||
The new syntax is cleaner and more intuitive.
|
||||
|
||||
#### Deprecated: `$js` without prefix
|
||||
|
||||
The use of `$js` in scripts without `$wire.$js` or `this.$js` prefix has been deprecated:
|
||||
|
||||
@boostsnippet('JS Without Prefix Deprecation', 'js')
|
||||
// Deprecated (v3)
|
||||
$js('bookmark', () => {
|
||||
// Toggle bookmark...
|
||||
})
|
||||
|
||||
// New (v4)
|
||||
$wire.$js.bookmark = () => {
|
||||
// Toggle bookmark...
|
||||
}
|
||||
// Or
|
||||
this.$js.bookmark = () => {
|
||||
// Toggle bookmark...
|
||||
}
|
||||
@endboostsnippet
|
||||
|
||||
> [!tip] Old syntax still works
|
||||
> Both `$wire.$js('bookmark', ...)` and `$js('bookmark', ...)` will continue to work in v4 for backward compatibility, but you should migrate to the new syntax when convenient.
|
||||
|
||||
#### Deprecated: `commit` and `request` hooks
|
||||
|
||||
The `commit` and `request` hooks have been deprecated in favor of a new interceptor system that provides more granular control and better performance.
|
||||
|
||||
> [!tip] Old hooks still work
|
||||
> The deprecated hooks will continue to work in v4 for backward compatibility, but you should migrate to the new system when convenient.
|
||||
|
||||
#### Migrating from `commit` hook
|
||||
|
||||
The old `commit` hook:
|
||||
|
||||
@boostsnippet('Old Commit Hook', 'js')
|
||||
// OLD - Deprecated
|
||||
Livewire.hook('commit', ({ component, commit, respond, succeed, fail }) => {
|
||||
respond(() => {
|
||||
// Runs after response received but before processing
|
||||
})
|
||||
|
||||
succeed(({ snapshot, effects }) => {
|
||||
// Runs after successful response
|
||||
})
|
||||
|
||||
fail(() => {
|
||||
// Runs if request failed
|
||||
})
|
||||
})
|
||||
@endboostsnippet
|
||||
|
||||
Should be replaced with the new `interceptMessage`:
|
||||
|
||||
@boostsnippet('New Intercept Message', 'js')
|
||||
// NEW - Recommended
|
||||
Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError, onFailure }) => {
|
||||
onFinish(() => {
|
||||
// Equivalent to respond()
|
||||
})
|
||||
|
||||
onSuccess(({ payload }) => {
|
||||
// Equivalent to succeed()
|
||||
// Access snapshot via payload.snapshot
|
||||
// Access effects via payload.effects
|
||||
})
|
||||
|
||||
onError(() => {
|
||||
// Equivalent to fail() for server errors
|
||||
})
|
||||
|
||||
onFailure(() => {
|
||||
// Equivalent to fail() for network errors
|
||||
})
|
||||
})
|
||||
@endboostsnippet
|
||||
|
||||
#### Migrating from `request` hook
|
||||
|
||||
The old `request` hook:
|
||||
|
||||
@boostsnippet('Old Request Hook', 'js')
|
||||
// OLD - Deprecated
|
||||
Livewire.hook('request', ({ url, options, payload, respond, succeed, fail }) => {
|
||||
respond(({ status, response }) => {
|
||||
// Runs when response received
|
||||
})
|
||||
|
||||
succeed(({ status, json }) => {
|
||||
// Runs on successful response
|
||||
})
|
||||
|
||||
fail(({ status, content, preventDefault }) => {
|
||||
// Runs on failed response
|
||||
})
|
||||
})
|
||||
@endboostsnippet
|
||||
|
||||
Should be replaced with the new `interceptRequest`:
|
||||
|
||||
@boostsnippet('New Intercept Request', 'js')
|
||||
// NEW - Recommended
|
||||
Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure }) => {
|
||||
// Access url via request.uri
|
||||
// Access options via request.options
|
||||
// Access payload via request.payload
|
||||
|
||||
onResponse(({ response }) => {
|
||||
// Equivalent to respond()
|
||||
// Access status via response.status
|
||||
})
|
||||
|
||||
onSuccess(({ response, responseJson }) => {
|
||||
// Equivalent to succeed()
|
||||
// Access status via response.status
|
||||
// Access json via responseJson
|
||||
})
|
||||
|
||||
onError(({ response, responseBody, preventDefault }) => {
|
||||
// Equivalent to fail() for server errors
|
||||
// Access status via response.status
|
||||
// Access content via responseBody
|
||||
})
|
||||
|
||||
onFailure(({ error }) => {
|
||||
// Equivalent to fail() for network errors
|
||||
})
|
||||
})
|
||||
@endboostsnippet
|
||||
|
||||
#### Key differences
|
||||
|
||||
1. **More granular error handling**: The new system separates network failures (`onFailure`) from server errors (`onError`)
|
||||
2. **Better lifecycle hooks**: Message interceptors provide additional hooks like `onSync`, `onMorph`, and `onRender`
|
||||
3. **Cancellation support**: Both messages and requests can be cancelled/aborted
|
||||
4. **Component scoping**: Message interceptors can be scoped to specific components using `$wire.intercept(...)`
|
||||
|
||||
For complete documentation on the new interceptor system, see the [JavaScript Interceptors documentation](/docs/4.x/javascript#interceptors).
|
||||
|
||||
## Upgrading Volt
|
||||
|
||||
Livewire v4 now supports single-file components, which use the same syntax as Volt class-based components. This means you can migrate from Volt to Livewire's built-in single-file components.
|
||||
|
||||
### Update component imports
|
||||
|
||||
Replace all instances of `Livewire\Volt\Component` with `Livewire\Component`:
|
||||
|
||||
@boostsnippet('Volt Import Update', 'php')
|
||||
// Before (Volt)
|
||||
use Livewire\Volt\Component;
|
||||
|
||||
new class extends Component { ... }
|
||||
|
||||
// After (Livewire v4)
|
||||
use Livewire\Component;
|
||||
|
||||
new class extends Component { ... }
|
||||
@endboostsnippet
|
||||
|
||||
### Remove Volt service provider
|
||||
|
||||
Delete the Volt service provider file:
|
||||
|
||||
@boostsnippet('Remove Volt Provider', 'bash')
|
||||
rm app/Providers/VoltServiceProvider.php
|
||||
@endboostsnippet
|
||||
|
||||
Then remove it from the providers array in `bootstrap/providers.php`:
|
||||
|
||||
@boostsnippet('Update Providers Array', 'php')
|
||||
// Before
|
||||
return [
|
||||
App\Providers\AppServiceProvider::class,
|
||||
App\Providers\VoltServiceProvider::class,
|
||||
];
|
||||
|
||||
// After
|
||||
return [
|
||||
App\Providers\AppServiceProvider::class,
|
||||
];
|
||||
@endboostsnippet
|
||||
|
||||
### Remove Volt package
|
||||
|
||||
Uninstall the Volt package:
|
||||
|
||||
@boostsnippet('Uninstall Volt', 'bash')
|
||||
composer remove livewire/volt
|
||||
@endboostsnippet
|
||||
|
||||
### Install Livewire v4
|
||||
|
||||
After completing the above changes, install Livewire v4. Your existing Volt class-based components will work without modification since they use the same syntax as Livewire's single-file components.
|
||||
|
||||
## New features in v4
|
||||
|
||||
Livewire v4 introduces several powerful new features you can start using immediately:
|
||||
|
||||
### Component features
|
||||
|
||||
**Single-file and multi-file components**
|
||||
|
||||
v4 introduces new component formats alongside the traditional class-based approach. Single-file components combine PHP and Blade in one file, while multi-file components organize PHP, Blade, JavaScript, and tests in a directory.
|
||||
|
||||
By default, view-based component files are prefixed with a ⚡ emoji to distinguish them from regular Blade files in your editor and searches. This can be disabled via the `make_command.emoji` config.
|
||||
|
||||
@boostsnippet('Make Livewire Commands', 'bash')
|
||||
php artisan make:livewire create-post # Single-file (default)
|
||||
php artisan make:livewire create-post --mfc # Multi-file
|
||||
php artisan livewire:convert create-post # Convert between formats
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about component formats →](/docs/4.x/components)
|
||||
|
||||
**Slots and attribute forwarding**
|
||||
|
||||
Components now support slots and automatic attribute bag forwarding using `@{{ $attributes }}`, making component composition more flexible.
|
||||
|
||||
[Learn more about nesting components →](/docs/4.x/nesting)
|
||||
|
||||
**JavaScript in view-based components**
|
||||
|
||||
View-based components can now include `<script>` tags without the `@@script` wrapper. These scripts are served as separate cached files for better performance and automatic `$wire` binding:
|
||||
|
||||
@boostsnippet('JavaScript in Components', 'blade')
|
||||
<div>
|
||||
<!-- Your component template -->
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// $wire is automatically bound as 'this'
|
||||
this.count++ // Same as $wire.count++
|
||||
|
||||
// $wire is still available if preferred
|
||||
$wire.save()
|
||||
</script>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about JavaScript in components →](/docs/4.x/javascript)
|
||||
|
||||
### Islands
|
||||
|
||||
Islands allow you to create isolated regions within a component that update independently, dramatically improving performance without creating separate child components.
|
||||
|
||||
@boostsnippet('Islands Example', 'blade')
|
||||
@@island(name: 'stats', lazy: true)
|
||||
<div>@{{ $this->expensiveStats }}</div>
|
||||
@@endisland
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about islands →](/docs/4.x/islands)
|
||||
|
||||
### Loading improvements
|
||||
|
||||
**Deferred loading**
|
||||
|
||||
In addition to lazy loading (viewport-based), components can now be deferred to load immediately after the initial page load:
|
||||
|
||||
@boostsnippet('Deferred Loading Blade', 'blade')
|
||||
<livewire:revenue defer />
|
||||
@endboostsnippet
|
||||
|
||||
@boostsnippet('Deferred Loading PHP', 'php')
|
||||
#[Defer]
|
||||
class Revenue extends Component { ... }
|
||||
@endboostsnippet
|
||||
|
||||
**Bundled loading**
|
||||
|
||||
Control whether multiple lazy/deferred components load in parallel or bundled together:
|
||||
|
||||
@boostsnippet('Bundled Loading Blade', 'blade')
|
||||
<livewire:revenue lazy.bundle />
|
||||
<livewire:expenses defer.bundle />
|
||||
@endboostsnippet
|
||||
|
||||
@boostsnippet('Bundled Loading PHP', 'php')
|
||||
#[Lazy(bundle: true)]
|
||||
class Revenue extends Component { ... }
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about lazy and deferred loading →](/docs/4.x/lazy)
|
||||
|
||||
### Async actions
|
||||
|
||||
Run actions in parallel without blocking other requests using the `.async` modifier or `#[Async]` attribute:
|
||||
|
||||
@boostsnippet('Async Actions Blade', 'blade')
|
||||
<button wire:click.async="logActivity">Track</button>
|
||||
@endboostsnippet
|
||||
|
||||
@boostsnippet('Async Actions PHP', 'php')
|
||||
#[Async]
|
||||
public function logActivity() { ... }
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about async actions →](/docs/4.x/actions#parallel-execution-with-async)
|
||||
|
||||
### New directives and modifiers
|
||||
|
||||
**`wire:sort` - Drag-and-drop sorting**
|
||||
|
||||
Built-in support for sortable lists with drag-and-drop:
|
||||
|
||||
@boostsnippet('Wire Sort', 'blade')
|
||||
<ul wire:sort="updateOrder">
|
||||
@@foreach ($items as $item)
|
||||
<li wire:sort:item="@{{ $item->id }}" wire:key="@{{ $item->id }}">@{{ $item->name }}</li>
|
||||
@@endforeach
|
||||
</ul>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about wire:sort →](/docs/4.x/wire-sort)
|
||||
|
||||
**`wire:intersect` - Viewport intersection**
|
||||
|
||||
Run actions when elements enter or leave the viewport, similar to Alpine's [`x-intersect`](https://alpinejs.dev/plugins/intersect):
|
||||
|
||||
@boostsnippet('Wire Intersect', 'blade')
|
||||
<!-- Basic usage -->
|
||||
<div wire:intersect="loadMore">...</div>
|
||||
|
||||
<!-- With modifiers -->
|
||||
<div wire:intersect.once="trackView">...</div>
|
||||
<div wire:intersect:leave="pauseVideo">...</div>
|
||||
<div wire:intersect.half="loadMore">...</div>
|
||||
<div wire:intersect.full="startAnimation">...</div>
|
||||
|
||||
<!-- With options -->
|
||||
<div wire:intersect.margin.200px="loadMore">...</div>
|
||||
<div wire:intersect.threshold.50="trackScroll">...</div>
|
||||
@endboostsnippet
|
||||
|
||||
Available modifiers:
|
||||
- `.once` - Fire only once
|
||||
- `.half` - Wait until half is visible
|
||||
- `.full` - Wait until fully visible
|
||||
- `.threshold.X` - Custom visibility percentage (0-100)
|
||||
- `.margin.Xpx` or `.margin.X%` - Intersection margin
|
||||
|
||||
[Learn more about wire:intersect →](/docs/4.x/wire-intersect)
|
||||
|
||||
**`wire:ref` - Element references**
|
||||
|
||||
Easily reference and interact with elements in your template:
|
||||
|
||||
@boostsnippet('Wire Ref', 'blade')
|
||||
<div wire:ref="modal">
|
||||
<!-- Modal content -->
|
||||
</div>
|
||||
|
||||
<button wire:click="$js.scrollToModal">Scroll to modal</button>
|
||||
|
||||
<script>
|
||||
this.$js.scrollToModal = () => {
|
||||
this.$refs.modal.scrollIntoView()
|
||||
}
|
||||
</script>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about wire:ref →](/docs/4.x/wire-ref)
|
||||
|
||||
**`.renderless` modifier**
|
||||
|
||||
Skip component re-rendering directly from the template:
|
||||
|
||||
@boostsnippet('Renderless Modifier', 'blade')
|
||||
<button wire:click.renderless="trackClick">Track</button>
|
||||
@endboostsnippet
|
||||
|
||||
This is an alternative to the `#[Renderless]` attribute for actions that don't need to update the UI.
|
||||
|
||||
**`.preserve-scroll` modifier**
|
||||
|
||||
Preserve scroll position during updates to prevent layout jumps:
|
||||
|
||||
@boostsnippet('Preserve Scroll', 'blade')
|
||||
<button wire:click.preserve-scroll="loadMore">Load More</button>
|
||||
@endboostsnippet
|
||||
|
||||
**`data-loading` attribute**
|
||||
|
||||
Every element that triggers a network request automatically receives a `data-loading` attribute, making it easy to style loading states with Tailwind:
|
||||
|
||||
@boostsnippet('Data Loading', 'blade')
|
||||
<button wire:click="save" class="data-loading:opacity-50 data-loading:pointer-events-none">
|
||||
Save Changes
|
||||
</button>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about loading states →](/docs/4.x/loading-states)
|
||||
|
||||
### JavaScript improvements
|
||||
|
||||
**`$errors` magic property**
|
||||
|
||||
Access your component's error bag from JavaScript:
|
||||
|
||||
@boostsnippet('Errors Magic Property', 'blade')
|
||||
<div wire:show="$errors.has('email')">
|
||||
<span wire:text="$errors.first('email')"></span>
|
||||
</div>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about validation →](/docs/4.x/validation)
|
||||
|
||||
**`$intercept` magic**
|
||||
|
||||
Intercept and modify Livewire requests from JavaScript:
|
||||
|
||||
@boostsnippet('Intercept Magic', 'blade')
|
||||
<script>
|
||||
this.$intercept('save', ({ ... }) => {
|
||||
// ...
|
||||
})
|
||||
</script>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about JavaScript interceptors →](/docs/4.x/javascript#interceptors)
|
||||
|
||||
**Island targeting from JavaScript**
|
||||
|
||||
Trigger island renders directly from the template:
|
||||
|
||||
@boostsnippet('Island Targeting', 'blade')
|
||||
<button wire:click="loadMore" wire:island.append="stats">
|
||||
Load more
|
||||
</button>
|
||||
@endboostsnippet
|
||||
|
||||
[Learn more about islands →](/docs/4.x/islands)
|
||||
|
||||
## Getting help
|
||||
|
||||
If you encounter issues during the upgrade:
|
||||
|
||||
- Check the [documentation](https://livewire.laravel.com) for detailed feature guides
|
||||
- Visit the [GitHub discussions](https://github.com/livewire/livewire/discussions) for community support
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Resources;
|
||||
|
||||
use Laravel\Boost\Mcp\ToolExecutor;
|
||||
use Laravel\Boost\Mcp\Tools\ApplicationInfo as ApplicationInfoTool;
|
||||
use Laravel\Mcp\Request;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Resource;
|
||||
|
||||
class ApplicationInfo extends Resource
|
||||
{
|
||||
public function __construct(protected ToolExecutor $toolExecutor) {}
|
||||
|
||||
/**
|
||||
* The resource's description.
|
||||
*/
|
||||
protected string $description = 'Comprehensive application information including PHP version, Laravel version, database engine, all installed packages with their versions, and all Eloquent models in the application.';
|
||||
|
||||
/**
|
||||
* The resource's URI.
|
||||
*/
|
||||
protected string $uri = 'file://instructions/application-info.md';
|
||||
|
||||
/**
|
||||
* The resource's MIME type.
|
||||
*/
|
||||
protected string $mimeType = 'text/markdown';
|
||||
|
||||
/**
|
||||
* Handle the resource request.
|
||||
*/
|
||||
public function handle(): Response
|
||||
{
|
||||
$response = $this->toolExecutor->execute(ApplicationInfoTool::class);
|
||||
|
||||
if ($response->isError()) {
|
||||
return $response; // Return the error response directly
|
||||
}
|
||||
|
||||
$data = json_decode((string) $response->content(), true);
|
||||
|
||||
if (! $data) {
|
||||
return Response::error('Error parsing application information');
|
||||
}
|
||||
|
||||
return Response::json($data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Laravel\Boost\Mcp\Resources;
|
||||
|
||||
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
|
||||
use Laravel\Mcp\Response;
|
||||
use Laravel\Mcp\Server\Resource;
|
||||
|
||||
class PackageGuidelineResource extends Resource
|
||||
{
|
||||
use RendersBladeGuidelines;
|
||||
|
||||
public function __construct(
|
||||
protected string $packageName,
|
||||
protected string $bladePath,
|
||||
) {
|
||||
$this->name = $this->packageName;
|
||||
$this->title = $this->packageName;
|
||||
$this->uri = "file://instructions/{$packageName}.md";
|
||||
$this->description = "Guidelines for {$packageName}";
|
||||
$this->mimeType = 'text/markdown';
|
||||
}
|
||||
|
||||
public function handle(): Response
|
||||
{
|
||||
$content = $this->renderGuidelineFile($this->bladePath);
|
||||
|
||||
return Response::text($content);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user