From 54b14ebb87487d1a43e75cad834eadd36b4bce89 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Wed, 7 Oct 2026 19:44:44 +0100 Subject: [PATCH 01/16] make servers supervisor `pull` for updates and work to make it so --- .../src/servers_supervisor/actor.rs | 79 ++++--- .../servers_supervisor/get_servers_handler.rs | 14 +- .../bsnext_core/src/servers_supervisor/mod.rs | 2 - .../src/servers_supervisor/resolve_servers.rs | 219 ++++++++++++------ .../src/servers_supervisor/start_handler.rs | 32 --- .../src/servers_supervisor/stop_handler.rs | 26 --- crates/bsnext_dto/src/lib.rs | 3 + crates/bsnext_dto/src/server_events.rs | 3 + crates/bsnext_dto/src/status_events.rs | 64 +++++ crates/bsnext_system/src/override_input.rs | 40 ++-- .../bsnext_system/src/start/start_command.rs | 3 +- crates/bsnext_system/src/system.rs | 118 +++++++++- 12 files changed, 415 insertions(+), 188 deletions(-) delete mode 100644 crates/bsnext_core/src/servers_supervisor/start_handler.rs delete mode 100644 crates/bsnext_core/src/servers_supervisor/stop_handler.rs create mode 100644 crates/bsnext_dto/src/status_events.rs diff --git a/crates/bsnext_core/src/servers_supervisor/actor.rs b/crates/bsnext_core/src/servers_supervisor/actor.rs index a453dbf6..efc00a95 100644 --- a/crates/bsnext_core/src/servers_supervisor/actor.rs +++ b/crates/bsnext_core/src/servers_supervisor/actor.rs @@ -1,11 +1,13 @@ use crate::server::handler_stop::Stop; -use actix::{Actor, Addr, ResponseFuture, Running}; +use actix::{Actor, Addr, Message, Recipient, ResponseFuture, Running}; use crate::server::actor::ServerActor; use bsnext_input::server_config::ServerIdentity; use bsnext_input::Input; use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::marker::PhantomData; use std::net::SocketAddr; use crate::runtime_ctx::RuntimeCtx; @@ -17,6 +19,7 @@ use bsnext_dto::server_events::PatchError; use bsnext_dto::server_events::{ ChildCreated, ChildHandlerMinimal, ChildNotCreated, ChildNotPatched, ChildPatched, ChildResult, }; +use bsnext_dto::status_events::{ServerStatusReader, ServerStatusWriter, ServersStatus}; use futures_util::future::join_all; use futures_util::FutureExt; use tokio::sync::oneshot::Sender; @@ -25,8 +28,11 @@ use tracing::{span, Instrument, Level}; #[derive(Debug)] pub struct ServersSupervisor { pub(crate) handlers: std::collections::HashMap, - pub(crate) ex_sender: tokio::sync::mpsc::Sender, + pub(crate) sender: tokio::sync::mpsc::Sender, + pub(crate) state_reader: Recipient, + pub(crate) state_writer: Recipient, tx: Option>, + pub(crate) status: ServersStatus, } #[derive(Debug, Clone)] @@ -34,6 +40,7 @@ pub struct ChildHandler { pub actor_address: Addr, pub identity: ServerIdentity, pub socket_addr: SocketAddr, + pub content_hash: u64, } impl ChildHandler { @@ -41,16 +48,25 @@ impl ChildHandler { ChildHandlerMinimal { identity: self.identity.clone(), socket_addr: self.socket_addr, + content_hash: self.content_hash, } } } impl ServersSupervisor { - pub fn new(tx: Sender<()>, ex_sender: tokio::sync::mpsc::Sender) -> Self { + pub fn new( + tx: Sender<()>, + ex_sender: tokio::sync::mpsc::Sender, + state_reader: Recipient, + state_writer: Recipient, + ) -> Self { Self { handlers: std::default::Default::default(), - ex_sender, + sender: ex_sender, tx: Some(tx), + status: ServersStatus::default(), + state_reader, + state_writer, } } @@ -119,7 +135,7 @@ impl ServersSupervisor { let server = ServerActor::new_from_config(server_config.clone()); let actor_addr = server.start(); let actor_addr_c = actor_addr.clone(); - let c = server_config.clone(); + let original_config = server_config.clone(); actor_addr .send(Listen { // todo: tie this to the input somehow? @@ -127,15 +143,19 @@ impl ServersSupervisor { parent: self_addr.clone().recipient(), evt_receiver: self_addr.clone().recipient(), }) - .map(|r| (r, c, actor_addr_c)) + .map(|r| (r, original_config, actor_addr_c)) }); let results = join_all(fts).await; let start_child_results = results.into_iter().map(|(r, c, addr)| match r { Ok(Ok(socket_addr)) => { + let mut hasher = DefaultHasher::new(); + c.hash(&mut hasher); + let content_hash = hasher.finish(); let evt = ChildResult::Created(ChildCreated { server_handler: ChildHandlerMinimal { identity: c.identity, socket_addr, + content_hash, }, }); (Some(addr), evt) @@ -151,32 +171,39 @@ impl ServersSupervisor { }); let patch_futures = patch_jobs.into_iter().map(|(child, server_config)| { + let mut hasher = DefaultHasher::new(); + server_config.hash(&mut hasher); + let content_hash = hasher.finish(); child .actor_address .send(Patch { server_config }) - .map(|r| (r, child)) + .map(move |r| (r, child, content_hash)) }); let results = join_all(patch_futures).await; - let patch_child_results = results.into_iter().map(|(r, child_handler)| match r { - Ok(Ok((route_change_set, client_config_change_set))) => { - let evt = ChildResult::Patched(ChildPatched { - server_handler: child_handler.minimal(), - route_change_set, - client_config_change_set, + let patch_child_results = + results + .into_iter() + .map(|(r, child_handler, next_content_hash)| match r { + Ok(Ok((route_change_set, client_config_change_set))) => { + let evt = ChildResult::Patched(ChildPatched { + server_handler: child_handler.minimal(), + route_change_set, + client_config_change_set, + next_content_hash, + }); + (Some(child_handler.actor_address), evt) + } + Ok(Err(err)) => { + let evt = ChildResult::PatchErr(ChildNotPatched { + patch_error: PatchError::DidNotPatch { + reason: err.to_string(), + }, + identity: child_handler.identity.clone(), + }); + (None, evt) + } + Err(_) => unreachable!("mailbox error on patch"), }); - (Some(child_handler.actor_address), evt) - } - Ok(Err(err)) => { - let evt = ChildResult::PatchErr(ChildNotPatched { - patch_error: PatchError::DidNotPatch { - reason: err.to_string(), - }, - identity: child_handler.identity.clone(), - }); - (None, evt) - } - Err(_) => unreachable!("mailbox error on patch"), - }); let changes = shutdown_child_results .chain(start_child_results) diff --git a/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs b/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs index 06898149..5e1e79f7 100644 --- a/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs +++ b/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs @@ -7,10 +7,8 @@ use bsnext_dto::{ActiveServer, GetActiveServersResponse}; #[rtype(result = "GetActiveServersResponse")] pub struct GetActiveServers; -impl actix::Handler for ServersSupervisor { - type Result = GetActiveServersResponse; - - fn handle(&mut self, _msg: GetActiveServers, _ctx: &mut Self::Context) -> Self::Result { +impl ServersSupervisor { + pub fn active_servers(&self) -> GetActiveServersResponse { GetActiveServersResponse { servers: self .handlers @@ -18,11 +16,19 @@ impl actix::Handler for ServersSupervisor { .map(|(identity, child_handler)| ActiveServer { identity: identity.clone(), socket_addr: child_handler.socket_addr, + content_hash: child_handler.content_hash, }) .collect(), } } } +impl actix::Handler for ServersSupervisor { + type Result = GetActiveServersResponse; + + fn handle(&mut self, _msg: GetActiveServers, _ctx: &mut Self::Context) -> Self::Result { + self.active_servers() + } +} #[derive(Debug, Clone, actix::Message)] #[rtype(result = "()")] diff --git a/crates/bsnext_core/src/servers_supervisor/mod.rs b/crates/bsnext_core/src/servers_supervisor/mod.rs index 18321c6d..f5a8e73b 100644 --- a/crates/bsnext_core/src/servers_supervisor/mod.rs +++ b/crates/bsnext_core/src/servers_supervisor/mod.rs @@ -3,5 +3,3 @@ pub mod file_changed_handler; pub mod get_servers_handler; pub mod input_changed_handler; pub mod resolve_servers; -pub mod start_handler; -pub mod stop_handler; diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index ab5c489e..238a74b7 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -2,109 +2,188 @@ use crate::server::handler_client_config::ClientConfigChange; use crate::server::handler_routes_updated::RoutesUpdated; use crate::servers_supervisor::actor::{ChildHandler, ChildStopped, ServersSupervisor}; use crate::servers_supervisor::get_servers_handler::GetActiveServers; -use crate::servers_supervisor::input_changed_handler::InputChanged; -use crate::servers_supervisor::start_handler::ChildCreatedInsert; -use actix::{Addr, AsyncContext, ResponseFuture}; +use crate::servers_supervisor::input_changed_handler::{InputChanged, InputChangedResponse}; +use actix::ActorFutureExt; +use actix::{Addr, AsyncContext, ResponseActFuture, ResponseFuture, WrapFuture}; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::server_events::{ChildResult, ServerError}; +use bsnext_dto::status_events::{ + active_server_status_hash, ServerStatusReader, ServerStatusWriter, ServersStatus, StateValue, +}; use bsnext_dto::{GetActiveServersResponse, ServerChangesetDTO}; use bsnext_input::Input; +use std::convert::Infallible; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::Duration; use tracing::debug; #[derive(actix::Message)] #[rtype(result = "Result<(), ServerError>")] -pub struct ResolveServers { - input: Input, -} +pub struct ResolveServers; impl ResolveServers { - pub fn new(input: Input) -> Self { - Self { input } + pub fn new() -> Self { + ResolveServers } } impl actix::Handler for ServersSupervisor { - type Result = ResponseFuture>; + type Result = ResponseActFuture>; - #[tracing::instrument(skip_all, name = "Handler->ResolveServers->BsSystem")] + #[tracing::instrument(skip_all, name = "Handler->ResolveServers->ServersSupervisor")] fn handle(&mut self, msg: ResolveServers, ctx: &mut Self::Context) -> Self::Result { - // let external_event_sender = self.sender().clone(); let addr = ctx.address(); - let sender = self.ex_sender.clone(); + let sender = self.sender.clone(); + let local_status = self.status; + let state_writer = self.state_writer.clone(); + let state_reader = self.state_reader.clone(); let f = async move { - debug!("will mark input as changed or new"); - let results = addr.send(InputChanged { input: msg.input }).await; + tracing::info!("will ask for server input..."); + let Ok((sys_server_status, input)) = state_reader.send(ServerStatusReader).await else { + unreachable!("can it fail?") + }; + + if let (ServersStatus::Ready { .. }, ServersStatus::Ready { .. }) = + (sys_server_status, local_status) + { + tracing::info!("doing nothing, sys + local state match"); + tracing::info!(?sys_server_status); + tracing::info!(?local_status); + + return Ok(None); + } + + tracing::info!("There's something to reconcile..."); + + let expected_id = match sys_server_status { + ServersStatus::Idle => todo!("how can we get here?"), + ServersStatus::Reconciling { desired, .. } => desired, + ServersStatus::Ready { .. } => todo!("how...?"), + }; + + let results = addr.send(InputChanged { input }).await; let Ok(result_set) = results else { let e = results.unwrap_err(); unreachable!("?1 {:?}", e); }; - debug!( - "result_set from resolve servers {}", - result_set.changes.len() - ); - - for (maybe_addr, x) in &result_set.changes { - match x { - ChildResult::Stopped(id) => addr.do_send(ChildStopped { - identity: id.clone(), - }), - ChildResult::Created(c) if maybe_addr.is_some() => { - let child_handler = ChildHandler { - actor_address: maybe_addr.clone().expect("guarded above"), - identity: c.server_handler.identity.clone(), - socket_addr: c.server_handler.socket_addr, - }; - addr.do_send(ChildCreatedInsert { child_handler }) - } - ChildResult::Created(_c) => { - unreachable!("can't be created without") - } - ChildResult::Patched(p) if maybe_addr.is_some() => { - if let Some(child_actor) = maybe_addr { - child_actor.do_send(ClientConfigChange { - change_set: p.client_config_change_set.clone(), - }); - child_actor.do_send(RoutesUpdated { - change_set: p.route_change_set.clone(), - }) - } else { - tracing::error!("missing actor addr where it was needed") + Ok::, ServerError>(Some(( + expected_id, + result_set, + ))) + }; + + Box::pin(f.into_actor(self).map(move |res, act, ctx| { + match res { + Err(e) => { + tracing::info!(e = ?e, "got error?"); + return Ok(()); + } + Ok(None) => { + tracing::info!("got None, returning with nothing to do...?"); + return Ok(()); + } + Ok(Some((desired, result_set))) => { + tracing::info!("got result_set"); + debug!( + "result_set from resolve servers {}", + result_set.changes.len() + ); + + for (maybe_addr, x) in &result_set.changes { + match x { + ChildResult::Stopped(id) => { + act.handlers.remove(id); + } + ChildResult::Created(c) if maybe_addr.is_some() => { + let child_handler = ChildHandler { + actor_address: maybe_addr.clone().expect("guarded above"), + identity: c.server_handler.identity.clone(), + socket_addr: c.server_handler.socket_addr, + content_hash: c.server_handler.content_hash, + }; + act.handlers + .insert(child_handler.identity.clone(), child_handler.clone()); + } + ChildResult::Created(_c) => { + unreachable!("can't be created without") + } + ChildResult::Patched(p) if maybe_addr.is_some() => { + // todo: must mark new content_id... + dbg!("must mark local content_hash as the resolved one"); + tracing::info!( + content_hash = p.server_handler.content_hash, + next_content_hash = p.next_content_hash, + "next--" + ); + if let Some(t) = act.handlers.get_mut(&p.server_handler.identity) { + t.content_hash = p.next_content_hash; + } + if let Some(child_actor) = maybe_addr { + child_actor.do_send(ClientConfigChange { + change_set: p.client_config_change_set.clone(), + }); + child_actor.do_send(RoutesUpdated { + change_set: p.route_change_set.clone(), + }) + } else { + tracing::error!("missing actor addr where it was needed") + } + } + ChildResult::Patched(p) => { + debug!("ChildResult::Patched {:?}", p); + } + ChildResult::PatchErr(e) => { + debug!("ChildResult::PatchErr {:?}", e); + } + ChildResult::CreateErr(e) => { + debug!("ChildResult::CreateErr {:?}", e); + } } } - ChildResult::Patched(p) => { - debug!("ChildResult::Patched {:?}", p); - } - ChildResult::PatchErr(e) => { - debug!("ChildResult::PatchErr {:?}", e); - } - ChildResult::CreateErr(e) => { - debug!("ChildResult::CreateErr {:?}", e); + + let res: Vec = result_set + .changes + .into_iter() + .map(|(_, child_result)| child_result) + .collect(); + + let resp = act.active_servers(); + let observed = StateValue::new(active_server_status_hash(&resp.servers)); + let len = resp.servers.len(); + if observed == desired { + act.status = ServersStatus::Ready { desired, observed }; + state_writer.do_send(ServerStatusWriter { + server_status: act.status, + }); + } else { + act.status = ServersStatus::Reconciling { + desired, + observed: Some(observed), + }; } - } - } + tracing::info!(observed = ?act.status, len, ?desired, "observed"); - let res: Vec = result_set - .changes - .into_iter() - .map(|(_, child_result)| child_result) - .collect(); + ctx.notify_later(ResolveServers, Duration::from_secs(2)); - let (resp, res) = get_servers(addr, res) - .await - .map_err(|e| ServerError::Unknown(e.to_string()))?; + // if the current state matches the desired state, we're done for now, shedule a new check + // if observed.eq(desired) { + // + // } - let dto = ServerChangesetDTO::from_changes(&resp, &res); - let _ = sender - .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) - .await; - Ok(()) - }; + // let dto = ServerChangesetDTO::from_changes(&resp, &res); + // dbg!(dto); - Box::pin(f) + // let _ = sender + // .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) + // .await; + } + } + Ok(()) + })) } } diff --git a/crates/bsnext_core/src/servers_supervisor/start_handler.rs b/crates/bsnext_core/src/servers_supervisor/start_handler.rs deleted file mode 100644 index 2ab36810..00000000 --- a/crates/bsnext_core/src/servers_supervisor/start_handler.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::servers_supervisor::actor::{ChildHandler, ServersSupervisor}; -use bsnext_dto::server_events::ChildNotCreated; - -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct ChildCreatedInsert { - pub child_handler: ChildHandler, -} - -impl actix::Handler for ServersSupervisor { - type Result = (); - - fn handle(&mut self, msg: ChildCreatedInsert, _ctx: &mut Self::Context) -> Self::Result { - self.handlers.insert( - msg.child_handler.identity.clone(), - msg.child_handler.clone(), - ); - tracing::trace!("ChildCreated child count: {}", self.handlers.len()); - } -} - -impl actix::Handler for ServersSupervisor { - type Result = (); - - fn handle(&mut self, _msg: ChildNotCreated, _ctx: &mut Self::Context) -> Self::Result { - // self.handlers.insert( - // msg.server_handler.identity.clone(), - // msg.server_handler.clone(), - // ); - // tracing::trace!("ChildCreated child count: {}", self.handlers.len()); - } -} diff --git a/crates/bsnext_core/src/servers_supervisor/stop_handler.rs b/crates/bsnext_core/src/servers_supervisor/stop_handler.rs deleted file mode 100644 index 93bd1536..00000000 --- a/crates/bsnext_core/src/servers_supervisor/stop_handler.rs +++ /dev/null @@ -1,26 +0,0 @@ -use crate::server::handler_stop::Stop; -use crate::servers_supervisor::actor::ServersSupervisor; -use futures_util::future::join_all; -use std::future::Future; -use std::pin::Pin; - -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct StopServers; - -impl actix::Handler for ServersSupervisor { - type Result = Pin>>; - - fn handle(&mut self, _msg: StopServers, _ctx: &mut Self::Context) -> Self::Result { - let aaddresses = self.handlers.clone(); - - Box::pin(async move { - tracing::debug!("stopping {} servers", aaddresses.len()); - let fts = aaddresses - .values() - .map(|handler| handler.actor_address.send(Stop)) - .collect::>(); - join_all(fts).await; - }) - } -} diff --git a/crates/bsnext_dto/src/lib.rs b/crates/bsnext_dto/src/lib.rs index aeb1bd1a..ae640480 100644 --- a/crates/bsnext_dto/src/lib.rs +++ b/crates/bsnext_dto/src/lib.rs @@ -22,6 +22,8 @@ pub mod server_events; pub mod startup_events; pub mod task_events; +pub mod status_events; + #[typeshare] #[derive(Debug, serde::Serialize)] pub struct ServerDesc { @@ -447,6 +449,7 @@ impl From<&ActiveServer> for ServerDTO { #[derive(Debug, Clone)] pub struct ActiveServer { pub identity: ServerIdentity, + pub content_hash: u64, pub socket_addr: SocketAddr, } diff --git a/crates/bsnext_dto/src/server_events.rs b/crates/bsnext_dto/src/server_events.rs index 21e1de5c..19217c15 100644 --- a/crates/bsnext_dto/src/server_events.rs +++ b/crates/bsnext_dto/src/server_events.rs @@ -1,3 +1,4 @@ +use actix::{Handler, ResponseFuture}; use bsnext_input::server_config::ServerIdentity; use std::net::SocketAddr; @@ -5,6 +6,7 @@ use std::net::SocketAddr; pub struct ChildHandlerMinimal { pub identity: ServerIdentity, pub socket_addr: SocketAddr, + pub content_hash: u64, } #[derive(Debug, Clone, actix::Message)] @@ -17,6 +19,7 @@ pub struct ChildCreated { #[rtype(result = "()")] pub struct ChildPatched { pub server_handler: ChildHandlerMinimal, + pub next_content_hash: u64, pub route_change_set: bsnext_input::route_manifest::RouteChangeSet, pub client_config_change_set: bsnext_input::client_config::ClientConfigChangeSet, } diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs new file mode 100644 index 00000000..41fd7ebe --- /dev/null +++ b/crates/bsnext_dto/src/status_events.rs @@ -0,0 +1,64 @@ +use crate::ActiveServer; +use bsnext_input::server_config::ServerConfig; +use bsnext_input::Input; +use std::hash::{DefaultHasher, Hash, Hasher}; + +#[derive(Debug, actix::Message)] +#[rtype(result = "(ServersStatus, Input)")] +pub struct ServerStatusReader; + +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +pub struct ServerStatusWriter { + pub server_status: ServersStatus, +} + +#[derive(Debug, Clone, Hash, Copy, Eq, Ord, PartialEq, PartialOrd)] +pub struct StateValue { + value: u64, +} + +impl StateValue { + pub fn new(value: u64) -> Self { + Self { value } + } +} + +#[derive(Debug, Default, Clone, Hash, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub enum ServersStatus { + #[default] + Idle, + Reconciling { + desired: StateValue, + observed: Option, + }, + Ready { + desired: StateValue, + observed: StateValue, + }, +} + +pub fn server_status_hash(servers: &[ServerConfig]) -> u64 { + let mut identities = servers + .iter() + .map(|x| { + let mut hasher = DefaultHasher::new(); + x.hash(&mut hasher); + hasher.finish() + }) + .collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + +pub fn active_server_status_hash(servers: &[ActiveServer]) -> u64 { + let mut identities = servers.iter().map(|x| x.content_hash).collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} diff --git a/crates/bsnext_system/src/override_input.rs b/crates/bsnext_system/src/override_input.rs index a4e62831..4ba953b7 100644 --- a/crates/bsnext_system/src/override_input.rs +++ b/crates/bsnext_system/src/override_input.rs @@ -1,4 +1,4 @@ -use crate::system::BsSystem; +use crate::system::{BsSystem, CommitInput}; use crate::watchables::MonitorPathWatchables; use actix::{ActorFutureExt, AsyncContext, ResponseActFuture, WrapFuture}; use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; @@ -16,29 +16,25 @@ impl actix::Handler for BsSystem { type Result = ResponseActFuture>; fn handle(&mut self, msg: OverrideInput, ctx: &mut Self::Context) -> Self::Result { - let input_clone = msg.input.clone(); let start_ctx_clone = self.start_context.clone(); let addr = ctx.address(); - // let ctx_clone = self.st - let f = self - .servers() - .send(ResolveServers::new(msg.input)) - .into_actor(self) - .map(move |res, actor, _ctx| { - tracing::debug!(" + did override input"); - let _output = match res { - Ok(Ok(res)) => Ok(res), - Ok(Err(s_e)) => Err(s_e), - Err(err) => Err(ServerError::Unknown(err.to_string())), - }; - // todo: only process the override if valid? - let msg = - MonitorPathWatchables::new(actor.cwd.clone(), &input_clone, addr.recipient()); - actor.path_monitors.do_send(msg); - actor.update_ctx(&input_clone, &start_ctx_clone); - Ok(()) - }); - Box::pin(f) + let addr_2 = ctx.address(); + let input = msg.input; + let f = async move { + let _ = addr + .send(CommitInput { + input: input.clone(), + }) + .await; + input + }; + Box::pin(f.into_actor(self).map(move |input, actor, _ctx| { + tracing::debug!(" + did override input"); + let msg = MonitorPathWatchables::new(actor.cwd.clone(), &input, addr_2.recipient()); + actor.path_monitors.do_send(msg); + actor.update_ctx(&input, &start_ctx_clone); + Ok(()) + })) } } diff --git a/crates/bsnext_system/src/start/start_command.rs b/crates/bsnext_system/src/start/start_command.rs index 6133954d..c15eb912 100644 --- a/crates/bsnext_system/src/start/start_command.rs +++ b/crates/bsnext_system/src/start/start_command.rs @@ -152,8 +152,7 @@ impl StartCommand { let identity = ServerIdentity::from_port_or_named(port).context("port")?; - let server_config = server_config_from_paths(cwd, &paths, &route_opts, identity) - .context("server config")?; + let server_config = server_config_from_paths(cwd, &paths, &route_opts, identity)?; Ok(server_config) } diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index 8a3ade40..6652213c 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -13,12 +13,18 @@ use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::internal_events::InternalEvents; +use bsnext_dto::status_events::{ + server_status_hash, ServerStatusReader, ServerStatusWriter, ServersStatus, StateValue, +}; use bsnext_dto::task_events::TaskReportAndTree; use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; +use bsnext_input::server_config::{ServerConfig, ServerIdentity}; use bsnext_input::startup::StartupContext; use bsnext_input::{Input, InputCtx, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::PathBuf; use tokio::sync::mpsc::Sender; use tokio::sync::oneshot::Receiver; @@ -28,6 +34,7 @@ pub struct BsSystem { pub(crate) self_addr: Option>, servers_addr: Addr, any_event_sender: Sender, + status_tracker: Addr, pub(crate) input_monitors: Option, pub(crate) fs_task_tracker: Addr, pub(crate) path_monitors: Addr, @@ -68,7 +75,14 @@ impl BsSystem { cwd: PathBuf, tx: tokio::sync::oneshot::Sender<()>, ) -> Self { - let servers = ServersSupervisor::new(tx, any_event_sender.clone()); + let status_tracker = StatusTracker::new(); + let status_tracker = status_tracker.start(); + let servers = ServersSupervisor::new( + tx, + any_event_sender.clone(), + status_tracker.clone().recipient(), + status_tracker.clone().recipient(), + ); let servers_addr = servers.start(); let capabilities = Capabilities::new(any_event_sender.clone(), servers_addr.clone()); let capabilities_addr = capabilities.start(); @@ -88,6 +102,7 @@ impl BsSystem { fs_task_tracker, cwd, start_context, + status_tracker, } } @@ -145,6 +160,86 @@ impl BsSystem { } } +pub struct StatusTracker { + input: Input, + servers_status: ServersStatus, +} + +impl Actor for StatusTracker { + type Context = actix::Context; +} + +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +struct Accept { + input: Input, +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: Accept, _ctx: &mut Self::Context) -> Self::Result { + self.mark_servers(&msg.input); + self.input = msg.input; + tracing::info!(status = ?self.servers_status, "did mark servers, next state"); + Box::pin(async move { + let a = ""; + }) + } +} + +impl StatusTracker { + pub fn new() -> Self { + Self { + servers_status: ServersStatus::default(), + input: Input::default(), + } + } + fn mark_servers(&mut self, input: &Input) { + tracing::info!("will mark servers"); + let id = server_status_hash(&input.servers); + let desired = StateValue::new(id); + self.servers_status = match self.servers_status { + ServersStatus::Idle => ServersStatus::Reconciling { + observed: None, + desired, + }, + ServersStatus::Reconciling { .. } => todo!("reconciling"), + ServersStatus::Ready { observed, .. } if observed != desired => { + ServersStatus::Reconciling { + observed: Some(observed), + desired, + } + } + ServersStatus::Ready { observed, desired } => { + ServersStatus::Ready { observed, desired } + } + }; + tracing::info!(id = id, "hasher for servers") + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServersStatus, Input)>; + + fn handle(&mut self, _msg: ServerStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.servers_status, + self.input.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + tracing::info!(status = ?msg.server_status, "got next server status"); + self.servers_status = msg.server_status; + Box::pin(async move {}) + } +} + #[derive(Debug, actix::Message)] #[rtype(result = "StartupContext")] pub struct GetStartContext; @@ -227,9 +322,24 @@ impl actix::Handler for BsSystem { let input = msg.input; let servers = self.servers().clone(); let self_addr = ctx.address(); - servers.do_send(ResolveServers::new(input.clone())); - self_addr.do_send(MonitorAny::new(input)); - Box::pin(async move { Ok(()) }) + tracing::info!("will commit input"); + + let status_tracker = self.status_tracker.clone(); + + // let servers_state = input.servers; + // self_addr.do_send(MonitorAny::new(input)); + Box::pin(async move { + let _ = status_tracker + .send(Accept { input }) + .await + .expect("mailbox"); + + tracing::info!("will ping servers"); + servers.do_send(ResolveServers::new()); + + tracing::info!("did send accept"); + Ok(()) + }) } } From d42f4e628a3f70fdbe28e0a63ec0e29eafb1df69 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Wed, 7 Oct 2026 20:28:37 +0100 Subject: [PATCH 02/16] support server patching --- .../src/servers_supervisor/resolve_servers.rs | 4 +-- crates/bsnext_html/src/lib.rs | 2 ++ crates/bsnext_system/src/run/mod.rs | 2 +- .../bsnext_system/src/start/start_command.rs | 5 +-- crates/bsnext_system/src/system.rs | 13 +++++--- crates/bsnext_system/src/watch/mod.rs | 2 +- examples/html/timer.html | 32 +++++++++++++++++++ 7 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 examples/html/timer.html diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index 238a74b7..1a8cacec 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -174,8 +174,8 @@ impl actix::Handler for ServersSupervisor { // // } - // let dto = ServerChangesetDTO::from_changes(&resp, &res); - // dbg!(dto); + let dto = ServerChangesetDTO::from_changes(&resp, &res); + dbg!(dto); // let _ = sender // .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) diff --git a/crates/bsnext_html/src/lib.rs b/crates/bsnext_html/src/lib.rs index 221148a1..81ebe610 100644 --- a/crates/bsnext_html/src/lib.rs +++ b/crates/bsnext_html/src/lib.rs @@ -113,6 +113,8 @@ fn playground_html_str_to_input( // Now start to build up the input let mut input = Input::default(); + dbg!(&input_ctx); + // 1: first try prev // 2: next try if 'port' was provided // 3: finally, make one up diff --git a/crates/bsnext_system/src/run/mod.rs b/crates/bsnext_system/src/run/mod.rs index aec9c7af..cdbe1f23 100644 --- a/crates/bsnext_system/src/run/mod.rs +++ b/crates/bsnext_system/src/run/mod.rs @@ -92,7 +92,7 @@ impl RunCommand { ) -> anyhow::Result<(Input, InputResolution)> { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, &None)) .await .context("mailbox")??; diff --git a/crates/bsnext_system/src/start/start_command.rs b/crates/bsnext_system/src/start/start_command.rs index c15eb912..f6cb72d8 100644 --- a/crates/bsnext_system/src/start/start_command.rs +++ b/crates/bsnext_system/src/start/start_command.rs @@ -73,7 +73,7 @@ impl SystemStart for StartCommand { .context("Trying to get ctx")?; // prepare initial input before any tasks should run - let (mut input, resolution) = self.prepare_input(&addr, &input_opts).await?; + let (mut input, resolution) = self.prepare_input(&addr, &input_opts, &self.port).await?; // now run any 'before' tasks run before we try anything. initial_tasks(&addr, input.clone()).await?; @@ -114,10 +114,11 @@ impl StartCommand { &self, addr: &Addr, input_opts: &InputOpts, + optional_port: &Option, ) -> anyhow::Result<(Input, InputResolution)> { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, optional_port)) .await .context("mailbox")??; diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index 6652213c..ad5ff660 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -21,7 +21,7 @@ use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; use bsnext_input::server_config::{ServerConfig, ServerIdentity}; use bsnext_input::startup::StartupContext; -use bsnext_input::{Input, InputCtx, InputError}; +use bsnext_input::{Input, InputArgs, InputCtx, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; use std::collections::{BTreeSet, HashMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -256,12 +256,14 @@ impl Handler for BsSystem { #[rtype(result = "Result, Box>")] pub struct ResolveInput { pub input_paths: Vec, + pub optional_port: Option, } impl ResolveInput { - pub fn from_strs>(paths: &[A]) -> Self { + pub fn from_strs>(paths: &[A], optional_port: &Option) -> Self { Self { input_paths: paths.iter().map(|s| s.as_ref().to_string()).collect(), + optional_port: optional_port.clone(), } } } @@ -278,18 +280,21 @@ impl Handler for BsSystem { fn handle(&mut self, msg: ResolveInput, _ctx: &mut Self::Context) -> Self::Result { let cwd = self.cwd.clone(); let start = self.start_context.clone(); + let optional_port = msg.optional_port; Box::pin(async move { match ResolvedInputOutcome::new(cwd.clone(), &msg.input_paths) { ResolvedInputOutcome::Missing { err, .. } => Err(err), ResolvedInputOutcome::GivenPath { ref absolute, .. } => { - let ctx = InputCtx::new(&[], None, &start, Some(absolute)); + let args = optional_port.map(InputArgs::new); + let ctx = InputCtx::new(&[], args, &start, Some(absolute)); Ok(Some(ResolveInputResult { input: from_input_path(absolute, &ctx)?, absolute: absolute.clone(), })) } ResolvedInputOutcome::Auto { ref absolute, .. } => { - let ctx = InputCtx::new(&[], None, &start, Some(absolute)); + let args = optional_port.map(InputArgs::new); + let ctx = InputCtx::new(&[], args, &start, Some(absolute)); Ok(Some(ResolveInputResult { input: from_input_path(absolute, &ctx)?, absolute: absolute.clone(), diff --git a/crates/bsnext_system/src/watch/mod.rs b/crates/bsnext_system/src/watch/mod.rs index 95545d65..44646746 100644 --- a/crates/bsnext_system/src/watch/mod.rs +++ b/crates/bsnext_system/src/watch/mod.rs @@ -62,7 +62,7 @@ impl WatchCommand { ) -> anyhow::Result { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, &None)) .await .context("mailbox")??; diff --git a/examples/html/timer.html b/examples/html/timer.html new file mode 100644 index 00000000..78d91912 --- /dev/null +++ b/examples/html/timer.html @@ -0,0 +1,32 @@ + + +count: + + \ No newline at end of file From 03586121df6e1dc2c8aff190451cf604e2c24ca3 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Wed, 7 Oct 2026 22:32:40 +0100 Subject: [PATCH 03/16] passing tests --- .../src/servers_supervisor/resolve_servers.rs | 15 +++++++++------ crates/bsnext_system/src/system.rs | 3 ++- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index 1a8cacec..8927186d 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -5,6 +5,7 @@ use crate::servers_supervisor::get_servers_handler::GetActiveServers; use crate::servers_supervisor::input_changed_handler::{InputChanged, InputChangedResponse}; use actix::ActorFutureExt; use actix::{Addr, AsyncContext, ResponseActFuture, ResponseFuture, WrapFuture}; +use actix_rt::Arbiter; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::server_events::{ChildResult, ServerError}; @@ -174,12 +175,14 @@ impl actix::Handler for ServersSupervisor { // // } - let dto = ServerChangesetDTO::from_changes(&resp, &res); - dbg!(dto); - - // let _ = sender - // .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) - // .await; + Arbiter::current().spawn({ + let dto = ServerChangesetDTO::from_changes(&resp, &res); + async move { + let _ = sender + .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) + .await; + } + }); } } Ok(()) diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index ad5ff660..dac18d5c 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -332,7 +332,8 @@ impl actix::Handler for BsSystem { let status_tracker = self.status_tracker.clone(); // let servers_state = input.servers; - // self_addr.do_send(MonitorAny::new(input)); + // todo: make this another thing to eventually come up + self_addr.do_send(MonitorAny::new(input.clone())); Box::pin(async move { let _ = status_tracker .send(Accept { input }) From 70d2d20ff15a39cc0d071288da502922b64af30a Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Tue, 13 Oct 2026 09:54:05 +0100 Subject: [PATCH 04/16] next --- .../src/servers_supervisor/actor.rs | 9 +- .../src/servers_supervisor/resolve_servers.rs | 55 ++-- crates/bsnext_dto/src/server_events.rs | 1 - crates/bsnext_dto/src/status_events.rs | 32 ++- crates/bsnext_html/src/lib.rs | 2 - .../bsnext_system/src/handle_fs_changeset.rs | 241 +++++++----------- crates/bsnext_system/src/monitor_any.rs | 64 ----- crates/bsnext_system/src/monitor_input.rs | 4 + crates/bsnext_system/src/override_input.rs | 10 +- crates/bsnext_system/src/path_monitors/mod.rs | 181 ++++++++++++- crates/bsnext_system/src/system.rs | 180 +++++++++++-- crates/bsnext_system/src/watchables/mod.rs | 21 +- 12 files changed, 491 insertions(+), 309 deletions(-) diff --git a/crates/bsnext_core/src/servers_supervisor/actor.rs b/crates/bsnext_core/src/servers_supervisor/actor.rs index efc00a95..3a338f34 100644 --- a/crates/bsnext_core/src/servers_supervisor/actor.rs +++ b/crates/bsnext_core/src/servers_supervisor/actor.rs @@ -1,5 +1,5 @@ use crate::server::handler_stop::Stop; -use actix::{Actor, Addr, Message, Recipient, ResponseFuture, Running}; +use actix::{Actor, Addr, Recipient, ResponseFuture, Running}; use crate::server::actor::ServerActor; @@ -7,7 +7,6 @@ use bsnext_input::server_config::ServerIdentity; use bsnext_input::Input; use std::collections::HashSet; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::marker::PhantomData; use std::net::SocketAddr; use crate::runtime_ctx::RuntimeCtx; @@ -19,7 +18,7 @@ use bsnext_dto::server_events::PatchError; use bsnext_dto::server_events::{ ChildCreated, ChildHandlerMinimal, ChildNotCreated, ChildNotPatched, ChildPatched, ChildResult, }; -use bsnext_dto::status_events::{ServerStatusReader, ServerStatusWriter, ServersStatus}; +use bsnext_dto::status_events::{ServerStatusReader, ServerStatusWriter, ServiceStatus}; use futures_util::future::join_all; use futures_util::FutureExt; use tokio::sync::oneshot::Sender; @@ -32,7 +31,7 @@ pub struct ServersSupervisor { pub(crate) state_reader: Recipient, pub(crate) state_writer: Recipient, tx: Option>, - pub(crate) status: ServersStatus, + pub(crate) status: ServiceStatus, } #[derive(Debug, Clone)] @@ -64,7 +63,7 @@ impl ServersSupervisor { handlers: std::default::Default::default(), sender: ex_sender, tx: Some(tx), - status: ServersStatus::default(), + status: ServiceStatus::default(), state_reader, state_writer, } diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index 8927186d..1d300c37 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -1,21 +1,17 @@ use crate::server::handler_client_config::ClientConfigChange; use crate::server::handler_routes_updated::RoutesUpdated; -use crate::servers_supervisor::actor::{ChildHandler, ChildStopped, ServersSupervisor}; -use crate::servers_supervisor::get_servers_handler::GetActiveServers; +use crate::servers_supervisor::actor::{ChildHandler, ServersSupervisor}; use crate::servers_supervisor::input_changed_handler::{InputChanged, InputChangedResponse}; use actix::ActorFutureExt; -use actix::{Addr, AsyncContext, ResponseActFuture, ResponseFuture, WrapFuture}; +use actix::{AsyncContext, ResponseActFuture, WrapFuture}; use actix_rt::Arbiter; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::server_events::{ChildResult, ServerError}; use bsnext_dto::status_events::{ - active_server_status_hash, ServerStatusReader, ServerStatusWriter, ServersStatus, StateValue, + active_server_status_hash, ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, }; -use bsnext_dto::{GetActiveServersResponse, ServerChangesetDTO}; -use bsnext_input::Input; -use std::convert::Infallible; -use std::hash::{DefaultHasher, Hash, Hasher}; +use bsnext_dto::ServerChangesetDTO; use std::time::Duration; use tracing::debug; @@ -23,6 +19,12 @@ use tracing::debug; #[rtype(result = "Result<(), ServerError>")] pub struct ResolveServers; +impl Default for ResolveServers { + fn default() -> Self { + Self::new() + } +} + impl ResolveServers { pub fn new() -> Self { ResolveServers @@ -33,7 +35,7 @@ impl actix::Handler for ServersSupervisor { type Result = ResponseActFuture>; #[tracing::instrument(skip_all, name = "Handler->ResolveServers->ServersSupervisor")] - fn handle(&mut self, msg: ResolveServers, ctx: &mut Self::Context) -> Self::Result { + fn handle(&mut self, _msg: ResolveServers, ctx: &mut Self::Context) -> Self::Result { let addr = ctx.address(); let sender = self.sender.clone(); let local_status = self.status; @@ -46,7 +48,7 @@ impl actix::Handler for ServersSupervisor { unreachable!("can it fail?") }; - if let (ServersStatus::Ready { .. }, ServersStatus::Ready { .. }) = + if let (ServiceStatus::Ready { .. }, ServiceStatus::Ready { .. }) = (sys_server_status, local_status) { tracing::info!("doing nothing, sys + local state match"); @@ -59,9 +61,9 @@ impl actix::Handler for ServersSupervisor { tracing::info!("There's something to reconcile..."); let expected_id = match sys_server_status { - ServersStatus::Idle => todo!("how can we get here?"), - ServersStatus::Reconciling { desired, .. } => desired, - ServersStatus::Ready { .. } => todo!("how...?"), + ServiceStatus::Idle => todo!("how can we get here?"), + ServiceStatus::Reconciling { desired, .. } => desired, + ServiceStatus::Ready { .. } => todo!("how...?"), }; let results = addr.send(InputChanged { input }).await; @@ -114,7 +116,6 @@ impl actix::Handler for ServersSupervisor { } ChildResult::Patched(p) if maybe_addr.is_some() => { // todo: must mark new content_id... - dbg!("must mark local content_hash as the resolved one"); tracing::info!( content_hash = p.server_handler.content_hash, next_content_hash = p.next_content_hash, @@ -156,24 +157,20 @@ impl actix::Handler for ServersSupervisor { let observed = StateValue::new(active_server_status_hash(&resp.servers)); let len = resp.servers.len(); if observed == desired { - act.status = ServersStatus::Ready { desired, observed }; + act.status = ServiceStatus::Ready { desired, observed }; state_writer.do_send(ServerStatusWriter { server_status: act.status, }); } else { - act.status = ServersStatus::Reconciling { - desired, - observed: Some(observed), - }; + todo!("will set to reconciling... but is it?"); + // act.status = ServiceStatus::Reconciling { + // desired, + // observed: Some(observed), + // }; } tracing::info!(observed = ?act.status, len, ?desired, "observed"); - ctx.notify_later(ResolveServers, Duration::from_secs(2)); - - // if the current state matches the desired state, we're done for now, shedule a new check - // if observed.eq(desired) { - // - // } + ctx.notify_later(ResolveServers, Duration::from_millis(1000)); Arbiter::current().spawn({ let dto = ServerChangesetDTO::from_changes(&resp, &res); @@ -189,11 +186,3 @@ impl actix::Handler for ServersSupervisor { })) } } - -async fn get_servers( - addr: Addr, - results: Vec, -) -> anyhow::Result<(GetActiveServersResponse, Vec)> { - let resp = addr.send(GetActiveServers).await?; - Ok((resp, results)) -} diff --git a/crates/bsnext_dto/src/server_events.rs b/crates/bsnext_dto/src/server_events.rs index 19217c15..b49c71af 100644 --- a/crates/bsnext_dto/src/server_events.rs +++ b/crates/bsnext_dto/src/server_events.rs @@ -1,4 +1,3 @@ -use actix::{Handler, ResponseFuture}; use bsnext_input::server_config::ServerIdentity; use std::net::SocketAddr; diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs index 41fd7ebe..d8855990 100644 --- a/crates/bsnext_dto/src/status_events.rs +++ b/crates/bsnext_dto/src/status_events.rs @@ -4,13 +4,23 @@ use bsnext_input::Input; use std::hash::{DefaultHasher, Hash, Hasher}; #[derive(Debug, actix::Message)] -#[rtype(result = "(ServersStatus, Input)")] +#[rtype(result = "(ServiceStatus, Input)")] pub struct ServerStatusReader; #[derive(Debug, actix::Message)] #[rtype(result = "()")] pub struct ServerStatusWriter { - pub server_status: ServersStatus, + pub server_status: ServiceStatus, +} + +#[derive(Debug, actix::Message)] +#[rtype(result = "(ServiceStatus, Input)")] +pub struct MonitorStatusReader; + +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +pub struct MonitorStatusWriter { + pub monitor_status: ServiceStatus, } #[derive(Debug, Clone, Hash, Copy, Eq, Ord, PartialEq, PartialOrd)] @@ -25,7 +35,7 @@ impl StateValue { } #[derive(Debug, Default, Clone, Hash, Copy, Eq, PartialEq, Ord, PartialOrd)] -pub enum ServersStatus { +pub enum ServiceStatus { #[default] Idle, Reconciling { @@ -54,6 +64,22 @@ pub fn server_status_hash(servers: &[ServerConfig]) -> u64 { hasher.finish() } +pub fn monitor_status_hash(servers: &[ServerConfig]) -> u64 { + let mut identities = servers + .iter() + .map(|x| { + let mut hasher = DefaultHasher::new(); + x.hash(&mut hasher); + hasher.finish() + }) + .collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + pub fn active_server_status_hash(servers: &[ActiveServer]) -> u64 { let mut identities = servers.iter().map(|x| x.content_hash).collect::>(); identities.sort_unstable(); diff --git a/crates/bsnext_html/src/lib.rs b/crates/bsnext_html/src/lib.rs index 81ebe610..221148a1 100644 --- a/crates/bsnext_html/src/lib.rs +++ b/crates/bsnext_html/src/lib.rs @@ -113,8 +113,6 @@ fn playground_html_str_to_input( // Now start to build up the input let mut input = Input::default(); - dbg!(&input_ctx); - // 1: first try prev // 2: next try if 'port' was provided // 3: finally, make one up diff --git a/crates/bsnext_system/src/handle_fs_changeset.rs b/crates/bsnext_system/src/handle_fs_changeset.rs index a9c8b2a1..b8bce0b4 100644 --- a/crates/bsnext_system/src/handle_fs_changeset.rs +++ b/crates/bsnext_system/src/handle_fs_changeset.rs @@ -1,11 +1,10 @@ use crate::fs_task_tracker::TriggerFsTask; -use crate::input_fs::from_input_path; -use crate::override_input::OverrideInput; -use crate::system::BsSystem; -use crate::tasks::task_comms::TaskComms; +use crate::monitor_input::InputMonitor; +use crate::system::{BsSystem, ResolveInputAgain}; use crate::tasks::task_spec::TaskSpec; use crate::tasks::Runnable; use actix::{Addr, AsyncContext}; +use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::file_changed_handler::FileChanged; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; @@ -16,9 +15,10 @@ use bsnext_fs::{ }; use bsnext_input::bs_live_built_in_task::BsLiveBuiltInTask; use bsnext_input::route::WatchSpec; -use bsnext_input::{Input, InputError, PathDefinition, PathDefs, PathError}; +use bsnext_input::{InputError, PathDefinition, PathDefs, PathError}; use bsnext_path_monitor::{Changeset, PathMonitorChangeset}; use bsnext_task::task_trigger::FsChangesTrigger; +use std::path::PathBuf; use tracing::{debug, debug_span, info}; impl actix::Handler for BsSystem { @@ -39,7 +39,9 @@ impl actix::Handler for BsSystem { None } Changeset::BufferedChange(buff) => { - if let Some((task_trigger, task_spec)) = self.handle_buffered(buff, watch_spec) { + if let Some((task_trigger, task_spec)) = + handle_buffered(self.input_monitors.as_ref(), buff, watch_spec) + { tracing::debug!("will trigger task runner"); self.fs_task_tracker .do_send(TriggerFsTask::new(task_spec, task_trigger)); @@ -66,160 +68,115 @@ impl BsSystem { match &fs_event.kind { FsEventKind::Change(ch) if fs_event.fs_event_ctx.is_root() => { tracing::info!("fs_event_ctx=root"); - match self.handle_input_change(ch) { - // if the change included a new Input, use it - Ok((_, Some(input))) => { - tracing::info!("will override input"); - addr.do_send(OverrideInput { input }); - // return None here so that the event is not published yet (the updated Input will do it) - None - } - // otherwise publish the change as usual - Ok((evt, None)) => Some(evt), - Err(e) => { - println!("{e}"); - None - } - } + addr.do_send(ResolveInputAgain); + None } FsEventKind::Change(inner) => { - let evt = self.handle_any_change(&fs_event.fs_event_ctx, inner); + let servers_addr = self.servers().clone(); + let evt = handle_any_change(servers_addr, &fs_event.fs_event_ctx, inner); Some(evt) } - FsEventKind::PathAdded(path) => self.handle_path_added(path, &debounce), - FsEventKind::PathRemoved(path) => self.handle_path_removed(path), - FsEventKind::PathNotFoundError(pdo) => self.handle_path_not_found(pdo), + FsEventKind::PathAdded(path) => handle_path_added(path, &debounce), + FsEventKind::PathRemoved(path) => handle_path_removed(path), + FsEventKind::PathNotFoundError(pdo) => handle_path_not_found(self.cwd.clone(), pdo), } } - #[tracing::instrument(skip_all)] - fn handle_buffered( - &mut self, - buf: BufferedChangeset, - watch_spec: WatchSpec, - ) -> Option<(FsChangesTrigger, TaskSpec)> { - tracing::debug!(msg.event_count = buf.changes.len(), msg.ctx = ?buf.fs_event_ctx, ?buf); +} - let change = if let Some(mon) = &self.input_monitors { - if let Some(fp) = mon.input_ctx.file_path() { - tracing::debug!("Dropping input crossover {}", fp.display()); - buf.dropping_absolute(fp) - } else { - buf - } +#[tracing::instrument(skip_all)] +fn handle_buffered( + input_monitor: Option<&InputMonitor>, + buf: BufferedChangeset, + watch_spec: WatchSpec, +) -> Option<(FsChangesTrigger, TaskSpec)> { + tracing::debug!(msg.event_count = buf.changes.len(), msg.ctx = ?buf.fs_event_ctx, ?buf); + + let change = if let Some(mon) = input_monitor { + if let Some(fp) = mon.input_ctx.file_path() { + tracing::debug!("Dropping input crossover {}", fp.display()); + buf.dropping_absolute(fp) } else { buf - }; - - if change.changes.is_empty() { - tracing::debug!( - "Ignoring handle_buffered events because it was empty after removing input monitor" - ); - return None; } - - let paths = change - .changes - .iter() - .map(|evt| evt.absolute.to_owned()) - .collect::>(); - - let task_spec = self.task_spec_for_fs_event(&watch_spec); - let trigger = FsChangesTrigger::new(paths, change.fs_event_ctx); - - Some((trigger, task_spec)) - } - - pub fn task_comms(&mut self) -> TaskComms { - TaskComms::new(self.sender().clone()) - } - - fn handle_any_change( - &mut self, - fs_event_ctx: &FsEventContext, - inner: &PathDescriptionOwned, - ) -> ExternalEventsDTO { - tracing::trace!(?inner, "Other file changed"); - self.servers().do_send(FileChanged { - path: inner.absolute.clone(), - ctx: *fs_event_ctx, - }); - ExternalEventsDTO::FileChanged(bsnext_dto::FileChangedDTO::from_path_buf( - inner.relative.as_ref().unwrap_or(&inner.absolute), - )) + } else { + buf + }; + + if change.changes.is_empty() { + tracing::debug!( + "Ignoring handle_buffered events because it was empty after removing input monitor" + ); + return None; } - fn handle_input_change( - &mut self, - inner: &PathDescriptionOwned, - ) -> Result<(ExternalEventsDTO, Option), Box> { - tracing::info!("InputFile file changed {:?}", inner); - let ctx = self - .input_monitors - .as_ref() - .map(|input_monitor| input_monitor.input_ctx.clone()) - .unwrap_or_default(); + let paths = change + .changes + .iter() + .map(|evt| evt.absolute.to_owned()) + .collect::>(); - let input = from_input_path(&inner.absolute, &ctx); + let task_spec = task_spec_for_fs_event(&watch_spec); + let trigger = FsChangesTrigger::new(paths, change.fs_event_ctx); - let Ok(input) = input else { - let err = input.unwrap_err(); - return Err(err); - }; - let path_to_report = inner.relative.as_ref().unwrap_or(&inner.absolute); + Some((trigger, task_spec)) +} - Ok(( - ExternalEventsDTO::InputFileChanged(bsnext_dto::FileChangedDTO::from_path_buf( - path_to_report, - )), - Some(input), - )) - } - fn handle_path_added( - &self, - path: &PathAddedEvent, - debounce: &Debounce, - ) -> Option { - Some(ExternalEventsDTO::Watching(WatchingDTO::from_path_buf( - &path.path, *debounce, - ))) - } +fn handle_any_change( + servers_addr: Addr, + fs_event_ctx: &FsEventContext, + inner: &PathDescriptionOwned, +) -> ExternalEventsDTO { + tracing::trace!(?inner, "Other file changed"); + servers_addr.do_send(FileChanged { + path: inner.absolute.clone(), + ctx: *fs_event_ctx, + }); + ExternalEventsDTO::FileChanged(bsnext_dto::FileChangedDTO::from_path_buf( + inner.relative.as_ref().unwrap_or(&inner.absolute), + )) +} - fn handle_path_removed(&mut self, path: &PathEvent) -> Option { - Some(ExternalEventsDTO::WatchingStopped( - StoppedWatchingDTO::from_path_buf(&path.path), - )) - } +fn handle_path_not_found(cwd: PathBuf, pdo: &PathEvent) -> Option { + let as_str = pdo.path.to_string_lossy().to_string(); + let cwd = cwd.clone(); + let abs = cwd.join(&as_str); + let def = PathDefinition { + input: as_str, + cwd: cwd.clone(), + absolute: abs, + }; + let err = InputError::PathError(PathError::MissingPaths { + paths: PathDefs(vec![def]), + }); + + Some(ExternalEventsDTO::InputError(InputErrorDetailDTO { + error: err.to_string(), + })) +} - fn handle_path_not_found(&mut self, pdo: &PathEvent) -> Option { - let as_str = pdo.path.to_string_lossy().to_string(); - let cwd = self.cwd.clone(); - let abs = cwd.join(&as_str); - let def = PathDefinition { - input: as_str, - cwd: self.cwd.clone(), - absolute: abs, - }; - let err = InputError::PathError(PathError::MissingPaths { - paths: PathDefs(vec![def]), - }); +fn handle_path_added(path: &PathAddedEvent, debounce: &Debounce) -> Option { + Some(ExternalEventsDTO::Watching(WatchingDTO::from_path_buf( + &path.path, *debounce, + ))) +} - Some(ExternalEventsDTO::InputError(InputErrorDetailDTO { - error: err.to_string(), - })) - } +fn handle_path_removed(path: &PathEvent) -> Option { + Some(ExternalEventsDTO::WatchingStopped( + StoppedWatchingDTO::from_path_buf(&path.path), + )) +} - #[tracing::instrument(skip_all)] - fn task_spec_for_fs_event(&self, watch_spec: &WatchSpec) -> TaskSpec { - if let Some(spec) = TaskSpec::opt_from(watch_spec) { - info!("matching task_spec: {:?}", spec); - info!("matching fs_event_ctx: {:?}", watch_spec); - spec.to_owned() - } else { - debug!("creating a default task spec on the fly because fs_event_ctx didn't match any task specs"); - TaskSpec::seq(&[ - Runnable::BsLiveTask(BsLiveBuiltInTask::NotifyServer), - Runnable::BsLiveTask(BsLiveBuiltInTask::PublishExternalEvent), - ]) - } +#[tracing::instrument(skip_all)] +fn task_spec_for_fs_event(watch_spec: &WatchSpec) -> TaskSpec { + if let Some(spec) = TaskSpec::opt_from(watch_spec) { + info!("matching task_spec: {:?}", spec); + info!("matching fs_event_ctx: {:?}", watch_spec); + spec.to_owned() + } else { + debug!("creating a default task spec on the fly because fs_event_ctx didn't match any task specs"); + TaskSpec::seq(&[ + Runnable::BsLiveTask(BsLiveBuiltInTask::NotifyServer), + Runnable::BsLiveTask(BsLiveBuiltInTask::PublishExternalEvent), + ]) } } diff --git a/crates/bsnext_system/src/monitor_any.rs b/crates/bsnext_system/src/monitor_any.rs index a638e6cd..8b137891 100644 --- a/crates/bsnext_system/src/monitor_any.rs +++ b/crates/bsnext_system/src/monitor_any.rs @@ -1,65 +1 @@ -use crate::system::BsSystem; -use crate::watchables::MonitorPathWatchables; -use actix::{ActorFutureExt, AsyncContext}; -use actix::{ResponseActFuture, WrapFuture}; -use bsnext_input::Input; -use tracing::debug_span; -/// Message to monitor file system paths based on the current input configuration. -/// -/// This handler processes an `Input` configuration to determine which paths should be -/// monitored for file system changes. It: -/// - Converts the input into a collection of watchables based on the configured watch strategy -/// (routes, servers, or any custom watchers) -/// - Sends these watchables to the `Monitor` actor to create individual `PathMonitor` instances -/// - Registers the resulting task specifications with the system for later use in handling -/// file system events -/// -/// The monitoring configuration respects the `watchers` and `infer` settings in the input, -/// allowing for flexible control over which files and directories are watched. -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct MonitorAny { - input: Input, -} - -impl MonitorAny { - pub fn new(input: Input) -> Self { - Self { input } - } -} - -impl actix::Handler for BsSystem { - type Result = ResponseActFuture; - - fn handle(&mut self, msg: MonitorAny, ctx: &mut Self::Context) -> Self::Result { - let cwd = self.cwd.clone(); - let recip = ctx.address().recipient(); - let monitor = self.path_monitors.clone(); - - let future = async move { - let input = msg.input; - let msg = MonitorPathWatchables::new(cwd, &input, recip); - monitor.send(msg).await?; - Ok::<_, anyhow::Error>(()) - }; - - Box::pin(future.into_actor(self).map(|res, _actor, _ctx| match res { - Ok(..) => { - let span = debug_span!("MonitorAny -> InsertResults"); - let _g = span.entered(); - // for (index, insert_result) in inner.into_iter().enumerate() { - // let task_spec = TaskSpec::opt_from(&insert_result.meta.watch_spec); - // let fs_ctx = insert_result.meta.fs_ctx; - // actor.insert_meta(insert_result.meta.fs_ctx, insert_result.meta); - // if let Some(spec) = task_spec { - // actor.insert_task_spec(fs_ctx, spec); - // } - // } - } - Err(err) => { - tracing::error!(?err); - } - })) - } -} diff --git a/crates/bsnext_system/src/monitor_input.rs b/crates/bsnext_system/src/monitor_input.rs index 5bbe1f98..cacd6997 100644 --- a/crates/bsnext_system/src/monitor_input.rs +++ b/crates/bsnext_system/src/monitor_input.rs @@ -41,6 +41,10 @@ impl actix::Handler for BsSystem { #[tracing::instrument(skip_all, name = "Handler->MonitorInput->BsSystem")] fn handle(&mut self, msg: MonitorInput, ctx: &mut Self::Context) -> Self::Result { + if self.input_monitors.as_ref().is_some() { + tracing::debug!("refusing to setup another input monitor"); + return; + } let sys = ctx.address().recipient(); let debounce = Debounce::Trailing { duration: Duration::from_millis(300), diff --git a/crates/bsnext_system/src/override_input.rs b/crates/bsnext_system/src/override_input.rs index 4ba953b7..d406ee0c 100644 --- a/crates/bsnext_system/src/override_input.rs +++ b/crates/bsnext_system/src/override_input.rs @@ -1,7 +1,7 @@ +use crate::path_monitors::RequestMonitor; use crate::system::{BsSystem, CommitInput}; use crate::watchables::MonitorPathWatchables; use actix::{ActorFutureExt, AsyncContext, ResponseActFuture, WrapFuture}; -use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; use bsnext_dto::server_events::ServerError; use bsnext_input::startup::StartupContext; use bsnext_input::{Input, InputCtx}; @@ -18,7 +18,6 @@ impl actix::Handler for BsSystem { fn handle(&mut self, msg: OverrideInput, ctx: &mut Self::Context) -> Self::Result { let start_ctx_clone = self.start_context.clone(); let addr = ctx.address(); - let addr_2 = ctx.address(); let input = msg.input; let f = async move { let _ = addr @@ -28,10 +27,11 @@ impl actix::Handler for BsSystem { .await; input }; - Box::pin(f.into_actor(self).map(move |input, actor, _ctx| { + Box::pin(f.into_actor(self).map(move |input, actor, ctx| { tracing::debug!(" + did override input"); - let msg = MonitorPathWatchables::new(actor.cwd.clone(), &input, addr_2.recipient()); - actor.path_monitors.do_send(msg); + let msg = MonitorPathWatchables::new(&input); + let request = RequestMonitor::new(msg, ctx.address().recipient(), actor.cwd.clone()); + actor.path_monitors.do_send(request); actor.update_ctx(&input, &start_ctx_clone); Ok(()) })) diff --git a/crates/bsnext_system/src/path_monitors/mod.rs b/crates/bsnext_system/src/path_monitors/mod.rs index 5af433fa..88d54ec5 100644 --- a/crates/bsnext_system/src/path_monitors/mod.rs +++ b/crates/bsnext_system/src/path_monitors/mod.rs @@ -1,22 +1,39 @@ use crate::watchables::path_watchable::PathWatchable; use crate::watchables::MonitorPathWatchables; -use actix::{Actor, Addr, AsyncContext, ResponseFuture}; +use actix::ActorFutureExt; +use actix::{Actor, Addr, AsyncContext, Recipient, ResponseActFuture, ResponseFuture, WrapFuture}; +use bsnext_dto::status_events::{MonitorStatusReader, MonitorStatusWriter, ServiceStatus}; use bsnext_fs::{Debounce, FsEventContext}; use bsnext_path_monitor::path_monitor::{PathMonitor, StopPathMonitor}; use bsnext_path_monitor::watch_paths_msg::WatchPaths; +use bsnext_path_monitor::PathMonitorChangeset; use std::collections::{BTreeSet, HashMap}; use std::path::PathBuf; use tracing::{debug, debug_span}; -#[derive(Debug, Default)] +#[derive(Debug)] pub struct PathMonitors { + cwd: PathBuf, path_monitors: HashMap>, + state_reader: Recipient, + state_writer: Recipient, + status: ServiceStatus, + recipient: Option>, } impl PathMonitors { - pub fn new() -> Self { + pub fn new( + cwd: PathBuf, + state_reader: Recipient, + state_writer: Recipient, + ) -> Self { Self { + cwd, path_monitors: Default::default(), + state_writer, + state_reader, + status: ServiceStatus::default(), + recipient: None, } } } @@ -33,15 +50,45 @@ pub struct DropMonitor(pub PathWatchable); #[rtype(result = "()")] pub struct InsertMonitor(pub PathWatchable, pub Addr, pub Vec); -impl actix::Handler for PathMonitors { +#[derive(actix::Message)] +#[rtype(result = "()")] +pub struct RequestMonitor { + inner: MonitorPathWatchables, + recipient: Recipient, + cwd: PathBuf, +} + +impl RequestMonitor { + pub(crate) fn new( + inner: MonitorPathWatchables, + recipient: Recipient, + cwd: PathBuf, + ) -> Self { + Self { + inner, + recipient, + cwd, + } + } +} + +impl actix::Handler for PathMonitors { type Result = ResponseFuture<()>; - #[tracing::instrument(skip_all, name = "MonitorPathWatchables->Monitor")] - fn handle(&mut self, msg: MonitorPathWatchables, ctx: &mut Self::Context) -> Self::Result { + #[tracing::instrument(skip_all, name = "RequestMonitor->Monitor")] + fn handle( + &mut self, + RequestMonitor { + inner, + recipient, + cwd, + }: RequestMonitor, + ctx: &mut Self::Context, + ) -> Self::Result { debug!("{}", file!()); let existing = self.path_monitors.keys().collect::>(); - let incoming = msg.watchables.iter().collect::>(); + let incoming = inner.watchables.iter().collect::>(); let in_both = incoming.intersection(&existing).collect::>(); let to_add = incoming.difference(&existing).collect::>(); @@ -84,9 +131,9 @@ impl actix::Handler for PathMonitors { tracing::trace!(?debounce); let path_monitor = PathMonitor::new( - msg.recipient.clone(), + recipient.clone(), debounce, - msg.cwd.clone(), + cwd.clone(), fs_ctx, spec.clone(), ); @@ -130,3 +177,119 @@ impl actix::Handler for PathMonitors { addr.do_send(WatchPaths { paths }); } } + +/// Message to monitor file system paths based on the current input configuration. +/// +/// This handler processes an `Input` configuration to determine which paths should be +/// monitored for file system changes. It: +/// - Converts the input into a collection of watchables based on the configured watch strategy +/// (routes, servers, or any custom watchers) +/// - Sends these watchables to the `Monitor` actor to create individual `PathMonitor` instances +/// - Registers the resulting task specifications with the system for later use in handling +/// file system events +/// +/// The monitoring configuration respects the `watchers` and `infer` settings in the input, +/// allowing for flexible control over which files and directories are watched. +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +pub struct MonitorAny; + +impl Default for MonitorAny { + fn default() -> Self { + Self::new() + } +} + +impl MonitorAny { + pub fn new() -> Self { + Self + } +} + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: MonitorAny, ctx: &mut Self::Context) -> Self::Result { + let cwd = self.cwd.clone(); + let monitors_addr = ctx.address(); + let state_reader = self.state_reader.clone(); + let local_status = self.status; + let Some(recipient) = self.recipient.clone() else { + todo!("How can this happen?"); + }; + // + let future = async move { + let Ok((sys_service_status, input)) = state_reader.send(MonitorStatusReader).await + else { + unreachable!("can it fail?") + }; + if let (ServiceStatus::Ready { .. }, ServiceStatus::Ready { .. }) = + (sys_service_status, local_status) + { + tracing::info!("doing nothing, sys + local state match"); + tracing::info!(?sys_service_status); + tracing::info!(?local_status); + + return Ok(None); + } + + tracing::info!("There's something to reconcile..."); + + let expected_id = match sys_service_status { + ServiceStatus::Idle => todo!("how can we get here?"), + ServiceStatus::Reconciling { desired, .. } => desired, + ServiceStatus::Ready { .. } => todo!("how...?"), + }; + + let watchables = MonitorPathWatchables::new(&input); + let request = RequestMonitor::new(watchables, recipient, cwd); + monitors_addr.send(request).await?; + Ok::<_, anyhow::Error>(Some(expected_id)) + }; + + Box::pin(future.into_actor(self).map(|res, actor, _ctx| { + match res { + Ok(None) => { + tracing::info!("got None, returning with nothing to do...?"); + return Ok(()); + } + Ok(Some(desired)) => { + // todo - make sure we can handle NOT being ready... + actor.status = ServiceStatus::Ready { + desired, + observed: desired, + }; + let state_writer = actor.state_writer.clone(); + + state_writer.do_send(MonitorStatusWriter { + monitor_status: actor.status, + }); + } + Err(err) => { + tracing::error!(?err); + } + } + Ok(()) + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "()")] +pub struct ConfigureRecipient { + recipient: Recipient, +} + +impl ConfigureRecipient { + pub fn new(recipient: Recipient) -> Self { + Self { recipient } + } +} + +impl actix::Handler for PathMonitors { + type Result = (); + + fn handle(&mut self, msg: ConfigureRecipient, _ctx: &mut Self::Context) -> Self::Result { + self.recipient = Some(msg.recipient); + } +} diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index dac18d5c..c87d5715 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -2,11 +2,14 @@ use crate::capabilities::Capabilities; use crate::fs_task_tracker::FsTaskTracker; use crate::input_fs::from_input_path; use crate::invoke_scope::{InvokeScope, Invoker}; -use crate::monitor_any::MonitorAny; use crate::monitor_input::{InputMonitor, MonitorInput}; -use crate::path_monitors::PathMonitors; +use crate::path_monitors::{ConfigureRecipient, MonitorAny, PathMonitors}; use crate::tasks::task_spec::TaskSpec; -use actix::{Actor, Addr, AsyncContext, Handler, ResponseFuture, Running}; +use crate::watchables::MonitorPathWatchables; +use actix::ActorFutureExt; +use actix::{ + Actor, Addr, AsyncContext, Handler, ResponseActFuture, ResponseFuture, Running, WrapFuture, +}; use actix_rt::Arbiter; use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; @@ -14,16 +17,15 @@ use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::internal_events::InternalEvents; use bsnext_dto::status_events::{ - server_status_hash, ServerStatusReader, ServerStatusWriter, ServersStatus, StateValue, + server_status_hash, MonitorStatusReader, MonitorStatusWriter, ServerStatusReader, + ServerStatusWriter, ServiceStatus, StateValue, }; use bsnext_dto::task_events::TaskReportAndTree; use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; -use bsnext_input::server_config::{ServerConfig, ServerIdentity}; use bsnext_input::startup::StartupContext; use bsnext_input::{Input, InputArgs, InputCtx, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; -use std::collections::{BTreeSet, HashMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::PathBuf; use tokio::sync::mpsc::Sender; @@ -34,7 +36,7 @@ pub struct BsSystem { pub(crate) self_addr: Option>, servers_addr: Addr, any_event_sender: Sender, - status_tracker: Addr, + pub(crate) status_tracker: Addr, pub(crate) input_monitors: Option, pub(crate) fs_task_tracker: Addr, pub(crate) path_monitors: Addr, @@ -49,6 +51,8 @@ impl Actor for BsSystem { fn started(&mut self, ctx: &mut Self::Context) { tracing::trace!(actor.name = "BsSystem", actor.lifecyle = "started"); self.self_addr = Some(ctx.address()); + self.path_monitors + .do_send(ConfigureRecipient::new(ctx.address().recipient())); } fn stopping(&mut self, _ctx: &mut Self::Context) -> Running { @@ -75,7 +79,7 @@ impl BsSystem { cwd: PathBuf, tx: tokio::sync::oneshot::Sender<()>, ) -> Self { - let status_tracker = StatusTracker::new(); + let status_tracker = StatusTracker::new(cwd.clone()); let status_tracker = status_tracker.start(); let servers = ServersSupervisor::new( tx, @@ -90,7 +94,11 @@ impl BsSystem { let invoker = Invoker::new(capabilities_addr.clone(), any_event_sender.clone()); let invoker_addr = invoker.start(); let fs_task_tracker = FsTaskTracker::new(invoker_addr.clone().recipient()).start(); - let monitor = PathMonitors::new(); + let monitor = PathMonitors::new( + cwd.clone(), + status_tracker.clone().recipient(), + status_tracker.clone().recipient(), + ); let monitor = monitor.start(); BsSystem { self_addr: None, @@ -162,7 +170,9 @@ impl BsSystem { pub struct StatusTracker { input: Input, - servers_status: ServersStatus, + cwd: PathBuf, + servers_status: ServiceStatus, + monitor_status: ServiceStatus, } impl Actor for StatusTracker { @@ -173,6 +183,7 @@ impl Actor for StatusTracker { #[rtype(result = "()")] struct Accept { input: Input, + cwd: PathBuf, } impl Handler for StatusTracker { @@ -180,19 +191,24 @@ impl Handler for StatusTracker { fn handle(&mut self, msg: Accept, _ctx: &mut Self::Context) -> Self::Result { self.mark_servers(&msg.input); + self.mark_monitors(&msg.input); self.input = msg.input; + self.cwd = msg.cwd; tracing::info!(status = ?self.servers_status, "did mark servers, next state"); + tracing::info!(status = ?self.monitor_status, "did mark monitors, next state"); Box::pin(async move { - let a = ""; + let _a = ""; }) } } impl StatusTracker { - pub fn new() -> Self { + pub fn new(cwd: PathBuf) -> Self { Self { - servers_status: ServersStatus::default(), + servers_status: ServiceStatus::default(), + monitor_status: ServiceStatus::default(), input: Input::default(), + cwd, } } fn mark_servers(&mut self, input: &Input) { @@ -200,27 +216,57 @@ impl StatusTracker { let id = server_status_hash(&input.servers); let desired = StateValue::new(id); self.servers_status = match self.servers_status { - ServersStatus::Idle => ServersStatus::Reconciling { + ServiceStatus::Idle => ServiceStatus::Reconciling { observed: None, desired, }, - ServersStatus::Reconciling { .. } => todo!("reconciling"), - ServersStatus::Ready { observed, .. } if observed != desired => { - ServersStatus::Reconciling { + ServiceStatus::Reconciling { observed, .. } => { + ServiceStatus::Reconciling { observed, desired } + } + ServiceStatus::Ready { observed, .. } if observed != desired => { + ServiceStatus::Reconciling { observed: Some(observed), desired, } } - ServersStatus::Ready { observed, desired } => { - ServersStatus::Ready { observed, desired } + ServiceStatus::Ready { observed, desired } => { + ServiceStatus::Ready { observed, desired } } }; tracing::info!(id = id, "hasher for servers") } + fn mark_monitors(&mut self, input: &Input) { + tracing::info!("will mark monitors"); + let content = MonitorPathWatchables::new(input); + let mut hasher = DefaultHasher::new(); + content.hash(&mut hasher); + let id = hasher.finish(); + let desired = StateValue::new(id); + self.monitor_status = match self.monitor_status { + ServiceStatus::Idle => ServiceStatus::Reconciling { + observed: None, + desired, + }, + ServiceStatus::Reconciling { .. } => todo!("how can both be reconciling?"), + ServiceStatus::Ready { observed, .. } if observed != desired => { + ServiceStatus::Reconciling { + observed: Some(observed), + desired, + } + } + ServiceStatus::Ready { observed, desired } => { + ServiceStatus::Ready { observed, desired } + } + }; + tracing::info!(id = id, "hasher for servers"); + // let id = server_status_hash(&input.servers); + // let desired = StateValue::new(id); + // todo!("how to compute monitors?") + } } impl Handler for StatusTracker { - type Result = ResponseFuture<(ServersStatus, Input)>; + type Result = ResponseFuture<(ServiceStatus, Input)>; fn handle(&mut self, _msg: ServerStatusReader, _ctx: &mut Self::Context) -> Self::Result { Box::pin(futures::future::ready(( @@ -230,11 +276,33 @@ impl Handler for StatusTracker { } } +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServiceStatus, Input)>; + + fn handle(&mut self, _msg: MonitorStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.monitor_status, + self.input.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: MonitorStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + tracing::info!(status = ?msg.monitor_status, "got next monitor status"); + self.monitor_status = msg.monitor_status; + Box::pin(async move {}) + } +} + impl Handler for StatusTracker { type Result = ResponseFuture<()>; fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { tracing::info!(status = ?msg.server_status, "got next server status"); + // dbg!(&msg.server_status); self.servers_status = msg.server_status; Box::pin(async move {}) } @@ -263,7 +331,7 @@ impl ResolveInput { pub fn from_strs>(paths: &[A], optional_port: &Option) -> Self { Self { input_paths: paths.iter().map(|s| s.as_ref().to_string()).collect(), - optional_port: optional_port.clone(), + optional_port: *optional_port, } } } @@ -286,7 +354,8 @@ impl Handler for BsSystem { ResolvedInputOutcome::Missing { err, .. } => Err(err), ResolvedInputOutcome::GivenPath { ref absolute, .. } => { let args = optional_port.map(InputArgs::new); - let ctx = InputCtx::new(&[], args, &start, Some(absolute)); + let ctx = InputCtx::new(&[], args.clone(), &start, Some(absolute)); + tracing::debug!(?absolute, ?args, ?ctx, "ResolvedInputOutcome::GivenPath"); Ok(Some(ResolveInputResult { input: from_input_path(absolute, &ctx)?, absolute: absolute.clone(), @@ -306,6 +375,61 @@ impl Handler for BsSystem { } } +#[derive(Debug, actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +pub(crate) struct ResolveInputAgain; + +impl actix::Handler for BsSystem { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: ResolveInputAgain, ctx: &mut Self::Context) -> Self::Result { + let Some(monitor) = &self.input_monitors else { + todo!("this cannot occur?"); + }; + + let Some(pb) = monitor.input_ctx.file_path() else { + todo!("this cannot occur?"); + }; + + let input_ctx = monitor.input_ctx.clone(); + let port = input_ctx.port(); + + let as_str = pb.to_string_lossy(); + let as_str = as_str.to_string(); + let msg = ResolveInput { + input_paths: vec![as_str], + optional_port: port, + }; + + self.publish_external_event(AnyEvent::External(ExternalEventsDTO::InputFileChanged( + bsnext_dto::FileChangedDTO::from_path_buf(pb), + ))); + + let sys_addr = ctx.address().clone(); + + let future = async move { + let Some(ResolveInputResult { input, absolute }) = sys_addr.send(msg).await?? else { + todo!("..."); + }; + + Ok::<_, anyhow::Error>((input, absolute, input_ctx)) + }; + + Box::pin(future.into_actor(self).map(|result, _actor, ctx| { + if let Ok((input, absolute, input_ctx)) = result { + ctx.notify(CommitInputFile { + input, + absolute, + ctx: input_ctx, + }); + } else { + tracing::error!("something went wrong?") + } + Ok(()) + })) + } +} + #[derive(Debug, actix::Message)] #[rtype(result = "Result<(), anyhow::Error>")] pub struct CommitInput { @@ -323,27 +447,29 @@ impl CommitInput { impl actix::Handler for BsSystem { type Result = ResponseFuture>; - fn handle(&mut self, msg: CommitInput, ctx: &mut Self::Context) -> Self::Result { + fn handle(&mut self, msg: CommitInput, _ctx: &mut Self::Context) -> Self::Result { let input = msg.input; let servers = self.servers().clone(); - let self_addr = ctx.address(); + let monitors = self.path_monitors.clone(); + let cwd = self.cwd.clone(); tracing::info!("will commit input"); let status_tracker = self.status_tracker.clone(); // let servers_state = input.servers; // todo: make this another thing to eventually come up - self_addr.do_send(MonitorAny::new(input.clone())); Box::pin(async move { - let _ = status_tracker - .send(Accept { input }) + status_tracker + .send(Accept { input, cwd }) .await .expect("mailbox"); tracing::info!("will ping servers"); servers.do_send(ResolveServers::new()); + monitors.do_send(MonitorAny::new()); tracing::info!("did send accept"); + Ok(()) }) } diff --git a/crates/bsnext_system/src/watchables/mod.rs b/crates/bsnext_system/src/watchables/mod.rs index e8a62b06..b37f48f5 100644 --- a/crates/bsnext_system/src/watchables/mod.rs +++ b/crates/bsnext_system/src/watchables/mod.rs @@ -2,10 +2,7 @@ use crate::watchables::any_watchable::to_any_watchables; use crate::watchables::path_watchable::PathWatchable; use crate::watchables::route_watchable::to_route_watchables; use crate::watchables::server_watchable::to_server_watchables; -use actix::Recipient; use bsnext_input::{InferWatchers, Input, WatchGlobalConfig}; -use bsnext_path_monitor::PathMonitorChangeset; -use std::path::PathBuf; use tracing::debug; pub mod any_watchable; @@ -13,16 +10,14 @@ pub mod path_watchable; pub mod route_watchable; pub mod server_watchable; -#[derive(actix::Message)] +#[derive(Debug, actix::Message, Hash, Eq, PartialEq)] #[rtype(result = "()")] pub struct MonitorPathWatchables { pub watchables: Vec, - pub cwd: PathBuf, - pub recipient: Recipient, } impl MonitorPathWatchables { - pub fn new(cwd: PathBuf, input: &Input, recipient: Recipient) -> Self { + pub fn new(input: &Input) -> Self { let route_watchables = to_route_watchables(input); let server_watchables = to_server_watchables(input); let any_watchables = to_any_watchables(input); @@ -65,16 +60,6 @@ impl MonitorPathWatchables { WatchGlobalConfig::Disabled => vec![], }; - debug!( - "{} watchables to add, cwd: {}", - watchables.len(), - cwd.display() - ); - - MonitorPathWatchables { - watchables, - cwd, - recipient, - } + MonitorPathWatchables { watchables } } } From 70969b45125463476274f926452c7017c038a30d Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Thu, 15 Oct 2026 09:50:15 +0100 Subject: [PATCH 05/16] well... --- Cargo.lock | 1 + .../src/servers_supervisor/resolve_servers.rs | 5 +- crates/bsnext_dto/src/status_events.rs | 28 +- crates/bsnext_fs/src/watch_path_handler.rs | 4 +- crates/bsnext_input/Cargo.toml | 1 + crates/bsnext_input/src/lib.rs | 1 + .../src/watchables/any_watchable.rs | 4 +- .../src/watchables/mod.rs | 13 +- .../src/watchables/path_watchable.rs | 2 +- .../src/watchables/route_watchable.rs | 8 +- .../src/watchables/server_watchable.rs | 6 +- .../bsnext_path_monitor/src/path_monitor.rs | 31 +- crates/bsnext_system/src/lib.rs | 1 - crates/bsnext_system/src/monitor_input.rs | 4 +- crates/bsnext_system/src/override_input.rs | 4 +- crates/bsnext_system/src/path_monitors/mod.rs | 281 +++++++++++++++--- crates/bsnext_system/src/system.rs | 50 ++-- 17 files changed, 349 insertions(+), 95 deletions(-) rename crates/{bsnext_system => bsnext_input}/src/watchables/any_watchable.rs (89%) rename crates/{bsnext_system => bsnext_input}/src/watchables/mod.rs (87%) rename crates/{bsnext_system => bsnext_input}/src/watchables/path_watchable.rs (98%) rename crates/{bsnext_system => bsnext_input}/src/watchables/route_watchable.rs (92%) rename crates/{bsnext_system => bsnext_input}/src/watchables/server_watchable.rs (87%) diff --git a/Cargo.lock b/Cargo.lock index bf3edaa1..edbe3272 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -597,6 +597,7 @@ dependencies = [ "serde_yaml", "shell-words", "thiserror 1.0.60", + "tracing", ] [[package]] diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index 1d300c37..6e17601f 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -157,9 +157,9 @@ impl actix::Handler for ServersSupervisor { let observed = StateValue::new(active_server_status_hash(&resp.servers)); let len = resp.servers.len(); if observed == desired { - act.status = ServiceStatus::Ready { desired, observed }; + act.status = ServiceStatus::Ready { observed }; state_writer.do_send(ServerStatusWriter { - server_status: act.status, + servers_status: act.status, }); } else { todo!("will set to reconciling... but is it?"); @@ -168,6 +168,7 @@ impl actix::Handler for ServersSupervisor { // observed: Some(observed), // }; } + tracing::info!(observed = ?act.status, len, ?desired, "observed"); ctx.notify_later(ResolveServers, Duration::from_millis(1000)); diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs index d8855990..064ab742 100644 --- a/crates/bsnext_dto/src/status_events.rs +++ b/crates/bsnext_dto/src/status_events.rs @@ -1,5 +1,6 @@ use crate::ActiveServer; use bsnext_input::server_config::ServerConfig; +use bsnext_input::watchables::PathWatchables; use bsnext_input::Input; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -10,7 +11,7 @@ pub struct ServerStatusReader; #[derive(Debug, actix::Message)] #[rtype(result = "()")] pub struct ServerStatusWriter { - pub server_status: ServiceStatus, + pub servers_status: ServiceStatus, } #[derive(Debug, actix::Message)] @@ -43,11 +44,20 @@ pub enum ServiceStatus { observed: Option, }, Ready { - desired: StateValue, observed: StateValue, }, } +impl ServiceStatus { + pub fn observed(&self) -> Option { + match self { + ServiceStatus::Idle => None, + ServiceStatus::Reconciling { observed, .. } => *observed, + ServiceStatus::Ready { observed, .. } => Some(*observed), + } + } +} + pub fn server_status_hash(servers: &[ServerConfig]) -> u64 { let mut identities = servers .iter() @@ -64,8 +74,9 @@ pub fn server_status_hash(servers: &[ServerConfig]) -> u64 { hasher.finish() } -pub fn monitor_status_hash(servers: &[ServerConfig]) -> u64 { - let mut identities = servers +pub fn monitor_status_hash(path_watchables: &PathWatchables) -> u64 { + let mut identities = path_watchables + .watchables .iter() .map(|x| { let mut hasher = DefaultHasher::new(); @@ -80,6 +91,15 @@ pub fn monitor_status_hash(servers: &[ServerConfig]) -> u64 { hasher.finish() } +pub fn list_hash(items: &[u64]) -> u64 { + let mut identities = items.iter().collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + pub fn active_server_status_hash(servers: &[ActiveServer]) -> u64 { let mut identities = servers.iter().map(|x| x.content_hash).collect::>(); identities.sort_unstable(); diff --git a/crates/bsnext_fs/src/watch_path_handler.rs b/crates/bsnext_fs/src/watch_path_handler.rs index 0ccd8589..b3136aad 100644 --- a/crates/bsnext_fs/src/watch_path_handler.rs +++ b/crates/bsnext_fs/src/watch_path_handler.rs @@ -14,7 +14,7 @@ impl Handler for FsWatcher { type Result = (); // todo: ensure this isn't sent for every input change - fn handle(&mut self, msg: RequestWatchPath, _ctx: &mut Self::Context) -> Self::Result { + fn handle(&mut self, msg: RequestWatchPath, ctx: &mut Self::Context) -> Self::Result { let Some(watcher) = self.watcher.as_mut() else { todo!("Can this ever be reached?"); }; @@ -55,7 +55,7 @@ impl Handler for FsWatcher { kind: evt, fs_event_ctx: self.ctx, }); - _ctx.stop(); + ctx.stop(); } } } diff --git a/crates/bsnext_input/Cargo.toml b/crates/bsnext_input/Cargo.toml index 6253188b..764cb3bb 100644 --- a/crates/bsnext_input/Cargo.toml +++ b/crates/bsnext_input/Cargo.toml @@ -23,6 +23,7 @@ anyhow = { workspace = true } serde_yaml = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +tracing = { workspace = true } [dev-dependencies] insta = { workspace = true } diff --git a/crates/bsnext_input/src/lib.rs b/crates/bsnext_input/src/lib.rs index 8aedbc8e..47deed05 100644 --- a/crates/bsnext_input/src/lib.rs +++ b/crates/bsnext_input/src/lib.rs @@ -28,6 +28,7 @@ pub mod target; #[cfg(test)] pub mod watch_opt_test; pub mod watch_opts; +pub mod watchables; pub mod when_guard; pub mod yml; diff --git a/crates/bsnext_system/src/watchables/any_watchable.rs b/crates/bsnext_input/src/watchables/any_watchable.rs similarity index 89% rename from crates/bsnext_system/src/watchables/any_watchable.rs rename to crates/bsnext_input/src/watchables/any_watchable.rs index 2cdb8559..18c32000 100644 --- a/crates/bsnext_system/src/watchables/any_watchable.rs +++ b/crates/bsnext_input/src/watchables/any_watchable.rs @@ -1,5 +1,5 @@ -use bsnext_input::route::WatchSpec; -use bsnext_input::Input; +use crate::route::WatchSpec; +use crate::Input; use std::path::PathBuf; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_system/src/watchables/mod.rs b/crates/bsnext_input/src/watchables/mod.rs similarity index 87% rename from crates/bsnext_system/src/watchables/mod.rs rename to crates/bsnext_input/src/watchables/mod.rs index b37f48f5..6dee3662 100644 --- a/crates/bsnext_system/src/watchables/mod.rs +++ b/crates/bsnext_input/src/watchables/mod.rs @@ -2,7 +2,7 @@ use crate::watchables::any_watchable::to_any_watchables; use crate::watchables::path_watchable::PathWatchable; use crate::watchables::route_watchable::to_route_watchables; use crate::watchables::server_watchable::to_server_watchables; -use bsnext_input::{InferWatchers, Input, WatchGlobalConfig}; +use crate::{InferWatchers, Input, WatchGlobalConfig}; use tracing::debug; pub mod any_watchable; @@ -10,13 +10,12 @@ pub mod path_watchable; pub mod route_watchable; pub mod server_watchable; -#[derive(Debug, actix::Message, Hash, Eq, PartialEq)] -#[rtype(result = "()")] -pub struct MonitorPathWatchables { +#[derive(Debug, Hash, Eq, PartialEq)] +pub struct PathWatchables { pub watchables: Vec, } -impl MonitorPathWatchables { +impl PathWatchables { pub fn new(input: &Input) -> Self { let route_watchables = to_route_watchables(input); let server_watchables = to_server_watchables(input); @@ -34,7 +33,7 @@ impl MonitorPathWatchables { .iter() .map(|w| PathWatchable::Any(w.to_owned())); - let watchables: Vec<_> = match &input.config.watchers { + let watchables: Vec = match &input.config.watchers { WatchGlobalConfig::Enabled { infer } => match infer { InferWatchers::None => { debug!("processing {} any watchables", any.len()); @@ -60,6 +59,6 @@ impl MonitorPathWatchables { WatchGlobalConfig::Disabled => vec![], }; - MonitorPathWatchables { watchables } + PathWatchables { watchables } } } diff --git a/crates/bsnext_system/src/watchables/path_watchable.rs b/crates/bsnext_input/src/watchables/path_watchable.rs similarity index 98% rename from crates/bsnext_system/src/watchables/path_watchable.rs rename to crates/bsnext_input/src/watchables/path_watchable.rs index 6ccbdccd..56fad7e4 100644 --- a/crates/bsnext_system/src/watchables/path_watchable.rs +++ b/crates/bsnext_input/src/watchables/path_watchable.rs @@ -1,10 +1,10 @@ use std::fmt::{Display, Formatter}; use std::hash::{DefaultHasher, Hash, Hasher}; +use crate::route::WatchSpec; use crate::watchables::any_watchable::AnyWatchable; use crate::watchables::route_watchable::RouteWatchable; use crate::watchables::server_watchable::ServerWatchable; -use bsnext_input::route::WatchSpec; use std::path::Path; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_system/src/watchables/route_watchable.rs b/crates/bsnext_input/src/watchables/route_watchable.rs similarity index 92% rename from crates/bsnext_system/src/watchables/route_watchable.rs rename to crates/bsnext_input/src/watchables/route_watchable.rs index 9ea30464..59219fb2 100644 --- a/crates/bsnext_system/src/watchables/route_watchable.rs +++ b/crates/bsnext_input/src/watchables/route_watchable.rs @@ -1,7 +1,7 @@ -use bsnext_input::route::{DirRoute, PathPattern, RawRoute, RouteKind, SseOpts, WatchSpec}; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::watch_opts::WatchOpts; -use bsnext_input::Input; +use crate::route::{DirRoute, PathPattern, RawRoute, RouteKind, SseOpts, WatchSpec}; +use crate::server_config::ServerIdentity; +use crate::watch_opts::WatchOpts; +use crate::Input; use std::path::{Path, PathBuf}; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_system/src/watchables/server_watchable.rs b/crates/bsnext_input/src/watchables/server_watchable.rs similarity index 87% rename from crates/bsnext_system/src/watchables/server_watchable.rs rename to crates/bsnext_input/src/watchables/server_watchable.rs index 652691ac..003635eb 100644 --- a/crates/bsnext_system/src/watchables/server_watchable.rs +++ b/crates/bsnext_input/src/watchables/server_watchable.rs @@ -1,6 +1,6 @@ -use bsnext_input::route::WatchSpec; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::Input; +use crate::route::WatchSpec; +use crate::server_config::ServerIdentity; +use crate::Input; use std::path::PathBuf; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_path_monitor/src/path_monitor.rs b/crates/bsnext_path_monitor/src/path_monitor.rs index f2f8601f..b8d2cee8 100644 --- a/crates/bsnext_path_monitor/src/path_monitor.rs +++ b/crates/bsnext_path_monitor/src/path_monitor.rs @@ -1,7 +1,10 @@ use crate::PathMonitorChangeset; use crate::path_and_filter::PathAndFilter; use crate::watch_paths_msg::WatchPaths; -use actix::{Actor, ActorContext, Addr, AsyncContext, Context, Handler, Recipient, StreamHandler}; +use actix::{ + Actor, ActorContext, Addr, AsyncContext, Context, Handler, Recipient, ResponseFuture, + StreamHandler, +}; use actix_rt::Arbiter; use bsnext_fs::actor::FsWatcher; use bsnext_fs::buffered_debounce::BufferedStreamOpsExt; @@ -108,6 +111,32 @@ impl actix::Handler for PathMonitor { } } +#[derive(Debug, actix::Message)] +#[rtype(result = "ConnectedWatchersResult")] +pub struct ConnectedWatchers; + +#[derive(Debug)] +pub struct ConnectedWatchersResult { + pub desired_len: usize, + pub observed_len: usize, +} + +impl actix::Handler for PathMonitor { + type Result = ResponseFuture; + + fn handle(&mut self, _msg: ConnectedWatchers, _ctx: &mut Self::Context) -> Self::Result { + let addrs = self.addrs.clone(); + Box::pin(async move { + let desired_len = addrs.len(); + let observed_len = addrs.iter().filter(|addr| addr.connected()).count(); + ConnectedWatchersResult { + desired_len, + observed_len, + } + }) + } +} + impl StreamHandler for PathMonitor { fn handle(&mut self, event: FsEvent, _ctx: &mut Context) { debug!("StreamHandler for PathMonitor"); diff --git a/crates/bsnext_system/src/lib.rs b/crates/bsnext_system/src/lib.rs index af1550e5..2f9ba2a3 100644 --- a/crates/bsnext_system/src/lib.rs +++ b/crates/bsnext_system/src/lib.rs @@ -17,4 +17,3 @@ pub mod start; mod system; pub mod tasks; pub mod watch; -pub mod watchables; diff --git a/crates/bsnext_system/src/monitor_input.rs b/crates/bsnext_system/src/monitor_input.rs index cacd6997..c627080b 100644 --- a/crates/bsnext_system/src/monitor_input.rs +++ b/crates/bsnext_system/src/monitor_input.rs @@ -1,9 +1,9 @@ use crate::system::BsSystem; -use crate::watchables::any_watchable::AnyWatchable; -use crate::watchables::path_watchable::PathWatchable; use actix::{Actor, Addr, AsyncContext}; use bsnext_fs::{Debounce, FsEventContext}; use bsnext_input::route::WatchSpec; +use bsnext_input::watchables::any_watchable::AnyWatchable; +use bsnext_input::watchables::path_watchable::PathWatchable; use bsnext_input::InputCtx; use bsnext_path_monitor::path_monitor::PathMonitor; use bsnext_path_monitor::watch_paths_msg::WatchPaths; diff --git a/crates/bsnext_system/src/override_input.rs b/crates/bsnext_system/src/override_input.rs index d406ee0c..8ed257d5 100644 --- a/crates/bsnext_system/src/override_input.rs +++ b/crates/bsnext_system/src/override_input.rs @@ -1,9 +1,9 @@ use crate::path_monitors::RequestMonitor; use crate::system::{BsSystem, CommitInput}; -use crate::watchables::MonitorPathWatchables; use actix::{ActorFutureExt, AsyncContext, ResponseActFuture, WrapFuture}; use bsnext_dto::server_events::ServerError; use bsnext_input::startup::StartupContext; +use bsnext_input::watchables::PathWatchables; use bsnext_input::{Input, InputCtx}; #[derive(Debug, actix::Message)] @@ -29,7 +29,7 @@ impl actix::Handler for BsSystem { }; Box::pin(f.into_actor(self).map(move |input, actor, ctx| { tracing::debug!(" + did override input"); - let msg = MonitorPathWatchables::new(&input); + let msg = PathWatchables::new(&input); let request = RequestMonitor::new(msg, ctx.address().recipient(), actor.cwd.clone()); actor.path_monitors.do_send(request); actor.update_ctx(&input, &start_ctx_clone); diff --git a/crates/bsnext_system/src/path_monitors/mod.rs b/crates/bsnext_system/src/path_monitors/mod.rs index 88d54ec5..52891ee4 100644 --- a/crates/bsnext_system/src/path_monitors/mod.rs +++ b/crates/bsnext_system/src/path_monitors/mod.rs @@ -1,14 +1,18 @@ -use crate::watchables::path_watchable::PathWatchable; -use crate::watchables::MonitorPathWatchables; use actix::ActorFutureExt; use actix::{Actor, Addr, AsyncContext, Recipient, ResponseActFuture, ResponseFuture, WrapFuture}; -use bsnext_dto::status_events::{MonitorStatusReader, MonitorStatusWriter, ServiceStatus}; +use bsnext_dto::status_events::{ + list_hash, MonitorStatusReader, MonitorStatusWriter, ServiceStatus, StateValue, +}; use bsnext_fs::{Debounce, FsEventContext}; -use bsnext_path_monitor::path_monitor::{PathMonitor, StopPathMonitor}; +use bsnext_input::watchables::path_watchable::PathWatchable; +use bsnext_input::watchables::PathWatchables; +use bsnext_input::Input; +use bsnext_path_monitor::path_monitor::{ConnectedWatchers, PathMonitor, StopPathMonitor}; use bsnext_path_monitor::watch_paths_msg::WatchPaths; use bsnext_path_monitor::PathMonitorChangeset; use std::collections::{BTreeSet, HashMap}; use std::path::PathBuf; +use std::time::Duration; use tracing::{debug, debug_span}; #[derive(Debug)] @@ -18,6 +22,7 @@ pub struct PathMonitors { state_reader: Recipient, state_writer: Recipient, status: ServiceStatus, + status_hashes: Vec, recipient: Option>, } @@ -32,6 +37,7 @@ impl PathMonitors { path_monitors: Default::default(), state_writer, state_reader, + status_hashes: vec![], status: ServiceStatus::default(), recipient: None, } @@ -53,14 +59,14 @@ pub struct InsertMonitor(pub PathWatchable, pub Addr, pub Vec, cwd: PathBuf, } impl RequestMonitor { pub(crate) fn new( - inner: MonitorPathWatchables, + inner: PathWatchables, recipient: Recipient, cwd: PathBuf, ) -> Self { @@ -105,18 +111,18 @@ impl actix::Handler for PathMonitors { } } - for (index, any_watchable) in to_add.into_iter().enumerate() { + for (index, path_watchable) in to_add.into_iter().enumerate() { let span = debug_span!("{}", index); let _guard = span.enter(); - let watchable_hash = any_watchable.as_id(); - let paths = any_watchable + let watchable_hash = path_watchable.as_id(); + let paths = path_watchable .watch_paths() .into_iter() .map(ToOwned::to_owned) .collect::>(); tracing::trace!(?watchable_hash); - let fs_ctx_id = match any_watchable { + let fs_ctx_id = match path_watchable { PathWatchable::Server(watchable) => watchable.server_identity.as_id(), PathWatchable::Route(watchable) => watchable.server_identity.as_id(), PathWatchable::Any(_) => watchable_hash, @@ -124,7 +130,7 @@ impl actix::Handler for PathMonitors { tracing::trace!(?fs_ctx_id); let fs_ctx = FsEventContext::new(fs_ctx_id, watchable_hash); - let spec = any_watchable.spec(); + let spec = path_watchable.spec(); tracing::trace!(?spec); let debounce = spec.debounce.map(Debounce::from).unwrap_or_default(); @@ -141,7 +147,7 @@ impl actix::Handler for PathMonitors { let path_monitor_addr = path_monitor.start(); ctx.notify(InsertMonitor( - (*any_watchable).clone(), + (*path_watchable).clone(), path_monitor_addr, paths, )) @@ -210,63 +216,256 @@ impl actix::Handler for PathMonitors { type Result = ResponseActFuture>; fn handle(&mut self, _msg: MonitorAny, ctx: &mut Self::Context) -> Self::Result { - let cwd = self.cwd.clone(); + let _cwd = self.cwd.clone(); let monitors_addr = ctx.address(); let state_reader = self.state_reader.clone(); let local_status = self.status; - let Some(recipient) = self.recipient.clone() else { + let _local_hashes = self.status_hashes.clone(); + let Some(_recipient) = self.recipient.clone() else { todo!("How can this happen?"); }; - // let future = async move { + let Ok(..) = monitors_addr.send(TryEvict).await else { + unreachable!("can it fail?") + }; let Ok((sys_service_status, input)) = state_reader.send(MonitorStatusReader).await else { unreachable!("can it fail?") }; + + tracing::info!(?sys_service_status, "incoming"); + tracing::info!(?local_status); + if let (ServiceStatus::Ready { .. }, ServiceStatus::Ready { .. }) = (sys_service_status, local_status) { - tracing::info!("doing nothing, sys + local state match"); - tracing::info!(?sys_service_status); - tracing::info!(?local_status); - return Ok(None); } - - tracing::info!("There's something to reconcile..."); - let expected_id = match sys_service_status { ServiceStatus::Idle => todo!("how can we get here?"), ServiceStatus::Reconciling { desired, .. } => desired, - ServiceStatus::Ready { .. } => todo!("how...?"), + ServiceStatus::Ready { observed, .. } => observed, }; - let watchables = MonitorPathWatchables::new(&input); - let request = RequestMonitor::new(watchables, recipient, cwd); - monitors_addr.send(request).await?; - Ok::<_, anyhow::Error>(Some(expected_id)) + Ok::<_, anyhow::Error>(Some((expected_id, input))) }; - Box::pin(future.into_actor(self).map(|res, actor, _ctx| { + Box::pin(future.into_actor(self).map(|res, actor, ctx| { + let Ok(res) = res else { + tracing::error!("how did it get here? {:?}", res.unwrap_err()); + return Ok(()); + }; match res { - Ok(None) => { - tracing::info!("got None, returning with nothing to do...?"); - return Ok(()); + None => { + tracing::debug!("--- we decided there's nothing to do because local and remote states match") } - Ok(Some(desired)) => { - // todo - make sure we can handle NOT being ready... - actor.status = ServiceStatus::Ready { + Some((desired, input)) => { + tracing::debug!("+++ There's something to reconcile..."); + actor.status = ServiceStatus::Reconciling { desired, - observed: desired, + observed: actor.status.observed(), + }; + ctx.notify(TryReconcile { input }); + } + } + Ok::<_, anyhow::Error>(()) + // if local_id.is_none() { + // tracing::info!("There's something to reconcile..."); + // } else if local_id.is_some_and(|v| v != expected_id) { + // tracing::info!("There's something to reconcile..."); + // } else { + // + // } + // dbg!("huh?", will_reconcile); + // let watchables = PathWatchables::new(&input); + // let content_hash = monitor_status_hash(&watchables); + // let list = list_hash(&local_hashes); + // + // if expected_id == list { + // todo!("it became 'ready'"); + // } + // tracing::debug!("{} computed from input, {} observed", content_hash, list); + // let request = RequestMonitor::new(watchables, recipient, cwd); + // monitors_addr.send(request).await?; + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryReconcile { + input: Input, +} + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, msg: TryReconcile, ctx: &mut Self::Context) -> Self::Result { + let input = msg.input; + let Some(recipient) = self.recipient.clone() else { + todo!("How can this happen?"); + }; + let monitors_addr = ctx.address(); + let cwd = self.cwd.clone(); + Box::pin( + async move { + tracing::debug!("will try to reconcile things..."); + let watchables = PathWatchables::new(&input); + // let content_hash = monitor_status_hash(&watchables); + let request = RequestMonitor::new(watchables, recipient, cwd); + monitors_addr.send(request).await?; + Ok::<_, anyhow::Error>(()) + } + .into_actor(self) + .map(|_result, _actor, ctx| { + ctx.notify(TryRead); + Ok(()) + }), + ) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryRead; + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: TryRead, _ctx: &mut Self::Context) -> Self::Result { + let addrs = self.path_monitors.clone(); + let addr_len = addrs.len(); + let state_writer = self.state_writer.clone(); + + #[derive(Debug)] + enum LocalResult { + Ready { observed_local: StateValue }, + NotReady { observed_local: StateValue }, + } + + let future = async move { + tracing::debug!( + "will ask {} addresses for their ConnectedWatchers", + addr_len + ); + let mut hashes = vec![]; + for (path_watchable, addr) in addrs { + let hash = path_watchable.as_id(); + let re = addr.send(ConnectedWatchers).await?; + if re.observed_len == re.desired_len { + hashes.push(hash); + } + } + let list = list_hash(&hashes); + let state_value = StateValue::new(list); + let result = if hashes.len() == addr_len { + LocalResult::Ready { + observed_local: state_value, + } + } else { + LocalResult::NotReady { + observed_local: state_value, + } + }; + Ok::<_, anyhow::Error>(result) + }; + + Box::pin(future.into_actor(self).map(move |res, act, ctx| { + let Ok(res) = res else { + tracing::error!("Failed to get ConnectedWatchers: {:?}", res.unwrap_err()); + return Ok(()); + }; + + match res { + LocalResult::Ready { observed_local } => match act.status { + ServiceStatus::Idle => { + todo!("how?") + } + ServiceStatus::Reconciling { desired, .. } if desired == observed_local => { + tracing::debug!("will set ready, desired matched local"); + act.status = ServiceStatus::Ready { + observed: observed_local, + }; + } + ServiceStatus::Reconciling { + desired: _, + observed: observed_prev, + } => { + tracing::debug!("still reconciling, but now it's a new thing"); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: observed_prev, + }; + } + ServiceStatus::Ready { observed } if observed == observed_local => { + tracing::debug!("nothing to do!"); + } + ServiceStatus::Ready { observed } => { + tracing::debug!("downgrading to reconciling"); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: Some(observed), + }; + } + }, + LocalResult::NotReady { observed_local } => { + tracing::debug!("local result was not ready, setting to reconciling..."); + let observed_prev = act.status.observed(); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: observed_prev, }; - let state_writer = actor.state_writer.clone(); + // match act.status {} + } + } + state_writer.do_send(MonitorStatusWriter { + monitor_status: act.status, + }); + ctx.notify_later(MonitorAny, Duration::from_secs(1)); + Ok(()) + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryEvict; + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; - state_writer.do_send(MonitorStatusWriter { - monitor_status: actor.status, - }); + fn handle(&mut self, _msg: TryEvict, _ctx: &mut Self::Context) -> Self::Result { + let addrs = self.path_monitors.clone(); + let addr_len = addrs.len(); + + let future = async move { + tracing::debug!( + "will ask {} addresses for their ConnectedWatchers", + addr_len + ); + let mut removals = vec![]; + for (path_watchable, addr) in addrs { + let re = addr.send(ConnectedWatchers).await?; + if re.observed_len != re.desired_len { + removals.push(path_watchable); } - Err(err) => { - tracing::error!(?err); + } + + if !removals.is_empty() { + return Ok::<_, anyhow::Error>(Some(removals)); + } + + Ok::<_, anyhow::Error>(None) + }; + + Box::pin(future.into_actor(self).map(|res, act, _ctx| { + if let Ok(Some(removals)) = res { + tracing::debug!( + "removing {} path watchables because they never connected", + removals.len() + ); + for path_watchable in removals { + act.path_monitors.remove(&path_watchable); } } Ok(()) diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index c87d5715..e9392ca7 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -5,7 +5,6 @@ use crate::invoke_scope::{InvokeScope, Invoker}; use crate::monitor_input::{InputMonitor, MonitorInput}; use crate::path_monitors::{ConfigureRecipient, MonitorAny, PathMonitors}; use crate::tasks::task_spec::TaskSpec; -use crate::watchables::MonitorPathWatchables; use actix::ActorFutureExt; use actix::{ Actor, Addr, AsyncContext, Handler, ResponseActFuture, ResponseFuture, Running, WrapFuture, @@ -17,16 +16,16 @@ use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::internal_events::InternalEvents; use bsnext_dto::status_events::{ - server_status_hash, MonitorStatusReader, MonitorStatusWriter, ServerStatusReader, - ServerStatusWriter, ServiceStatus, StateValue, + monitor_status_hash, server_status_hash, MonitorStatusReader, MonitorStatusWriter, + ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, }; use bsnext_dto::task_events::TaskReportAndTree; use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; use bsnext_input::startup::StartupContext; +use bsnext_input::watchables::PathWatchables; use bsnext_input::{Input, InputArgs, InputCtx, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; -use std::hash::{DefaultHasher, Hash, Hasher}; use std::path::PathBuf; use tokio::sync::mpsc::Sender; use tokio::sync::oneshot::Receiver; @@ -223,40 +222,41 @@ impl StatusTracker { ServiceStatus::Reconciling { observed, .. } => { ServiceStatus::Reconciling { observed, desired } } - ServiceStatus::Ready { observed, .. } if observed != desired => { + ServiceStatus::Ready { observed } if observed != desired => { ServiceStatus::Reconciling { observed: Some(observed), desired, } } - ServiceStatus::Ready { observed, desired } => { - ServiceStatus::Ready { observed, desired } - } + ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, }; tracing::info!(id = id, "hasher for servers") } fn mark_monitors(&mut self, input: &Input) { tracing::info!("will mark monitors"); - let content = MonitorPathWatchables::new(input); - let mut hasher = DefaultHasher::new(); - content.hash(&mut hasher); - let id = hasher.finish(); - let desired = StateValue::new(id); + let path_watchables = PathWatchables::new(input); + let id = monitor_status_hash(&path_watchables); + let next_desired = StateValue::new(id); self.monitor_status = match self.monitor_status { ServiceStatus::Idle => ServiceStatus::Reconciling { observed: None, - desired, + desired: next_desired, }, - ServiceStatus::Reconciling { .. } => todo!("how can both be reconciling?"), - ServiceStatus::Ready { observed, .. } if observed != desired => { + ServiceStatus::Reconciling { + // here we drop the old desired state + desired: _, + observed, + } => ServiceStatus::Reconciling { + observed, + desired: next_desired, + }, + ServiceStatus::Ready { observed } if observed != next_desired => { ServiceStatus::Reconciling { observed: Some(observed), - desired, + desired: next_desired, } } - ServiceStatus::Ready { observed, desired } => { - ServiceStatus::Ready { observed, desired } - } + ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, }; tracing::info!(id = id, "hasher for servers"); // let id = server_status_hash(&input.servers); @@ -291,7 +291,9 @@ impl Handler for StatusTracker { type Result = ResponseFuture<()>; fn handle(&mut self, msg: MonitorStatusWriter, _ctx: &mut Self::Context) -> Self::Result { - tracing::info!(status = ?msg.monitor_status, "got next monitor status"); + tracing::info!("status writer for monitor"); + tracing::info!(next.status = ?msg.monitor_status, " --> "); + tracing::info!(prev.status = ?self.monitor_status, " --> "); self.monitor_status = msg.monitor_status; Box::pin(async move {}) } @@ -301,9 +303,11 @@ impl Handler for StatusTracker { type Result = ResponseFuture<()>; fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { - tracing::info!(status = ?msg.server_status, "got next server status"); + tracing::info!("status writer for servers"); + tracing::info!(next.status = ?msg.servers_status, " --> "); + tracing::info!(prev.status = ?self.servers_status, " --> "); // dbg!(&msg.server_status); - self.servers_status = msg.server_status; + self.servers_status = msg.servers_status; Box::pin(async move {}) } } From c03365071882612347581aeadd980fac4488f095 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Fri, 16 Oct 2026 08:26:09 +0100 Subject: [PATCH 06/16] some color --- crates/bsnext_dto/Cargo.toml | 1 + crates/bsnext_dto/src/external_events.rs | 5 +-- crates/bsnext_fs/examples/watch_cmd.rs | 2 +- crates/bsnext_fs/src/actor.rs | 6 ++-- crates/bsnext_fs/src/lib.rs | 13 ++++++-- crates/bsnext_fs/src/watch_path_handler.rs | 12 ++----- .../bsnext_path_monitor/src/path_monitor.rs | 4 +-- .../bsnext_system/src/handle_fs_changeset.rs | 31 +++++++++---------- 8 files changed, 38 insertions(+), 36 deletions(-) diff --git a/crates/bsnext_dto/Cargo.toml b/crates/bsnext_dto/Cargo.toml index e7fc7efe..4cd848a8 100644 --- a/crates/bsnext_dto/Cargo.toml +++ b/crates/bsnext_dto/Cargo.toml @@ -20,3 +20,4 @@ typeshare = { workspace = true } anyhow = { workspace = true } miette = { workspace = true } tracing = { workspace = true } +console = { version = "0.16.6" } diff --git a/crates/bsnext_dto/src/external_events.rs b/crates/bsnext_dto/src/external_events.rs index 109c8575..ace905ae 100644 --- a/crates/bsnext_dto/src/external_events.rs +++ b/crates/bsnext_dto/src/external_events.rs @@ -8,6 +8,7 @@ use crate::{ use bsnext_output::OutputWriterTrait; use bsnext_task::task_report::TaskReport; use bsnext_task::NodePath; +use console::style; use std::collections::HashMap; use std::io::Write; use std::path::PathBuf; @@ -169,11 +170,11 @@ impl OutputWriterTrait for ExternalEventsDTO { Ok(()) } ExternalEventsDTO::InputError(InputErrorDetailDTO { error }) => { - writeln!(sink, "{error}")?; + writeln!(sink, "{} {error}", style("[warning]").on_yellow())?; Ok(()) } ExternalEventsDTO::StartupError(StartupErrorDTO { error }) => { - writeln!(sink, "{error}")?; + writeln!(sink, "{} {error}", style("[error]").on_red())?; Ok(()) } } diff --git a/crates/bsnext_fs/examples/watch_cmd.rs b/crates/bsnext_fs/examples/watch_cmd.rs index f2337b75..96590778 100644 --- a/crates/bsnext_fs/examples/watch_cmd.rs +++ b/crates/bsnext_fs/examples/watch_cmd.rs @@ -71,7 +71,7 @@ impl actix::Handler for Example { fn handle(&mut self, msg: FsEvent, _ctx: &mut Self::Context) { tracing::info!(running = self.running, " ++ incoming"); tracing::info!(cmd = self.cmd.0.to_str()); - tracing::info!(?msg.kind); + tracing::info!(kind = ?msg.kind()); } } diff --git a/crates/bsnext_fs/src/actor.rs b/crates/bsnext_fs/src/actor.rs index ef6f8866..c6420d6f 100644 --- a/crates/bsnext_fs/src/actor.rs +++ b/crates/bsnext_fs/src/actor.rs @@ -94,10 +94,8 @@ impl FsWatcher { tracing::trace!("ignored: count: {}: {ignored}", ignore.len()); if any_match && !ignored { - let as_fs_event = FsEvent { - kind: FsEventKind::Change(PathDescriptionOwned::from(&pd)), - fs_event_ctx: ctx, - }; + let as_fs_event = + FsEvent::new(FsEventKind::Change(PathDescriptionOwned::from(&pd)), ctx); receiver.do_send(as_fs_event); } else { tracing::trace!( diff --git a/crates/bsnext_fs/src/lib.rs b/crates/bsnext_fs/src/lib.rs index 176a4f4a..b75d5cc6 100644 --- a/crates/bsnext_fs/src/lib.rs +++ b/crates/bsnext_fs/src/lib.rs @@ -86,11 +86,20 @@ impl Default for FsEventContext { #[derive(actix::Message, Debug, Clone, Hash, PartialEq, PartialOrd, Eq, Ord)] #[rtype(result = "()")] pub struct FsEvent { - pub kind: FsEventKind, - pub fs_event_ctx: FsEventContext, + kind: FsEventKind, + fs_event_ctx: FsEventContext, } impl FsEvent { + pub fn kind(&self) -> &FsEventKind { + &self.kind + } + pub fn fs_event_ctx(&self) -> &FsEventContext { + &self.fs_event_ctx + } + pub fn new(kind: FsEventKind, fs_event_ctx: FsEventContext) -> Self { + Self { kind, fs_event_ctx } + } pub fn changed>(absolute: A, relative: A, ctx_id: u64) -> Self { Self { kind: FsEventKind::Change(PathDescriptionOwned { diff --git a/crates/bsnext_fs/src/watch_path_handler.rs b/crates/bsnext_fs/src/watch_path_handler.rs index b3136aad..5a0bdb61 100644 --- a/crates/bsnext_fs/src/watch_path_handler.rs +++ b/crates/bsnext_fs/src/watch_path_handler.rs @@ -41,20 +41,14 @@ impl Handler for FsWatcher { let evt = FsEventKind::PathAdded(PathAddedEvent { path: relative.clone(), }); - self.receiver.do_send(FsEvent { - kind: evt, - fs_event_ctx: self.ctx, - }) + self.receiver.do_send(FsEvent::new(evt, self.ctx)) } Err(err) => { - tracing::error!("cannot watch: {}", err); + tracing::debug!("cannot watch, error: {}", err); let evt = FsEventKind::PathNotFoundError(PathEvent { path: msg.path.clone(), }); - self.receiver.do_send(FsEvent { - kind: evt, - fs_event_ctx: self.ctx, - }); + self.receiver.do_send(FsEvent::new(evt, self.ctx)); ctx.stop(); } } diff --git a/crates/bsnext_path_monitor/src/path_monitor.rs b/crates/bsnext_path_monitor/src/path_monitor.rs index b8d2cee8..55d4b601 100644 --- a/crates/bsnext_path_monitor/src/path_monitor.rs +++ b/crates/bsnext_path_monitor/src/path_monitor.rs @@ -160,7 +160,7 @@ impl StreamHandler> for PathMonitor { debug!(" └ {:?}", unique); let outgoing = unique .into_iter() - .filter_map(|e| match &e.kind { + .filter_map(|e| match e.kind() { FsEventKind::Change(pd) => Some(pd.to_owned()), _ => None, }) @@ -252,7 +252,7 @@ impl Handler for PathMonitor { let span = debug_span!("Handler->FsEvent->PathMonitor"); let _guard = span.enter(); let sender = self.inner_sender.clone(); - match &msg.kind { + match &msg.kind() { FsEventKind::Change(PathDescriptionOwned { .. }) => { debug!("FsEventKind::Change"); Arbiter::current().spawn(async move { diff --git a/crates/bsnext_system/src/handle_fs_changeset.rs b/crates/bsnext_system/src/handle_fs_changeset.rs index b8bce0b4..862d2db8 100644 --- a/crates/bsnext_system/src/handle_fs_changeset.rs +++ b/crates/bsnext_system/src/handle_fs_changeset.rs @@ -15,7 +15,6 @@ use bsnext_fs::{ }; use bsnext_input::bs_live_built_in_task::BsLiveBuiltInTask; use bsnext_input::route::WatchSpec; -use bsnext_input::{InputError, PathDefinition, PathDefs, PathError}; use bsnext_path_monitor::{Changeset, PathMonitorChangeset}; use bsnext_task::task_trigger::FsChangesTrigger; use std::path::PathBuf; @@ -65,15 +64,15 @@ impl BsSystem { addr: Addr, debounce: Debounce, ) -> Option { - match &fs_event.kind { - FsEventKind::Change(ch) if fs_event.fs_event_ctx.is_root() => { + match &fs_event.kind() { + FsEventKind::Change(ch) if fs_event.fs_event_ctx().is_root() => { tracing::info!("fs_event_ctx=root"); addr.do_send(ResolveInputAgain); None } FsEventKind::Change(inner) => { let servers_addr = self.servers().clone(); - let evt = handle_any_change(servers_addr, &fs_event.fs_event_ctx, inner); + let evt = handle_any_change(servers_addr, fs_event.fs_event_ctx(), inner); Some(evt) } FsEventKind::PathAdded(path) => handle_path_added(path, &debounce), @@ -136,21 +135,21 @@ fn handle_any_change( )) } -fn handle_path_not_found(cwd: PathBuf, pdo: &PathEvent) -> Option { +fn handle_path_not_found(_cwd: PathBuf, pdo: &PathEvent) -> Option { let as_str = pdo.path.to_string_lossy().to_string(); - let cwd = cwd.clone(); - let abs = cwd.join(&as_str); - let def = PathDefinition { - input: as_str, - cwd: cwd.clone(), - absolute: abs, - }; - let err = InputError::PathError(PathError::MissingPaths { - paths: PathDefs(vec![def]), - }); + // let cwd = cwd.clone(); + // let abs = cwd.join(&as_str); + // let def = PathDefinition { + // input: as_str, + // cwd: cwd.clone(), + // absolute: abs, + // }; + // let err = InputError::PathError(PathError::MissingPaths { + // paths: PathDefs(vec![def]), + // }); Some(ExternalEventsDTO::InputError(InputErrorDetailDTO { - error: err.to_string(), + error: format!("{} not found, trying again in 2 second intervals", as_str), })) } From 952cf85c17b2f29e7e7b2e916a93b34f06857d83 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Sat, 17 Oct 2026 10:35:11 +0100 Subject: [PATCH 07/16] some moving --- Cargo.lock | 35 ++- crates/bsnext_dto/src/status_events.rs | 16 ++ .../src/watchables/path_watchable.rs | 32 ++- .../bsnext_system/src/handle_fs_changeset.rs | 29 +- crates/bsnext_system/src/lib.rs | 1 + crates/bsnext_system/src/path_monitors/mod.rs | 269 +++++++++++++----- crates/bsnext_system/src/status_tracker.rs | 175 ++++++++++++ crates/bsnext_system/src/system.rs | 154 +--------- 8 files changed, 473 insertions(+), 238 deletions(-) create mode 100644 crates/bsnext_system/src/status_tracker.rs diff --git a/Cargo.lock b/Cargo.lock index edbe3272..4db5ec4a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -516,6 +516,7 @@ dependencies = [ "bsnext_output", "bsnext_task", "bsnext_tracing", + "console 0.16.6", "miette", "serde", "serde_json", @@ -891,12 +892,24 @@ version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" dependencies = [ - "encode_unicode", + "encode_unicode 0.3.6", "lazy_static", "libc", "windows-sys 0.52.0", ] +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode 1.0.0", + "libc", + "unicode-width 0.2.2", + "windows-sys 0.61.2", +] + [[package]] name = "convert_case" version = "0.11.0" @@ -1129,6 +1142,12 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -1345,7 +1364,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" dependencies = [ - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -1671,7 +1690,7 @@ version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eab73f58e59ca6526037208f0e98851159ec1633cf17b6cd2e1f2c3fd5d53cc" dependencies = [ - "console", + "console 0.15.8", "lazy_static", "linked-hash-map", "serde", @@ -1896,7 +1915,7 @@ dependencies = [ "terminal_size", "textwrap", "thiserror 1.0.60", - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -3288,7 +3307,7 @@ checksum = "23d434d3f8967a09480fb04132ebe0a3e088c173e6d0ee7897abbdf4eab0f8b9" dependencies = [ "smawk", "unicode-linebreak", - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -3831,6 +3850,12 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "unindent" version = "0.2.3" diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs index 064ab742..34dc0250 100644 --- a/crates/bsnext_dto/src/status_events.rs +++ b/crates/bsnext_dto/src/status_events.rs @@ -1,7 +1,9 @@ use crate::ActiveServer; use bsnext_input::server_config::ServerConfig; +use bsnext_input::watchables::path_watchable::PathWatchable; use bsnext_input::watchables::PathWatchables; use bsnext_input::Input; +use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; #[derive(Debug, actix::Message)] @@ -22,6 +24,7 @@ pub struct MonitorStatusReader; #[rtype(result = "()")] pub struct MonitorStatusWriter { pub monitor_status: ServiceStatus, + pub monitor_resource_status: HashMap, } #[derive(Debug, Clone, Hash, Copy, Eq, Ord, PartialEq, PartialOrd)] @@ -35,6 +38,19 @@ impl StateValue { } } +#[derive(Debug, Default, Clone, Eq, PartialEq)] +pub enum ResourceStatus { + #[default] + Pending, + Waiting { + reason: String, + }, + Ready, + Failed { + reason: String, + }, +} + #[derive(Debug, Default, Clone, Hash, Copy, Eq, PartialEq, Ord, PartialOrd)] pub enum ServiceStatus { #[default] diff --git a/crates/bsnext_input/src/watchables/path_watchable.rs b/crates/bsnext_input/src/watchables/path_watchable.rs index 56fad7e4..6ef70560 100644 --- a/crates/bsnext_input/src/watchables/path_watchable.rs +++ b/crates/bsnext_input/src/watchables/path_watchable.rs @@ -1,4 +1,4 @@ -use std::fmt::{Display, Formatter}; +use std::fmt::{Debug, Display, Formatter}; use std::hash::{DefaultHasher, Hash, Hasher}; use crate::route::WatchSpec; @@ -7,13 +7,41 @@ use crate::watchables::route_watchable::RouteWatchable; use crate::watchables::server_watchable::ServerWatchable; use std::path::Path; -#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] +#[derive(PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] pub enum PathWatchable { Server(ServerWatchable), Route(RouteWatchable), Any(AnyWatchable), } +impl Debug for PathWatchable { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + match &self { + PathWatchable::Server(server) => { + let lines = server + .dirs + .iter() + .map(|x| format!("'{}'", x.display())) + .collect::>() + .join(", "); + write!(f, "PathWatchable::Server({lines})")?; + } + PathWatchable::Route(route) => { + write!(f, "PathWatchable::Route('{}')", route.dir.display())?; + } + PathWatchable::Any(any) => { + let lines = any + .dirs + .iter() + .map(|x| format!("'{}'", x.display())) + .collect::>() + .join(", "); + write!(f, "PathWatchable::Any({lines})")?; + } + } + Ok(()) + } +} impl Display for PathWatchable { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match &self { diff --git a/crates/bsnext_system/src/handle_fs_changeset.rs b/crates/bsnext_system/src/handle_fs_changeset.rs index 862d2db8..90dda79a 100644 --- a/crates/bsnext_system/src/handle_fs_changeset.rs +++ b/crates/bsnext_system/src/handle_fs_changeset.rs @@ -8,13 +8,14 @@ use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::file_changed_handler::FileChanged; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; -use bsnext_dto::{InputErrorDetailDTO, StoppedWatchingDTO, WatchingDTO}; +use bsnext_dto::{StoppedWatchingDTO, WatchingDTO}; use bsnext_fs::{ BufferedChangeset, Debounce, FsEvent, FsEventContext, FsEventKind, PathAddedEvent, PathDescriptionOwned, PathEvent, }; use bsnext_input::bs_live_built_in_task::BsLiveBuiltInTask; use bsnext_input::route::WatchSpec; +use bsnext_input::PathDefinition; use bsnext_path_monitor::{Changeset, PathMonitorChangeset}; use bsnext_task::task_trigger::FsChangesTrigger; use std::path::PathBuf; @@ -135,22 +136,18 @@ fn handle_any_change( )) } -fn handle_path_not_found(_cwd: PathBuf, pdo: &PathEvent) -> Option { +#[tracing::instrument] +fn handle_path_not_found(cwd: PathBuf, pdo: &PathEvent) -> Option { let as_str = pdo.path.to_string_lossy().to_string(); - // let cwd = cwd.clone(); - // let abs = cwd.join(&as_str); - // let def = PathDefinition { - // input: as_str, - // cwd: cwd.clone(), - // absolute: abs, - // }; - // let err = InputError::PathError(PathError::MissingPaths { - // paths: PathDefs(vec![def]), - // }); - - Some(ExternalEventsDTO::InputError(InputErrorDetailDTO { - error: format!("{} not found, trying again in 2 second intervals", as_str), - })) + let cwd = cwd.clone(); + let abs = cwd.join(&as_str); + let def = PathDefinition { + input: as_str, + cwd: cwd.clone(), + absolute: abs, + }; + tracing::debug!(?def, "path not found"); + None } fn handle_path_added(path: &PathAddedEvent, debounce: &Debounce) -> Option { diff --git a/crates/bsnext_system/src/lib.rs b/crates/bsnext_system/src/lib.rs index 2f9ba2a3..1e4a354f 100644 --- a/crates/bsnext_system/src/lib.rs +++ b/crates/bsnext_system/src/lib.rs @@ -14,6 +14,7 @@ pub mod path_monitors; pub mod run; mod servers; pub mod start; +mod status_tracker; mod system; pub mod tasks; pub mod watch; diff --git a/crates/bsnext_system/src/path_monitors/mod.rs b/crates/bsnext_system/src/path_monitors/mod.rs index 52891ee4..5af9708b 100644 --- a/crates/bsnext_system/src/path_monitors/mod.rs +++ b/crates/bsnext_system/src/path_monitors/mod.rs @@ -1,7 +1,7 @@ -use actix::ActorFutureExt; use actix::{Actor, Addr, AsyncContext, Recipient, ResponseActFuture, ResponseFuture, WrapFuture}; +use actix::{ActorFutureExt, Running}; use bsnext_dto::status_events::{ - list_hash, MonitorStatusReader, MonitorStatusWriter, ServiceStatus, StateValue, + list_hash, MonitorStatusReader, MonitorStatusWriter, ResourceStatus, ServiceStatus, StateValue, }; use bsnext_fs::{Debounce, FsEventContext}; use bsnext_input::watchables::path_watchable::PathWatchable; @@ -13,12 +13,57 @@ use bsnext_path_monitor::PathMonitorChangeset; use std::collections::{BTreeSet, HashMap}; use std::path::PathBuf; use std::time::Duration; -use tracing::{debug, debug_span}; +use tracing::{debug, debug_span, Instrument}; + +#[derive(Debug, Default, Clone)] +enum LocalResource { + #[default] + Pending, + Waiting { + reason: String, + attempts: usize, + }, + Ready, + Failed { + reason: String, + }, +} + +impl From<&'_ LocalResource> for ResourceStatus { + fn from(value: &'_ LocalResource) -> Self { + match value { + LocalResource::Pending => ResourceStatus::Pending, + LocalResource::Waiting { reason, .. } => ResourceStatus::Waiting { + reason: reason.clone(), + }, + LocalResource::Ready => ResourceStatus::Ready, + LocalResource::Failed { reason } => ResourceStatus::Failed { + reason: reason.clone(), + }, + } + } +} + +#[derive(Debug, Default)] +struct LocalState { + inner: HashMap, +} + +impl LocalState { + pub(crate) fn as_resource_status(&self) -> HashMap { + let mut resource_status = HashMap::new(); + for (path_watchable, local_resource) in &self.inner { + resource_status.insert(path_watchable.clone(), local_resource.into()); + } + resource_status + } +} #[derive(Debug)] pub struct PathMonitors { cwd: PathBuf, path_monitors: HashMap>, + local_state: LocalState, state_reader: Recipient, state_writer: Recipient, status: ServiceStatus, @@ -35,6 +80,7 @@ impl PathMonitors { Self { cwd, path_monitors: Default::default(), + local_state: Default::default(), state_writer, state_reader, status_hashes: vec![], @@ -46,6 +92,21 @@ impl PathMonitors { impl actix::Actor for PathMonitors { type Context = actix::Context; + + fn started(&mut self, _ctx: &mut Self::Context) { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "started"); + } + + fn stopping(&mut self, _ctx: &mut Self::Context) -> Running { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "stopping"); + Running::Stop + } + + fn stopped(&mut self, _ctx: &mut Self::Context) { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "stopped"); + self.local_state.inner.clear(); + todo!("we cleared all local state here...") + } } #[derive(actix::Message)] @@ -97,12 +158,25 @@ impl actix::Handler for PathMonitors { let incoming = inner.watchables.iter().collect::>(); let in_both = incoming.intersection(&existing).collect::>(); - let to_add = incoming.difference(&existing).collect::>(); + let to_skip = self + .local_state + .inner + .iter() + .filter_map(|(k, v)| match v { + LocalResource::Failed { .. } => Some(k.clone()), + _ => None, + }) + .collect::>(); + let to_add = incoming + .difference(&existing) + .filter(|x| !to_skip.contains(x)) + .collect::>(); let to_remove = existing.difference(&incoming).collect::>(); debug!("{} duplicates", in_both.len()); debug!("{} monitors to remove", to_remove.len()); debug!("{} monitors to add", to_add.len()); + debug!("{} monitors to skip", to_skip.len()); for any_watchable in to_remove { if let Some(path_monitor_addr) = self.path_monitors.get(any_watchable) { @@ -145,9 +219,11 @@ impl actix::Handler for PathMonitors { ); let path_monitor_addr = path_monitor.start(); - + if let Some(matching_state) = self.local_state.inner.get(path_watchable) { + tracing::debug!(?matching_state) + } ctx.notify(InsertMonitor( - (*path_watchable).clone(), + (**path_watchable).clone(), path_monitor_addr, paths, )) @@ -269,24 +345,6 @@ impl actix::Handler for PathMonitors { } } Ok::<_, anyhow::Error>(()) - // if local_id.is_none() { - // tracing::info!("There's something to reconcile..."); - // } else if local_id.is_some_and(|v| v != expected_id) { - // tracing::info!("There's something to reconcile..."); - // } else { - // - // } - // dbg!("huh?", will_reconcile); - // let watchables = PathWatchables::new(&input); - // let content_hash = monitor_status_hash(&watchables); - // let list = list_hash(&local_hashes); - // - // if expected_id == list { - // todo!("it became 'ready'"); - // } - // tracing::debug!("{} computed from input, {} observed", content_hash, list); - // let request = RequestMonitor::new(watchables, recipient, cwd); - // monitors_addr.send(request).await?; })) } } @@ -307,15 +365,25 @@ impl actix::Handler for PathMonitors { }; let monitors_addr = ctx.address(); let cwd = self.cwd.clone(); + let watchables = PathWatchables::new(&input); + for x in &watchables.watchables { + self.local_state.inner.entry(x.clone()).or_default(); + } + self.state_writer.do_send(MonitorStatusWriter { + monitor_status: self.status, + monitor_resource_status: self.local_state.as_resource_status(), + }); + let states = self.local_state.inner.clone(); Box::pin( async move { - tracing::debug!("will try to reconcile things..."); - let watchables = PathWatchables::new(&input); - // let content_hash = monitor_status_hash(&watchables); + let span = tracing::debug_span!("try reconcile"); + let _enter = span.enter(); + tracing::debug!(?states); let request = RequestMonitor::new(watchables, recipient, cwd); monitors_addr.send(request).await?; Ok::<_, anyhow::Error>(()) } + .in_current_span() .into_actor(self) .map(|_result, _actor, ctx| { ctx.notify(TryRead); @@ -333,38 +401,90 @@ impl actix::Handler for PathMonitors { type Result = ResponseActFuture>; fn handle(&mut self, _msg: TryRead, _ctx: &mut Self::Context) -> Self::Result { - let addrs = self.path_monitors.clone(); - let addr_len = addrs.len(); + let jobs = self + .path_monitors + .clone() + .iter() + .map(|(path_watchable, v)| { + ( + path_watchable.clone(), + ( + v.clone(), + self.local_state + .inner + .get(path_watchable) + .map(ToOwned::to_owned) + .expect("If we get here there's a buug"), + ), + ) + }) + .collect::, LocalResource)>>(); + let jobs_len = jobs.len(); let state_writer = self.state_writer.clone(); #[derive(Debug)] enum LocalResult { - Ready { observed_local: StateValue }, - NotReady { observed_local: StateValue }, + Ready { + observed_status: StateValue, + local_states: HashMap, + }, + NotReady { + observed_status: StateValue, + local_states: HashMap, + }, } let future = async move { tracing::debug!( "will ask {} addresses for their ConnectedWatchers", - addr_len + jobs_len ); let mut hashes = vec![]; - for (path_watchable, addr) in addrs { + let mut local_states: HashMap = HashMap::new(); + for (path_watchable, (addr, local_resource)) in jobs { let hash = path_watchable.as_id(); let re = addr.send(ConnectedWatchers).await?; - if re.observed_len == re.desired_len { + let is_good = re.observed_len == re.desired_len; + if is_good { hashes.push(hash); + local_states.insert(path_watchable, LocalResource::Ready); + } else { + let next = match local_resource { + LocalResource::Pending => LocalResource::Waiting { + reason: "didn't start".to_string(), + attempts: 1, + }, + LocalResource::Waiting { attempts, .. } if attempts == 5 => { + LocalResource::Failed { + reason: format!("max attempts reached ({})", attempts), + } + } + LocalResource::Waiting { attempts, .. } => LocalResource::Waiting { + reason: "didn't start".to_string(), + attempts: attempts + 1, + }, + LocalResource::Ready => LocalResource::Waiting { + reason: "was ready, lost?".to_string(), + attempts: 0, + }, + LocalResource::Failed { reason: _ } => LocalResource::Failed { + reason: "failed again...".to_string(), + }, + }; + local_states.insert(path_watchable, next); } } let list = list_hash(&hashes); let state_value = StateValue::new(list); - let result = if hashes.len() == addr_len { + let result = if hashes.len() == jobs_len { LocalResult::Ready { - observed_local: state_value, + observed_status: state_value, + local_states, } } else { LocalResult::NotReady { - observed_local: state_value, + observed_status: state_value, + local_states, } }; Ok::<_, anyhow::Error>(result) @@ -377,39 +497,53 @@ impl actix::Handler for PathMonitors { }; match res { - LocalResult::Ready { observed_local } => match act.status { - ServiceStatus::Idle => { - todo!("how?") - } - ServiceStatus::Reconciling { desired, .. } if desired == observed_local => { - tracing::debug!("will set ready, desired matched local"); - act.status = ServiceStatus::Ready { - observed: observed_local, - }; - } - ServiceStatus::Reconciling { - desired: _, - observed: observed_prev, - } => { - tracing::debug!("still reconciling, but now it's a new thing"); - act.status = ServiceStatus::Reconciling { - desired: observed_local, + LocalResult::Ready { + observed_status: observed_local, + local_states, + } => { + act.local_state = LocalState { + inner: local_states, + }; + match act.status { + ServiceStatus::Idle => { + todo!("how?") + } + ServiceStatus::Reconciling { desired, .. } if desired == observed_local => { + tracing::debug!("will set ready, desired matched local"); + act.status = ServiceStatus::Ready { + observed: observed_local, + }; + } + ServiceStatus::Reconciling { + desired: _, observed: observed_prev, - }; - } - ServiceStatus::Ready { observed } if observed == observed_local => { - tracing::debug!("nothing to do!"); + } => { + tracing::debug!("still reconciling, but now it's a new thing"); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: observed_prev, + }; + } + ServiceStatus::Ready { observed } if observed == observed_local => { + tracing::debug!("nothing to do!"); + } + ServiceStatus::Ready { observed } => { + tracing::debug!("downgrading to reconciling"); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: Some(observed), + }; + } } - ServiceStatus::Ready { observed } => { - tracing::debug!("downgrading to reconciling"); - act.status = ServiceStatus::Reconciling { - desired: observed_local, - observed: Some(observed), - }; - } - }, - LocalResult::NotReady { observed_local } => { + } + LocalResult::NotReady { + observed_status: observed_local, + local_states, + } => { tracing::debug!("local result was not ready, setting to reconciling..."); + act.local_state = LocalState { + inner: local_states, + }; let observed_prev = act.status.observed(); act.status = ServiceStatus::Reconciling { desired: observed_local, @@ -420,6 +554,7 @@ impl actix::Handler for PathMonitors { } state_writer.do_send(MonitorStatusWriter { monitor_status: act.status, + monitor_resource_status: act.local_state.as_resource_status(), }); ctx.notify_later(MonitorAny, Duration::from_secs(1)); Ok(()) diff --git a/crates/bsnext_system/src/status_tracker.rs b/crates/bsnext_system/src/status_tracker.rs new file mode 100644 index 00000000..ae45c448 --- /dev/null +++ b/crates/bsnext_system/src/status_tracker.rs @@ -0,0 +1,175 @@ +use crate::system::Accept; +use actix::{Actor, Handler, ResponseFuture}; +use bsnext_dto::status_events::{ + monitor_status_hash, server_status_hash, MonitorStatusReader, MonitorStatusWriter, + ResourceStatus, ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, +}; +use bsnext_input::watchables::path_watchable::PathWatchable; +use bsnext_input::watchables::PathWatchables; +use bsnext_input::Input; +use std::collections::HashMap; +use std::path::PathBuf; +use tracing::debug_span; + +pub struct StatusTracker { + input: Input, + cwd: PathBuf, + servers_status: ServiceStatus, + monitor_status: ServiceStatus, + monitor_resource_status: HashMap, +} + +impl Actor for StatusTracker { + type Context = actix::Context; +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: Accept, _ctx: &mut Self::Context) -> Self::Result { + self.mark_servers(&msg.input); + self.mark_monitors(&msg.input); + self.input = msg.input; + self.cwd = msg.cwd; + tracing::info!(status = ?self.servers_status, "did mark servers, next state"); + tracing::info!(status = ?self.monitor_status, "did mark monitors, next state"); + Box::pin(async move { + let _a = ""; + }) + } +} + +impl StatusTracker { + pub fn new(cwd: PathBuf) -> Self { + Self { + servers_status: ServiceStatus::default(), + monitor_status: ServiceStatus::default(), + monitor_resource_status: Default::default(), + input: Input::default(), + cwd, + } + } + fn mark_servers(&mut self, input: &Input) { + tracing::info!("will mark servers"); + let id = server_status_hash(&input.servers); + let desired = StateValue::new(id); + self.servers_status = match self.servers_status { + ServiceStatus::Idle => ServiceStatus::Reconciling { + observed: None, + desired, + }, + ServiceStatus::Reconciling { observed, .. } => { + ServiceStatus::Reconciling { observed, desired } + } + ServiceStatus::Ready { observed } if observed != desired => { + ServiceStatus::Reconciling { + observed: Some(observed), + desired, + } + } + ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, + }; + tracing::info!(id = id, "hasher for servers") + } + fn mark_monitors(&mut self, input: &Input) { + tracing::info!("will mark monitors"); + let path_watchables = PathWatchables::new(input); + let id = monitor_status_hash(&path_watchables); + let next_desired = StateValue::new(id); + self.monitor_status = match self.monitor_status { + ServiceStatus::Idle => ServiceStatus::Reconciling { + observed: None, + desired: next_desired, + }, + ServiceStatus::Reconciling { + // here we drop the old desired state + desired: _, + observed, + } => ServiceStatus::Reconciling { + observed, + desired: next_desired, + }, + ServiceStatus::Ready { observed } if observed != next_desired => { + ServiceStatus::Reconciling { + observed: Some(observed), + desired: next_desired, + } + } + ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, + }; + tracing::info!(id = id, "hasher for servers"); + // let id = server_status_hash(&input.servers); + // let desired = StateValue::new(id); + // todo!("how to compute monitors?") + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServiceStatus, Input)>; + + fn handle(&mut self, _msg: ServerStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.servers_status, + self.input.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServiceStatus, Input)>; + + fn handle(&mut self, _msg: MonitorStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.monitor_status, + self.input.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = (); + + fn handle(&mut self, msg: MonitorStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + let span = tracing::info_span!("monitor status"); + let _g = span.enter(); + tracing::debug!(prev.status = ?self.monitor_status, " --> "); + tracing::debug!(prev.resource_status = ?self.monitor_resource_status, " --> "); + tracing::debug!(next.status = ?msg.monitor_status, " --> "); + tracing::debug!(next.resource_status = ?msg.monitor_resource_status, " --> "); + for (id, status) in &msg.monitor_resource_status { + let span = debug_span!("monitor resource status", id = ?id); + let _g = span.enter(); + let did_transition = self + .monitor_resource_status + .get(id) + .is_some_and(|x| x != status); + tracing::info!(did_transition); + if did_transition { + match status { + ResourceStatus::Pending => {} + ResourceStatus::Waiting { reason } => { + tracing::info!("waiting! reason: {reason}") + } + ResourceStatus::Ready => tracing::info!("ready!"), + ResourceStatus::Failed { reason } => tracing::info!("failed reason: {reason}!"), + } + } + } + self.monitor_status = msg.monitor_status; + self.monitor_resource_status = msg.monitor_resource_status; + println!("...") + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + tracing::info!("status writer for servers"); + tracing::info!(next.status = ?msg.servers_status, " --> "); + tracing::info!(prev.status = ?self.servers_status, " --> "); + // dbg!(&msg.server_status); + self.servers_status = msg.servers_status; + Box::pin(async move {}) + } +} diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index e9392ca7..43f04cad 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -4,6 +4,7 @@ use crate::input_fs::from_input_path; use crate::invoke_scope::{InvokeScope, Invoker}; use crate::monitor_input::{InputMonitor, MonitorInput}; use crate::path_monitors::{ConfigureRecipient, MonitorAny, PathMonitors}; +use crate::status_tracker::StatusTracker; use crate::tasks::task_spec::TaskSpec; use actix::ActorFutureExt; use actix::{ @@ -15,15 +16,10 @@ use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; use bsnext_dto::internal_events::InternalEvents; -use bsnext_dto::status_events::{ - monitor_status_hash, server_status_hash, MonitorStatusReader, MonitorStatusWriter, - ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, -}; use bsnext_dto::task_events::TaskReportAndTree; use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; use bsnext_input::startup::StartupContext; -use bsnext_input::watchables::PathWatchables; use bsnext_input::{Input, InputArgs, InputCtx, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; use std::path::PathBuf; @@ -93,12 +89,12 @@ impl BsSystem { let invoker = Invoker::new(capabilities_addr.clone(), any_event_sender.clone()); let invoker_addr = invoker.start(); let fs_task_tracker = FsTaskTracker::new(invoker_addr.clone().recipient()).start(); - let monitor = PathMonitors::new( + let path_monitors = PathMonitors::new( cwd.clone(), status_tracker.clone().recipient(), status_tracker.clone().recipient(), ); - let monitor = monitor.start(); + let monitor = path_monitors.start(); BsSystem { self_addr: None, servers_addr, @@ -167,149 +163,11 @@ impl BsSystem { } } -pub struct StatusTracker { - input: Input, - cwd: PathBuf, - servers_status: ServiceStatus, - monitor_status: ServiceStatus, -} - -impl Actor for StatusTracker { - type Context = actix::Context; -} - #[derive(Debug, actix::Message)] #[rtype(result = "()")] -struct Accept { - input: Input, - cwd: PathBuf, -} - -impl Handler for StatusTracker { - type Result = ResponseFuture<()>; - - fn handle(&mut self, msg: Accept, _ctx: &mut Self::Context) -> Self::Result { - self.mark_servers(&msg.input); - self.mark_monitors(&msg.input); - self.input = msg.input; - self.cwd = msg.cwd; - tracing::info!(status = ?self.servers_status, "did mark servers, next state"); - tracing::info!(status = ?self.monitor_status, "did mark monitors, next state"); - Box::pin(async move { - let _a = ""; - }) - } -} - -impl StatusTracker { - pub fn new(cwd: PathBuf) -> Self { - Self { - servers_status: ServiceStatus::default(), - monitor_status: ServiceStatus::default(), - input: Input::default(), - cwd, - } - } - fn mark_servers(&mut self, input: &Input) { - tracing::info!("will mark servers"); - let id = server_status_hash(&input.servers); - let desired = StateValue::new(id); - self.servers_status = match self.servers_status { - ServiceStatus::Idle => ServiceStatus::Reconciling { - observed: None, - desired, - }, - ServiceStatus::Reconciling { observed, .. } => { - ServiceStatus::Reconciling { observed, desired } - } - ServiceStatus::Ready { observed } if observed != desired => { - ServiceStatus::Reconciling { - observed: Some(observed), - desired, - } - } - ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, - }; - tracing::info!(id = id, "hasher for servers") - } - fn mark_monitors(&mut self, input: &Input) { - tracing::info!("will mark monitors"); - let path_watchables = PathWatchables::new(input); - let id = monitor_status_hash(&path_watchables); - let next_desired = StateValue::new(id); - self.monitor_status = match self.monitor_status { - ServiceStatus::Idle => ServiceStatus::Reconciling { - observed: None, - desired: next_desired, - }, - ServiceStatus::Reconciling { - // here we drop the old desired state - desired: _, - observed, - } => ServiceStatus::Reconciling { - observed, - desired: next_desired, - }, - ServiceStatus::Ready { observed } if observed != next_desired => { - ServiceStatus::Reconciling { - observed: Some(observed), - desired: next_desired, - } - } - ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, - }; - tracing::info!(id = id, "hasher for servers"); - // let id = server_status_hash(&input.servers); - // let desired = StateValue::new(id); - // todo!("how to compute monitors?") - } -} - -impl Handler for StatusTracker { - type Result = ResponseFuture<(ServiceStatus, Input)>; - - fn handle(&mut self, _msg: ServerStatusReader, _ctx: &mut Self::Context) -> Self::Result { - Box::pin(futures::future::ready(( - self.servers_status, - self.input.clone(), - ))) - } -} - -impl Handler for StatusTracker { - type Result = ResponseFuture<(ServiceStatus, Input)>; - - fn handle(&mut self, _msg: MonitorStatusReader, _ctx: &mut Self::Context) -> Self::Result { - Box::pin(futures::future::ready(( - self.monitor_status, - self.input.clone(), - ))) - } -} - -impl Handler for StatusTracker { - type Result = ResponseFuture<()>; - - fn handle(&mut self, msg: MonitorStatusWriter, _ctx: &mut Self::Context) -> Self::Result { - tracing::info!("status writer for monitor"); - tracing::info!(next.status = ?msg.monitor_status, " --> "); - tracing::info!(prev.status = ?self.monitor_status, " --> "); - self.monitor_status = msg.monitor_status; - Box::pin(async move {}) - } -} - -impl Handler for StatusTracker { - type Result = ResponseFuture<()>; - - fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { - tracing::info!("status writer for servers"); - tracing::info!(next.status = ?msg.servers_status, " --> "); - tracing::info!(prev.status = ?self.servers_status, " --> "); - // dbg!(&msg.server_status); - self.servers_status = msg.servers_status; - Box::pin(async move {}) - } +pub struct Accept { + pub input: Input, + pub cwd: PathBuf, } #[derive(Debug, actix::Message)] From ea293277667d5a9676f6e892dc15057436f6fe96 Mon Sep 17 00:00:00 2001 From: Shane Osbourne Date: Tue, 27 Oct 2026 21:44:31 +0000 Subject: [PATCH 08/16] general refactoring --- Cargo.lock | 1 + crates/bsnext_dto/src/external_events.rs | 2 +- crates/bsnext_dto/src/lib.rs | 1 + crates/bsnext_dto/src/status_events.rs | 47 +++++--- crates/bsnext_dto/src/status_events_dto.rs | 71 ++++++++++++ crates/bsnext_html/src/html_writer.rs | 102 +++++++++--------- crates/bsnext_input/src/lib.rs | 6 +- crates/bsnext_input/src/server_config.rs | 10 +- crates/bsnext_md/Cargo.toml | 1 + crates/bsnext_md/src/md_writer.rs | 14 +-- crates/bsnext_md/tests/md_serialize.rs | 16 --- .../bsnext_system/src/handle_fs_changeset.rs | 7 +- crates/bsnext_system/src/path_monitors/mod.rs | 3 +- crates/bsnext_system/src/status_tracker.rs | 14 ++- crates/bsnext_system/src/system.rs | 3 +- crates/bsnext_yaml/src/yaml_writer.rs | 16 ++- generated/dto.ts | 46 ++++++++ generated/schema.js | 73 +++++++++++++ generated/schema.ts | 73 +++++++++++++ inject/dist/index.js | 28 ++--- 20 files changed, 397 insertions(+), 137 deletions(-) create mode 100644 crates/bsnext_dto/src/status_events_dto.rs delete mode 100644 crates/bsnext_md/tests/md_serialize.rs diff --git a/Cargo.lock b/Cargo.lock index 4db5ec4a..5d611cbd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -613,6 +613,7 @@ name = "bsnext_md" version = "0.28.2" dependencies = [ "anyhow", + "bsnext_dto", "bsnext_input", "insta", "markdown", diff --git a/crates/bsnext_dto/src/external_events.rs b/crates/bsnext_dto/src/external_events.rs index ace905ae..c89a68b0 100644 --- a/crates/bsnext_dto/src/external_events.rs +++ b/crates/bsnext_dto/src/external_events.rs @@ -176,7 +176,7 @@ impl OutputWriterTrait for ExternalEventsDTO { ExternalEventsDTO::StartupError(StartupErrorDTO { error }) => { writeln!(sink, "{} {error}", style("[error]").on_red())?; Ok(()) - } + } // ExternalEventsDTO::Transition() => {} } } } diff --git a/crates/bsnext_dto/src/lib.rs b/crates/bsnext_dto/src/lib.rs index ae640480..33a45d40 100644 --- a/crates/bsnext_dto/src/lib.rs +++ b/crates/bsnext_dto/src/lib.rs @@ -23,6 +23,7 @@ pub mod startup_events; pub mod task_events; pub mod status_events; +pub mod status_events_dto; #[typeshare] #[derive(Debug, serde::Serialize)] diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs index 34dc0250..53510e1d 100644 --- a/crates/bsnext_dto/src/status_events.rs +++ b/crates/bsnext_dto/src/status_events.rs @@ -1,5 +1,6 @@ +use crate::status_events_dto::ResourceStatus; use crate::ActiveServer; -use bsnext_input::server_config::ServerConfig; +use bsnext_input::server_config::{ServerConfig, ServerIdentity}; use bsnext_input::watchables::path_watchable::PathWatchable; use bsnext_input::watchables::PathWatchables; use bsnext_input::Input; @@ -27,6 +28,37 @@ pub struct MonitorStatusWriter { pub monitor_resource_status: HashMap, } +/// This is the event we'll broadcast, it will grow with more sub systems +#[derive(Debug)] +pub enum Transition { + Server(ServerResource), + PathMonitor(PathMonitorResource), +} + +impl Transition { + pub fn path_monitor(status: ResourceStatus, watchable: PathWatchable) -> Self { + Transition::PathMonitor(PathMonitorResource::new(status, watchable)) + } +} + +#[derive(Debug)] +pub struct ServerResource { + status: ResourceStatus, + server: ServerIdentity, +} + +#[derive(Debug)] +pub struct PathMonitorResource { + status: ResourceStatus, + watchable: PathWatchable, +} + +impl PathMonitorResource { + pub fn new(status: ResourceStatus, watchable: PathWatchable) -> Self { + Self { status, watchable } + } +} + #[derive(Debug, Clone, Hash, Copy, Eq, Ord, PartialEq, PartialOrd)] pub struct StateValue { value: u64, @@ -38,19 +70,6 @@ impl StateValue { } } -#[derive(Debug, Default, Clone, Eq, PartialEq)] -pub enum ResourceStatus { - #[default] - Pending, - Waiting { - reason: String, - }, - Ready, - Failed { - reason: String, - }, -} - #[derive(Debug, Default, Clone, Hash, Copy, Eq, PartialEq, Ord, PartialOrd)] pub enum ServiceStatus { #[default] diff --git a/crates/bsnext_dto/src/status_events_dto.rs b/crates/bsnext_dto/src/status_events_dto.rs new file mode 100644 index 00000000..b2ba9d94 --- /dev/null +++ b/crates/bsnext_dto/src/status_events_dto.rs @@ -0,0 +1,71 @@ +use crate::ServerIdentityDTO; +use typeshare::typeshare; + +/// @discriminator kind +#[typeshare] +#[derive(Debug, serde::Serialize)] +#[serde(tag = "kind", content = "payload")] +pub enum TransitionDTO { + Server(ServerResourceDTO), + PathMonitor(PathMonitorResourceDTO), +} + +#[typeshare] +#[derive(Debug, serde::Serialize)] +pub struct ServerResourceDTO { + status: ResourceStatus, + server: ServerIdentityDTO, +} + +#[typeshare] +#[derive(Debug, serde::Serialize)] +pub struct PathMonitorResourceDTO { + status: ResourceStatus, + watchable: PathWatchableDTO, +} + +/// @discriminator kind +#[typeshare] +#[derive(Debug, serde::Serialize)] +#[serde(tag = "kind", content = "payload")] +pub enum PathWatchableDTO { + Server(ServerWatchableDTO), + Route(RouteWatchableDTO), + Any(AnyWatchableDTO), +} + +#[typeshare] +#[derive(Debug, serde::Serialize)] +pub struct ServerWatchableDTO { + address: String, + dir: String, +} + +#[typeshare] +#[derive(Debug, serde::Serialize)] +pub struct RouteWatchableDTO { + address: String, + dir: String, +} + +#[typeshare] +#[derive(Debug, serde::Serialize)] +pub struct AnyWatchableDTO { + dir: String, +} + +/// @discriminator kind +#[typeshare] +#[derive(Debug, Default, Clone, Eq, PartialEq, serde::Serialize)] +#[serde(tag = "kind", content = "payload")] +pub enum ResourceStatus { + #[default] + Pending, + Waiting { + reason: String, + }, + Ready, + Failed { + reason: String, + }, +} diff --git a/crates/bsnext_html/src/html_writer.rs b/crates/bsnext_html/src/html_writer.rs index 95b4ae38..c3afe480 100644 --- a/crates/bsnext_html/src/html_writer.rs +++ b/crates/bsnext_html/src/html_writer.rs @@ -1,54 +1,52 @@ -use bsnext_input::{Input, InputWriter}; - pub struct HtmlWriter; -impl InputWriter for HtmlWriter { - fn input_to_str(&self, input: &Input) -> String { - if input.servers.is_empty() { - todo!("html requires at least 1 server definition") - } - if input.servers.len() > 1 { - todo!("more than 1 server not supported yet") - } - let server = input.servers.first().expect("must access first"); - let Some(playground) = &server.playground else { - todo!("only playground is supported in HTML for now") - }; - let mut blocks: Vec = vec![]; - if let Some(css) = &playground.css { - blocks.push("".into()); - } - blocks.push(playground.html.clone()); - if let Some(js) = &playground.js { - blocks.push("".into()); - } - blocks.join("\n") - } -} - -#[test] -fn test_html_writer_for_playground() { - use bsnext_input::playground::Playground; - use bsnext_input::server_config::ServerConfig; - let css = r#"body { - background: red; -}"#; - let js = r#"console.log("hello world!")"#; - let playground = Playground { - html: "

