use std::fmt;
use std::sync::Arc;
use laravel::config::app::Environment;
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::http::{IntoMiddleware, MiddlewareGroup, Request};
use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;
use crate::config::{AuthorizeFn, StudioConfig, StudioGate};
use crate::docs::InstallSkill;
use crate::hooks;
use crate::http;
use crate::layer::StudioLayer;
use crate::store::StudioStore;
#[derive(Default)]
pub struct StudioServiceProvider {
authorize: Option<AuthorizeFn>,
middleware: Option<MiddlewareGroup>,
}
impl StudioServiceProvider {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn authorize(mut self, check: impl Fn(&Request) -> bool + Send + Sync + 'static) -> Self {
self.authorize = Some(Arc::new(check));
self
}
#[must_use]
pub fn middleware(mut self, middleware: impl IntoMiddleware) -> Self {
self.middleware = Some(self.middleware.unwrap_or_default().with(middleware));
self
}
fn is_open(&self, config: &Config) -> bool {
let environment = &config.app.env;
self.authorize.is_some()
|| environment.is_local()
|| *environment == Environment::Testing
|| config.section::<StudioConfig>().allow_in_production
}
}
impl fmt::Debug for StudioServiceProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("StudioServiceProvider")
.field("authorizes", &self.authorize.is_some())
.finish_non_exhaustive()
}
}
impl ServiceProvider for StudioServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
fn register(&self, app: &mut Registrar) {
app.commands().add::<InstallSkill>();
let config = app.config().section::<StudioConfig>().clone();
if !config.enabled {
return;
}
let environment = app.config().app.env.clone();
let testing = environment == Environment::Testing;
let mut allowed_hosts: Vec<String> = config
.allowed_hosts
.iter()
.map(|host| host.trim().to_ascii_lowercase())
.filter(|host| !host.is_empty())
.collect();
allowed_hosts.extend(host_of(&app.config().app.url));
let gate = StudioGate {
enabled: true,
is_local_or_testing: environment.is_local() || testing,
allow_in_production: config.allow_in_production,
authorize: self.authorize.clone(),
allowed_hosts,
};
let open = self.is_open(app.config());
let store = if open && config.journal && !testing {
StudioStore::with_journal(config.clone(), app.config().app.storage_path("studio"))
} else {
StudioStore::new(config.clone())
};
app.instance(store.clone());
if open {
app.logging()
.layer(StudioLayer::new(store.clone()).with_filter(LevelFilter::DEBUG));
hooks::register_hooks(app, &store);
}
app.routing().assets("studio", laravel::embed!("dist"));
let mount = config.mount_path();
let in_web_group = self.middleware.is_some();
let middleware = self.middleware.clone().unwrap_or_default();
let routes = move |route: &mut laravel::routing::Router| {
http::register_routes(route, &mount, gate, middleware, store, config.mcp_enabled);
};
if in_web_group {
app.routing().web(routes);
} else {
app.routing().routes(routes);
}
}
async fn boot(&self, app: &Container) -> laravel::Result<()> {
#[cfg(feature = "database")]
if app.config().section::<StudioConfig>().enabled && self.is_open(app.config()) {
let store = app.resolve::<StudioStore>().await?;
hooks::install_db_listener((*store).clone());
}
#[cfg(not(feature = "database"))]
let _ = app;
Ok(())
}
}
fn host_of(url: &str) -> Option<String> {
let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
let authority = rest.split(['/', '?', '#']).next()?;
let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
let host = match host.strip_prefix('[') {
Some(bracketed) => bracketed.split(']').next()?,
None => host.split(':').next()?,
};
Some(host.to_ascii_lowercase()).filter(|host| !host.is_empty())
}
#[cfg(test)]
mod tests {
use super::host_of;
#[test]
fn the_application_urls_host_is_found() {
assert_eq!(host_of("https://app.test:8443/path").as_deref(), Some("app.test"));
assert_eq!(host_of("http://127.0.0.1:8000").as_deref(), Some("127.0.0.1"));
assert_eq!(host_of("http://[::1]:8000").as_deref(), Some("::1"));
assert_eq!(
host_of("https://user:secret@Example.com").as_deref(),
Some("example.com")
);
assert_eq!(host_of(""), None);
}
}