1#[cfg(feature = "context")]
2pub mod context;
3#[cfg(feature = "envelope")]
4pub mod envelope;
5#[cfg(feature = "i18n")]
6pub mod i18n;
7#[cfg(feature = "masks")]
8pub mod masks;
9#[cfg(feature = "module")]
10pub mod module;
11#[cfg(feature = "repository")]
12pub mod repository;
13#[cfg(feature = "smtp")]
14mod smtp;
15#[cfg(feature = "tokens")]
16pub mod tokens;
17#[cfg(feature = "view")]
18pub mod view;
19
20#[cfg(feature = "i18n")]
21use std::collections::BTreeMap;
22#[cfg(any(feature = "context", feature = "envelope", feature = "i18n", feature = "view"))]
23use std::sync::Arc;
24#[cfg(feature = "context")]
25use std::sync::Mutex;
26
27use laravel::config::{Config, Env, Section};
28use laravel::container::Registrar;
29use laravel::foundation::ServiceProvider;
30#[cfg(feature = "envelope")]
31use laravel::http::Request;
32#[cfg(feature = "envelope")]
33use serde_json::Value;
34
35#[cfg(feature = "context")]
36use context::{ContextRegistry, ContextSpec, RouteEntry, SharedRouteIndex};
37#[cfg(feature = "envelope")]
38use envelope::ClientShare;
39#[cfg(feature = "i18n")]
40use i18n::{ClientCatalogs, LanguageStore, MemoryLanguageStore, ScopeDefinition, TextResolver};
41#[cfg(feature = "module")]
42use module::{ModuleRegistry, SaolaModule};
43
44#[derive(Debug, Clone, Section)]
45pub struct SaolaConfig {
46 #[env("SAOLA_PRIMARY_HOST", default = "")]
47 pub primary_host: String,
48 #[env("SAOLA_DEFAULT_LOCALE", default = "vi")]
49 pub default_locale: String,
50 #[env("SAOLA_FALLBACK_LOCALE", default = "en")]
51 pub fallback_locale: String,
52}
53
54#[cfg(feature = "envelope")]
55type ShareInit = Box<dyn Fn(&ClientShare) + Send + Sync>;
56
57#[derive(Default)]
59pub struct SaolaServiceProvider {
60 #[cfg(feature = "context")]
61 context_registry: ContextRegistry,
62 #[cfg(feature = "module")]
63 module_registry: ModuleRegistry,
64 #[cfg(feature = "envelope")]
65 share_inits: Vec<ShareInit>,
66 #[cfg(feature = "i18n")]
67 language_store: Option<Arc<dyn LanguageStore>>,
68 #[cfg(feature = "i18n")]
69 language_scopes: BTreeMap<String, ScopeDefinition>,
70 #[cfg(feature = "view")]
71 enable_view_helpers: bool,
72 #[cfg(feature = "view")]
73 ssr_site: Option<Arc<dyn view::SsrSite>>,
74}
75
76impl std::fmt::Debug for SaolaServiceProvider {
77 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78 f.debug_struct("SaolaServiceProvider").finish_non_exhaustive()
79 }
80}
81
82impl SaolaServiceProvider {
83 pub fn new() -> Self {
84 Self::default()
85 }
86
87 #[cfg(feature = "context")]
88 pub fn with_context(mut self, spec: ContextSpec) -> Self {
89 self.context_registry.add_context(spec);
90 self
91 }
92
93 #[cfg(feature = "context")]
94 pub fn with_route(mut self, entry: RouteEntry) -> Self {
95 self.context_registry.add_route(entry);
96 self
97 }
98
99 #[cfg(feature = "module")]
100 pub fn with_module<M: SaolaModule>(mut self, module: M) -> Self {
101 self.module_registry.add(module);
102 self
103 }
104
105 #[cfg(feature = "envelope")]
106 pub fn with_share<F>(mut self, key: &'static str, resolver: F) -> Self
107 where
108 F: Fn(&Request) -> laravel::Result<Option<Value>> + Send + Sync + 'static,
109 {
110 let resolver = Arc::new(resolver);
111 self.share_inits.push(Box::new(move |share| {
112 let resolver = Arc::clone(&resolver);
113 if let Err(err) = share.share(key, move |req| resolver(req)) {
114 tracing::error!(error = %err, "Failed to register Saola share key");
115 }
116 }));
117 self
118 }
119
120 #[cfg(feature = "i18n")]
121 pub fn with_language_store(mut self, store: Arc<dyn LanguageStore>) -> Self {
122 self.language_store = Some(store);
123 self
124 }
125
126 #[cfg(feature = "i18n")]
127 pub fn with_language_scope(
128 mut self,
129 name: impl Into<String>,
130 definition: ScopeDefinition,
131 ) -> Self {
132 self.language_scopes.insert(name.into(), definition);
133 self
134 }
135
136 #[cfg(feature = "view")]
137 pub fn with_minijinja_helpers(mut self) -> Self {
138 self.enable_view_helpers = true;
139 self
140 }
141
142 #[cfg(feature = "view")]
144 pub fn with_ssr_site(mut self, site: Arc<dyn view::SsrSite>) -> Self {
145 self.enable_view_helpers = true;
146 self.ssr_site = Some(site);
147 self
148 }
149}
150
151impl ServiceProvider for SaolaServiceProvider {
152 fn config(&self, config: &mut Config, env: &Env) {
153 config.discover(env!("CARGO_CRATE_NAME"), env);
154 #[cfg(feature = "smtp")]
155 smtp::configure(config, env);
156 }
157
158 fn register(&self, app: &mut Registrar) {
159 let _ = app;
160 #[cfg(feature = "smtp")]
161 smtp::register(app);
162 #[cfg(any(feature = "context", feature = "i18n"))]
163 let saola_config = app.config().section::<SaolaConfig>().clone();
164
165 #[cfg(feature = "context")]
166 #[allow(unused_variables)]
167 let (shared_registry, shared_route_index) = {
168 let primary = if saola_config.primary_host.is_empty() {
169 app.config().app.url.clone()
170 } else {
171 saola_config.primary_host.clone()
172 };
173 let registry = Arc::new(Mutex::new(self.context_registry.clone()));
174 let shared_index = SharedRouteIndex::new(Arc::clone(®istry), primary);
175 app.instance(self.context_registry.clone());
176 app.instance(shared_index.clone());
177
178 let shared_for_singleton = shared_index.clone();
179 app.singleton(move |_| {
180 let shared = shared_for_singleton.clone();
181 async move {
182 shared
183 .index()
184 .map(|arc| (*arc).clone())
185 .map_err(|err| laravel::Error::msg(err.to_string()))
186 }
187 });
188
189 (registry, shared_index)
190 };
191
192 #[cfg(feature = "envelope")]
193 {
194 let share = ClientShare::new();
195 for init in &self.share_inits {
196 init(&share);
197 }
198 app.instance(share);
199 }
200
201 #[cfg(feature = "i18n")]
202 #[allow(unused_variables)]
203 let text_resolver = {
204 let store: Arc<dyn LanguageStore> = self
205 .language_store
206 .clone()
207 .unwrap_or_else(|| Arc::new(MemoryLanguageStore::new()));
208 let resolver = TextResolver::new(
209 store,
210 saola_config.default_locale,
211 saola_config.fallback_locale,
212 );
213 let catalogs = ClientCatalogs::new(resolver.clone(), self.language_scopes.clone());
214 let resolver_arc = Arc::new(resolver.clone());
215 app.instance(resolver);
216 app.instance(catalogs);
217 resolver_arc
218 };
219
220 #[cfg(feature = "module")]
221 {
222 app.instance(self.module_registry.clone());
223 self.module_registry.register_all(app);
224 let specs = shared_registry
225 .lock()
226 .unwrap_or_else(std::sync::PoisonError::into_inner)
227 .contexts()
228 .to_vec();
229 self.module_registry
230 .register_context_routes(app, specs, Arc::clone(&shared_registry));
231 }
232
233 #[cfg(feature = "view")]
234 if self.enable_view_helpers {
235 let resolver = Arc::clone(&text_resolver);
236 let routes = Some(shared_route_index.clone());
237 let site = self.ssr_site.clone();
238 app.views().minijinja(move |env| {
239 view::register_ssr_helpers(env, Arc::clone(&resolver), routes.clone(), site.clone());
240 });
241 }
242 }
243}
244
245pub mod prelude {
246 pub use crate::{SaolaConfig, SaolaServiceProvider};
247
248 #[cfg(feature = "context")]
249 pub use crate::context::{
250 ContextError, ContextHosts, ContextLinksRule, ContextRegistry, ContextRoute, ContextRoutes,
251 ContextSpec, ContextTarget, HrefOptions, RouteEntry, RouteIndex, SetCurrentContext,
252 SharedRouteIndex, current_context, set_current_context,
253 };
254
255 #[cfg(feature = "envelope")]
256 pub use crate::envelope::{
257 AppBootConfig, ClientAuthProjection, ClientAuthUser, ClientShare, Envelope, PageResponse,
258 ViewContextState, render, wants_saola_json,
259 };
260
261 #[cfg(feature = "i18n")]
262 pub use crate::i18n::{
263 ClientCatalogs, FileLanguageStore, LanguageJson, LanguageNode, LanguageStore,
264 LanguageTree, MemoryLanguageStore, ScopeDefinition, TextResolver,
265 };
266
267 #[cfg(feature = "masks")]
268 pub use crate::masks::{Mask, MaskExt, PiiMask, mask_all};
269
270 #[cfg(feature = "module")]
271 pub use crate::module::{ModuleMeta, ModuleRegistry, SaolaModule};
272
273 #[cfg(feature = "repository")]
274 pub use crate::repository::{CursorParams, PageMeta, PageParams, PageResult};
275
276 #[cfg(feature = "tokens")]
277 pub use crate::tokens::{
278 CurrentAccessToken, NewAccessToken, PersonalAccessToken, SanctumGuard, TokenStore,
279 create_personal_access_tokens_table, current_access_token, has_token_ability,
280 require_ability, token_can,
281 };
282}