Hello world

".to_string(), - js: Some(js.to_string()), - css: Some(css.to_string()), - }; - let mut input = Input::default(); - let mut server = ServerConfig::default(); - server.playground = Some(playground); - input.servers.push(server); - let output = HtmlWriter.input_to_str(&input); - insta::assert_snapshot!(output); -} +// impl InputWriter for HtmlWriter { +// fn input_to_str(&self, input: &Input) -> String { +// if input.servers.is_empty() { +// todo!("html requires at least 1 server definition") +// } +// if input.servers.len() > 1 { +// todo!("more than 1 server not supported yet") +// } +// let server = input.servers.first().expect("must access first"); +// let Some(playground) = &server.playground else { +// todo!("only playground is supported in HTML for now") +// }; +// let mut blocks: Vec = vec![]; +// if let Some(css) = &playground.css { +// blocks.push("".into()); +// } +// blocks.push(playground.html.clone()); +// if let Some(js) = &playground.js { +// blocks.push("".into()); +// } +// blocks.join("\n") +// } +// } +// +// #[test] +// fn test_html_writer_for_playground() { +// use bsnext_input::playground::Playground; +// use bsnext_input::server_config::ServerConfig; +// let css = r#"body { +// background: red; +// }"#; +// let js = r#"console.log("hello world!")"#; +// let playground = Playground { +// html: "

Hello world

".to_string(), +// js: Some(js.to_string()), +// css: Some(css.to_string()), +// }; +// let mut input = Input::default(); +// let mut server = ServerConfig::default(); +// server.playground = Some(playground); +// input.servers.push(server); +// let output = HtmlWriter.input_to_str(&input); +// insta::assert_snapshot!(output); +// } diff --git a/crates/bsnext_input/src/lib.rs b/crates/bsnext_input/src/lib.rs index 47deed05..63f05104 100644 --- a/crates/bsnext_input/src/lib.rs +++ b/crates/bsnext_input/src/lib.rs @@ -32,7 +32,7 @@ pub mod watchables; pub mod when_guard; pub mod yml; -#[derive(Debug, Default, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Default, Hash, Clone, serde::Deserialize)] pub struct Input { #[serde(default)] pub servers: Vec, @@ -283,10 +283,6 @@ pub trait InputCreation { ) -> Result>; } -pub trait InputWriter { - fn input_to_str(&self, input: &Input) -> String; -} - #[derive(Debug, miette::Diagnostic, thiserror::Error)] pub enum InputError { #[error("no suitable inputs could be found")] diff --git a/crates/bsnext_input/src/server_config.rs b/crates/bsnext_input/src/server_config.rs index 3ff75fc5..54f5c9ef 100644 --- a/crates/bsnext_input/src/server_config.rs +++ b/crates/bsnext_input/src/server_config.rs @@ -7,7 +7,7 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use std::net::SocketAddr; use std::str::FromStr; -#[derive(Debug, Default, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Default, Hash, Clone, serde::Deserialize)] pub struct ServerConfig { #[serde(flatten)] pub identity: ServerIdentity, @@ -51,9 +51,7 @@ impl ServerConfig { } } -#[derive( - Debug, Ord, PartialOrd, PartialEq, Hash, Eq, Clone, serde::Deserialize, serde::Serialize, -)] +#[derive(Debug, Ord, PartialOrd, PartialEq, Hash, Eq, Clone, serde::Deserialize)] #[serde(untagged)] pub enum ServerIdentity { PortNamed { @@ -162,7 +160,7 @@ impl ServerIdentity { #[test] fn server_config_as_enum() { - #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] + #[derive(Debug, Clone, serde::Deserialize)] struct C { servers: Vec, } @@ -189,7 +187,7 @@ servers: #[test] fn with_port() { - #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] + #[derive(Debug, Clone, serde::Deserialize)] struct C { servers: Vec, } diff --git a/crates/bsnext_md/Cargo.toml b/crates/bsnext_md/Cargo.toml index 1017ecfd..b45853a1 100644 --- a/crates/bsnext_md/Cargo.toml +++ b/crates/bsnext_md/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" markdown = { version = "1.0.0-alpha.16" } nom = "7.1.3" bsnext_input = { path = "../bsnext_input" } +bsnext_dto = { path = "../bsnext_dto" } mime_guess = { workspace = true } anyhow = { workspace = true } diff --git a/crates/bsnext_md/src/md_writer.rs b/crates/bsnext_md/src/md_writer.rs index aae27632..4daa3a86 100644 --- a/crates/bsnext_md/src/md_writer.rs +++ b/crates/bsnext_md/src/md_writer.rs @@ -1,24 +1,18 @@ +use bsnext_dto::ServerIdentityDTO; use bsnext_input::route::{RawRoute, RouteKind}; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::{Input, InputWriter}; +use bsnext_input::Input; use mime_guess::get_mime_extensions_str; use serde_json::json; pub struct MdWriter; -impl InputWriter for MdWriter { - fn input_to_str(&self, input: &Input) -> String { - _input_to_str(input) - } -} - fn _input_to_str(input: &Input) -> String { let mut chunks = vec![]; if let Some(server_config) = input.servers.first() { #[derive(Debug, serde::Serialize)] struct FakeServerConfig { #[serde(flatten)] - identity: ServerIdentity, + identity: ServerIdentityDTO, } #[derive(Debug, serde::Serialize)] struct FakeInput { @@ -26,7 +20,7 @@ fn _input_to_str(input: &Input) -> String { } let just_identity = FakeInput { servers: vec![FakeServerConfig { - identity: server_config.identity.clone(), + identity: ServerIdentityDTO::from(&server_config.identity), }], }; let yml = serde_yaml::to_string(&just_identity).expect("never fail here"); diff --git a/crates/bsnext_md/tests/md_serialize.rs b/crates/bsnext_md/tests/md_serialize.rs deleted file mode 100644 index 801512d0..00000000 --- a/crates/bsnext_md/tests/md_serialize.rs +++ /dev/null @@ -1,16 +0,0 @@ -use bsnext_input::{InputCreation, InputWriter}; -use bsnext_md::md_fs::MdFs; -use bsnext_md::md_writer::MdWriter; - -#[test] -fn test_input_to_str() -> anyhow::Result<()> { - let input_str = include_str!("../../../examples/markdown/single.md"); - let input = MdFs::from_input_str(&input_str, &Default::default()).expect("unwrap"); - let output = MdWriter.input_to_str(&input); - println!("{}", output); - let input = MdFs::from_input_str(&output, &Default::default()).expect("unwrapped 2"); - println!("{:?}", input); - assert_eq!(input.servers.len(), 1); - assert_eq!(input.servers.first().unwrap().routes.len(), 2); - Ok(()) -} diff --git a/crates/bsnext_system/src/handle_fs_changeset.rs b/crates/bsnext_system/src/handle_fs_changeset.rs index 90dda79a..c4253c73 100644 --- a/crates/bsnext_system/src/handle_fs_changeset.rs +++ b/crates/bsnext_system/src/handle_fs_changeset.rs @@ -8,7 +8,7 @@ use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::file_changed_handler::FileChanged; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; -use bsnext_dto::{StoppedWatchingDTO, WatchingDTO}; +use bsnext_dto::StoppedWatchingDTO; use bsnext_fs::{ BufferedChangeset, Debounce, FsEvent, FsEventContext, FsEventKind, PathAddedEvent, PathDescriptionOwned, PathEvent, @@ -151,9 +151,8 @@ fn handle_path_not_found(cwd: PathBuf, pdo: &PathEvent) -> Option Option { - Some(ExternalEventsDTO::Watching(WatchingDTO::from_path_buf( - &path.path, *debounce, - ))) + tracing::debug!(?path.path, ?debounce, "path added"); + None } fn handle_path_removed(path: &PathEvent) -> Option { diff --git a/crates/bsnext_system/src/path_monitors/mod.rs b/crates/bsnext_system/src/path_monitors/mod.rs index 5af9708b..cac14777 100644 --- a/crates/bsnext_system/src/path_monitors/mod.rs +++ b/crates/bsnext_system/src/path_monitors/mod.rs @@ -1,8 +1,9 @@ use actix::{Actor, Addr, AsyncContext, Recipient, ResponseActFuture, ResponseFuture, WrapFuture}; use actix::{ActorFutureExt, Running}; use bsnext_dto::status_events::{ - list_hash, MonitorStatusReader, MonitorStatusWriter, ResourceStatus, ServiceStatus, StateValue, + list_hash, MonitorStatusReader, MonitorStatusWriter, ServiceStatus, StateValue, }; +use bsnext_dto::status_events_dto::ResourceStatus; use bsnext_fs::{Debounce, FsEventContext}; use bsnext_input::watchables::path_watchable::PathWatchable; use bsnext_input::watchables::PathWatchables; diff --git a/crates/bsnext_system/src/status_tracker.rs b/crates/bsnext_system/src/status_tracker.rs index ae45c448..61d614df 100644 --- a/crates/bsnext_system/src/status_tracker.rs +++ b/crates/bsnext_system/src/status_tracker.rs @@ -1,14 +1,17 @@ use crate::system::Accept; use actix::{Actor, Handler, ResponseFuture}; +use bsnext_dto::any_event::AnyEvent; use bsnext_dto::status_events::{ monitor_status_hash, server_status_hash, MonitorStatusReader, MonitorStatusWriter, - ResourceStatus, ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, + ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, Transition, }; +use bsnext_dto::status_events_dto::ResourceStatus; use bsnext_input::watchables::path_watchable::PathWatchable; use bsnext_input::watchables::PathWatchables; use bsnext_input::Input; use std::collections::HashMap; use std::path::PathBuf; +use tokio::sync::mpsc::Sender; use tracing::debug_span; pub struct StatusTracker { @@ -17,6 +20,7 @@ pub struct StatusTracker { servers_status: ServiceStatus, monitor_status: ServiceStatus, monitor_resource_status: HashMap, + sender: Sender, } impl Actor for StatusTracker { @@ -40,13 +44,14 @@ impl Handler for StatusTracker { } impl StatusTracker { - pub fn new(cwd: PathBuf) -> Self { + pub fn new(cwd: PathBuf, sender: Sender) -> Self { Self { servers_status: ServiceStatus::default(), monitor_status: ServiceStatus::default(), monitor_resource_status: Default::default(), input: Input::default(), cwd, + sender, } } fn mark_servers(&mut self, input: &Input) { @@ -145,6 +150,10 @@ impl Handler for StatusTracker { .is_some_and(|x| x != status); tracing::info!(did_transition); if did_transition { + let _evt = Transition::path_monitor(status.clone(), id.clone()); + todo!("publish the event!"); + // dbg!(&evt); + // self.sender.send(evt).await.unwrap(); match status { ResourceStatus::Pending => {} ResourceStatus::Waiting { reason } => { @@ -157,7 +166,6 @@ impl Handler for StatusTracker { } self.monitor_status = msg.monitor_status; self.monitor_resource_status = msg.monitor_resource_status; - println!("...") } } diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index 43f04cad..4785a2fd 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -74,7 +74,8 @@ impl BsSystem { cwd: PathBuf, tx: tokio::sync::oneshot::Sender<()>, ) -> Self { - let status_tracker = StatusTracker::new(cwd.clone()); + // todo!("figure where the event goes? probably the status tracker can broadcast updates onto any_event_sender?"); + let status_tracker = StatusTracker::new(cwd.clone(), any_event_sender.clone()); let status_tracker = status_tracker.start(); let servers = ServersSupervisor::new( tx, diff --git a/crates/bsnext_yaml/src/yaml_writer.rs b/crates/bsnext_yaml/src/yaml_writer.rs index bf686a5e..83b3e5df 100644 --- a/crates/bsnext_yaml/src/yaml_writer.rs +++ b/crates/bsnext_yaml/src/yaml_writer.rs @@ -1,13 +1,9 @@ -use bsnext_input::{Input, InputWriter}; +// use bsnext_input::{Input}; pub struct YamlWriter; -impl InputWriter for YamlWriter { - fn input_to_str(&self, input: &Input) -> String { - input_to_str(input) - } -} - -fn input_to_str(input: &Input) -> String { - serde_yaml::to_string(&input).expect("create yaml?") -} +// impl InputWriter for YamlWriter { +// fn input_to_str(&self, _input: &Input) -> String { +// todo!("not implemented yet!"); +// } +// } diff --git a/generated/dto.ts b/generated/dto.ts index 62975809..3c0e961f 100644 --- a/generated/dto.ts +++ b/generated/dto.ts @@ -4,6 +4,10 @@ export type InvocationIdDTO = string; +export interface AnyWatchableDTO { + dir: string; +} + export interface ArchyNode { id: string; label: string; @@ -87,6 +91,28 @@ export interface InputErrorDetailDTO { error: string; } +/** @discriminator kind */ +export type ResourceStatus = + | { kind: "Pending", payload?: undefined } + | { kind: "Waiting", payload: { + reason: string; +}} + | { kind: "Ready", payload?: undefined } + | { kind: "Failed", payload: { + reason: string; +}}; + +/** @discriminator kind */ +export type PathWatchableDTO = + | { kind: "Server", payload: ServerWatchableDTO } + | { kind: "Route", payload: RouteWatchableDTO } + | { kind: "Any", payload: AnyWatchableDTO }; + +export interface PathMonitorResourceDTO { + status: ResourceStatus; + watchable: PathWatchableDTO; +} + /** @discriminator kind */ export type RouteKindDTO = | { kind: "Html", payload: { @@ -119,6 +145,11 @@ export interface RouteIdentityDTO { kind_str: string; } +export interface RouteWatchableDTO { + address: string; + dir: string; +} + /** @discriminator kind */ export type ServerChange = | { kind: "Stopped", payload: { @@ -171,6 +202,16 @@ export interface ServerDesc { id: string; } +export interface ServerResourceDTO { + status: ResourceStatus; + server: ServerIdentityDTO; +} + +export interface ServerWatchableDTO { + address: string; + dir: string; +} + export interface SseDTOOpts { body: string; } @@ -311,3 +352,8 @@ export type StartupEventDTO = | { kind: "Started", payload?: undefined } | { kind: "FailedStartup", payload: string }; +/** @discriminator kind */ +export type TransitionDTO = + | { kind: "Server", payload: ServerResourceDTO } + | { kind: "PathMonitor", payload: PathMonitorResourceDTO }; + diff --git a/generated/schema.js b/generated/schema.js index 02840909..4e35eed6 100644 --- a/generated/schema.js +++ b/generated/schema.js @@ -22,6 +22,9 @@ var EventLevel = /* @__PURE__ */ ((EventLevel2) => { // schema.ts var invocationIdDTOSchema = z.string(); +var anyWatchableDTOSchema = z.object({ + dir: z.string() +}); var archyNodeSchema = z.lazy( () => z.object({ id: z.string(), @@ -103,6 +106,50 @@ var inputAcceptedDTOSchema = z.object({ var inputErrorDetailDTOSchema = z.object({ error: z.string() }); +var resourceStatusSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Pending"), + payload: z.undefined().optional() + }), + z.object({ + kind: z.literal("Waiting"), + payload: z.object({ + reason: z.string() + }) + }), + z.object({ + kind: z.literal("Ready"), + payload: z.undefined().optional() + }), + z.object({ + kind: z.literal("Failed"), + payload: z.object({ + reason: z.string() + }) + }) +]); +var serverWatchableDTOSchema = z.object({ + address: z.string(), + dir: z.string() +}); +var routeWatchableDTOSchema = z.object({ + address: z.string(), + dir: z.string() +}); +var pathWatchableDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverWatchableDTOSchema + }), + z.object({ + kind: z.literal("Route"), + payload: routeWatchableDTOSchema + }), + z.object({ + kind: z.literal("Any"), + payload: anyWatchableDTOSchema + }) +]); var sseDTOOptsSchema = z.object({ body: z.string() }); @@ -222,6 +269,10 @@ var routeDTOSchema = z.object({ path: z.string(), kind: routeKindDTOSchema }); +var serverResourceDTOSchema = z.object({ + status: resourceStatusSchema, + server: serverIdentityDTOSchema +}); var startupErrorDTOSchema = z.object({ error: z.string() }); @@ -375,10 +426,24 @@ var startupEventDTOSchema = z.discriminatedUnion("kind", [ payload: z.string() }) ]); +var pathMonitorResourceDTOSchema = z.object({ + status: resourceStatusSchema, + watchable: pathWatchableDTOSchema +}); var serverDescSchema = z.object({ routes: z.array(routeDTOSchema), id: z.string() }); +var transitionDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverResourceDTOSchema + }), + z.object({ + kind: z.literal("PathMonitor"), + payload: pathMonitorResourceDTOSchema + }) +]); var taskActionStageDTOSchema = z.lazy( () => z.discriminatedUnion("kind", [ z.object({ @@ -481,6 +546,7 @@ var externalEventsDTOSchema = z.lazy( ]) ); export { + anyWatchableDTOSchema, archyNodeSchema, changeDTOSchema, changeKindSchema, @@ -501,9 +567,13 @@ export { invocationIdDTOSchema, logLevelDTOSchema, outputLineDTOSchema, + pathMonitorResourceDTOSchema, + pathWatchableDTOSchema, + resourceStatusSchema, routeDTOSchema, routeIdentityDTOSchema, routeKindDTOSchema, + routeWatchableDTOSchema, serverChangeDTOSchema, serverChangeSchema, serverChangeSetItemSchema, @@ -512,6 +582,8 @@ export { serverDTOSchema, serverDescSchema, serverIdentityDTOSchema, + serverResourceDTOSchema, + serverWatchableDTOSchema, sseDTOOptsSchema, startupErrorDTOSchema, startupEventDTOSchema, @@ -525,5 +597,6 @@ export { taskResultDTOSchema, taskTreePreviewSchema, taskTreeSummarySchema, + transitionDTOSchema, watchingDTOSchema }; diff --git a/generated/schema.ts b/generated/schema.ts index 0bcf856c..7f2d9e8c 100644 --- a/generated/schema.ts +++ b/generated/schema.ts @@ -16,6 +16,10 @@ import { export const invocationIdDTOSchema = z.string(); +export const anyWatchableDTOSchema = z.object({ + dir: z.string(), +}); + export const archyNodeSchema: z.ZodSchema = z.lazy(() => z.object({ id: z.string(), @@ -111,6 +115,54 @@ export const inputErrorDetailDTOSchema = z.object({ error: z.string(), }); +export const resourceStatusSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Pending"), + payload: z.undefined().optional(), + }), + z.object({ + kind: z.literal("Waiting"), + payload: z.object({ + reason: z.string(), + }), + }), + z.object({ + kind: z.literal("Ready"), + payload: z.undefined().optional(), + }), + z.object({ + kind: z.literal("Failed"), + payload: z.object({ + reason: z.string(), + }), + }), +]); + +export const serverWatchableDTOSchema = z.object({ + address: z.string(), + dir: z.string(), +}); + +export const routeWatchableDTOSchema = z.object({ + address: z.string(), + dir: z.string(), +}); + +export const pathWatchableDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverWatchableDTOSchema, + }), + z.object({ + kind: z.literal("Route"), + payload: routeWatchableDTOSchema, + }), + z.object({ + kind: z.literal("Any"), + payload: anyWatchableDTOSchema, + }), +]); + export const sseDTOOptsSchema = z.object({ body: z.string(), }); @@ -239,6 +291,11 @@ export const routeDTOSchema = z.object({ kind: routeKindDTOSchema, }); +export const serverResourceDTOSchema = z.object({ + status: resourceStatusSchema, + server: serverIdentityDTOSchema, +}); + export const startupErrorDTOSchema = z.object({ error: z.string(), }); @@ -406,11 +463,27 @@ export const startupEventDTOSchema = z.discriminatedUnion("kind", [ }), ]); +export const pathMonitorResourceDTOSchema = z.object({ + status: resourceStatusSchema, + watchable: pathWatchableDTOSchema, +}); + export const serverDescSchema = z.object({ routes: z.array(routeDTOSchema), id: z.string(), }); +export const transitionDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverResourceDTOSchema, + }), + z.object({ + kind: z.literal("PathMonitor"), + payload: pathMonitorResourceDTOSchema, + }), +]); + export const taskActionStageDTOSchema: z.ZodSchema = z.lazy( () => z.discriminatedUnion("kind", [ diff --git a/inject/dist/index.js b/inject/dist/index.js index 97c3f509..afe077ae 100644 --- a/inject/dist/index.js +++ b/inject/dist/index.js @@ -1,8 +1,8 @@ -var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var qi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Gi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!Hi.call(r,i)&&i!==t&&Or(r,i,{get:()=>e[i],enumerable:!(n=ln(e,i))||n.enumerable});return r};var Yi=(r,e,t)=>(t=r!=null?Vi(Wi(r)):{},Gi(e||!r||!r.__esModule?Or(t,"default",{value:r,enumerable:!0}):t,r));var W=(r,e,t,n)=>{for(var i=n>1?void 0:n?ln(e,t):e,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Or(e,t,i),i};var hi=qi(pi=>{"use strict";var ur=class{constructor(e){this.func=e,this.running=!1,this.id=null,this._handler=()=>(this.running=!1,this.id=null,this.func())}start(e){this.running&&clearTimeout(this.id),this.id=setTimeout(this._handler,e),this.running=!0}stop(){this.running&&(clearTimeout(this.id),this.running=!1,this.id=null)}};ur.start=(r,e)=>setTimeout(e,r);pi.Timer=ur});var Cr=function(r,e){return Cr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])},Cr(r,e)};function I(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Cr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var It=function(){return It=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&o[o.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function q(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n1||l(y,S)})},E&&(i[y]=E(i[y])))}function l(y,E){try{d(n[y](E))}catch(S){w(o[0][3],S)}}function d(y){y.value instanceof ve?Promise.resolve(y.value.v).then(u,p):w(o[0][2],y)}function u(y){l("next",y)}function p(y){l("throw",y)}function w(y,E){y(E),o.shift(),o.length&&l(o[0][0],o[0][1])}}function fn(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof re=="function"?re(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(c,l){s=r[o](s),i(c,l,s.done,s.value)})}}function i(o,s,c,l){Promise.resolve(l).then(function(d){o({value:d,done:c})},s)}}function k(r){return typeof r=="function"}function Pt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Dt=Pt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription: +var Wi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var Hi=Object.getPrototypeOf,qi=Object.prototype.hasOwnProperty;var Gi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Yi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!qi.call(r,i)&&i!==t&&Or(r,i,{get:()=>e[i],enumerable:!(n=ln(e,i))||n.enumerable});return r};var Ji=(r,e,t)=>(t=r!=null?Wi(Hi(r)):{},Yi(e||!r||!r.__esModule?Or(t,"default",{value:r,enumerable:!0}):t,r));var B=(r,e,t,n)=>{for(var i=n>1?void 0:n?ln(e,t):e,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Or(e,t,i),i};var mi=Gi(hi=>{"use strict";var ur=class{constructor(e){this.func=e,this.running=!1,this.id=null,this._handler=()=>(this.running=!1,this.id=null,this.func())}start(e){this.running&&clearTimeout(this.id),this.id=setTimeout(this._handler,e),this.running=!0}stop(){this.running&&(clearTimeout(this.id),this.running=!1,this.id=null)}};ur.start=(r,e)=>setTimeout(e,r);hi.Timer=ur});var Cr=function(r,e){return Cr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])},Cr(r,e)};function R(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Cr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Rt=function(){return Rt=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&o[o.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function q(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n1||l(v,w)})},A&&(i[v]=A(i[v])))}function l(v,A){try{d(n[v](A))}catch(w){S(o[0][3],w)}}function d(v){v.value instanceof ye?Promise.resolve(v.value.v).then(u,p):S(o[0][2],v)}function u(v){l("next",v)}function p(v){l("throw",v)}function S(v,A){v(A),o.shift(),o.length&&l(o[0][0],o[0][1])}}function fn(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof re=="function"?re(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(c,l){s=r[o](s),i(c,l,s.done,s.value)})}}function i(o,s,c,l){Promise.resolve(l).then(function(d){o({value:d,done:c})},s)}}function k(r){return typeof r=="function"}function Dt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Pt=Dt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription: `+t.map(function(n,i){return i+1+") "+n.toString()}).join(` - `):"",this.name="UnsubscriptionError",this.errors=t}});function ye(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var X=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=re(s),l=c.next();!l.done;l=c.next()){var d=l.value;d.remove(this)}}catch(S){e={error:S}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var u=this.initialTeardown;if(k(u))try{u()}catch(S){o=S instanceof Dt?S.errors:[S]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var w=re(p),y=w.next();!y.done;y=w.next()){var E=y.value;try{pn(E)}catch(S){o=o??[],S instanceof Dt?o=q(q([],H(o)),H(S.errors)):o.push(S)}}}catch(S){n={error:S}}finally{try{y&&!y.done&&(i=w.return)&&i.call(w)}finally{if(n)throw n.error}}}if(o)throw new Dt(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)pn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ye(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ye(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var $r=X.EMPTY;function Mt(r){return r instanceof X||r&&"closed"in r&&k(r.remove)&&k(r.add)&&k(r.unsubscribe)}function pn(r){k(r)?r():r.unsubscribe()}var G={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var qe={setTimeout:function(r,e){for(var t=[],n=2;n0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,s=i.isStopped,c=i.observers;return o||s?$r:(this.currentObservers=null,c.push(t),new X(function(){n.currentObservers=null,ye(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?t.error(o):s&&t.complete()},e.prototype.asObservable=function(){var t=new A;return t.source=this,t},e.create=function(t,n){return new Ut(t,n)},e})(A);var Ut=(function(r){I(e,r);function e(t,n){var i=r.call(this)||this;return i.destination=t,i.source=n,i}return e.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},e.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:$r},e})(Y);var ut={now:function(){return(ut.delegate||Date).now()},delegate:void 0};var zt=(function(r){I(e,r);function e(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=ut);var o=r.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return e.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,c=n._timestampProvider,l=n._windowTime;i||(o.push(t),!s&&o.push(c.now()+l)),this._trimBuffer(),r.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,s=i._buffer,c=s.slice(),l=0;l0&&(u=new be({next:function(jt){return $t.next(jt)},error:function(jt){S=!0,R(),p=Nr(U,i,jt),$t.error(jt)},complete:function(){E=!0,R(),p=Nr(U,s),$t.complete()}}),j(lt).subscribe(u))})(d)}}function Nr(r,e){for(var t=[],n=2;n{let e=new URL(window.location.href),t=e.protocol==="https:"?"wss":"ws",n;if(r.host)n=new URL(r.ws_path,t+"://"+r.host);else{let o=new URL(e);o.protocol=t,o.pathname=r.ws_path,n=o}return Ur(n.toString()).pipe(Mr({delay:5e3}))}}}var Fn={debug(...r){},error(...r){},info(...r){},trace(...r){}},zr={name:"console",globalSetup:r=>{let e=new Y;return[e,{debug:function(...n){e.next({level:"debug",args:n})},info:function(...n){e.next({level:"info",args:n})},trace:function(...n){e.next({level:"trace",args:n})},error:function(...n){e.next({level:"error",args:n})}}]},resetSink:(r,e,t)=>r.pipe(we(n=>{let i=["trace","debug","info","error"],o=i.indexOf(n.level),s=i.indexOf(t.log_level);o>=s&&console.log(`[${n.level}]`,...n.args)}),xe())};var T;(function(r){r.assertEqual=i=>i;function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),s={};for(let c of o)s[c]=i[c];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(T||(T={}));var Fr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fr||(Fr={}));var m=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},f=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let c=n,l=0;for(;lt.message){let t={},n=[];for(let i of this.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Xe=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}},Hn=Xe;function vo(r){Hn=r}function tr(){return Hn}var rr=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(s,{data:e,defaultError:c}).message;return{...i,path:o,message:c}},yo=[];function h(r,e){let t=tr(),n=rr({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Xe?void 0:Xe].filter(i=>!!i)});r.common.issues.push(n)}var P=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return _;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return _;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},_=Object.freeze({status:"aborted"}),Ke=r=>({status:"dirty",value:r}),D=r=>({status:"valid",value:r}),Vr=r=>r.status==="aborted",Br=r=>r.status==="dirty",Se=r=>r.status==="valid",yt=r=>typeof Promise<"u"&&r instanceof Promise;function nr(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}function qn(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var mt,vt,B=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vn=(r,e)=>{if(Se(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function b(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,c)=>{var l,d;let{message:u}=r;return s.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??n)!==null&&l!==void 0?l:c.defaultError}:s.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??t)!==null&&d!==void 0?d:c.defaultError}},description:i}}var x=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(yt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;let i={common:{issues:[],async:(n=t?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Vn(i,o)}"~validate"(e){var t,n;let i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:i});return Se(o)?{value:o.value}:{issues:i.common.issues}}catch(o){!((n=(t=o?.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:i}).then(o=>Se(o)?{value:o.value}:{issues:i.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(yt(i)?i:Promise.resolve(i));return Vn(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),c=()=>o.addIssue({code:f.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(c(),!1)):s?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Z({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return V.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return pe.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new Z({...b(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Me({...b(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new gt({typeName:g.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ne({...b(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},go=/^c[^\s-]{8,}$/i,_o=/^[0-9a-z]+$/,bo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wo=/^[a-z0-9_-]{21}$/i,So=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ko=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,To=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zr,Ao=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Co=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$o=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Io=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ro=new RegExp(`^${Gn}$`);function Yn(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Po(r){return new RegExp(`^${Yn(r)}$`)}function Jn(r){let e=`${Gn}T${Yn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Do(r,e){return!!((e==="v4"||!e)&&Ao.test(r)||(e==="v6"||!e)&&Co.test(r))}function Mo(r,e){if(!So.test(r))return!1;try{let[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||!i.typ||!i.alg||e&&i.alg!==e)}catch{return!1}}function No(r,e){return!!((e==="v4"||!e)&&Oo.test(r)||(e==="v6"||!e)&&$o.test(r))}var ue=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.string,received:o.parsedType}),_}let n=new P,i;for(let o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,c=e.data.lengthe.test(i),{validation:t,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new ue({checks:[],typeName:g.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...b(r)})};function Lo(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=parseInt(r.toFixed(i).replace(".","")),s=parseInt(e.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}var ke=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.number,received:o.parsedType}),_}let n,i=new P;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Lo(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_finite,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew ke({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Te=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let n,i=new P;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Te({checks:[],typeName:g.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...b(r)})};var Ee=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.boolean,received:n.parsedType}),_}return D(e.data)}};Ee.create=r=>new Ee({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Ae=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.date,received:o.parsedType}),_}if(isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),_}let n=new P,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):T.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Ae({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...b(r)});var Qe=class extends x{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.symbol,received:n.parsedType}),_}return D(e.data)}};Qe.create=r=>new Qe({typeName:g.ZodSymbol,...b(r)});var Oe=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.undefined,received:n.parsedType}),_}return D(e.data)}};Oe.create=r=>new Oe({typeName:g.ZodUndefined,...b(r)});var Ce=class extends x{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.null,received:n.parsedType}),_}return D(e.data)}};Ce.create=r=>new Ce({typeName:g.ZodNull,...b(r)});var fe=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return D(e.data)}};fe.create=r=>new fe({typeName:g.ZodAny,...b(r)});var oe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return D(e.data)}};oe.create=r=>new oe({typeName:g.ZodUnknown,...b(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),_}};J.create=r=>new J({typeName:g.ZodNever,...b(r)});var et=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.void,received:n.parsedType}),_}return D(e.data)}};et.create=r=>new et({typeName:g.ZodVoid,...b(r)});var se=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),_;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,c=t.data.lengthi.maxLength.value&&(h(t,{code:f.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,c)=>i.type._parseAsync(new B(t,s,t.path,c)))).then(s=>P.mergeArray(n,s));let o=[...t.data].map((s,c)=>i.type._parseSync(new B(t,s,t.path,c)));return P.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...b(e)});function Je(r){if(r instanceof M){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=V.create(Je(n))}return new M({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:Je(r.element)}):r instanceof V?V.create(Je(r.unwrap())):r instanceof te?te.create(Je(r.unwrap())):r instanceof ee?ee.create(r.items.map(e=>Je(e))):r}var M=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return h(d,{code:f.invalid_type,expected:m.object,received:d.parsedType}),_}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),c=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let d in i.data)s.includes(d)||c.push(d);let l=[];for(let d of s){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new B(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof J){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(h(i,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new B(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,w=await u.value;d.push({key:p,value:w,alwaysSet:u.alwaysSet})}return d}).then(d=>P.mergeObjectSync(n,d)):P.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,o,s,c;let l=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,t,n).message)!==null&&s!==void 0?s:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return T.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}omit(e){let t={};return T.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}deepPartial(){return Je(this)}partial(e){let t={};return T.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}),new r({...this._def,shape:()=>t})}required(e){let t={};return T.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof V;)o=o._def.innerType;t[n]=o}}),new r({...this._def,shape:()=>t})}keyof(){return Kn(T.objectKeys(this.shape))}};M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,...b(e)});M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:g.ZodObject,...b(e)});M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,...b(e)});var $e=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let s=o.map(c=>new z(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:s}),_}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let c=s.map(l=>new z(l));return h(t,{code:f.invalid_union,unionErrors:c}),_}}get options(){return this._def.options}};$e.create=(r,e)=>new $e({options:r,typeName:g.ZodUnion,...b(e)});var ne=r=>r instanceof Ie?ne(r.schema):r instanceof Z?ne(r.innerType()):r instanceof Re?[r.value]:r instanceof Pe?r.options:r instanceof De?T.objectValues(r.enum):r instanceof Me?ne(r._def.innerType):r instanceof Oe?[void 0]:r instanceof Ce?[null]:r instanceof V?[void 0,...ne(r.unwrap())]:r instanceof te?[null,...ne(r.unwrap())]:r instanceof gt||r instanceof Le?ne(r.unwrap()):r instanceof Ne?ne(r._def.innerType):[],ir=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),_;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=ne(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of s){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,o)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...b(n)})}};function Wr(r,e){let t=ie(r),n=ie(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let i=T.objectKeys(e),o=T.objectKeys(r).filter(c=>i.indexOf(c)!==-1),s={...r,...e};for(let c of o){let l=Wr(r[c],e[c]);if(!l.valid)return{valid:!1};s[c]=l.data}return{valid:!0,data:s}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o{if(Vr(o)||Vr(s))return _;let c=Wr(o.value,s.value);return c.valid?((Br(o)||Br(s))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),_)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};je.create=(r,e,t)=>new je({left:r,right:e,typeName:g.ZodIntersection,...b(t)});var ee=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return h(n,{code:f.invalid_type,expected:m.array,received:n.parsedType}),_;if(n.data.lengththis._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new B(n,s,n.path,c)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>P.mergeArray(t,s)):P.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ee.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:r,typeName:g.ZodTuple,rest:null,...b(e)})};var or=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return h(n,{code:f.invalid_type,expected:m.object,received:n.parsedType}),_;let i=[],o=this._def.keyType,s=this._def.valueType;for(let c in n.data)i.push({key:o._parse(new B(n,c,n.path,c)),value:s._parse(new B(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?P.mergeObjectAsync(t,i):P.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...b(n)}):new r({keyType:ue.create(),valueType:e,typeName:g.ZodRecord,...b(t)})}},tt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return h(n,{code:f.invalid_type,expected:m.map,received:n.parsedType}),_;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([c,l],d)=>({key:i._parse(new B(n,c,n.path,[d,"key"])),value:o._parse(new B(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of s){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return _;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of s){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return _;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}}}};tt.create=(r,e,t)=>new tt({valueType:e,keyType:r,typeName:g.ZodMap,...b(t)});var rt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return h(n,{code:f.invalid_type,expected:m.set,received:n.parsedType}),_;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(h(n,{code:f.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(l){let d=new Set;for(let u of l){if(u.status==="aborted")return _;u.status==="dirty"&&t.dirty(),d.add(u.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>o._parse(new B(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>s(l)):s(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};rt.create=(r,e)=>new rt({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...b(e)});var sr=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),_;function n(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Xe].filter(d=>!!d),issueData:{code:f.invalid_arguments,argumentsError:l}})}function i(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Xe].filter(d=>!!d),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof pe){let c=this;return D(async function(...l){let d=new z([]),u=await c._def.args.parseAsync(l,o).catch(y=>{throw d.addIssue(n(l,y)),d}),p=await Reflect.apply(s,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(y=>{throw d.addIssue(i(p,y)),d})})}else{let c=this;return D(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new z([n(l,d.error)]);let u=Reflect.apply(s,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new z([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ee.create(e).rest(oe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ee.create([]).rest(oe.create()),returns:t||oe.create(),typeName:g.ZodFunction,...b(n)})}},Ie=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ie.create=(r,e)=>new Ie({getter:r,typeName:g.ZodLazy,...b(e)});var Re=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}};Re.create=(r,e)=>new Re({value:r,typeName:g.ZodLiteral,...b(e)});function Kn(r,e){return new Pe({values:r,typeName:g.ZodEnum,...b(e)})}var Pe=class r extends x{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:T.joinValues(n),received:t.parsedType,code:f.invalid_type}),_}if(nr(this,mt,"f")||qn(this,mt,new Set(this._def.values),"f"),!nr(this,mt,"f").has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),_}return D(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};mt=new WeakMap;Pe.create=Kn;var De=class extends x{constructor(){super(...arguments),vt.set(this,void 0)}_parse(e){let t=T.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let i=T.objectValues(t);return h(n,{expected:T.joinValues(i),received:n.parsedType,code:f.invalid_type}),_}if(nr(this,vt,"f")||qn(this,vt,new Set(T.getValidEnumValues(this._def.values)),"f"),!nr(this,vt,"f").has(e.data)){let i=T.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:i}),_}return D(e.data)}get enum(){return this._def.values}};vt=new WeakMap;De.create=(r,e)=>new De({values:r,typeName:g.ZodNativeEnum,...b(e)});var pe=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),_;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return D(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};pe.create=(r,e)=>new pe({type:r,typeName:g.ZodPromise,...b(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{h(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async c=>{if(t.value==="aborted")return _;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?Ke(l.value):l});{if(t.value==="aborted")return _;let c=this._def.schema._parseSync({data:s,path:n.path,parent:n});return c.status==="aborted"?_:c.status==="dirty"||t.value==="dirty"?Ke(c.value):c}}if(i.type==="refinement"){let s=c=>{let l=i.refinement(c,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?_:(c.status==="dirty"&&t.dirty(),s(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?_:(c.status==="dirty"&&t.dirty(),s(c.value).then(()=>({status:t.value,value:c.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Se(s))return s;let c=i.transform(s.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Se(s)?Promise.resolve(i.transform(s.value,o)).then(c=>({status:t.value,value:c})):s);T.assertNever(i)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:g.ZodEffects,effect:e,...b(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...b(t)});var V=class extends x{_parse(e){return this._getType(e)===m.undefined?D(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(r,e)=>new V({innerType:r,typeName:g.ZodOptional,...b(e)});var te=class extends x{_parse(e){return this._getType(e)===m.null?D(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:g.ZodNullable,...b(e)});var Me=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Me.create=(r,e)=>new Me({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var Ne=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return yt(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var nt=class extends x{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.nan,received:n.parsedType}),_}return{status:"valid",value:e.data}}};nt.create=r=>new nt({typeName:g.ZodNaN,...b(r)});var Uo=Symbol("zod_brand"),gt=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_t=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?_:o.status==="dirty"?(t.dirty(),Ke(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},Le=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=i=>(Se(i)&&(i.value=Object.freeze(i.value)),i);return yt(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:g.ZodReadonly,...b(e)});function Bn(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xn(r,e={},t){return r?fe.create().superRefine((n,i)=>{var o,s;let c=r(n);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){let p=Bn(e,n),w=(u=(d=p.fatal)!==null&&d!==void 0?d:t)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...p,fatal:w})}});if(!c){let l=Bn(e,n),d=(s=(o=l.fatal)!==null&&o!==void 0?o:t)!==null&&s!==void 0?s:!0;i.addIssue({code:"custom",...l,fatal:d})}}):fe.create()}var zo={object:M.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Zo=(r,e={message:`Input not instance of ${r.name}`})=>Xn(t=>t instanceof r,e),Qn=ue.create,ei=ke.create,Fo=nt.create,Vo=Te.create,ti=Ee.create,Bo=Ae.create,Wo=Qe.create,Ho=Oe.create,qo=Ce.create,Go=fe.create,Yo=oe.create,Jo=J.create,Ko=et.create,Xo=se.create,Qo=M.create,es=M.strictCreate,ts=$e.create,rs=ir.create,ns=je.create,is=ee.create,os=or.create,ss=tt.create,as=rt.create,cs=sr.create,ls=Ie.create,ds=Re.create,us=Pe.create,fs=De.create,ps=pe.create,Wn=Z.create,hs=V.create,ms=te.create,vs=Z.createWithPreprocess,ys=_t.create,gs=()=>Qn().optional(),_s=()=>ei().optional(),bs=()=>ti().optional(),xs={string:(r=>ue.create({...r,coerce:!0})),number:(r=>ke.create({...r,coerce:!0})),boolean:(r=>Ee.create({...r,coerce:!0})),bigint:(r=>Te.create({...r,coerce:!0})),date:(r=>Ae.create({...r,coerce:!0}))},ws=_,a=Object.freeze({__proto__:null,defaultErrorMap:Xe,setErrorMap:vo,getErrorMap:tr,makeIssue:rr,EMPTY_PATH:yo,addIssueToContext:h,ParseStatus:P,INVALID:_,DIRTY:Ke,OK:D,isAborted:Vr,isDirty:Br,isValid:Se,isAsync:yt,get util(){return T},get objectUtil(){return Fr},ZodParsedType:m,getParsedType:ie,ZodType:x,datetimeRegex:Jn,ZodString:ue,ZodNumber:ke,ZodBigInt:Te,ZodBoolean:Ee,ZodDate:Ae,ZodSymbol:Qe,ZodUndefined:Oe,ZodNull:Ce,ZodAny:fe,ZodUnknown:oe,ZodNever:J,ZodVoid:et,ZodArray:se,ZodObject:M,ZodUnion:$e,ZodDiscriminatedUnion:ir,ZodIntersection:je,ZodTuple:ee,ZodRecord:or,ZodMap:tt,ZodSet:rt,ZodFunction:sr,ZodLazy:Ie,ZodLiteral:Re,ZodEnum:Pe,ZodNativeEnum:De,ZodPromise:pe,ZodEffects:Z,ZodTransformer:Z,ZodOptional:V,ZodNullable:te,ZodDefault:Me,ZodCatch:Ne,ZodNaN:nt,BRAND:Uo,ZodBranded:gt,ZodPipeline:_t,ZodReadonly:Le,custom:Xn,Schema:x,ZodSchema:x,late:zo,get ZodFirstPartyTypeKind(){return g},coerce:xs,any:Go,array:Xo,bigint:Vo,boolean:ti,date:Bo,discriminatedUnion:rs,effect:Wn,enum:us,function:cs,instanceof:Zo,intersection:ns,lazy:ls,literal:ds,map:ss,nan:Fo,nativeEnum:fs,never:Jo,null:qo,nullable:ms,number:ei,object:Qo,oboolean:bs,onumber:_s,optional:hs,ostring:gs,pipeline:ys,preprocess:vs,promise:ps,record:os,set:as,strictObject:es,string:Qn,symbol:Wo,transformer:Wn,tuple:is,undefined:Ho,union:ts,unknown:Yo,void:Ko,NEVER:ws,ZodIssueCode:f,quotelessJson:mo,ZodError:z});var oi=(r=>(r.Info="info",r.Debug="debug",r.Trace="trace",r.Error="error",r))(oi||{}),si=(r=>(r.Changed="Changed",r.Added="Added",r.Removed="Removed",r))(si||{}),ai=(r=>(r.External="BSLIVE_EXTERNAL",r))(ai||{}),Ss=a.string(),bt=a.lazy(()=>a.object({id:a.string(),label:a.string(),nodes:a.array(bt)})),ks=a.nativeEnum(oi),ri=a.object({log_level:ks}),Ts=a.object({ws_path:a.string(),host:a.string().optional()}),Es=a.object({kind:a.string(),ms:a.string()}),As=a.object({message:a.string(),reason:a.string().optional()}),ni=a.object({path:a.string()}),Os=a.object({paths:a.array(a.string())}),it=a.discriminatedUnion("kind",[a.object({kind:a.literal("Both"),payload:a.object({name:a.string(),bind_address:a.string()})}),a.object({kind:a.literal("Address"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Named"),payload:a.object({name:a.string()})}),a.object({kind:a.literal("Port"),payload:a.object({port:a.number()})}),a.object({kind:a.literal("PortNamed"),payload:a.object({port:a.number(),name:a.string()})})]),Cs=a.object({id:a.string(),identity:it,socket_addr:a.string()}),$s=a.object({servers:a.array(Cs)}),ci=a.object({connect:Ts,ctx_message:a.string()}),js=a.object({path:a.string()}),Is=a.object({error:a.string()}),Rs=a.object({body:a.string()}),Ps=a.discriminatedUnion("kind",[a.object({kind:a.literal("Html"),payload:a.object({html:a.string()})}),a.object({kind:a.literal("Json"),payload:a.object({json_str:a.string()})}),a.object({kind:a.literal("Raw"),payload:a.object({raw:a.string()})}),a.object({kind:a.literal("Sse"),payload:a.object({sse:Rs})}),a.object({kind:a.literal("Proxy"),payload:a.object({proxy:a.string()})}),a.object({kind:a.literal("Dir"),payload:a.object({dir:a.string(),base:a.string().optional()})})]),ii=a.object({path:a.string(),kind_str:a.string()}),Ds=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stopped"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("Patched"),payload:a.undefined().optional()}),a.object({kind:a.literal("Errored"),payload:a.object({error:a.string()})})]),Ms=a.object({identity:it,change:Ds}),tf=a.object({items:a.array(Ms)}),Ns=a.discriminatedUnion("kind",[a.object({kind:a.literal("Created"),payload:a.object({identity:it,socket_addr:a.string()})}),a.object({kind:a.literal("Stopped"),payload:a.object({identity:it})}),a.object({kind:a.literal("CreateErr"),payload:a.object({error:a.string()})}),a.object({kind:a.literal("Patched"),payload:a.object({identity:it,added:a.array(ii),changed:a.array(ii)})}),a.object({kind:a.literal("PatchErr"),payload:a.object({identity:it,error:a.string()})})]),Ls=a.object({changeset:a.array(Ns),servers_resp:$s}),Us=a.object({path:a.string(),kind:Ps}),zs=a.object({error:a.string()}),Zs=a.object({line:a.string(),prefix:a.string().optional()}),Fs=a.object({line:a.string(),prefix:a.string().optional()}),Vs=a.object({paths:a.array(a.string())}),Bs=a.union([a.object({kind:a.literal("Ok"),payload:a.undefined().optional()}),a.object({kind:a.literal("Err"),payload:a.string()}),a.object({kind:a.literal("Cancelled"),payload:a.undefined().optional()})]),Ws=a.object({tree:bt,will_exec:a.boolean()}),Hs=a.object({paths:a.array(a.string()),debounce:Es}),qs=a.nativeEnum(si),cr=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Fs"),payload:a.object({path:a.string(),change_kind:qs})}),a.object({kind:a.literal("FsMany"),payload:a.array(cr)})])),rf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Change"),payload:cr}),a.object({kind:a.literal("WsConnection"),payload:ri}),a.object({kind:a.literal("Config"),payload:ri}),a.object({kind:a.literal("DisplayMessage"),payload:As})]),nf=a.nativeEnum(ai),Gs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stdout"),payload:Fs}),a.object({kind:a.literal("Stderr"),payload:Zs})]),of=a.discriminatedUnion("kind",[a.object({kind:a.literal("MissingInputs"),payload:a.string()}),a.object({kind:a.literal("InvalidInput"),payload:a.string()}),a.object({kind:a.literal("NotFound"),payload:a.string()}),a.object({kind:a.literal("InputWriteError"),payload:a.string()}),a.object({kind:a.literal("PathError"),payload:a.string()}),a.object({kind:a.literal("PortError"),payload:a.string()}),a.object({kind:a.literal("DirError"),payload:a.string()}),a.object({kind:a.literal("YamlError"),payload:a.string()}),a.object({kind:a.literal("MarkdownError"),payload:a.string()}),a.object({kind:a.literal("HtmlError"),payload:a.string()}),a.object({kind:a.literal("Io"),payload:a.string()}),a.object({kind:a.literal("UnsupportedExtension"),payload:a.string()}),a.object({kind:a.literal("MissingExtension"),payload:a.string()}),a.object({kind:a.literal("EmptyInput"),payload:a.string()}),a.object({kind:a.literal("BsLiveRules"),payload:a.string()})]),sf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("FailedStartup"),payload:a.string()})]),af=a.object({routes:a.array(Us),id:a.string()}),Ys=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.object({tree:bt})}),a.object({kind:a.literal("Ended"),payload:a.object({tree:bt,report:ar,report_map:a.record(ar)})}),a.object({kind:a.literal("Error"),payload:a.undefined().optional()})])),ar=a.lazy(()=>a.object({result:Ks})),Js=a.lazy(()=>a.object({stage:Ys})),Ks=a.lazy(()=>a.object({conclusion:Bs,invocation_id:Ss,task_reports:a.array(ar)})),Xs=a.lazy(()=>a.object({tree:bt,report_map:a.record(ar)})),cf=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("FileChanged"),payload:ni}),a.object({kind:a.literal("FilesChanged"),payload:Os}),a.object({kind:a.literal("OutputLine"),payload:Gs}),a.object({kind:a.literal("InputFileChanged"),payload:ni}),a.object({kind:a.literal("InputAccepted"),payload:js}),a.object({kind:a.literal("InputError"),payload:Is}),a.object({kind:a.literal("StartupError"),payload:zs}),a.object({kind:a.literal("ServerChangeset"),payload:Ls}),a.object({kind:a.literal("TaskAction"),payload:Js}),a.object({kind:a.literal("TaskTreePreview"),payload:Ws}),a.object({kind:a.literal("TaskTreeSummary"),payload:Xs}),a.object({kind:a.literal("Watching"),payload:Hs}),a.object({kind:a.literal("WatchingStopped"),payload:Vs})]));var li=[{selector:"background",styleNames:["backgroundImage"]},{selector:"border",styleNames:["borderImage","webkitBorderImage","MozBorderImage"]}],lr={stylesheetReloadTimeout:15e3},Qs=/\.(jpe?g|png|gif|svg)$/i,dr=class{constructor(e,t,n){this.window=e,this.console=t,this.Timer=n,this.document=this.window.document,this.importCacheWaitPeriod=200,this.plugins=[]}addPlugin(e){return this.plugins.push(e)}analyze(e){}reload(e,t={}){if(this.options={...lr,...t},!(t.liveCSS&&e.match(/\.css(?:\.map)?$/i)&&this.reloadStylesheet(e))){if(t.liveImg&&e.match(Qs)){this.reloadImages(e);return}if(t.isChromeExtension){this.reloadChromeExtension();return}return this.reloadPage()}}reloadPage(){return this.window.document.location.reload()}reloadChromeExtension(){return this.window.chrome.runtime.reload()}reloadImages(e){let t,n=this.generateUniqueString();for(t of Array.from(this.document.images))di(e,Hr(t.src))&&(t.src=this.generateCacheBustUrl(t.src,n));if(this.document.querySelectorAll)for(let{selector:i,styleNames:o}of li)for(t of Array.from(this.document.querySelectorAll(`[style*=${i}]`)))this.reloadStyleImages(t.style,o,e,n);if(this.document.styleSheets)return Array.from(this.document.styleSheets).map(i=>this.reloadStylesheetImages(i,e,n))}reloadStylesheetImages(e,t,n){let i;try{i=(e||{}).cssRules}catch{}if(i)for(let o of Array.from(i))switch(o.type){case CSSRule.IMPORT_RULE:this.reloadStylesheetImages(o.styleSheet,t,n);break;case CSSRule.STYLE_RULE:for(let{styleNames:s}of li)this.reloadStyleImages(o.style,s,t,n);break;case CSSRule.MEDIA_RULE:this.reloadStylesheetImages(o,t,n);break}}reloadStyleImages(e,t,n,i){for(let o of t){let s=e[o];if(typeof s=="string"){let c=s.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"),(l,d)=>di(n,Hr(d))?`url(${this.generateCacheBustUrl(d,i)})`:l);c!==s&&(e[o]=c)}}}reloadStylesheet(e){let t=this.options||lr,n,i,o=(()=>{let l=[];for(i of Array.from(this.document.getElementsByTagName("link")))i.rel.match(/^stylesheet$/i)&&!i.__LiveReload_pendingRemoval&&l.push(i);return l})(),s=[];for(n of Array.from(this.document.getElementsByTagName("style")))n.sheet&&this.collectImportedStylesheets(n,n.sheet,s);for(i of Array.from(o))this.collectImportedStylesheets(i,i.sheet,s);if(this.window.StyleFix&&this.document.querySelectorAll)for(n of Array.from(this.document.querySelectorAll("style[data-href]")))o.push(n);this.console.debug(`found ${o.length} LINKed stylesheets, ${s.length} @imported stylesheets`);let c=ea(e,o.concat(s),l=>Hr(this.linkHref(l)));if(c)c.object.rule?(this.console.debug(`is reloading imported stylesheet: ${c.object.href}`),this.reattachImportedRule(c.object)):(this.console.debug(`is reloading stylesheet: ${this.linkHref(c.object)}`),this.reattachStylesheetLink(c.object));else if(t.reloadMissingCSS){this.console.debug(`will reload all stylesheets because path '${e}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`);for(i of Array.from(o))this.reattachStylesheetLink(i)}else this.console.debug(`will not reload path '${e}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.`);return!0}collectImportedStylesheets(e,t,n){let i;try{i=(t||{}).cssRules}catch{}if(i&&i.length)for(let o=0;o{if(!i)return i=!0,t()};if(e.onload=()=>(this.console.debug("the new stylesheet has finished loading"),this.knownToSupportCssOnLoad=!0,o()),!this.knownToSupportCssOnLoad){let s;(s=()=>e.sheet?(this.console.debug("is polling until the new CSS finishes loading..."),o()):this.Timer.start(50,s))()}return this.Timer.start(n.stylesheetReloadTimeout,o)}linkHref(e){return e.href||e.getAttribute&&e.getAttribute("data-href")}reattachStylesheetLink(e){let t;if(e.__LiveReload_pendingRemoval)return;e.__LiveReload_pendingRemoval=!0,e.tagName==="STYLE"?(t=this.document.createElement("link"),t.rel="stylesheet",t.media=e.media,t.disabled=e.disabled):t=e.cloneNode(!1),t.href=this.generateCacheBustUrl(this.linkHref(e));let n=e.parentNode;return n.lastChild===e?n.appendChild(t):n.insertBefore(t,e.nextSibling),this.waitUntilCssLoads(t,()=>{let i;return/AppleWebKit/.test(this.window.navigator.userAgent)?i=5:i=200,this.Timer.start(i,()=>{if(e.parentNode)return e.parentNode.removeChild(e),t.onreadystatechange=null,this.window.StyleFix?this.window.StyleFix.link(t):void 0})})}reattachImportedRule({rule:e,index:t,link:n}){let i=e.parentStyleSheet,o=this.generateCacheBustUrl(e.href),s=e.media.length?[].join.call(e.media,", "):"",c=`@import url("${o}") ${s};`;e.__LiveReload_newHref=o;let l=this.document.createElement("link");return l.rel="stylesheet",l.href=o,l.__LiveReload_pendingRemoval=!0,n.parentNode&&n.parentNode.insertBefore(l,n),this.Timer.start(this.importCacheWaitPeriod,()=>{if(l.parentNode&&l.parentNode.removeChild(l),e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1),e=i.cssRules[t],e.__LiveReload_newHref=o,this.Timer.start(this.importCacheWaitPeriod,()=>{if(e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1)})})}generateUniqueString(){return`livereload=${Date.now()}`}generateCacheBustUrl(e,t){let n=this.options||lr,i,o;if(t||(t=this.generateUniqueString()),{url:e,hash:i,params:o}=ui(e),n.overrideURL&&e.indexOf(n.serverURL)<0){let c=e;e=n.serverURL+n.overrideURL+"?url="+encodeURIComponent(e),this.console.debug(`is overriding source URL ${c} with ${e}`)}let s=o.replace(/(\?|&)livereload=(\d+)/,(c,l)=>`${l}${t}`);return s===o&&(o.length===0?s=`?${t}`:s=`${o}&${t}`),e+s+i}};function ui(r){let e="",t="",n=r.indexOf("#");n>=0&&(e=r.slice(n),r=r.slice(0,n));let i=r.indexOf("??");return i>=0?i+1!==r.lastIndexOf("?")&&(n=r.lastIndexOf("?")):n=r.indexOf("?"),n>=0&&(t=r.slice(n),r=r.slice(0,n)),{url:r,params:t,hash:e}}function Hr(r){if(!r)return"";let e;return{url:r}=ui(r),r.indexOf("file://")===0?e=r.replace(new RegExp("^file://(localhost)?"),""):e=r.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"),"/"),decodeURIComponent(e)}function fi(r,e){if(r=r.replace(/^\/+/,"").toLowerCase(),e=e.replace(/^\/+/,"").toLowerCase(),r===e)return 1e4;let t=r.split(/\/|\\/).reverse(),n=e.split(/\/|\\/).reverse(),i=Math.min(t.length,n.length),o=0;for(;on){let n,i={score:0};for(let o of e)n=fi(r,t(o)),n>i.score&&(i={object:o,score:n});return i.score===0?null:i}function di(r,e){return fi(r,e)>0}var mi=Yi(hi(),1);var ta=/\.(jpe?g|png|gif|svg)$/i;function qr(r,e,t){switch(r.kind){case"FsMany":{if(r.payload.some(i=>{switch(i.kind){case"Fs":return!(i.payload.path.match(/\.css(?:\.map)?$/i)||i.payload.path.match(ta));case"FsMany":throw new Error("unreachable")}}))return window.__playwright?.record?window.__playwright?.record({kind:"reloadPage"}):t.reloadPage();for(let i of r.payload)qr(i,e,t);break}case"Fs":{let n=r.payload.path,i={liveCSS:!0,liveImg:!0,reloadMissingCSS:!0,originalPath:"",overrideURL:"",serverURL:""};window.__playwright?.record?window.__playwright?.record({kind:"reload",args:{path:n,opts:i}}):(e.trace("will reload a file with path ",n),t.reload(n,i))}}}var Gr={name:"dom plugin",globalSetup:(r,e)=>{let t=new dr(window,e,mi.Timer);return[r,[e,t]]},resetSink(r,e,t){let[n,i]=e;return r.pipe(de(o=>o.kind==="Change"),Q(o=>o.payload),we(o=>{n.trace("incoming message",JSON.stringify({change:o,config:t},null,2));let s=cr.parse(o);qr(s,n,i)}),xe())}};var fr=globalThis,pr=fr.ShadowRoot&&(fr.ShadyCSS===void 0||fr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Yr=Symbol(),vi=new WeakMap,xt=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Yr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(pr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=vi.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&vi.set(t,e))}return e}toString(){return this.cssText}},yi=r=>new xt(typeof r=="string"?r:r+"",void 0,Yr),K=(r,...e)=>{let t=r.length===1?r[0]:e.reduce((n,i,o)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[o+1],r[0]);return new xt(t,r,Yr)},gi=(r,e)=>{if(pr)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),i=fr.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Jr=pr?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return yi(t)})(r):r;var{is:ra,defineProperty:na,getOwnPropertyDescriptor:ia,getOwnPropertyNames:oa,getOwnPropertySymbols:sa,getPrototypeOf:aa}=Object,hr=globalThis,_i=hr.trustedTypes,ca=_i?_i.emptyScript:"",la=hr.reactiveElementPolyfillSupport,wt=(r,e)=>r,St={toAttribute(r,e){switch(e){case Boolean:r=r?ca:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mr=(r,e)=>!ra(r,e),bi={attribute:!0,type:String,converter:St,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),hr.litPropertyMetadata??=new WeakMap;var ae=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=bi){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&na(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){let{get:i,set:o}=ia(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){let c=i?.call(this);o?.call(this,s),this.requestUpdate(e,c,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??bi}static _$Ei(){if(this.hasOwnProperty(wt("elementProperties")))return;let e=aa(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(wt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(wt("properties"))){let t=this.properties,n=[...oa(t),...sa(t)];for(let i of n)this.createProperty(i,t[i])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let i of n)t.unshift(Jr(i))}else e!==void 0&&t.push(Jr(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gi(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){let o=(n.converter?.toAttribute!==void 0?n.converter:St).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,t){let n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){let o=n.getPropertyOptions(i),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:St;this._$Em=i;let c=s.fromAttribute(t,o.type);this[i]=c??this._$Ej?.get(i)??c,this._$Em=null}}requestUpdate(e,t,n,i=!1,o){if(e!==void 0){let s=this.constructor;if(i===!1&&(o=this[e]),n??=s.getPropertyOptions(e),!((n.hasChanged??mr)(o,t)||n.useDefault&&n.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:o},s){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[i,o]of n){let{wrapped:s}=o,c=this[i];s!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};ae.elementStyles=[],ae.shadowRootOptions={mode:"open"},ae[wt("elementProperties")]=new Map,ae[wt("finalized")]=new Map,la?.({ReactiveElement:ae}),(hr.reactiveElementVersions??=[]).push("2.1.2");var Xr=globalThis,xi=r=>r,vr=Xr.trustedTypes,wi=vr?vr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Qr="$lit$",ce=`lit$${Math.random().toFixed(9).slice(2)}$`,en="?"+ce,da=`<${en}>`,Ze=document,Tt=()=>Ze.createComment(""),Et=r=>r===null||typeof r!="object"&&typeof r!="function",tn=Array.isArray,Oi=r=>tn(r)||typeof r?.[Symbol.iterator]=="function",Kr=`[ -\f\r]`,kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Si=/-->/g,ki=/>/g,Ue=RegExp(`>|${Kr}(?:([^\\s"'>=/]+)(${Kr}*=${Kr}*(?:[^ -\f\r"'\`<>=]|("|')|))|$)`,"g"),Ti=/'/g,Ei=/"/g,Ci=/^(?:script|style|textarea|title)$/i,rn=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),N=rn(1),Sf=rn(2),kf=rn(3),Fe=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),Ai=new WeakMap,ze=Ze.createTreeWalker(Ze,129);function $i(r,e){if(!tn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return wi!==void 0?wi.createHTML(e):e}var ji=(r,e)=>{let t=r.length-1,n=[],i,o=e===2?"":e===3?"":"",s=kt;for(let c=0;c"?(s=i??kt,p=-1):u[1]===void 0?p=-2:(p=s.lastIndex-u[2].length,d=u[1],s=u[3]===void 0?Ue:u[3]==='"'?Ei:Ti):s===Ei||s===Ti?s=Ue:s===Si||s===ki?s=kt:(s=Ue,i=void 0);let y=s===Ue&&r[c+1].startsWith("/>")?" ":"";o+=s===kt?l+da:p>=0?(n.push(d),l.slice(0,p)+Qr+l.slice(p)+ce+y):l+ce+(p===-2?c:y)}return[$i(r,o+(r[t]||"")+(e===2?"":e===3?"":"")),n]},At=class r{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let o=0,s=0,c=e.length-1,l=this.parts,[d,u]=ji(e,t);if(this.el=r.createElement(d,n),ze.currentNode=this.el.content,t===2||t===3){let p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(i=ze.nextNode())!==null&&l.length0){i.textContent=vr?vr.emptyScript:"";for(let y=0;y2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=O}_$AI(e,t=this,n,i){let o=this.strings,s=!1;if(o===void 0)e=Ve(this,e,t,0),s=!Et(e)||e!==this._$AH&&e!==Fe,s&&(this._$AH=e);else{let c=e,l,d;for(e=o[0],l=0;l{let n=t?.renderBefore??e,i=n._$litPart$;if(i===void 0){let o=t?.renderBefore??null;n._$litPart$=i=new ot(e.insertBefore(Tt(),o),o,void 0,t??{})}return i._$AI(r),i};var nn=globalThis,L=class extends ae{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=wr(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};L._$litElement$=!0,L.finalized=!0,nn.litElementHydrateSupport?.({LitElement:L});var fa=nn.litElementPolyfillSupport;fa?.({LitElement:L});(nn.litElementVersions??=[]).push("4.2.2");var st=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)};var pa={attribute:!0,type:String,converter:St,reflect:!1,hasChanged:mr},ha=(r=pa,e,t)=>{let{kind:n,metadata:i}=t,o=globalThis.litPropertyMetadata.get(i);if(o===void 0&&globalThis.litPropertyMetadata.set(i,o=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),o.set(t.name,r),n==="accessor"){let{name:s}=t;return{set(c){let l=e.get.call(this);e.set.call(this,c),this.requestUpdate(s,l,r,!0,c)},init(c){return c!==void 0&&this.C(s,void 0,r,c),c}}}if(n==="setter"){let{name:s}=t;return function(c){let l=this[s];e.call(this,c),this.requestUpdate(s,l,r,!0,c)}}throw Error("Unsupported decorator location: "+n)};function he(r){return(e,t)=>typeof t=="object"?ha(r,e,t):((n,i,o)=>{let s=i.hasOwnProperty(o);return i.constructor.createProperty(o,n),s?Object.getOwnPropertyDescriptor(i,o):void 0})(r,e,t)}var{I:up}=Ii;var Ri=r=>r.strings===void 0;var Pi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},on=r=>(...e)=>({_$litDirective$:r,values:e}),kr=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};var Ot=(r,e)=>{let t=r._$AN;if(t===void 0)return!1;for(let n of t)n._$AO?.(e,!1),Ot(n,e);return!0},Tr=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while(t?.size===0)},Di=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),ya(e)}};function ma(r){this._$AN!==void 0?(Tr(this),this._$AM=r,Di(this)):this._$AM=r}function va(r,e=!1,t=0){let n=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(n))for(let o=t;o{r.type==Pi.CHILD&&(r._$AP??=va,r._$AQ??=ma)},Er=class extends kr{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),Di(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Ot(this,e),Tr(this))}setValue(e){if(Ri(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};var Mi=()=>new an,an=class{},sn=new WeakMap,Ni=on(class extends Er{render(r){return O}update(r,[e]){let t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=r.options?.host,this.rt(this.ct=r.element)),O}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){let e=this.ht??globalThis,t=sn.get(e);t===void 0&&(t=new WeakMap,sn.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){return typeof this.G=="function"?sn.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var me=K` + `):"",this.name="UnsubscriptionError",this.errors=t}});function ve(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var X=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=re(s),l=c.next();!l.done;l=c.next()){var d=l.value;d.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var u=this.initialTeardown;if(k(u))try{u()}catch(w){o=w instanceof Pt?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var S=re(p),v=S.next();!v.done;v=S.next()){var A=v.value;try{pn(A)}catch(w){o=o??[],w instanceof Pt?o=q(q([],H(o)),H(w.errors)):o.push(w)}}}catch(w){n={error:w}}finally{try{v&&!v.done&&(i=S.return)&&i.call(S)}finally{if(n)throw n.error}}}if(o)throw new Pt(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)pn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ve(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ve(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var $r=X.EMPTY;function Mt(r){return r instanceof X||r&&"closed"in r&&k(r.remove)&&k(r.add)&&k(r.unsubscribe)}function pn(r){k(r)?r():r.unsubscribe()}var G={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ge={setTimeout:function(r,e){for(var t=[],n=2;n0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,s=i.isStopped,c=i.observers;return o||s?$r:(this.currentObservers=null,c.push(t),new X(function(){n.currentObservers=null,ve(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?t.error(o):s&&t.complete()},e.prototype.asObservable=function(){var t=new E;return t.source=this,t},e.create=function(t,n){return new Ut(t,n)},e})(E);var Ut=(function(r){R(e,r);function e(t,n){var i=r.call(this)||this;return i.destination=t,i.source=n,i}return e.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},e.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:$r},e})(Y);var ut={now:function(){return(ut.delegate||Date).now()},delegate:void 0};var zt=(function(r){R(e,r);function e(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=ut);var o=r.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return e.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,c=n._timestampProvider,l=n._windowTime;i||(o.push(t),!s&&o.push(c.now()+l)),this._trimBuffer(),r.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,s=i._buffer,c=s.slice(),l=0;l0&&(u=new _e({next:function(jt){return $t.next(jt)},error:function(jt){w=!0,I(),p=Nr(U,i,jt),$t.error(jt)},complete:function(){A=!0,I(),p=Nr(U,s),$t.complete()}}),j(lt).subscribe(u))})(d)}}function Nr(r,e){for(var t=[],n=2;n{let e=new URL(window.location.href),t=e.protocol==="https:"?"wss":"ws",n;if(r.host)n=new URL(r.ws_path,t+"://"+r.host);else{let o=new URL(e);o.protocol=t,o.pathname=r.ws_path,n=o}return Ur(n.toString()).pipe(Mr({delay:5e3}))}}}var Fn={debug(...r){},error(...r){},info(...r){},trace(...r){}},zr={name:"console",globalSetup:r=>{let e=new Y;return[e,{debug:function(...n){e.next({level:"debug",args:n})},info:function(...n){e.next({level:"info",args:n})},trace:function(...n){e.next({level:"trace",args:n})},error:function(...n){e.next({level:"error",args:n})}}]},resetSink:(r,e,t)=>r.pipe(Se(n=>{let i=["trace","debug","info","error"],o=i.indexOf(n.level),s=i.indexOf(t.log_level);o>=s&&console.log(`[${n.level}]`,...n.args)}),xe())};var T;(function(r){r.assertEqual=i=>i;function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),s={};for(let c of o)s[c]=i[c];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(T||(T={}));var Fr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fr||(Fr={}));var m=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},f=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),yo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let c=n,l=0;for(;lt.message){let t={},n=[];for(let i of this.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Qe=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}},Hn=Qe;function vo(r){Hn=r}function tr(){return Hn}var rr=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(s,{data:e,defaultError:c}).message;return{...i,path:o,message:c}},go=[];function h(r,e){let t=tr(),n=rr({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Qe?void 0:Qe].filter(i=>!!i)});r.common.issues.push(n)}var D=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return b;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return b;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},b=Object.freeze({status:"aborted"}),Xe=r=>({status:"dirty",value:r}),P=r=>({status:"valid",value:r}),Vr=r=>r.status==="aborted",Wr=r=>r.status==="dirty",we=r=>r.status==="valid",vt=r=>typeof Promise<"u"&&r instanceof Promise;function nr(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}function qn(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}var y;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(y||(y={}));var mt,yt,W=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vn=(r,e)=>{if(we(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function _(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,c)=>{var l,d;let{message:u}=r;return s.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??n)!==null&&l!==void 0?l:c.defaultError}:s.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??t)!==null&&d!==void 0?d:c.defaultError}},description:i}}var x=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new D,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(vt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;let i={common:{issues:[],async:(n=t?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Vn(i,o)}"~validate"(e){var t,n;let i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:i});return we(o)?{value:o.value}:{issues:i.common.issues}}catch(o){!((n=(t=o?.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:i}).then(o=>we(o)?{value:o.value}:{issues:i.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(vt(i)?i:Promise.resolve(i));return Vn(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),c=()=>o.addIssue({code:f.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(c(),!1)):s?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Z({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return V.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return pe.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new Z({..._(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Me({..._(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new gt({typeName:g.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ne({..._(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return bt.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bo=/^c[^\s-]{8,}$/i,_o=/^[0-9a-z]+$/,xo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,So=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wo=/^[a-z0-9_-]{21}$/i,ko=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,To=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ao=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zr,Oo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Co=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$o=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,jo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ro=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Io=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Do=new RegExp(`^${Gn}$`);function Yn(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Po(r){return new RegExp(`^${Yn(r)}$`)}function Jn(r){let e=`${Gn}T${Yn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Mo(r,e){return!!((e==="v4"||!e)&&Oo.test(r)||(e==="v6"||!e)&&$o.test(r))}function No(r,e){if(!ko.test(r))return!1;try{let[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||!i.typ||!i.alg||e&&i.alg!==e)}catch{return!1}}function Lo(r,e){return!!((e==="v4"||!e)&&Co.test(r)||(e==="v6"||!e)&&jo.test(r))}var ue=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.string,received:o.parsedType}),b}let n=new D,i;for(let o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,c=e.data.lengthe.test(i),{validation:t,code:f.invalid_string,...y.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...y.errToObj(e)})}url(e){return this._addCheck({kind:"url",...y.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...y.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...y.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...y.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...y.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...y.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...y.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...y.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...y.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...y.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...y.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...y.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...y.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...y.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...y.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...y.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...y.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...y.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...y.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...y.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...y.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...y.errToObj(t)})}nonempty(e){return this.min(1,y.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new ue({checks:[],typeName:g.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};function Uo(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=parseInt(r.toFixed(i).replace(".","")),s=parseInt(e.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}var ke=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.number,received:o.parsedType}),b}let n,i=new D;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Uo(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_finite,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:y.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:y.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:y.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew ke({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,..._(r)});var Te=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let n,i=new D;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.bigint,received:t.parsedType}),b}gte(e,t){return this.setLimit("min",e,!0,y.toString(t))}gt(e,t){return this.setLimit("min",e,!1,y.toString(t))}lte(e,t){return this.setLimit("max",e,!0,y.toString(t))}lt(e,t){return this.setLimit("max",e,!1,y.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:y.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:y.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Te({checks:[],typeName:g.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};var Ae=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.boolean,received:n.parsedType}),b}return P(e.data)}};Ae.create=r=>new Ae({typeName:g.ZodBoolean,coerce:r?.coerce||!1,..._(r)});var Ee=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.date,received:o.parsedType}),b}if(isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),b}let n=new D,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):T.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:y.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:y.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Ee({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,..._(r)});var et=class extends x{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.symbol,received:n.parsedType}),b}return P(e.data)}};et.create=r=>new et({typeName:g.ZodSymbol,..._(r)});var Oe=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.undefined,received:n.parsedType}),b}return P(e.data)}};Oe.create=r=>new Oe({typeName:g.ZodUndefined,..._(r)});var Ce=class extends x{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.null,received:n.parsedType}),b}return P(e.data)}};Ce.create=r=>new Ce({typeName:g.ZodNull,..._(r)});var fe=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return P(e.data)}};fe.create=r=>new fe({typeName:g.ZodAny,..._(r)});var oe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return P(e.data)}};oe.create=r=>new oe({typeName:g.ZodUnknown,..._(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),b}};J.create=r=>new J({typeName:g.ZodNever,..._(r)});var tt=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.void,received:n.parsedType}),b}return P(e.data)}};tt.create=r=>new tt({typeName:g.ZodVoid,..._(r)});var se=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),b;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,c=t.data.lengthi.maxLength.value&&(h(t,{code:f.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,c)=>i.type._parseAsync(new W(t,s,t.path,c)))).then(s=>D.mergeArray(n,s));let o=[...t.data].map((s,c)=>i.type._parseSync(new W(t,s,t.path,c)));return D.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:y.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:y.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:y.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,..._(e)});function Ke(r){if(r instanceof M){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=V.create(Ke(n))}return new M({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:Ke(r.element)}):r instanceof V?V.create(Ke(r.unwrap())):r instanceof te?te.create(Ke(r.unwrap())):r instanceof ee?ee.create(r.items.map(e=>Ke(e))):r}var M=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return h(d,{code:f.invalid_type,expected:m.object,received:d.parsedType}),b}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),c=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let d in i.data)s.includes(d)||c.push(d);let l=[];for(let d of s){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new W(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof J){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(h(i,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new W(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,S=await u.value;d.push({key:p,value:S,alwaysSet:u.alwaysSet})}return d}).then(d=>D.mergeObjectSync(n,d)):D.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return y.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,o,s,c;let l=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,t,n).message)!==null&&s!==void 0?s:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=y.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return T.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}omit(e){let t={};return T.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}deepPartial(){return Ke(this)}partial(e){let t={};return T.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}),new r({...this._def,shape:()=>t})}required(e){let t={};return T.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof V;)o=o._def.innerType;t[n]=o}}),new r({...this._def,shape:()=>t})}keyof(){return Kn(T.objectKeys(this.shape))}};M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,..._(e)});M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:g.ZodObject,..._(e)});M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,..._(e)});var $e=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let s=o.map(c=>new z(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:s}),b}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let c=s.map(l=>new z(l));return h(t,{code:f.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}};$e.create=(r,e)=>new $e({options:r,typeName:g.ZodUnion,..._(e)});var ne=r=>r instanceof Re?ne(r.schema):r instanceof Z?ne(r.innerType()):r instanceof Ie?[r.value]:r instanceof De?r.options:r instanceof Pe?T.objectValues(r.enum):r instanceof Me?ne(r._def.innerType):r instanceof Oe?[void 0]:r instanceof Ce?[null]:r instanceof V?[void 0,...ne(r.unwrap())]:r instanceof te?[null,...ne(r.unwrap())]:r instanceof gt||r instanceof Le?ne(r.unwrap()):r instanceof Ne?ne(r._def.innerType):[],ir=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),b;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=ne(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of s){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,o)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,..._(n)})}};function Br(r,e){let t=ie(r),n=ie(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let i=T.objectKeys(e),o=T.objectKeys(r).filter(c=>i.indexOf(c)!==-1),s={...r,...e};for(let c of o){let l=Br(r[c],e[c]);if(!l.valid)return{valid:!1};s[c]=l.data}return{valid:!0,data:s}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o{if(Vr(o)||Vr(s))return b;let c=Br(o.value,s.value);return c.valid?((Wr(o)||Wr(s))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),b)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};je.create=(r,e,t)=>new je({left:r,right:e,typeName:g.ZodIntersection,..._(t)});var ee=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return h(n,{code:f.invalid_type,expected:m.array,received:n.parsedType}),b;if(n.data.lengththis._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new W(n,s,n.path,c)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>D.mergeArray(t,s)):D.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ee.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:r,typeName:g.ZodTuple,rest:null,..._(e)})};var or=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return h(n,{code:f.invalid_type,expected:m.object,received:n.parsedType}),b;let i=[],o=this._def.keyType,s=this._def.valueType;for(let c in n.data)i.push({key:o._parse(new W(n,c,n.path,c)),value:s._parse(new W(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?D.mergeObjectAsync(t,i):D.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:g.ZodRecord,..._(n)}):new r({keyType:ue.create(),valueType:e,typeName:g.ZodRecord,..._(t)})}},rt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return h(n,{code:f.invalid_type,expected:m.map,received:n.parsedType}),b;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([c,l],d)=>({key:i._parse(new W(n,c,n.path,[d,"key"])),value:o._parse(new W(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of s){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return b;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of s){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return b;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}}}};rt.create=(r,e,t)=>new rt({valueType:e,keyType:r,typeName:g.ZodMap,..._(t)});var nt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return h(n,{code:f.invalid_type,expected:m.set,received:n.parsedType}),b;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(h(n,{code:f.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(l){let d=new Set;for(let u of l){if(u.status==="aborted")return b;u.status==="dirty"&&t.dirty(),d.add(u.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>o._parse(new W(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>s(l)):s(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:y.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:y.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,..._(e)});var sr=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),b;function n(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Qe].filter(d=>!!d),issueData:{code:f.invalid_arguments,argumentsError:l}})}function i(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Qe].filter(d=>!!d),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof pe){let c=this;return P(async function(...l){let d=new z([]),u=await c._def.args.parseAsync(l,o).catch(v=>{throw d.addIssue(n(l,v)),d}),p=await Reflect.apply(s,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(v=>{throw d.addIssue(i(p,v)),d})})}else{let c=this;return P(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new z([n(l,d.error)]);let u=Reflect.apply(s,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new z([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ee.create(e).rest(oe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ee.create([]).rest(oe.create()),returns:t||oe.create(),typeName:g.ZodFunction,..._(n)})}},Re=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Re.create=(r,e)=>new Re({getter:r,typeName:g.ZodLazy,..._(e)});var Ie=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ie.create=(r,e)=>new Ie({value:r,typeName:g.ZodLiteral,..._(e)});function Kn(r,e){return new De({values:r,typeName:g.ZodEnum,..._(e)})}var De=class r extends x{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:T.joinValues(n),received:t.parsedType,code:f.invalid_type}),b}if(nr(this,mt,"f")||qn(this,mt,new Set(this._def.values),"f"),!nr(this,mt,"f").has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),b}return P(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};mt=new WeakMap;De.create=Kn;var Pe=class extends x{constructor(){super(...arguments),yt.set(this,void 0)}_parse(e){let t=T.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let i=T.objectValues(t);return h(n,{expected:T.joinValues(i),received:n.parsedType,code:f.invalid_type}),b}if(nr(this,yt,"f")||qn(this,yt,new Set(T.getValidEnumValues(this._def.values)),"f"),!nr(this,yt,"f").has(e.data)){let i=T.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:i}),b}return P(e.data)}get enum(){return this._def.values}};yt=new WeakMap;Pe.create=(r,e)=>new Pe({values:r,typeName:g.ZodNativeEnum,..._(e)});var pe=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),b;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return P(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};pe.create=(r,e)=>new pe({type:r,typeName:g.ZodPromise,..._(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{h(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async c=>{if(t.value==="aborted")return b;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?b:l.status==="dirty"||t.value==="dirty"?Xe(l.value):l});{if(t.value==="aborted")return b;let c=this._def.schema._parseSync({data:s,path:n.path,parent:n});return c.status==="aborted"?b:c.status==="dirty"||t.value==="dirty"?Xe(c.value):c}}if(i.type==="refinement"){let s=c=>{let l=i.refinement(c,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?b:(c.status==="dirty"&&t.dirty(),s(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?b:(c.status==="dirty"&&t.dirty(),s(c.value).then(()=>({status:t.value,value:c.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!we(s))return s;let c=i.transform(s.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>we(s)?Promise.resolve(i.transform(s.value,o)).then(c=>({status:t.value,value:c})):s);T.assertNever(i)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:g.ZodEffects,effect:e,..._(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,..._(t)});var V=class extends x{_parse(e){return this._getType(e)===m.undefined?P(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(r,e)=>new V({innerType:r,typeName:g.ZodOptional,..._(e)});var te=class extends x{_parse(e){return this._getType(e)===m.null?P(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:g.ZodNullable,..._(e)});var Me=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Me.create=(r,e)=>new Me({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var Ne=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return vt(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var it=class extends x{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.nan,received:n.parsedType}),b}return{status:"valid",value:e.data}}};it.create=r=>new it({typeName:g.ZodNaN,..._(r)});var zo=Symbol("zod_brand"),gt=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},bt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?b:o.status==="dirty"?(t.dirty(),Xe(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?b:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},Le=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=i=>(we(i)&&(i.value=Object.freeze(i.value)),i);return vt(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:g.ZodReadonly,..._(e)});function Wn(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xn(r,e={},t){return r?fe.create().superRefine((n,i)=>{var o,s;let c=r(n);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){let p=Wn(e,n),S=(u=(d=p.fatal)!==null&&d!==void 0?d:t)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...p,fatal:S})}});if(!c){let l=Wn(e,n),d=(s=(o=l.fatal)!==null&&o!==void 0?o:t)!==null&&s!==void 0?s:!0;i.addIssue({code:"custom",...l,fatal:d})}}):fe.create()}var Zo={object:M.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Fo=(r,e={message:`Input not instance of ${r.name}`})=>Xn(t=>t instanceof r,e),Qn=ue.create,ei=ke.create,Vo=it.create,Wo=Te.create,ti=Ae.create,Bo=Ee.create,Ho=et.create,qo=Oe.create,Go=Ce.create,Yo=fe.create,Jo=oe.create,Ko=J.create,Xo=tt.create,Qo=se.create,es=M.create,ts=M.strictCreate,rs=$e.create,ns=ir.create,is=je.create,os=ee.create,ss=or.create,as=rt.create,cs=nt.create,ls=sr.create,ds=Re.create,us=Ie.create,fs=De.create,ps=Pe.create,hs=pe.create,Bn=Z.create,ms=V.create,ys=te.create,vs=Z.createWithPreprocess,gs=bt.create,bs=()=>Qn().optional(),_s=()=>ei().optional(),xs=()=>ti().optional(),Ss={string:(r=>ue.create({...r,coerce:!0})),number:(r=>ke.create({...r,coerce:!0})),boolean:(r=>Ae.create({...r,coerce:!0})),bigint:(r=>Te.create({...r,coerce:!0})),date:(r=>Ee.create({...r,coerce:!0}))},ws=b,a=Object.freeze({__proto__:null,defaultErrorMap:Qe,setErrorMap:vo,getErrorMap:tr,makeIssue:rr,EMPTY_PATH:go,addIssueToContext:h,ParseStatus:D,INVALID:b,DIRTY:Xe,OK:P,isAborted:Vr,isDirty:Wr,isValid:we,isAsync:vt,get util(){return T},get objectUtil(){return Fr},ZodParsedType:m,getParsedType:ie,ZodType:x,datetimeRegex:Jn,ZodString:ue,ZodNumber:ke,ZodBigInt:Te,ZodBoolean:Ae,ZodDate:Ee,ZodSymbol:et,ZodUndefined:Oe,ZodNull:Ce,ZodAny:fe,ZodUnknown:oe,ZodNever:J,ZodVoid:tt,ZodArray:se,ZodObject:M,ZodUnion:$e,ZodDiscriminatedUnion:ir,ZodIntersection:je,ZodTuple:ee,ZodRecord:or,ZodMap:rt,ZodSet:nt,ZodFunction:sr,ZodLazy:Re,ZodLiteral:Ie,ZodEnum:De,ZodNativeEnum:Pe,ZodPromise:pe,ZodEffects:Z,ZodTransformer:Z,ZodOptional:V,ZodNullable:te,ZodDefault:Me,ZodCatch:Ne,ZodNaN:it,BRAND:zo,ZodBranded:gt,ZodPipeline:bt,ZodReadonly:Le,custom:Xn,Schema:x,ZodSchema:x,late:Zo,get ZodFirstPartyTypeKind(){return g},coerce:Ss,any:Yo,array:Qo,bigint:Wo,boolean:ti,date:Bo,discriminatedUnion:ns,effect:Bn,enum:fs,function:ls,instanceof:Fo,intersection:is,lazy:ds,literal:us,map:as,nan:Vo,nativeEnum:ps,never:Ko,null:Go,nullable:ys,number:ei,object:es,oboolean:xs,onumber:_s,optional:ms,ostring:bs,pipeline:gs,preprocess:vs,promise:hs,record:ss,set:cs,strictObject:ts,string:Qn,symbol:Ho,transformer:Bn,tuple:os,undefined:qo,union:rs,unknown:Jo,void:Xo,NEVER:ws,ZodIssueCode:f,quotelessJson:yo,ZodError:z});var oi=(r=>(r.Info="info",r.Debug="debug",r.Trace="trace",r.Error="error",r))(oi||{}),si=(r=>(r.Changed="Changed",r.Added="Added",r.Removed="Removed",r))(si||{}),ai=(r=>(r.External="BSLIVE_EXTERNAL",r))(ai||{}),ks=a.string(),Ts=a.object({dir:a.string()}),_t=a.lazy(()=>a.object({id:a.string(),label:a.string(),nodes:a.array(_t)})),As=a.nativeEnum(oi),ri=a.object({log_level:As}),Es=a.object({ws_path:a.string(),host:a.string().optional()}),Os=a.object({kind:a.string(),ms:a.string()}),Cs=a.object({message:a.string(),reason:a.string().optional()}),ni=a.object({path:a.string()}),$s=a.object({paths:a.array(a.string())}),Ue=a.discriminatedUnion("kind",[a.object({kind:a.literal("Both"),payload:a.object({name:a.string(),bind_address:a.string()})}),a.object({kind:a.literal("Address"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Named"),payload:a.object({name:a.string()})}),a.object({kind:a.literal("Port"),payload:a.object({port:a.number()})}),a.object({kind:a.literal("PortNamed"),payload:a.object({port:a.number(),name:a.string()})})]),js=a.object({id:a.string(),identity:Ue,socket_addr:a.string()}),Rs=a.object({servers:a.array(js)}),ci=a.object({connect:Es,ctx_message:a.string()}),Is=a.object({path:a.string()}),Ds=a.object({error:a.string()}),li=a.discriminatedUnion("kind",[a.object({kind:a.literal("Pending"),payload:a.undefined().optional()}),a.object({kind:a.literal("Waiting"),payload:a.object({reason:a.string()})}),a.object({kind:a.literal("Ready"),payload:a.undefined().optional()}),a.object({kind:a.literal("Failed"),payload:a.object({reason:a.string()})})]),Ps=a.object({address:a.string(),dir:a.string()}),Ms=a.object({address:a.string(),dir:a.string()}),Ns=a.discriminatedUnion("kind",[a.object({kind:a.literal("Server"),payload:Ps}),a.object({kind:a.literal("Route"),payload:Ms}),a.object({kind:a.literal("Any"),payload:Ts})]),Ls=a.object({body:a.string()}),Us=a.discriminatedUnion("kind",[a.object({kind:a.literal("Html"),payload:a.object({html:a.string()})}),a.object({kind:a.literal("Json"),payload:a.object({json_str:a.string()})}),a.object({kind:a.literal("Raw"),payload:a.object({raw:a.string()})}),a.object({kind:a.literal("Sse"),payload:a.object({sse:Ls})}),a.object({kind:a.literal("Proxy"),payload:a.object({proxy:a.string()})}),a.object({kind:a.literal("Dir"),payload:a.object({dir:a.string(),base:a.string().optional()})})]),ii=a.object({path:a.string(),kind_str:a.string()}),zs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stopped"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("Patched"),payload:a.undefined().optional()}),a.object({kind:a.literal("Errored"),payload:a.object({error:a.string()})})]),Zs=a.object({identity:Ue,change:zs}),lf=a.object({items:a.array(Zs)}),Fs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Created"),payload:a.object({identity:Ue,socket_addr:a.string()})}),a.object({kind:a.literal("Stopped"),payload:a.object({identity:Ue})}),a.object({kind:a.literal("CreateErr"),payload:a.object({error:a.string()})}),a.object({kind:a.literal("Patched"),payload:a.object({identity:Ue,added:a.array(ii),changed:a.array(ii)})}),a.object({kind:a.literal("PatchErr"),payload:a.object({identity:Ue,error:a.string()})})]),Vs=a.object({changeset:a.array(Fs),servers_resp:Rs}),Ws=a.object({path:a.string(),kind:Us}),Bs=a.object({status:li,server:Ue}),Hs=a.object({error:a.string()}),qs=a.object({line:a.string(),prefix:a.string().optional()}),Gs=a.object({line:a.string(),prefix:a.string().optional()}),Ys=a.object({paths:a.array(a.string())}),Js=a.union([a.object({kind:a.literal("Ok"),payload:a.undefined().optional()}),a.object({kind:a.literal("Err"),payload:a.string()}),a.object({kind:a.literal("Cancelled"),payload:a.undefined().optional()})]),Ks=a.object({tree:_t,will_exec:a.boolean()}),Xs=a.object({paths:a.array(a.string()),debounce:Os}),Qs=a.nativeEnum(si),cr=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Fs"),payload:a.object({path:a.string(),change_kind:Qs})}),a.object({kind:a.literal("FsMany"),payload:a.array(cr)})])),df=a.discriminatedUnion("kind",[a.object({kind:a.literal("Change"),payload:cr}),a.object({kind:a.literal("WsConnection"),payload:ri}),a.object({kind:a.literal("Config"),payload:ri}),a.object({kind:a.literal("DisplayMessage"),payload:Cs})]),uf=a.nativeEnum(ai),ea=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stdout"),payload:Gs}),a.object({kind:a.literal("Stderr"),payload:qs})]),ff=a.discriminatedUnion("kind",[a.object({kind:a.literal("MissingInputs"),payload:a.string()}),a.object({kind:a.literal("InvalidInput"),payload:a.string()}),a.object({kind:a.literal("NotFound"),payload:a.string()}),a.object({kind:a.literal("InputWriteError"),payload:a.string()}),a.object({kind:a.literal("PathError"),payload:a.string()}),a.object({kind:a.literal("PortError"),payload:a.string()}),a.object({kind:a.literal("DirError"),payload:a.string()}),a.object({kind:a.literal("YamlError"),payload:a.string()}),a.object({kind:a.literal("MarkdownError"),payload:a.string()}),a.object({kind:a.literal("HtmlError"),payload:a.string()}),a.object({kind:a.literal("Io"),payload:a.string()}),a.object({kind:a.literal("UnsupportedExtension"),payload:a.string()}),a.object({kind:a.literal("MissingExtension"),payload:a.string()}),a.object({kind:a.literal("EmptyInput"),payload:a.string()}),a.object({kind:a.literal("BsLiveRules"),payload:a.string()})]),pf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("FailedStartup"),payload:a.string()})]),ta=a.object({status:li,watchable:Ns}),hf=a.object({routes:a.array(Ws),id:a.string()}),mf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Server"),payload:Bs}),a.object({kind:a.literal("PathMonitor"),payload:ta})]),ra=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.object({tree:_t})}),a.object({kind:a.literal("Ended"),payload:a.object({tree:_t,report:ar,report_map:a.record(ar)})}),a.object({kind:a.literal("Error"),payload:a.undefined().optional()})])),ar=a.lazy(()=>a.object({result:ia})),na=a.lazy(()=>a.object({stage:ra})),ia=a.lazy(()=>a.object({conclusion:Js,invocation_id:ks,task_reports:a.array(ar)})),oa=a.lazy(()=>a.object({tree:_t,report_map:a.record(ar)})),yf=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("FileChanged"),payload:ni}),a.object({kind:a.literal("FilesChanged"),payload:$s}),a.object({kind:a.literal("OutputLine"),payload:ea}),a.object({kind:a.literal("InputFileChanged"),payload:ni}),a.object({kind:a.literal("InputAccepted"),payload:Is}),a.object({kind:a.literal("InputError"),payload:Ds}),a.object({kind:a.literal("StartupError"),payload:Hs}),a.object({kind:a.literal("ServerChangeset"),payload:Vs}),a.object({kind:a.literal("TaskAction"),payload:na}),a.object({kind:a.literal("TaskTreePreview"),payload:Ks}),a.object({kind:a.literal("TaskTreeSummary"),payload:oa}),a.object({kind:a.literal("Watching"),payload:Xs}),a.object({kind:a.literal("WatchingStopped"),payload:Ys})]));var di=[{selector:"background",styleNames:["backgroundImage"]},{selector:"border",styleNames:["borderImage","webkitBorderImage","MozBorderImage"]}],lr={stylesheetReloadTimeout:15e3},sa=/\.(jpe?g|png|gif|svg)$/i,dr=class{constructor(e,t,n){this.window=e,this.console=t,this.Timer=n,this.document=this.window.document,this.importCacheWaitPeriod=200,this.plugins=[]}addPlugin(e){return this.plugins.push(e)}analyze(e){}reload(e,t={}){if(this.options={...lr,...t},!(t.liveCSS&&e.match(/\.css(?:\.map)?$/i)&&this.reloadStylesheet(e))){if(t.liveImg&&e.match(sa)){this.reloadImages(e);return}if(t.isChromeExtension){this.reloadChromeExtension();return}return this.reloadPage()}}reloadPage(){return this.window.document.location.reload()}reloadChromeExtension(){return this.window.chrome.runtime.reload()}reloadImages(e){let t,n=this.generateUniqueString();for(t of Array.from(this.document.images))ui(e,Hr(t.src))&&(t.src=this.generateCacheBustUrl(t.src,n));if(this.document.querySelectorAll)for(let{selector:i,styleNames:o}of di)for(t of Array.from(this.document.querySelectorAll(`[style*=${i}]`)))this.reloadStyleImages(t.style,o,e,n);if(this.document.styleSheets)return Array.from(this.document.styleSheets).map(i=>this.reloadStylesheetImages(i,e,n))}reloadStylesheetImages(e,t,n){let i;try{i=(e||{}).cssRules}catch{}if(i)for(let o of Array.from(i))switch(o.type){case CSSRule.IMPORT_RULE:this.reloadStylesheetImages(o.styleSheet,t,n);break;case CSSRule.STYLE_RULE:for(let{styleNames:s}of di)this.reloadStyleImages(o.style,s,t,n);break;case CSSRule.MEDIA_RULE:this.reloadStylesheetImages(o,t,n);break}}reloadStyleImages(e,t,n,i){for(let o of t){let s=e[o];if(typeof s=="string"){let c=s.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"),(l,d)=>ui(n,Hr(d))?`url(${this.generateCacheBustUrl(d,i)})`:l);c!==s&&(e[o]=c)}}}reloadStylesheet(e){let t=this.options||lr,n,i,o=(()=>{let l=[];for(i of Array.from(this.document.getElementsByTagName("link")))i.rel.match(/^stylesheet$/i)&&!i.__LiveReload_pendingRemoval&&l.push(i);return l})(),s=[];for(n of Array.from(this.document.getElementsByTagName("style")))n.sheet&&this.collectImportedStylesheets(n,n.sheet,s);for(i of Array.from(o))this.collectImportedStylesheets(i,i.sheet,s);if(this.window.StyleFix&&this.document.querySelectorAll)for(n of Array.from(this.document.querySelectorAll("style[data-href]")))o.push(n);this.console.debug(`found ${o.length} LINKed stylesheets, ${s.length} @imported stylesheets`);let c=aa(e,o.concat(s),l=>Hr(this.linkHref(l)));if(c)c.object.rule?(this.console.debug(`is reloading imported stylesheet: ${c.object.href}`),this.reattachImportedRule(c.object)):(this.console.debug(`is reloading stylesheet: ${this.linkHref(c.object)}`),this.reattachStylesheetLink(c.object));else if(t.reloadMissingCSS){this.console.debug(`will reload all stylesheets because path '${e}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`);for(i of Array.from(o))this.reattachStylesheetLink(i)}else this.console.debug(`will not reload path '${e}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.`);return!0}collectImportedStylesheets(e,t,n){let i;try{i=(t||{}).cssRules}catch{}if(i&&i.length)for(let o=0;o{if(!i)return i=!0,t()};if(e.onload=()=>(this.console.debug("the new stylesheet has finished loading"),this.knownToSupportCssOnLoad=!0,o()),!this.knownToSupportCssOnLoad){let s;(s=()=>e.sheet?(this.console.debug("is polling until the new CSS finishes loading..."),o()):this.Timer.start(50,s))()}return this.Timer.start(n.stylesheetReloadTimeout,o)}linkHref(e){return e.href||e.getAttribute&&e.getAttribute("data-href")}reattachStylesheetLink(e){let t;if(e.__LiveReload_pendingRemoval)return;e.__LiveReload_pendingRemoval=!0,e.tagName==="STYLE"?(t=this.document.createElement("link"),t.rel="stylesheet",t.media=e.media,t.disabled=e.disabled):t=e.cloneNode(!1),t.href=this.generateCacheBustUrl(this.linkHref(e));let n=e.parentNode;return n.lastChild===e?n.appendChild(t):n.insertBefore(t,e.nextSibling),this.waitUntilCssLoads(t,()=>{let i;return/AppleWebKit/.test(this.window.navigator.userAgent)?i=5:i=200,this.Timer.start(i,()=>{if(e.parentNode)return e.parentNode.removeChild(e),t.onreadystatechange=null,this.window.StyleFix?this.window.StyleFix.link(t):void 0})})}reattachImportedRule({rule:e,index:t,link:n}){let i=e.parentStyleSheet,o=this.generateCacheBustUrl(e.href),s=e.media.length?[].join.call(e.media,", "):"",c=`@import url("${o}") ${s};`;e.__LiveReload_newHref=o;let l=this.document.createElement("link");return l.rel="stylesheet",l.href=o,l.__LiveReload_pendingRemoval=!0,n.parentNode&&n.parentNode.insertBefore(l,n),this.Timer.start(this.importCacheWaitPeriod,()=>{if(l.parentNode&&l.parentNode.removeChild(l),e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1),e=i.cssRules[t],e.__LiveReload_newHref=o,this.Timer.start(this.importCacheWaitPeriod,()=>{if(e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1)})})}generateUniqueString(){return`livereload=${Date.now()}`}generateCacheBustUrl(e,t){let n=this.options||lr,i,o;if(t||(t=this.generateUniqueString()),{url:e,hash:i,params:o}=fi(e),n.overrideURL&&e.indexOf(n.serverURL)<0){let c=e;e=n.serverURL+n.overrideURL+"?url="+encodeURIComponent(e),this.console.debug(`is overriding source URL ${c} with ${e}`)}let s=o.replace(/(\?|&)livereload=(\d+)/,(c,l)=>`${l}${t}`);return s===o&&(o.length===0?s=`?${t}`:s=`${o}&${t}`),e+s+i}};function fi(r){let e="",t="",n=r.indexOf("#");n>=0&&(e=r.slice(n),r=r.slice(0,n));let i=r.indexOf("??");return i>=0?i+1!==r.lastIndexOf("?")&&(n=r.lastIndexOf("?")):n=r.indexOf("?"),n>=0&&(t=r.slice(n),r=r.slice(0,n)),{url:r,params:t,hash:e}}function Hr(r){if(!r)return"";let e;return{url:r}=fi(r),r.indexOf("file://")===0?e=r.replace(new RegExp("^file://(localhost)?"),""):e=r.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"),"/"),decodeURIComponent(e)}function pi(r,e){if(r=r.replace(/^\/+/,"").toLowerCase(),e=e.replace(/^\/+/,"").toLowerCase(),r===e)return 1e4;let t=r.split(/\/|\\/).reverse(),n=e.split(/\/|\\/).reverse(),i=Math.min(t.length,n.length),o=0;for(;on){let n,i={score:0};for(let o of e)n=pi(r,t(o)),n>i.score&&(i={object:o,score:n});return i.score===0?null:i}function ui(r,e){return pi(r,e)>0}var yi=Ji(mi(),1);var ca=/\.(jpe?g|png|gif|svg)$/i;function qr(r,e,t){switch(r.kind){case"FsMany":{if(r.payload.some(i=>{switch(i.kind){case"Fs":return!(i.payload.path.match(/\.css(?:\.map)?$/i)||i.payload.path.match(ca));case"FsMany":throw new Error("unreachable")}}))return window.__playwright?.record?window.__playwright?.record({kind:"reloadPage"}):t.reloadPage();for(let i of r.payload)qr(i,e,t);break}case"Fs":{let n=r.payload.path,i={liveCSS:!0,liveImg:!0,reloadMissingCSS:!0,originalPath:"",overrideURL:"",serverURL:""};window.__playwright?.record?window.__playwright?.record({kind:"reload",args:{path:n,opts:i}}):(e.trace("will reload a file with path ",n),t.reload(n,i))}}}var Gr={name:"dom plugin",globalSetup:(r,e)=>{let t=new dr(window,e,yi.Timer);return[r,[e,t]]},resetSink(r,e,t){let[n,i]=e;return r.pipe(de(o=>o.kind==="Change"),Q(o=>o.payload),Se(o=>{n.trace("incoming message",JSON.stringify({change:o,config:t},null,2));let s=cr.parse(o);qr(s,n,i)}),xe())}};var fr=globalThis,pr=fr.ShadowRoot&&(fr.ShadyCSS===void 0||fr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Yr=Symbol(),vi=new WeakMap,xt=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Yr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(pr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=vi.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&vi.set(t,e))}return e}toString(){return this.cssText}},gi=r=>new xt(typeof r=="string"?r:r+"",void 0,Yr),K=(r,...e)=>{let t=r.length===1?r[0]:e.reduce((n,i,o)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[o+1],r[0]);return new xt(t,r,Yr)},bi=(r,e)=>{if(pr)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),i=fr.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Jr=pr?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return gi(t)})(r):r;var{is:la,defineProperty:da,getOwnPropertyDescriptor:ua,getOwnPropertyNames:fa,getOwnPropertySymbols:pa,getPrototypeOf:ha}=Object,hr=globalThis,_i=hr.trustedTypes,ma=_i?_i.emptyScript:"",ya=hr.reactiveElementPolyfillSupport,St=(r,e)=>r,wt={toAttribute(r,e){switch(e){case Boolean:r=r?ma:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mr=(r,e)=>!la(r,e),xi={attribute:!0,type:String,converter:wt,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),hr.litPropertyMetadata??=new WeakMap;var ae=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=xi){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&da(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){let{get:i,set:o}=ua(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){let c=i?.call(this);o?.call(this,s),this.requestUpdate(e,c,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??xi}static _$Ei(){if(this.hasOwnProperty(St("elementProperties")))return;let e=ha(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(St("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(St("properties"))){let t=this.properties,n=[...fa(t),...pa(t)];for(let i of n)this.createProperty(i,t[i])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let i of n)t.unshift(Jr(i))}else e!==void 0&&t.push(Jr(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return bi(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){let o=(n.converter?.toAttribute!==void 0?n.converter:wt).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,t){let n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){let o=n.getPropertyOptions(i),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:wt;this._$Em=i;let c=s.fromAttribute(t,o.type);this[i]=c??this._$Ej?.get(i)??c,this._$Em=null}}requestUpdate(e,t,n,i=!1,o){if(e!==void 0){let s=this.constructor;if(i===!1&&(o=this[e]),n??=s.getPropertyOptions(e),!((n.hasChanged??mr)(o,t)||n.useDefault&&n.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:o},s){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[i,o]of n){let{wrapped:s}=o,c=this[i];s!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};ae.elementStyles=[],ae.shadowRootOptions={mode:"open"},ae[St("elementProperties")]=new Map,ae[St("finalized")]=new Map,ya?.({ReactiveElement:ae}),(hr.reactiveElementVersions??=[]).push("2.1.2");var Xr=globalThis,Si=r=>r,yr=Xr.trustedTypes,wi=yr?yr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Qr="$lit$",ce=`lit$${Math.random().toFixed(9).slice(2)}$`,en="?"+ce,va=`<${en}>`,Fe=document,Tt=()=>Fe.createComment(""),At=r=>r===null||typeof r!="object"&&typeof r!="function",tn=Array.isArray,Ci=r=>tn(r)||typeof r?.[Symbol.iterator]=="function",Kr=`[ +\f\r]`,kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ki=/-->/g,Ti=/>/g,ze=RegExp(`>|${Kr}(?:([^\\s"'>=/]+)(${Kr}*=${Kr}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Ai=/'/g,Ei=/"/g,$i=/^(?:script|style|textarea|title)$/i,rn=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),N=rn(1),jf=rn(2),Rf=rn(3),Ve=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),Oi=new WeakMap,Ze=Fe.createTreeWalker(Fe,129);function ji(r,e){if(!tn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return wi!==void 0?wi.createHTML(e):e}var Ri=(r,e)=>{let t=r.length-1,n=[],i,o=e===2?"":e===3?"":"",s=kt;for(let c=0;c"?(s=i??kt,p=-1):u[1]===void 0?p=-2:(p=s.lastIndex-u[2].length,d=u[1],s=u[3]===void 0?ze:u[3]==='"'?Ei:Ai):s===Ei||s===Ai?s=ze:s===ki||s===Ti?s=kt:(s=ze,i=void 0);let v=s===ze&&r[c+1].startsWith("/>")?" ":"";o+=s===kt?l+va:p>=0?(n.push(d),l.slice(0,p)+Qr+l.slice(p)+ce+v):l+ce+(p===-2?c:v)}return[ji(r,o+(r[t]||"")+(e===2?"":e===3?"":"")),n]},Et=class r{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let o=0,s=0,c=e.length-1,l=this.parts,[d,u]=Ri(e,t);if(this.el=r.createElement(d,n),Ze.currentNode=this.el.content,t===2||t===3){let p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(i=Ze.nextNode())!==null&&l.length0){i.textContent=yr?yr.emptyScript:"";for(let v=0;v2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=O}_$AI(e,t=this,n,i){let o=this.strings,s=!1;if(o===void 0)e=We(this,e,t,0),s=!At(e)||e!==this._$AH&&e!==Ve,s&&(this._$AH=e);else{let c=e,l,d;for(e=o[0],l=0;l{let n=t?.renderBefore??e,i=n._$litPart$;if(i===void 0){let o=t?.renderBefore??null;n._$litPart$=i=new ot(e.insertBefore(Tt(),o),o,void 0,t??{})}return i._$AI(r),i};var nn=globalThis,L=class extends ae{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Sr(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ve}};L._$litElement$=!0,L.finalized=!0,nn.litElementHydrateSupport?.({LitElement:L});var ba=nn.litElementPolyfillSupport;ba?.({LitElement:L});(nn.litElementVersions??=[]).push("4.2.2");var st=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)};var _a={attribute:!0,type:String,converter:wt,reflect:!1,hasChanged:mr},xa=(r=_a,e,t)=>{let{kind:n,metadata:i}=t,o=globalThis.litPropertyMetadata.get(i);if(o===void 0&&globalThis.litPropertyMetadata.set(i,o=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),o.set(t.name,r),n==="accessor"){let{name:s}=t;return{set(c){let l=e.get.call(this);e.set.call(this,c),this.requestUpdate(s,l,r,!0,c)},init(c){return c!==void 0&&this.C(s,void 0,r,c),c}}}if(n==="setter"){let{name:s}=t;return function(c){let l=this[s];e.call(this,c),this.requestUpdate(s,l,r,!0,c)}}throw Error("Unsupported decorator location: "+n)};function he(r){return(e,t)=>typeof t=="object"?xa(r,e,t):((n,i,o)=>{let s=i.hasOwnProperty(o);return i.constructor.createProperty(o,n),s?Object.getOwnPropertyDescriptor(i,o):void 0})(r,e,t)}var{I:bp}=Ii;var Di=r=>r.strings===void 0;var Pi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},on=r=>(...e)=>({_$litDirective$:r,values:e}),kr=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};var Ot=(r,e)=>{let t=r._$AN;if(t===void 0)return!1;for(let n of t)n._$AO?.(e,!1),Ot(n,e);return!0},Tr=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while(t?.size===0)},Mi=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),ka(e)}};function Sa(r){this._$AN!==void 0?(Tr(this),this._$AM=r,Mi(this)):this._$AM=r}function wa(r,e=!1,t=0){let n=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(n))for(let o=t;o{r.type==Pi.CHILD&&(r._$AP??=wa,r._$AQ??=Sa)},Ar=class extends kr{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),Mi(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Ot(this,e),Tr(this))}setValue(e){if(Di(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};var Ni=()=>new an,an=class{},sn=new WeakMap,Li=on(class extends Ar{render(r){return O}update(r,[e]){let t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=r.options?.host,this.rt(this.ct=r.element)),O}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){let e=this.ht??globalThis,t=sn.get(e);t===void 0&&(t=new WeakMap,sn.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){return typeof this.G=="function"?sn.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var me=K` * { box-sizing: border-box; } @@ -33,10 +33,10 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } -`;var Li="narrow",Ui="wide",We=class extends L{constructor(){super(...arguments);this.kind="overlay";this.dialogRef=Mi();this.width="narrow"}firstUpdated(t){super.firstUpdated(t),this.dialogRef.value?.showModal()}closed(){this.dispatchEvent(new Event("closed",{bubbles:!0,composed:!0}))}toggleWidth(t){if(t.currentTarget instanceof HTMLButtonElement){let n=t.currentTarget.value;(n===Ui||n===Li)&&(this.width=n)}}render(){return N` +`;var Ui="narrow",zi="wide",He=class extends L{constructor(){super(...arguments);this.kind="overlay";this.dialogRef=Ni();this.width="narrow"}firstUpdated(t){super.firstUpdated(t),this.dialogRef.value?.showModal()}closed(){this.dispatchEvent(new Event("closed",{bubbles:!0,composed:!0}))}toggleWidth(t){if(t.currentTarget instanceof HTMLButtonElement){let n=t.currentTarget.value;(n===zi||n===Ui)&&(this.width=n)}}render(){return N` @@ -44,14 +44,14 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe - `}};We.styles=[at,me,K` + `}};He.styles=[at,me,K` ::backdrop { background: rgba(0, 0, 0, 0.7); } @@ -100,7 +100,7 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe justify-content: flex-end; gap: 0.5rem; } - `],W([he({type:String})],We.prototype,"kind",2),W([he({type:String})],We.prototype,"width",2),We=W([st("bs-overlay")],We);var Ar=class extends L{static{this.styles=[me,K` + `],B([he({type:String})],He.prototype,"kind",2),B([he({type:String})],He.prototype,"width",2),He=B([st("bs-overlay")],He);var Er=class extends L{static{this.styles=[me,K` .svg-icon { display: inline-block; fill: var(--bs-icon-color, currentColor); @@ -234,9 +234,9 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe /> - ${this.icon}`}};W([he({type:String,attribute:"icon-name"})],Ar.prototype,"iconName",2);customElements.define("bs-icon",Ar);function zi(){return N``}var ct=class extends L{constructor(){super(...arguments);this.title="..."}render(){return N`
+ ${this.icon}`}};B([he({type:String,attribute:"icon-name"})],Er.prototype,"iconName",2);customElements.define("bs-icon",Er);function Zi(){return N``}var ct=class extends L{constructor(){super(...arguments);this.title="..."}render(){return N`
- ${zi()} + ${Zi()} ${this.title} @@ -279,7 +279,7 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe slot::slotted(*) { font-size: 10px; } - `],W([he({type:String})],ct.prototype,"title",2),ct=W([st("bs-panel")],ct);var Ct=class extends L{render(){return N` `}};Ct.styles=[me,at],Ct=W([st("bs-token-env")],Ct);function Zi({displayMessage:r}){let t=N` + `],B([he({type:String})],ct.prototype,"title",2),ct=B([st("bs-panel")],ct);var Ct=class extends L{render(){return N` `}};Ct.styles=[me,at],Ct=B([st("bs-token-env")],Ct);function Fi({displayMessage:r}){let t=N`