1use php_std::json::{self, DEFAULT_DEPTH, Flags};
6use php_std::types::KeyRef;
7use php_std::{Value, yaml};
8
9use crate::{Detected, Error};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Adapter {
17 Ssr,
19 Static,
21}
22
23impl Adapter {
24 pub fn as_str(&self) -> &'static str {
26 match self {
27 Adapter::Ssr => "ssr",
28 Adapter::Static => "static",
29 }
30 }
31}
32
33pub trait Framework: Send + Sync {
38 fn name(&self) -> &str;
42
43 fn files(&self) -> &[&str];
47
48 fn packages(&self) -> &[&str] {
52 &[]
53 }
54
55 fn install_command(&self, packager: &str) -> &str;
60
61 fn build_command(&self, packager: &str) -> &str;
65
66 fn output_directory(&self) -> &str;
70
71 fn config_files(&self) -> &[&str] {
76 &[]
77 }
78
79 fn adapter(&self, config: &[u8]) -> Option<Adapter> {
84 let _ = config;
85 None
86 }
87
88 fn parents(&self) -> usize;
94}
95
96fn js_install(packager: &str) -> &'static str {
98 match packager {
99 "yarn" => "yarn install",
100 "npm" => "npm install",
101 _ => "pnpm install",
102 }
103}
104
105fn js_build(packager: &str) -> &'static str {
107 match packager {
108 "yarn" => "yarn build",
109 "npm" => "npm run build",
110 _ => "pnpm run build",
111 }
112}
113
114fn strip_comments(config: &[u8]) -> std::borrow::Cow<'_, [u8]> {
120 if memchr::memmem::find(config, b"//").is_none() {
121 return std::borrow::Cow::Borrowed(config);
122 }
123 let mut out = Vec::with_capacity(config.len());
124 let (mut copied, mut i) = (0, 0);
125 while let Some(n) = memchr::memchr(b'/', &config[i..]) {
128 let at = i + n;
129 if config.get(at + 1) == Some(&b'/') && (at == 0 || config[at - 1] != b':') {
130 out.extend_from_slice(&config[copied..at]);
131 copied = memchr::memchr(b'\n', &config[at..]).map_or(config.len(), |n| at + n);
132 i = copied;
133 } else {
134 i = at + 1;
135 }
136 }
137 out.extend_from_slice(&config[copied..]);
138 std::borrow::Cow::Owned(out)
139}
140
141fn contains(haystack: &[u8], needle: &[u8]) -> bool {
142 memchr::memmem::find(haystack, needle).is_some()
143}
144
145fn word(b: u8) -> bool {
147 b.is_ascii_alphanumeric() || b == b'_'
148}
149
150fn space(b: u8) -> bool {
152 matches!(b, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
153}
154
155fn skip_spaces(s: &[u8], mut i: usize) -> usize {
157 while i < s.len() && space(s[i]) {
158 i += 1;
159 }
160 i
161}
162
163fn words_at<'a>(s: &'a [u8], name: &'a [u8]) -> impl Iterator<Item = usize> + 'a {
165 memchr::memmem::find_iter(s, name).filter(move |&i| i == 0 || !word(s[i - 1])).map(move |i| i + name.len())
166}
167
168fn prerender(s: &[u8]) -> (bool, bool) {
171 let mut found = false;
172 for mut i in words_at(s, b"prerender") {
173 found |= i == s.len() || !word(s[i]);
174 if i < s.len() && (s[i] == b'\'' || s[i] == b'"') {
175 i += 1;
176 }
177 i = skip_spaces(s, i);
178 if s.get(i) != Some(&b':') {
179 continue;
180 }
181 i = skip_spaces(s, i + 1);
182 if s[i..].starts_with(b"false") && s.get(i + 5).is_none_or(|&b| !word(b)) {
183 return (true, true);
184 }
185 }
186 (found, false)
187}
188
189fn output_server(s: &[u8]) -> bool {
191 let quote = |b: Option<&u8>| matches!(b, Some(b'\'' | b'"' | b'`'));
192 words_at(s, b"output").any(|i| {
193 let i = skip_spaces(s, i);
194 if s.get(i) != Some(&b':') {
195 return false;
196 }
197 let i = skip_spaces(s, i + 1);
198 if !quote(s.get(i)) {
199 return false;
200 }
201 let rest = &s[i + 1..];
202 (rest.starts_with(b"server") || rest.starts_with(b"hybrid")) && quote(rest.get(6))
203 })
204}
205
206macro_rules! framework {
207 (
208 $(#[$doc:meta])* $ty:ident, $name:literal,
209 files: $files:expr, packages: $packages:expr,
210 install: $install:expr, build: $build:expr, output: $output:literal,
211 config: $config:expr, adapter: $adapter:expr, parents: $parents:literal
212 ) => {
213 $(#[$doc])*
214 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
215 pub struct $ty;
216
217 impl Framework for $ty {
218 fn name(&self) -> &str {
219 $name
220 }
221
222 fn files(&self) -> &[&str] {
223 &$files
224 }
225
226 fn packages(&self) -> &[&str] {
227 &$packages
228 }
229
230 fn install_command(&self, packager: &str) -> &str {
231 let install: fn(&str) -> &'static str = $install;
232 install(packager)
233 }
234
235 fn build_command(&self, packager: &str) -> &str {
236 let build: fn(&str) -> &'static str = $build;
237 build(packager)
238 }
239
240 fn output_directory(&self) -> &str {
241 $output
242 }
243
244 fn config_files(&self) -> &[&str] {
245 &$config
246 }
247
248 fn adapter(&self, config: &[u8]) -> Option<Adapter> {
249 let adapter: fn(&[u8]) -> Option<Adapter> = $adapter;
250 adapter(config)
251 }
252
253 fn parents(&self) -> usize {
254 $parents
255 }
256 }
257 };
258}
259
260framework!(
261 Analog, "analog",
265 files: ["angular.json"], packages: ["@analogjs/platform", "@angular/core"],
266 install: js_install, build: js_build, output: "./dist/analog",
267 config: [], adapter: |_| None, parents: 4
268);
269
270framework!(
271 Angular, "angular",
275 files: ["angular.json"], packages: ["@angular/core"],
276 install: js_install, build: js_build, output: "./dist/angular",
277 config: [], adapter: |_| None, parents: 3
278);
279
280framework!(
281 Astro, "astro",
290 files: [
291 "astro.config.mjs", "astro.config.js", "astro.config.ts", "angular.json",
292 "svelte.config.js", "svelte.config.mjs", "svelte.config.ts",
293 ],
294 packages: ["astro", "@angular/core", "react", "vue", "svelte"],
295 install: js_install, build: js_build, output: "./dist",
296 config: ["astro.config.mjs", "astro.config.js", "astro.config.ts"],
297 adapter: |config| {
298 let stripped = strip_comments(config);
299 Some(if output_server(&stripped) {
300 Adapter::Ssr
301 } else {
302 Adapter::Static
303 })
304 },
305 parents: 3
306);
307
308framework!(
309 Flutter, "flutter",
313 files: ["pubspec.yaml", "pubspec.lock"], packages: ["flutter"],
314 install: |_| "", build: |_| "flutter build web", output: "./build/web",
315 config: [], adapter: |_| None, parents: 2
316);
317
318framework!(
319 Jaspr, "jaspr",
328 files: ["pubspec.yaml", "pubspec.lock"], packages: ["jaspr", "jaspr_builder", "flutter"],
329 install: |_| "dart pub get", build: |_| "jaspr build", output: "./build/jaspr",
330 config: ["pubspec.yaml"],
331 adapter: |config| {
332 let Some(Value::Array(pubspec)) = yaml::parse(config) else { return None };
333 let Some(Value::Array(jaspr)) = pubspec.get_ref(KeyRef::Str(b"jaspr")) else { return None };
334 match jaspr.get_ref(KeyRef::Str(b"mode")) {
335 Some(Value::Str(mode)) if mode.as_bytes() == b"server" => Some(Adapter::Ssr),
336 Some(Value::Str(mode)) if mode.as_bytes() == b"static" || mode.as_bytes() == b"client" => {
337 Some(Adapter::Static)
338 }
339 _ => None,
340 }
341 },
342 parents: 3
343);
344
345framework!(
346 Lynx, "lynx",
350 files: ["lynx.config.ts", "lynx.config.js", "lynx.config.mjs"], packages: ["@lynx-js/react", "react"],
351 install: js_install, build: js_build, output: "./dist",
352 config: [], adapter: |_| None, parents: 4
353);
354
355framework!(
356 NextJs, "nextjs",
360 files: ["next.config.js", "next.config.ts", "next.config.mjs"], packages: ["next", "react"],
361 install: js_install, build: js_build, output: "./.next",
362 config: [], adapter: |_| None, parents: 4
363);
364
365framework!(
366 Nuxt, "nuxt",
370 files: ["nuxt.config.js", "nuxt.config.ts", "nuxt.config.mjs"], packages: ["nuxt", "vue"],
371 install: js_install, build: js_build, output: "./.output",
372 config: [], adapter: |_| None, parents: 4
373);
374
375framework!(
376 React, "react",
380 files: [], packages: ["react"],
381 install: js_install, build: js_build, output: "./dist",
382 config: [], adapter: |_| None, parents: 3
383);
384
385framework!(
386 ReactNative, "react-native",
390 files: [], packages: ["react-native", "react"],
391 install: js_install, build: js_build, output: "./dist",
392 config: [], adapter: |_| None, parents: 4
393);
394
395framework!(
396 Remix, "remix",
400 files: ["remix.config.js", "remix.config.ts", "remix.config.mjs"], packages: ["@remix-run/react", "react"],
401 install: js_install, build: js_build, output: "./build",
402 config: ["package.json"], adapter: |_| Some(Adapter::Ssr), parents: 4
403);
404
405framework!(
406 Svelte, "svelte",
410 files: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts"], packages: ["svelte"],
411 install: js_install, build: js_build, output: "./build",
412 config: [], adapter: |_| None, parents: 3
413);
414
415framework!(
416 SvelteKit, "sveltekit",
421 files: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts"], packages: ["@sveltejs/kit", "svelte"],
422 install: js_install, build: js_build, output: "./build",
423 config: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts", "package.json"],
424 adapter: |config| {
425 Some(if contains(&strip_comments(config), b"@sveltejs/adapter-static") { Adapter::Static } else { Adapter::Ssr })
426 },
427 parents: 4
428);
429
430framework!(
431 TanStackStart, "tanstack-start",
436 files: [], packages: ["@tanstack/react-start", "@tanstack/solid-start", "react"],
437 install: js_install, build: js_build, output: "./.output",
438 config: ["vite.config.ts", "vite.config.js", "vite.config.mjs"],
439 adapter: |config| {
440 let stripped = strip_comments(config);
441 if contains(&stripped, b"nitro/vite") || contains(&stripped, b"@tanstack/nitro-v2-vite-plugin") {
443 return Some(Adapter::Ssr);
444 }
445 let (prerenders, disabled) = prerender(&stripped);
446 if !prerenders || disabled {
447 return Some(Adapter::Ssr);
448 }
449 Some(Adapter::Static)
450 },
451 parents: 4
452);
453
454framework!(
455 Vue, "vue",
459 files: [], packages: ["vue"],
460 install: js_install, build: js_build, output: "./dist",
461 config: [], adapter: |_| None, parents: 3
462);
463
464#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum Input {
469 File,
473 Packages,
478}
479
480impl Input {
481 pub fn new(kind: &str) -> Result<Self, Error> {
486 match kind {
487 "file" => Ok(Input::File),
488 "packages" => Ok(Input::Packages),
489 _ => Err(Error::InvalidArgument(format!("Invalid input type '{kind}'"))),
490 }
491 }
492}
493
494const DEPENDENCY_SECTIONS: &[&[u8]] = &[
496 b"dependencies",
497 b"devDependencies",
498 b"peerDependencies",
499 b"optionalDependencies",
500 b"dev_dependencies",
501 b"dependency_overrides",
502];
503
504pub fn dependencies(manifest: &[u8]) -> Vec<Vec<u8>> {
510 let parsed = match json::decode(manifest, Some(true), DEFAULT_DEPTH, Flags::NONE) {
511 Ok(Value::Array(a)) => a,
512 _ => match yaml::parse(manifest) {
513 Some(Value::Array(a)) => a,
514 _ => return Vec::new(),
515 },
516 };
517 let mut names = Vec::new();
518 for section in DEPENDENCY_SECTIONS {
519 if let Some(Value::Array(packages)) = parsed.get_ref(KeyRef::Str(section)) {
520 names.extend(packages.keys().map(|k| match k {
521 KeyRef::Int(i) => i.to_string().into_bytes(),
522 KeyRef::Str(s) => s.to_vec(),
523 }));
524 }
525 }
526 names
527}
528
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
534pub struct Score<'a> {
535 pub name: &'a [u8],
537 pub matches: usize,
539 pub parents: usize,
541}
542
543pub fn matches<'a>(
550 files: impl IntoIterator<Item = &'a [u8]>,
551 packages: impl IntoIterator<Item = &'a [u8]>,
552 inputs: &[&[u8]],
553 manifests: &[Vec<Vec<u8>>],
554) -> usize {
555 let packages: usize = packages
556 .into_iter()
557 .map(|p| manifests.iter().filter(|dependencies| dependencies.iter().any(|d| d == p)).count())
558 .sum();
559 packages + files.into_iter().filter(|f| inputs.contains(f)).count()
560}
561
562pub fn best<'a>(scores: impl IntoIterator<Item = Score<'a>>) -> Option<&'a [u8]> {
570 let mut merged: Vec<Score<'a>> = Vec::new();
572 for score in scores {
573 match merged.iter_mut().find(|s| s.name == score.name) {
574 Some(merged) => {
575 merged.matches += score.matches;
576 merged.parents += score.parents;
577 }
578 None => merged.push(score),
579 }
580 }
581
582 merged.retain(|s| s.matches > 0);
583 merged.sort_by_key(|s| std::cmp::Reverse(s.matches));
585 let highest = merged.first()?.matches;
586 merged.retain(|s| s.matches == highest);
587 if merged.len() == 1 {
588 return Some(merged[0].name);
589 }
590
591 merged.sort_by_key(|s| s.parents);
593 if merged[0].name == Astro.name().as_bytes() && merged[0].matches == merged[1].matches {
596 Some(merged[1].name)
597 } else {
598 Some(merged[0].name)
599 }
600}
601
602pub struct FrameworkDetector {
642 packager: String,
643 options: Vec<Box<dyn Framework>>,
644 files: Vec<String>,
645 manifests: Vec<Vec<u8>>,
646}
647
648impl FrameworkDetector {
649 pub fn new(packager: impl Into<String>) -> Self {
653 FrameworkDetector { packager: packager.into(), options: Vec::new(), files: Vec::new(), manifests: Vec::new() }
654 }
655
656 pub fn add_option(&mut self, option: impl Framework + 'static) -> &mut Self {
660 self.options.push(Box::new(option));
661 self
662 }
663
664 pub fn add_file(&mut self, file: impl Into<String>) -> &mut Self {
668 self.files.push(file.into());
669 self
670 }
671
672 pub fn add_manifest(&mut self, content: impl Into<Vec<u8>>) -> &mut Self {
677 self.manifests.push(content.into());
678 self
679 }
680
681 pub fn detect(&self) -> Option<Detected<'_, dyn Framework>> {
687 let manifests: Vec<Vec<Vec<u8>>> = self.manifests.iter().map(|m| dependencies(m)).collect();
688 let files: Vec<&[u8]> = self.files.iter().map(|f| f.as_bytes()).collect();
689 let best = best(self.options.iter().map(|option| Score {
690 name: option.name().as_bytes(),
691 matches: matches(
692 option.files().iter().map(|f| f.as_bytes()),
693 option.packages().iter().map(|p| p.as_bytes()),
694 &files,
695 &manifests,
696 ),
697 parents: option.parents(),
698 }))?;
699 self.options.iter().find(|o| o.name().as_bytes() == best).map(|o| Detected::new(o.as_ref(), &self.packager))
700 }
701}
702
703impl std::fmt::Debug for FrameworkDetector {
704 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
706 f.debug_struct("FrameworkDetector")
707 .field("packager", &self.packager)
708 .field("options", &self.options.iter().map(|o| o.name()).collect::<Vec<_>>())
709 .field("files", &self.files)
710 .field("manifests", &self.manifests.len())
711 .finish()
712 }
713}
714
715impl<T: Framework + ?Sized> Detected<'_, T> {
716 pub fn install_command(&self) -> &str {
720 self.item().install_command(self.packager())
721 }
722
723 pub fn build_command(&self) -> &str {
727 self.item().build_command(self.packager())
728 }
729}
730
731#[cfg(test)]
733mod equivalence {
734 use php_std::pcre::{self, StrOrArray};
735
736 use super::{output_server, prerender, strip_comments};
737
738 fn regex_strip(s: &[u8]) -> Vec<u8> {
739 match pcre::preg_replace(
740 &StrOrArray::Str(br"/(?<!:)\/\/[^\n]*/"),
741 &StrOrArray::Str(b""),
742 &StrOrArray::Str(s),
743 -1,
744 ) {
745 Ok(p) => match p.value.result {
746 pcre::Value::Str(s) => s,
747 _ => s.to_vec(),
748 },
749 Err(_) => s.to_vec(),
750 }
751 }
752
753 fn regex(pattern: &[u8], s: &[u8]) -> bool {
754 pcre::preg_match_bare(pattern, s).is_ok_and(|p| matches!(p.value, pcre::Value::Int(n) if n > 0))
755 }
756
757 fn inputs() -> impl Iterator<Item = Vec<u8>> {
760 const PIECES: &[&[u8]] = &[
761 b"prerender",
762 b"output",
763 b"server",
764 b"hybrid",
765 b"false",
766 b"falsey",
767 b":",
768 b"//",
769 b"/",
770 b"https:",
771 b"\n",
772 b" ",
773 b"\t",
774 b"\x0b",
775 b"\x0c",
776 b"\r",
777 b"'",
778 b"\"",
779 b"`",
780 b"_",
781 b"x",
782 b"9",
783 b"\xc3\xa9",
784 b"{",
785 b"}",
786 b"=",
787 b"prerender:",
788 b"enabled: true",
789 ];
790 let mut state = 0x9E37_79B9_7F4A_7C15u64;
791 (0..30_000).map(move |_| {
792 let mut next = || {
793 state ^= state << 13;
794 state ^= state >> 7;
795 state ^= state << 17;
796 state
797 };
798 let n = (next() % 12) as usize;
799 (0..n).flat_map(|_| PIECES[(next() % PIECES.len() as u64) as usize].to_vec()).collect()
800 })
801 }
802
803 #[test]
804 fn native_scans_match_the_regexes() {
805 for s in inputs() {
806 assert_eq!(&*strip_comments(&s), ®ex_strip(&s)[..], "strip {:?}", String::from_utf8_lossy(&s));
807 let (found, disabled) = prerender(&s);
808 assert_eq!(found, regex(br"/\bprerender\b/", &s), "prerender {:?}", String::from_utf8_lossy(&s));
809 assert_eq!(
810 disabled,
811 regex(br"/\bprerender[\x27\x22]?\s*:\s*false\b/", &s),
812 "prerender false {:?}",
813 String::from_utf8_lossy(&s)
814 );
815 assert_eq!(
816 output_server(&s),
817 regex(br"/\boutput\s*:\s*[\x27\x22\x60](?:server|hybrid)[\x27\x22\x60]/", &s),
818 "output {:?}",
819 String::from_utf8_lossy(&s)
820 );
821 }
822 }
823}