utopia_detector/rendering.rs
1//! Rendering: [`Rendering`], server-side ([`Ssr`]) and static ([`Static`])
2//! output, and the [`RenderingDetector`] that tells them apart from a build's
3//! files.
4
5use php_std::path::pathinfo_extension;
6
7/// How a framework's build output is served, recognised by the files the
8/// build leaves for a given framework.
9///
10/// PHP: `Utopia\Detector\Detection\Rendering`.
11pub trait Rendering: Send + Sync {
12 /// The rendering's name: `ssr` or `static`.
13 ///
14 /// PHP: `getName()`.
15 fn name(&self) -> &str;
16
17 /// The build files that reveal this rendering for `framework` (a
18 /// framework name, such as `nextjs`).
19 ///
20 /// PHP: `getFiles($framework)`.
21 fn files(&self, framework: &str) -> &[&str];
22
23 /// The page to serve for paths without a file, if any.
24 ///
25 /// PHP: `getFallbackFile()`.
26 fn fallback_file(&self) -> Option<&str>;
27}
28
29/// Server-side rendering: the build has a server entry for the framework.
30///
31/// PHP: `Utopia\Detector\Detection\Rendering\SSR`.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct Ssr {
34 fallback_file: Option<String>,
35}
36
37impl Ssr {
38 /// Server-side rendering without a fallback file.
39 ///
40 /// PHP: `new SSR()`.
41 pub fn new() -> Self {
42 Ssr::default()
43 }
44
45 /// Server-side rendering that serves `fallback_file` for paths without
46 /// a file.
47 ///
48 /// PHP: `new SSR($fallbackFile)`.
49 pub fn with_fallback(fallback_file: impl Into<String>) -> Self {
50 Ssr { fallback_file: Some(fallback_file.into()) }
51 }
52
53 /// The server entry files of each framework's build.
54 ///
55 /// PHP: `SSR::FRAMEWORK_FILES`.
56 pub const FRAMEWORK_FILES: &'static [(&'static str, &'static [&'static str])] = &[
57 ("nextjs", &[".next/server/webpack-runtime.js", ".next/turbopack", "server.js"]),
58 ("nuxt", &["server/index.mjs"]),
59 ("sveltekit", &["handler.js"]),
60 ("astro", &["server/entry.mjs"]),
61 ("remix", &["build/server/index.js"]),
62 ("angular", &["server/server.mjs"]),
63 ("analog", &["server/index.mjs"]),
64 ("tanstack-start", &["server/server.js", "server/index.mjs"]),
65 ("flutter", &[]),
66 ("jaspr", &["app"]),
67 ("lynx", &[]),
68 ];
69}
70
71impl Rendering for Ssr {
72 /// `ssr`.
73 fn name(&self) -> &str {
74 "ssr"
75 }
76
77 /// The server entry files of `framework`, none for an unknown one.
78 fn files(&self, framework: &str) -> &[&str] {
79 Ssr::FRAMEWORK_FILES.iter().find(|(name, _)| *name == framework).map_or(&[], |(_, files)| files)
80 }
81
82 /// The fallback file given at construction.
83 fn fallback_file(&self) -> Option<&str> {
84 self.fallback_file.as_deref()
85 }
86}
87
88/// Static output: plain files, with an optional fallback page.
89///
90/// PHP: `Utopia\Detector\Detection\Rendering\XStatic`.
91#[derive(Debug, Clone, Default, PartialEq, Eq)]
92pub struct Static {
93 fallback_file: Option<String>,
94}
95
96impl Static {
97 /// Static output without a fallback file.
98 ///
99 /// PHP: `new XStatic()`.
100 pub fn new() -> Self {
101 Static::default()
102 }
103
104 /// Static output that serves `fallback_file` for paths without a file.
105 ///
106 /// PHP: `new XStatic($fallbackFile)`.
107 pub fn with_fallback(fallback_file: impl Into<String>) -> Self {
108 Static { fallback_file: Some(fallback_file.into()) }
109 }
110}
111
112impl Rendering for Static {
113 /// `static`.
114 fn name(&self) -> &str {
115 "static"
116 }
117
118 /// None: static output is what remains when nothing else matches.
119 fn files(&self, _framework: &str) -> &[&str] {
120 &[]
121 }
122
123 /// The fallback file given at construction.
124 fn fallback_file(&self) -> Option<&str> {
125 self.fallback_file.as_deref()
126 }
127}
128
129/// What a [`RenderingDetector`] found: one of its options, or static output
130/// it made up because none matched.
131#[derive(Debug, Clone)]
132pub enum Rendered<'a> {
133 /// An option whose files are in the build.
134 Option(&'a dyn Rendering),
135 /// Static output with the build's only HTML file as the fallback, if it
136 /// has exactly one.
137 Static(Static),
138}
139
140impl Rendered<'_> {
141 /// The rendering found.
142 pub fn rendering(&self) -> &dyn Rendering {
143 match self {
144 Rendered::Option(r) => *r,
145 Rendered::Static(s) => s,
146 }
147 }
148
149 /// Its name: `ssr` or `static`.
150 ///
151 /// PHP: `getName()` on the detected rendering.
152 pub fn name(&self) -> &str {
153 self.rendering().name()
154 }
155
156 /// Its fallback file, if any.
157 ///
158 /// PHP: `getFallbackFile()` on the detected rendering.
159 pub fn fallback_file(&self) -> Option<&str> {
160 self.rendering().fallback_file()
161 }
162}
163
164impl std::fmt::Debug for dyn Rendering + '_ {
165 /// The name and fallback file.
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 f.debug_struct("Rendering").field("name", &self.name()).field("fallback_file", &self.fallback_file()).finish()
168 }
169}
170
171/// The only file among `inputs` with the extension `html`, the static
172/// output's fallback; `None` with none or several.
173///
174/// PHP: the `pathinfo($file, PATHINFO_EXTENSION) === 'html'` scan at the end
175/// of `Rendering::detect()`.
176pub fn html_fallback<'a>(inputs: impl IntoIterator<Item = &'a [u8]>) -> Option<&'a [u8]> {
177 let mut html = inputs.into_iter().filter(|f| pathinfo_extension(f) == b"html");
178 match (html.next(), html.next()) {
179 (Some(only), None) => Some(only),
180 _ => None,
181 }
182}
183
184/// Tells how a framework's build is served from the build's file names: the
185/// first option, in the order they were added, with one of its files for the
186/// framework among the inputs; otherwise static output, falling back to the
187/// only HTML file when there is exactly one.
188///
189/// PHP: `Utopia\Detector\Detector\Rendering`.
190///
191/// ```
192/// use utopia_detector::{RenderingDetector, Ssr, Static};
193///
194/// let mut detector = RenderingDetector::new("nextjs");
195/// detector.add_option(Ssr::new()).add_option(Static::new());
196/// detector.add_input("server/pages/index.html").add_input("server/pages/api/users.js");
197///
198/// let rendering = detector.detect();
199/// assert_eq!(rendering.name(), "static");
200/// assert_eq!(rendering.fallback_file(), Some("server/pages/index.html"));
201/// ```
202///
203/// ```php
204/// use Utopia\Detector\Detection\Rendering\SSR;
205/// use Utopia\Detector\Detection\Rendering\XStatic;
206/// use Utopia\Detector\Detector\Rendering;
207///
208/// $detector = new Rendering('nextjs');
209/// $detector->addOption(new SSR())->addOption(new XStatic());
210/// $detector->addInput('server/pages/index.html')->addInput('server/pages/api/users.js');
211///
212/// $rendering = $detector->detect();
213/// echo $rendering->getName(), "\n"; // static
214/// echo $rendering->getFallbackFile(), "\n"; // server/pages/index.html
215/// ```
216pub struct RenderingDetector {
217 framework: String,
218 options: Vec<Box<dyn Rendering>>,
219 inputs: Vec<String>,
220}
221
222impl RenderingDetector {
223 /// A detector for the build of `framework` (a framework name, such as
224 /// `nextjs`).
225 ///
226 /// PHP: `new Rendering($framework)`.
227 pub fn new(framework: impl Into<String>) -> Self {
228 RenderingDetector { framework: framework.into(), options: Vec::new(), inputs: Vec::new() }
229 }
230
231 /// Adds a rendering, tried after the others.
232 ///
233 /// PHP: `addOption($rendering)`.
234 pub fn add_option(&mut self, option: impl Rendering + 'static) -> &mut Self {
235 self.options.push(Box::new(option));
236 self
237 }
238
239 /// Adds a file name of the build.
240 ///
241 /// PHP: `addInput($file)`.
242 pub fn add_input(&mut self, file: impl Into<String>) -> &mut Self {
243 self.inputs.push(file.into());
244 self
245 }
246
247 fn static_fallback(&self) -> Static {
248 match html_fallback(self.inputs.iter().map(String::as_bytes)) {
249 Some(only) => Static::with_fallback(String::from_utf8_lossy(only)),
250 None => Static::new(),
251 }
252 }
253
254 /// The first option with a file for the framework among the inputs, or
255 /// static output (with the only HTML file as the fallback, when there is
256 /// exactly one).
257 ///
258 /// PHP: `detect()`.
259 pub fn detect(&self) -> Rendered<'_> {
260 self.options
261 .iter()
262 .find(|r| r.files(&self.framework).iter().any(|f| self.inputs.iter().any(|i| i == f)))
263 .map_or_else(|| Rendered::Static(self.static_fallback()), |r| Rendered::Option(r.as_ref()))
264 }
265}
266
267impl std::fmt::Debug for RenderingDetector {
268 /// The framework, options' names and inputs.
269 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
270 f.debug_struct("RenderingDetector")
271 .field("framework", &self.framework)
272 .field("options", &self.options.iter().map(|o| o.name()).collect::<Vec<_>>())
273 .field("inputs", &self.inputs)
274 .finish()
275 }
276}