1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! The `livewire` config section and its defaults, which mirror `config/livewire.php` in upstream
//! Livewire 4.x.
use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
use laravel::time::ExactDuration;
/// Everything the `livewire` section configures.
///
/// The defaults match upstream Livewire's `config/livewire.php`. An application replaces any of
/// them with a `livewire` config section of its own, or by changing the section in
/// `with_config`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LivewireConfig {
/// The directories that hold view components, searched in order.
pub component_locations: Vec<String>,
/// Namespaces that resolve relative to a directory, such as `layouts` to
/// `resources/views/layouts`.
pub component_namespaces: BTreeMap<String, String>,
/// The view that wraps a page component, or `None` to render the component alone.
pub component_layout: Option<String>,
/// The view a lazy component shows before it loads, or `None` for the built-in placeholder.
pub component_placeholder: Option<String>,
/// The defaults of `make:livewire`.
pub make_command: MakeCommand,
/// Where `make:livewire` writes component modules.
pub component_path: String,
/// Where `make:livewire` writes `.livewire` views.
pub view_path: String,
/// How temporary uploads are stored and validated.
pub temporary_file_upload: TemporaryFileUpload,
/// Whether to render a component that redirected, before answering with the redirect.
pub render_on_redirect: bool,
/// Whether `wire:model` may bind a model directly, as Livewire 2 did.
pub legacy_model_binding: bool,
/// Whether the server injects its styles and scripts into HTML responses.
pub inject_assets: bool,
/// How `wire:navigate` presents a visit.
pub navigate: Navigate,
/// Whether to inject morph markers around conditionals, loops, and class output.
pub inject_morph_markers: bool,
/// Whether to derive keys for nested components inside loops.
pub smart_wire_keys: bool,
/// The CSS framework the pagination views target.
pub pagination_theme: PaginationTheme,
/// The token in each snapshot that a redeployment changes.
pub release_token: String,
/// Whether to serve and run the CSP-safe Alpine build.
pub csp_safe: bool,
/// A base URL that serves the frontend assets from somewhere other than the application.
pub asset_url: Option<String>,
/// A path for the update endpoint other than the default one.
pub update_uri: Option<String>,
/// The limits that guard the update endpoint against oversized requests.
pub payload: PayloadLimits,
}
impl Default for LivewireConfig {
fn default() -> Self {
Self {
component_locations: vec![
"resources/views/components".to_owned(),
"resources/views/livewire".to_owned(),
],
component_namespaces: BTreeMap::from([
("layouts".to_owned(), "resources/views/layouts".to_owned()),
("pages".to_owned(), "resources/views/pages".to_owned()),
]),
component_layout: Some("layouts::app".to_owned()),
component_placeholder: None,
make_command: MakeCommand::default(),
component_path: "src/livewire".to_owned(),
view_path: "resources/views/livewire".to_owned(),
temporary_file_upload: TemporaryFileUpload::default(),
render_on_redirect: false,
legacy_model_binding: false,
inject_assets: true,
navigate: Navigate::default(),
inject_morph_markers: true,
smart_wire_keys: true,
pagination_theme: PaginationTheme::Tailwind,
release_token: "a".to_owned(),
csp_safe: false,
asset_url: None,
update_uri: None,
payload: PayloadLimits::default(),
}
}
}
impl LivewireConfig {
/// The `livewire` section of a framework configuration, or the defaults when the application
/// never set one.
#[must_use]
pub fn of(config: &laravel::config::Config) -> &Self {
static DEFAULTS: std::sync::LazyLock<LivewireConfig> = std::sync::LazyLock::new(LivewireConfig::default);
config.get::<LivewireConfig>().unwrap_or(&DEFAULTS)
}
/// The first configured component directory, which `make:livewire` writes new components to.
#[must_use]
pub fn first_component_location(&self) -> Option<&str> {
self.component_locations.first().map(String::as_str)
}
/// The `temporary_file_upload.middleware` as a route throttle, or `None` when the
/// configuration names no allowed attempts.
#[must_use]
pub fn upload_throttle(&self) -> Option<laravel::http::middleware::Throttle> {
let middleware = &self.temporary_file_upload.middleware;
Some(laravel::http::middleware::Throttle::per(
middleware.max_attempts,
ExactDuration::from(Duration::from_secs(middleware.decay_seconds)),
))
}
}
/// The kind of component `make:livewire` creates by default.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ComponentKind {
/// A view component whose markup and module live in one `.livewire` file.
#[default]
Sfc,
/// A view component whose Rust module sits beside a `.livewire` file.
Mfc,
/// A component whose module declares its own view. In this port it writes the same files as
/// [`Mfc`](Self::Mfc), because a Rust component always has a module.
Class,
}
impl ComponentKind {
/// The name the configuration uses, as upstream names it.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Sfc => "sfc",
Self::Mfc => "mfc",
Self::Class => "class",
}
}
}
impl fmt::Display for ComponentKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
/// The defaults of `make:livewire`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MakeCommand {
/// The component kind to create.
pub kind: ComponentKind,
/// Whether view component names carry the `âš¡` counting emoji.
pub emoji: bool,
/// Whether to create a `.js` module beside the component.
pub js: bool,
/// Whether to create a `.css` module beside the component.
pub css: bool,
/// Whether to create a test file beside the component.
pub test: bool,
}
impl Default for MakeCommand {
fn default() -> Self {
Self {
kind: ComponentKind::Sfc,
emoji: true,
js: false,
css: false,
test: false,
}
}
}
/// How temporary uploads are stored, validated, and cleaned up.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TemporaryFileUpload {
/// The disk to store temporary uploads on, or `None` for the application's default disk.
pub disk: Option<String>,
/// The validation rules of an upload.
pub rules: Vec<String>,
/// The directory on the disk, or `None` for `livewire-tmp`.
pub directory: Option<String>,
/// The throttle on the upload endpoint.
pub middleware: UploadMiddleware,
/// The extensions a temporary upload's preview may have.
pub preview_mimes: Vec<String>,
/// How long an upload stays valid, in minutes.
pub max_upload_time: u64,
/// Whether expired uploads are removed on the scheduled cleanup.
pub cleanup: bool,
}
impl Default for TemporaryFileUpload {
fn default() -> Self {
Self {
disk: None,
rules: vec!["required".to_owned(), "file".to_owned(), "max:12288".to_owned()],
directory: None,
middleware: UploadMiddleware::default(),
preview_mimes: [
"png", "gif", "bmp", "svg", "wav", "mp4", "mov", "avi", "wmv", "mp3", "m4a", "jpg", "jpeg", "mpga",
"webp", "wma",
]
.into_iter()
.map(str::to_owned)
.collect(),
max_upload_time: 5,
cleanup: true,
}
}
}
impl TemporaryFileUpload {
/// The directory that holds temporary uploads.
#[must_use]
pub fn directory(&self) -> &str {
self.directory.as_deref().unwrap_or("livewire-tmp")
}
/// How long an upload stays valid.
#[must_use]
pub fn max_upload_time(&self) -> ExactDuration {
ExactDuration::from(Duration::from_secs(self.max_upload_time.saturating_mul(60)))
}
}
/// The throttle on the upload endpoint, written as `throttle:{max_attempts},{decay_seconds}`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UploadMiddleware {
/// How many uploads one client may make in the decay window.
pub max_attempts: u32,
/// The length of the decay window, in seconds.
pub decay_seconds: u64,
}
impl Default for UploadMiddleware {
fn default() -> Self {
Self {
max_attempts: 60,
decay_seconds: 60,
}
}
}
/// How `wire:navigate` presents a visit.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Navigate {
/// Whether a progress bar shows while a visit loads.
pub show_progress_bar: bool,
/// The progress bar's colour.
pub progress_bar_color: String,
}
impl Default for Navigate {
fn default() -> Self {
Self {
show_progress_bar: true,
progress_bar_color: "#2299dd".to_owned(),
}
}
}
/// The CSS framework the pagination views target.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PaginationTheme {
/// Tailwind CSS, the default.
#[default]
Tailwind,
/// Bootstrap.
Bootstrap,
}
impl PaginationTheme {
/// The name the configuration uses.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Tailwind => "tailwind",
Self::Bootstrap => "bootstrap",
}
}
}
impl fmt::Display for PaginationTheme {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
/// The limits that guard the update endpoint. `None` disables a limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PayloadLimits {
/// The largest request body, in bytes.
pub max_size: Option<usize>,
/// The deepest dot-notation property path an update may set.
pub max_nesting_depth: Option<usize>,
/// The most method calls a batch may make.
pub max_calls: Option<usize>,
/// The most components a batch may update.
pub max_components: Option<usize>,
}
impl Default for PayloadLimits {
fn default() -> Self {
Self {
max_size: Some(1_048_576),
max_nesting_depth: Some(10),
max_calls: Some(50),
max_components: Some(200),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_upstream_config_defaults() {
let config = LivewireConfig::default();
assert_eq!(
config.component_locations,
["resources/views/components", "resources/views/livewire"]
);
assert_eq!(config.component_layout.as_deref(), Some("layouts::app"));
assert_eq!(config.component_namespaces["pages"], "resources/views/pages");
assert_eq!(config.make_command.kind, ComponentKind::Sfc);
assert!(config.make_command.emoji);
assert_eq!(config.temporary_file_upload.rules, ["required", "file", "max:12288"]);
assert_eq!(config.temporary_file_upload.directory(), "livewire-tmp");
assert_eq!(config.temporary_file_upload.preview_mimes.len(), 16);
assert_eq!(
config.temporary_file_upload.max_upload_time(),
ExactDuration::from(Duration::from_secs(300))
);
assert!(config.temporary_file_upload.cleanup);
assert_eq!(config.navigate.progress_bar_color, "#2299dd");
assert_eq!(config.pagination_theme, PaginationTheme::Tailwind);
assert_eq!(config.release_token, "a");
assert_eq!(config.payload.max_size, Some(1_048_576));
assert_eq!(config.payload.max_nesting_depth, Some(10));
assert_eq!(config.payload.max_calls, Some(50));
assert_eq!(config.payload.max_components, Some(200));
}
#[test]
fn the_upload_throttle_is_a_sixty_per_minute_limit() {
let throttle = LivewireConfig::default().upload_throttle().expect("a throttle");
assert_eq!(
throttle,
laravel::http::middleware::Throttle::per(60, ExactDuration::from(Duration::from_secs(60)))
);
}
}