use php_std::json::{self, DEFAULT_DEPTH, Flags};
use php_std::types::KeyRef;
use php_std::{Value, yaml};
use crate::{Detected, Error};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Adapter {
Ssr,
Static,
}
impl Adapter {
pub fn as_str(&self) -> &'static str {
match self {
Adapter::Ssr => "ssr",
Adapter::Static => "static",
}
}
}
pub trait Framework: Send + Sync {
fn name(&self) -> &str;
fn files(&self) -> &[&str];
fn packages(&self) -> &[&str] {
&[]
}
fn install_command(&self, packager: &str) -> &str;
fn build_command(&self, packager: &str) -> &str;
fn output_directory(&self) -> &str;
fn config_files(&self) -> &[&str] {
&[]
}
fn adapter(&self, config: &[u8]) -> Option<Adapter> {
let _ = config;
None
}
fn parents(&self) -> usize;
}
fn js_install(packager: &str) -> &'static str {
match packager {
"yarn" => "yarn install",
"npm" => "npm install",
_ => "pnpm install",
}
}
fn js_build(packager: &str) -> &'static str {
match packager {
"yarn" => "yarn build",
"npm" => "npm run build",
_ => "pnpm run build",
}
}
fn strip_comments(config: &[u8]) -> std::borrow::Cow<'_, [u8]> {
if memchr::memmem::find(config, b"//").is_none() {
return std::borrow::Cow::Borrowed(config);
}
let mut out = Vec::with_capacity(config.len());
let (mut copied, mut i) = (0, 0);
while let Some(n) = memchr::memchr(b'/', &config[i..]) {
let at = i + n;
if config.get(at + 1) == Some(&b'/') && (at == 0 || config[at - 1] != b':') {
out.extend_from_slice(&config[copied..at]);
copied = memchr::memchr(b'\n', &config[at..]).map_or(config.len(), |n| at + n);
i = copied;
} else {
i = at + 1;
}
}
out.extend_from_slice(&config[copied..]);
std::borrow::Cow::Owned(out)
}
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
memchr::memmem::find(haystack, needle).is_some()
}
fn word(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
}
fn skip_spaces(s: &[u8], mut i: usize) -> usize {
while i < s.len() && space(s[i]) {
i += 1;
}
i
}
fn words_at<'a>(s: &'a [u8], name: &'a [u8]) -> impl Iterator<Item = usize> + 'a {
memchr::memmem::find_iter(s, name).filter(move |&i| i == 0 || !word(s[i - 1])).map(move |i| i + name.len())
}
fn prerender(s: &[u8]) -> (bool, bool) {
let mut found = false;
for mut i in words_at(s, b"prerender") {
found |= i == s.len() || !word(s[i]);
if i < s.len() && (s[i] == b'\'' || s[i] == b'"') {
i += 1;
}
i = skip_spaces(s, i);
if s.get(i) != Some(&b':') {
continue;
}
i = skip_spaces(s, i + 1);
if s[i..].starts_with(b"false") && s.get(i + 5).is_none_or(|&b| !word(b)) {
return (true, true);
}
}
(found, false)
}
fn output_server(s: &[u8]) -> bool {
let quote = |b: Option<&u8>| matches!(b, Some(b'\'' | b'"' | b'`'));
words_at(s, b"output").any(|i| {
let i = skip_spaces(s, i);
if s.get(i) != Some(&b':') {
return false;
}
let i = skip_spaces(s, i + 1);
if !quote(s.get(i)) {
return false;
}
let rest = &s[i + 1..];
(rest.starts_with(b"server") || rest.starts_with(b"hybrid")) && quote(rest.get(6))
})
}
macro_rules! framework {
(
$(#[$doc:meta])* $ty:ident, $name:literal,
files: $files:expr, packages: $packages:expr,
install: $install:expr, build: $build:expr, output: $output:literal,
config: $config:expr, adapter: $adapter:expr, parents: $parents:literal
) => {
$(#[$doc])*
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct $ty;
impl Framework for $ty {
fn name(&self) -> &str {
$name
}
fn files(&self) -> &[&str] {
&$files
}
fn packages(&self) -> &[&str] {
&$packages
}
fn install_command(&self, packager: &str) -> &str {
let install: fn(&str) -> &'static str = $install;
install(packager)
}
fn build_command(&self, packager: &str) -> &str {
let build: fn(&str) -> &'static str = $build;
build(packager)
}
fn output_directory(&self) -> &str {
$output
}
fn config_files(&self) -> &[&str] {
&$config
}
fn adapter(&self, config: &[u8]) -> Option<Adapter> {
let adapter: fn(&[u8]) -> Option<Adapter> = $adapter;
adapter(config)
}
fn parents(&self) -> usize {
$parents
}
}
};
}
framework!(
Analog, "analog",
files: ["angular.json"], packages: ["@analogjs/platform", "@angular/core"],
install: js_install, build: js_build, output: "./dist/analog",
config: [], adapter: |_| None, parents: 4
);
framework!(
Angular, "angular",
files: ["angular.json"], packages: ["@angular/core"],
install: js_install, build: js_build, output: "./dist/angular",
config: [], adapter: |_| None, parents: 3
);
framework!(
Astro, "astro",
files: [
"astro.config.mjs", "astro.config.js", "astro.config.ts", "angular.json",
"svelte.config.js", "svelte.config.mjs", "svelte.config.ts",
],
packages: ["astro", "@angular/core", "react", "vue", "svelte"],
install: js_install, build: js_build, output: "./dist",
config: ["astro.config.mjs", "astro.config.js", "astro.config.ts"],
adapter: |config| {
let stripped = strip_comments(config);
Some(if output_server(&stripped) {
Adapter::Ssr
} else {
Adapter::Static
})
},
parents: 3
);
framework!(
Flutter, "flutter",
files: ["pubspec.yaml", "pubspec.lock"], packages: ["flutter"],
install: |_| "", build: |_| "flutter build web", output: "./build/web",
config: [], adapter: |_| None, parents: 2
);
framework!(
Jaspr, "jaspr",
files: ["pubspec.yaml", "pubspec.lock"], packages: ["jaspr", "jaspr_builder", "flutter"],
install: |_| "dart pub get", build: |_| "jaspr build", output: "./build/jaspr",
config: ["pubspec.yaml"],
adapter: |config| {
let Some(Value::Array(pubspec)) = yaml::parse(config) else { return None };
let Some(Value::Array(jaspr)) = pubspec.get_ref(KeyRef::Str(b"jaspr")) else { return None };
match jaspr.get_ref(KeyRef::Str(b"mode")) {
Some(Value::Str(mode)) if mode.as_bytes() == b"server" => Some(Adapter::Ssr),
Some(Value::Str(mode)) if mode.as_bytes() == b"static" || mode.as_bytes() == b"client" => {
Some(Adapter::Static)
}
_ => None,
}
},
parents: 3
);
framework!(
Lynx, "lynx",
files: ["lynx.config.ts", "lynx.config.js", "lynx.config.mjs"], packages: ["@lynx-js/react", "react"],
install: js_install, build: js_build, output: "./dist",
config: [], adapter: |_| None, parents: 4
);
framework!(
NextJs, "nextjs",
files: ["next.config.js", "next.config.ts", "next.config.mjs"], packages: ["next", "react"],
install: js_install, build: js_build, output: "./.next",
config: [], adapter: |_| None, parents: 4
);
framework!(
Nuxt, "nuxt",
files: ["nuxt.config.js", "nuxt.config.ts", "nuxt.config.mjs"], packages: ["nuxt", "vue"],
install: js_install, build: js_build, output: "./.output",
config: [], adapter: |_| None, parents: 4
);
framework!(
React, "react",
files: [], packages: ["react"],
install: js_install, build: js_build, output: "./dist",
config: [], adapter: |_| None, parents: 3
);
framework!(
ReactNative, "react-native",
files: [], packages: ["react-native", "react"],
install: js_install, build: js_build, output: "./dist",
config: [], adapter: |_| None, parents: 4
);
framework!(
Remix, "remix",
files: ["remix.config.js", "remix.config.ts", "remix.config.mjs"], packages: ["@remix-run/react", "react"],
install: js_install, build: js_build, output: "./build",
config: ["package.json"], adapter: |_| Some(Adapter::Ssr), parents: 4
);
framework!(
Svelte, "svelte",
files: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts"], packages: ["svelte"],
install: js_install, build: js_build, output: "./build",
config: [], adapter: |_| None, parents: 3
);
framework!(
SvelteKit, "sveltekit",
files: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts"], packages: ["@sveltejs/kit", "svelte"],
install: js_install, build: js_build, output: "./build",
config: ["svelte.config.js", "svelte.config.mjs", "svelte.config.ts", "package.json"],
adapter: |config| {
Some(if contains(&strip_comments(config), b"@sveltejs/adapter-static") { Adapter::Static } else { Adapter::Ssr })
},
parents: 4
);
framework!(
TanStackStart, "tanstack-start",
files: [], packages: ["@tanstack/react-start", "@tanstack/solid-start", "react"],
install: js_install, build: js_build, output: "./.output",
config: ["vite.config.ts", "vite.config.js", "vite.config.mjs"],
adapter: |config| {
let stripped = strip_comments(config);
if contains(&stripped, b"nitro/vite") || contains(&stripped, b"@tanstack/nitro-v2-vite-plugin") {
return Some(Adapter::Ssr);
}
let (prerenders, disabled) = prerender(&stripped);
if !prerenders || disabled {
return Some(Adapter::Ssr);
}
Some(Adapter::Static)
},
parents: 4
);
framework!(
Vue, "vue",
files: [], packages: ["vue"],
install: js_install, build: js_build, output: "./dist",
config: [], adapter: |_| None, parents: 3
);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Input {
File,
Packages,
}
impl Input {
pub fn new(kind: &str) -> Result<Self, Error> {
match kind {
"file" => Ok(Input::File),
"packages" => Ok(Input::Packages),
_ => Err(Error::InvalidArgument(format!("Invalid input type '{kind}'"))),
}
}
}
const DEPENDENCY_SECTIONS: &[&[u8]] = &[
b"dependencies",
b"devDependencies",
b"peerDependencies",
b"optionalDependencies",
b"dev_dependencies",
b"dependency_overrides",
];
pub fn dependencies(manifest: &[u8]) -> Vec<Vec<u8>> {
let parsed = match json::decode(manifest, Some(true), DEFAULT_DEPTH, Flags::NONE) {
Ok(Value::Array(a)) => a,
_ => match yaml::parse(manifest) {
Some(Value::Array(a)) => a,
_ => return Vec::new(),
},
};
let mut names = Vec::new();
for section in DEPENDENCY_SECTIONS {
if let Some(Value::Array(packages)) = parsed.get_ref(KeyRef::Str(section)) {
names.extend(packages.keys().map(|k| match k {
KeyRef::Int(i) => i.to_string().into_bytes(),
KeyRef::Str(s) => s.to_vec(),
}));
}
}
names
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Score<'a> {
pub name: &'a [u8],
pub matches: usize,
pub parents: usize,
}
pub fn matches<'a>(
files: impl IntoIterator<Item = &'a [u8]>,
packages: impl IntoIterator<Item = &'a [u8]>,
inputs: &[&[u8]],
manifests: &[Vec<Vec<u8>>],
) -> usize {
let packages: usize = packages
.into_iter()
.map(|p| manifests.iter().filter(|dependencies| dependencies.iter().any(|d| d == p)).count())
.sum();
packages + files.into_iter().filter(|f| inputs.contains(f)).count()
}
pub fn best<'a>(scores: impl IntoIterator<Item = Score<'a>>) -> Option<&'a [u8]> {
let mut merged: Vec<Score<'a>> = Vec::new();
for score in scores {
match merged.iter_mut().find(|s| s.name == score.name) {
Some(merged) => {
merged.matches += score.matches;
merged.parents += score.parents;
}
None => merged.push(score),
}
}
merged.retain(|s| s.matches > 0);
merged.sort_by_key(|s| std::cmp::Reverse(s.matches));
let highest = merged.first()?.matches;
merged.retain(|s| s.matches == highest);
if merged.len() == 1 {
return Some(merged[0].name);
}
merged.sort_by_key(|s| s.parents);
if merged[0].name == Astro.name().as_bytes() && merged[0].matches == merged[1].matches {
Some(merged[1].name)
} else {
Some(merged[0].name)
}
}
pub struct FrameworkDetector {
packager: String,
options: Vec<Box<dyn Framework>>,
files: Vec<String>,
manifests: Vec<Vec<u8>>,
}
impl FrameworkDetector {
pub fn new(packager: impl Into<String>) -> Self {
FrameworkDetector { packager: packager.into(), options: Vec::new(), files: Vec::new(), manifests: Vec::new() }
}
pub fn add_option(&mut self, option: impl Framework + 'static) -> &mut Self {
self.options.push(Box::new(option));
self
}
pub fn add_file(&mut self, file: impl Into<String>) -> &mut Self {
self.files.push(file.into());
self
}
pub fn add_manifest(&mut self, content: impl Into<Vec<u8>>) -> &mut Self {
self.manifests.push(content.into());
self
}
pub fn detect(&self) -> Option<Detected<'_, dyn Framework>> {
let manifests: Vec<Vec<Vec<u8>>> = self.manifests.iter().map(|m| dependencies(m)).collect();
let files: Vec<&[u8]> = self.files.iter().map(|f| f.as_bytes()).collect();
let best = best(self.options.iter().map(|option| Score {
name: option.name().as_bytes(),
matches: matches(
option.files().iter().map(|f| f.as_bytes()),
option.packages().iter().map(|p| p.as_bytes()),
&files,
&manifests,
),
parents: option.parents(),
}))?;
self.options.iter().find(|o| o.name().as_bytes() == best).map(|o| Detected::new(o.as_ref(), &self.packager))
}
}
impl std::fmt::Debug for FrameworkDetector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FrameworkDetector")
.field("packager", &self.packager)
.field("options", &self.options.iter().map(|o| o.name()).collect::<Vec<_>>())
.field("files", &self.files)
.field("manifests", &self.manifests.len())
.finish()
}
}
impl<T: Framework + ?Sized> Detected<'_, T> {
pub fn install_command(&self) -> &str {
self.item().install_command(self.packager())
}
pub fn build_command(&self) -> &str {
self.item().build_command(self.packager())
}
}
#[cfg(test)]
mod equivalence {
use php_std::pcre::{self, StrOrArray};
use super::{output_server, prerender, strip_comments};
fn regex_strip(s: &[u8]) -> Vec<u8> {
match pcre::preg_replace(
&StrOrArray::Str(br"/(?<!:)\/\/[^\n]*/"),
&StrOrArray::Str(b""),
&StrOrArray::Str(s),
-1,
) {
Ok(p) => match p.value.result {
pcre::Value::Str(s) => s,
_ => s.to_vec(),
},
Err(_) => s.to_vec(),
}
}
fn regex(pattern: &[u8], s: &[u8]) -> bool {
pcre::preg_match_bare(pattern, s).is_ok_and(|p| matches!(p.value, pcre::Value::Int(n) if n > 0))
}
fn inputs() -> impl Iterator<Item = Vec<u8>> {
const PIECES: &[&[u8]] = &[
b"prerender",
b"output",
b"server",
b"hybrid",
b"false",
b"falsey",
b":",
b"//",
b"/",
b"https:",
b"\n",
b" ",
b"\t",
b"\x0b",
b"\x0c",
b"\r",
b"'",
b"\"",
b"`",
b"_",
b"x",
b"9",
b"\xc3\xa9",
b"{",
b"}",
b"=",
b"prerender:",
b"enabled: true",
];
let mut state = 0x9E37_79B9_7F4A_7C15u64;
(0..30_000).map(move |_| {
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
let n = (next() % 12) as usize;
(0..n).flat_map(|_| PIECES[(next() % PIECES.len() as u64) as usize].to_vec()).collect()
})
}
#[test]
fn native_scans_match_the_regexes() {
for s in inputs() {
assert_eq!(&*strip_comments(&s), ®ex_strip(&s)[..], "strip {:?}", String::from_utf8_lossy(&s));
let (found, disabled) = prerender(&s);
assert_eq!(found, regex(br"/\bprerender\b/", &s), "prerender {:?}", String::from_utf8_lossy(&s));
assert_eq!(
disabled,
regex(br"/\bprerender[\x27\x22]?\s*:\s*false\b/", &s),
"prerender false {:?}",
String::from_utf8_lossy(&s)
);
assert_eq!(
output_server(&s),
regex(br"/\boutput\s*:\s*[\x27\x22\x60](?:server|hybrid)[\x27\x22\x60]/", &s),
"output {:?}",
String::from_utf8_lossy(&s)
);
}
}
}