Skip to main content

utopia_detector/
framework.rs

1//! Frameworks: [`Framework`], the built-in frameworks, and the
2//! [`FrameworkDetector`] that scores them on file names and manifest
3//! dependencies.
4
5use php_std::json::{self, DEFAULT_DEPTH, Flags};
6use php_std::types::KeyRef;
7use php_std::{Value, yaml};
8
9use crate::{Detected, Error};
10
11/// How a framework's build is served, as its configuration says.
12///
13/// PHP: the `'ssr'` and `'static'` strings `getAdapter()` returns (`''`
14/// is `None`).
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Adapter {
17    /// A server renders pages: `ssr`.
18    Ssr,
19    /// Pages are files: `static`.
20    Static,
21}
22
23impl Adapter {
24    /// `ssr` or `static`.
25    pub fn as_str(&self) -> &'static str {
26        match self {
27            Adapter::Ssr => "ssr",
28            Adapter::Static => "static",
29        }
30    }
31}
32
33/// A web framework, recognised by its configuration files and the packages
34/// a project depends on.
35///
36/// PHP: `Utopia\Detector\Detection\Framework`.
37pub trait Framework: Send + Sync {
38    /// The framework's name, such as `nextjs`.
39    ///
40    /// PHP: `getName()`.
41    fn name(&self) -> &str;
42
43    /// The file names that reveal it, such as `next.config.js`.
44    ///
45    /// PHP: `getFiles()`.
46    fn files(&self) -> &[&str];
47
48    /// The dependencies that reveal it, such as `next`.
49    ///
50    /// PHP: `getPackages()`.
51    fn packages(&self) -> &[&str] {
52        &[]
53    }
54
55    /// The command that installs dependencies with `packager` (`npm`,
56    /// `pnpm`, `yarn`; anything else, or empty, as pnpm).
57    ///
58    /// PHP: `getInstallCommand()`, with the packager `setPackager()` set.
59    fn install_command(&self, packager: &str) -> &str;
60
61    /// The command that builds with `packager`.
62    ///
63    /// PHP: `getBuildCommand()`, with the packager `setPackager()` set.
64    fn build_command(&self, packager: &str) -> &str;
65
66    /// Where the build writes its output, such as `./.next`.
67    ///
68    /// PHP: `getOutputDirectory()`.
69    fn output_directory(&self) -> &str;
70
71    /// The configuration files to read for [`Framework::adapter`], in
72    /// priority order.
73    ///
74    /// PHP: `getConfigFiles()`.
75    fn config_files(&self) -> &[&str] {
76        &[]
77    }
78
79    /// How the build is served, read from a configuration file's content, or
80    /// `None` when it cannot tell.
81    ///
82    /// PHP: `getAdapter($configContent)`.
83    fn adapter(&self, config: &[u8]) -> Option<Adapter> {
84        let _ = config;
85        None
86    }
87
88    /// How many classes the framework's PHP class extends (React extends
89    /// JS, Framework and Detection: 3). When frameworks tie on matches, the
90    /// one with the fewest wins: the more general framework.
91    ///
92    /// PHP: the `get_parent_class()` chain `detect()` counts.
93    fn parents(&self) -> usize;
94}
95
96/// `install` for the JavaScript frameworks: the packager's install command.
97fn js_install(packager: &str) -> &'static str {
98    match packager {
99        "yarn" => "yarn install",
100        "npm" => "npm install",
101        _ => "pnpm install",
102    }
103}
104
105/// `build` for the JavaScript frameworks: the packager's build script.
106fn 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
114/// `$content` without `//` comments, leaving `https://` alone.
115///
116/// PHP: `preg_replace('/(?<!:)\/\/[^\n]*/', '', $content)`: a `//` not right
117/// after a `:` starts a comment that runs to the end of the line (the
118/// newline stays). Scanned natively; `equivalence` tests pin it to the regex.
119fn 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    // Every `/`, so overlapping candidates (`:///`) are all tried, as the
126    // regex tries every position.
127    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
145/// A PCRE word character outside UTF mode: `[A-Za-z0-9_]`.
146fn word(b: u8) -> bool {
147    b.is_ascii_alphanumeric() || b == b'_'
148}
149
150/// PCRE's `\s` outside UTF mode: space, `\t`, `\n`, `\v`, `\f`, `\r`.
151fn space(b: u8) -> bool {
152    matches!(b, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
153}
154
155/// Where `s[i..]` continues after any `\s*`.
156fn skip_spaces(s: &[u8], mut i: usize) -> usize {
157    while i < s.len() && space(s[i]) {
158        i += 1;
159    }
160    i
161}
162
163/// The positions just after each `\b<name>` in `s` (a word boundary before it).
164fn 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
168/// Whether `s` matches `/\bprerender\b/`, and whether it matches
169/// `/\bprerender[\x27\x22]?\s*:\s*false\b/`, in one pass.
170fn 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
189/// `/\boutput\s*:\s*[\x27\x22\x60](?:server|hybrid)[\x27\x22\x60]/`.
190fn 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, the Angular meta-framework.
262    ///
263    /// PHP: `Utopia\Detector\Detection\Framework\Analog`.
264    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.
272    ///
273    /// PHP: `Utopia\Detector\Detection\Framework\Angular`.
274    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. It renders components of other frameworks, so their files and
282    /// packages count for it too; a tie between Astro and another framework
283    /// goes to the other one.
284    ///
285    /// The adapter is server-side when the configuration sets `output` to
286    /// `server` or `hybrid`, and static otherwise.
287    ///
288    /// PHP: `Utopia\Detector\Detection\Framework\Astro`.
289    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 (web).
310    ///
311    /// PHP: `Utopia\Detector\Detection\Framework\Flutter`.
312    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, the Dart web framework. It is detected from the same pubspec
320    /// files as Flutter and wins once a `jaspr` package appears, whatever
321    /// order the options were added in.
322    ///
323    /// The adapter follows `jaspr.mode` in `pubspec.yaml`: `server` is
324    /// server-side, `static` and `client` are static.
325    ///
326    /// PHP: `Utopia\Detector\Detection\Framework\Jaspr`.
327    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.
347    ///
348    /// PHP: `Utopia\Detector\Detection\Framework\Lynx`.
349    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    /// Next.js.
357    ///
358    /// PHP: `Utopia\Detector\Detection\Framework\NextJs`.
359    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.
367    ///
368    /// PHP: `Utopia\Detector\Detection\Framework\Nuxt`.
369    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.
377    ///
378    /// PHP: `Utopia\Detector\Detection\Framework\React`.
379    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    /// React Native.
387    ///
388    /// PHP: `Utopia\Detector\Detection\Framework\ReactNative`.
389    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: always server-side.
397    ///
398    /// PHP: `Utopia\Detector\Detection\Framework\Remix`.
399    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.
407    ///
408    /// PHP: `Utopia\Detector\Detection\Framework\Svelte`.
409    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: static when the configuration (or `package.json`) uses
417    /// `@sveltejs/adapter-static`, server-side otherwise.
418    ///
419    /// PHP: `Utopia\Detector\Detection\Framework\SvelteKit`.
420    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    /// TanStack Start: server-side with a Nitro plugin or without
432    /// prerendering, static when it prerenders.
433    ///
434    /// PHP: `Utopia\Detector\Detection\Framework\TanStackStart`.
435    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        // Nitro emits `.output/server/index.mjs` even when every route is prerendered.
442        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.
456    ///
457    /// PHP: `Utopia\Detector\Detection\Framework\Vue`.
458    Vue, "vue",
459    files: [], packages: ["vue"],
460    install: js_install, build: js_build, output: "./dist",
461    config: [], adapter: |_| None, parents: 3
462);
463
464/// What a framework detector input is.
465///
466/// PHP: the `$type` of `Framework::addInput()`.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum Input {
469    /// A file name of the project.
470    ///
471    /// PHP: `Framework::INPUT_FILE` (`file`).
472    File,
473    /// The content of a manifest (`package.json`, `pubspec.yaml`) whose
474    /// dependencies are read.
475    ///
476    /// PHP: `Framework::INPUT_PACKAGES` (`packages`).
477    Packages,
478}
479
480impl Input {
481    /// The input kind named `kind`: `file` or `packages`.
482    ///
483    /// PHP: the check in `Framework::addInput()`, which throws for any
484    /// other type.
485    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
494/// The manifest sections whose keys are dependencies.
495const 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
504/// The dependency names declared in a `package.json` (JSON) or
505/// `pubspec.yaml` (YAML), section by section; none when it parses as
506/// neither.
507///
508/// PHP: `Framework::dependencies()`.
509pub 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/// One option as a framework detector scores it.
530///
531/// PHP: the option's entries in `detect()`'s `$frameworkMatches` and
532/// `$fameworkParents`.
533#[derive(Debug, Clone, Copy, PartialEq, Eq)]
534pub struct Score<'a> {
535    /// The option's name (`getName()`).
536    pub name: &'a [u8],
537    /// How many of its files and packages the inputs hold ([`matches`]).
538    pub matches: usize,
539    /// How many classes its PHP class extends ([`Framework::parents`]).
540    pub parents: usize,
541}
542
543/// How many of an option's `files` are among the file `inputs`, plus how many
544/// of its `packages` each manifest's [`dependencies`] declare. A file or
545/// package the option lists twice counts twice.
546///
547/// PHP: `count(array_intersect($detector->getFiles(), $files))` plus the
548/// `in_array($packageNeeded, $dependencies, true)` hits of `detect()`.
549pub 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
562/// The name of the framework a detector picks from `scores`, one per option
563/// in the order the options were added: options sharing a name add up; the
564/// most matches win; a tie goes to the fewest parents, except that Astro
565/// yields to the runner-up. `None` when nothing matches.
566///
567/// PHP: the ranking in `Framework::detect()` (a stable `arsort()`, then a
568/// stable `usort()` on parents).
569pub fn best<'a>(scores: impl IntoIterator<Item = Score<'a>>) -> Option<&'a [u8]> {
570    // By name, in the order the names first appear.
571    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    // A stable sort, most matches first, as PHP's arsort().
584    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    // A stable sort, fewest parents first, as PHP's usort().
592    merged.sort_by_key(|s| s.parents);
593    // Astro renders the other frameworks' components: an equal match goes to
594    // the other framework.
595    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
602/// Finds a project's framework by scoring every option: one point per
603/// framework file among the file inputs, and one per framework package
604/// declared in each manifest input. The highest score wins; a tie goes to
605/// the framework with the fewest [parents](Framework::parents), except that
606/// Astro yields to the runner-up.
607///
608/// Options are scored by name: two options with one name share a score.
609///
610/// PHP: `Utopia\Detector\Detector\Framework`.
611///
612/// ```
613/// use utopia_detector::{FrameworkDetector, NextJs, React};
614///
615/// let mut detector = FrameworkDetector::new("npm");
616/// detector.add_option(React).add_option(NextJs);
617/// detector.add_file("next.config.js");
618/// detector.add_manifest(r#"{"dependencies": {"react": "^18.0.0"}}"#);
619///
620/// let framework = detector.detect().expect("a framework");
621/// assert_eq!(framework.name(), "nextjs");
622/// assert_eq!(framework.install_command(), "npm install");
623/// assert_eq!(framework.output_directory(), "./.next");
624/// ```
625///
626/// ```php
627/// use Utopia\Detector\Detection\Framework\NextJs;
628/// use Utopia\Detector\Detection\Framework\React;
629/// use Utopia\Detector\Detector\Framework;
630///
631/// $detector = new Framework('npm');
632/// $detector->addOption(new React())->addOption(new NextJs());
633/// $detector->addInput('next.config.js', Framework::INPUT_FILE);
634/// $detector->addInput('{"dependencies": {"react": "^18.0.0"}}', Framework::INPUT_PACKAGES);
635///
636/// $framework = $detector->detect();
637/// echo $framework->getName(), "\n";            // nextjs
638/// echo $framework->getInstallCommand(), "\n";  // npm install
639/// echo $framework->getOutputDirectory(), "\n"; // ./.next
640/// ```
641pub 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    /// A detector for a project using `packager` (`pnpm` when unsure).
650    ///
651    /// PHP: `new Framework($packager)`.
652    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    /// Adds a framework to score.
657    ///
658    /// PHP: `addOption($framework)`.
659    pub fn add_option(&mut self, option: impl Framework + 'static) -> &mut Self {
660        self.options.push(Box::new(option));
661        self
662    }
663
664    /// Adds a file name of the project.
665    ///
666    /// PHP: `addInput($file, Framework::INPUT_FILE)`.
667    pub fn add_file(&mut self, file: impl Into<String>) -> &mut Self {
668        self.files.push(file.into());
669        self
670    }
671
672    /// Adds the content of a manifest (`package.json`, `pubspec.yaml`), whose
673    /// dependencies count for the frameworks that list them.
674    ///
675    /// PHP: `addInput($content, Framework::INPUT_PACKAGES)`.
676    pub fn add_manifest(&mut self, content: impl Into<Vec<u8>>) -> &mut Self {
677        self.manifests.push(content.into());
678        self
679    }
680
681    /// The best scoring framework, with the detector's packager, or `None`
682    /// when no option scores.
683    ///
684    /// PHP: `detect()`, which also sets the packager on the framework it
685    /// returns.
686    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    /// The packager, options' names and file inputs.
705    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    /// The install command for the detector's packager.
717    ///
718    /// PHP: `getInstallCommand()` on the detected framework.
719    pub fn install_command(&self) -> &str {
720        self.item().install_command(self.packager())
721    }
722
723    /// The build command for the detector's packager.
724    ///
725    /// PHP: `getBuildCommand()` on the detected framework.
726    pub fn build_command(&self) -> &str {
727        self.item().build_command(self.packager())
728    }
729}
730
731/// The native scans against the regexes PHP runs, on generated configs.
732#[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    /// Strings built from the pieces the patterns care about, by a small
758    /// deterministic generator (xorshift), so failures replay.
759    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), &regex_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}