Skip to main content

larust_convert/
composer.rs

1//! `composer.json` → third-party package report. No PHP parsing needed
2//! here - `composer.json` is plain JSON, read with `serde_json` (already a
3//! workspace dependency).
4//!
5//! **Packages are never auto-ported.** A small, hand-curated mapping table
6//! (below) is populated deliberately over time, the same one-at-a-time way
7//! `larust-mail`/`larust-queue`/`larust-scheduler`/`larust-notifications`
8//! were each built as individual crates - never auto-generated PHP-to-Rust
9//! translation of a package's internals. Anything not in the table is
10//! named, with its version constraint, in the report - never silently
11//! dropped, never guessed at.
12
13use crate::report::PackageNote;
14use anyhow::{Context, Result};
15use std::collections::BTreeMap;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Package {
19    pub name: String,
20    pub version: String,
21}
22
23/// A single hand-curated entry: a composer package name mapped to a short
24/// note pointing at its Larust equivalent. Starts empty/near-empty - its
25/// value is the mechanism and the detection, not a pre-built library of
26/// ports (see this module's own doc comment). Add an entry here only once
27/// a real Larust equivalent actually exists and has been verified to cover
28/// the package's common usage - never as a hopeful placeholder.
29///
30/// Not every entry here points at a hand-built Larust crate - three
31/// shapes of note actually land in this table:
32/// - a real, hand-built crate in this workspace (`spatie/laravel-permission`);
33/// - a package whose role is already fully covered by Larust's own
34///   architecture, nothing to port (`laravel/octane` - its whole reason
35///   to exist, avoiding PHP's per-request bootstrap cost, doesn't apply
36///   to an already-compiled, already-long-running native binary);
37/// - a package that trivially maps to an existing crates.io crate, no
38///   Larust-specific wrapper needed at all (`stripe/stripe-php` →
39///   `async-stripe`).
40///
41/// The third field is the `larust-support` Cargo feature this package's
42/// mapping needs turned on in the generated app (see [`required_features`]) -
43/// `None` when a mapping doesn't correspond to one of the five optional
44/// Tier-1 shim crates at all: `laravel/octane` is a no-op, `stripe/
45/// stripe-php` maps to an external crates.io crate (not `larust-support`),
46/// and `spatie/laravel-responsecache` maps to `larust_http::responsecache`,
47/// which is unconditional (core `larust-http`, not one of the five
48/// optional shims).
49const TIER_1: &[(&str, &str, Option<&str>)] = &[
50    (
51        "laravel/cashier",
52        "maps to larust_support::cashier::stripe (this workspace, backed by the \
53         larust-cashier-stripe crate) - subscription billing via create_customer()/ \
54         checkout_url()/cancel_subscription()/resume_subscription()/swap_subscription(), with \
55         handle_webhook() keeping a local subscription mirror in sync; one of possibly several \
56         independently-selectable Cashier backends (see its own doc comment), with no \
57         Checkout UI/customer portal, one subscription item per subscription, no invoice \
58         listing or payment-method management",
59        Some("cashier-stripe"),
60    ),
61    (
62        "spatie/laravel-permission",
63        "maps to larust-permissions (this workspace) - compile-checked permission/role names, \
64         DB-backed assignment; see its own doc comment for the hybrid design and what's still \
65         manual (Blade @can/@role directives, role:/permission: middleware strings)",
66        Some("permissions"),
67    ),
68    (
69        "laravel/octane",
70        "not needed - Larust's own compiled, long-running native binary already avoids the \
71         per-request PHP bootstrap cost Octane exists to eliminate",
72        None,
73    ),
74    (
75        "stripe/stripe-php",
76        "maps to the async-stripe crate (crates.io) - Stripe's own actively-maintained Rust \
77         SDK; add it directly, no Larust-specific wrapper needed",
78        None,
79    ),
80    (
81        "spatie/laravel-responsecache",
82        "maps to larust_http::responsecache (this workspace) - GET/200-only page caching \
83         keyed by URL, backed by larust-cache; see its own doc comment for what's \
84         deliberately out of scope (Vary/per-user caching, auto-invalidation on writes, \
85         bulk cache-clear - only per-URL forget(url) and TTL expiry)",
86        None,
87    ),
88    (
89        "laravel/sanctum",
90        "maps to larust_support::sanctum (this workspace, backed by the larust-sanctum \
91         crate) - bearer-token API authentication via the ApiAuth<U> extractor, sibling \
92         to larust_auth::Auth<U>; see its own doc comment for what's deliberately out of \
93         scope (token abilities/scopes, SPA stateful-cookie mode - Auth<U> already covers \
94         that, auth:sanctum middleware-string recognition)",
95        Some("sanctum"),
96    ),
97    (
98        "spatie/laravel-sitemap",
99        "maps to larust_support::sitemap (this workspace, backed by the larust-sitemap \
100         crate) - an XML <urlset> builder plus a response wrapper, not an auto-mounted \
101         route; from_static_routes() covers static GET routes, dynamic per-model URLs \
102         are supplied by the app itself; see its own doc comment for what's deliberately \
103         out of scope (sitemap index/pagination past 50k URLs, built-in caching - wrap \
104         the route in larust_http::responsecache instead)",
105        Some("sitemap"),
106    ),
107    (
108        "laravel/socialite",
109        "maps to larust_support::socialite (this workspace, backed by the larust-socialite \
110         crate) - OAuth Authorization Code login (GitHub/Google built in), via \
111         redirect_url()/user_from_callback(); see its own doc comment for what's \
112         deliberately out of scope (OIDC ID-token verification, token refresh/storage, \
113         an extend()-style provider registry - a third provider is just a hand-built \
114         OAuthProvider value)",
115        Some("socialite"),
116    ),
117    (
118        "laravel/reverb",
119        "maps to larust_support::reverb (this workspace, backed by the larust-reverb \
120         crate) - generic WebSocket pub/sub broadcasting, public and private channels, \
121         via broadcast_event()/authorize()/socket(); see its own doc comment for what's \
122         deliberately out of scope (presence channels, Pusher-wire-protocol \
123         compatibility, a per-channel-pattern authorization registry - one global \
124         authorize() callback does its own channel-name matching instead)",
125        Some("reverb"),
126    ),
127    (
128        "bezhansalleh/filament-shield",
129        "maps to larust_support::shield (this workspace, backed by the larust-shield crate) - \
130         resource/ability permission bundles on top of larust-permissions, filament-shield's \
131         own `view`/`create`/`update`/`delete`-per-resource shape narrowed to those four plus \
132         `view_any`; see its own doc comment for what's deliberately out of scope (no \
133         auto-scanning of your models/Filament resources - list your own resources by hand, \
134         no generated admin UI for editing role grants, no abilities beyond those five)",
135        Some("shield"),
136    ),
137    (
138        "laravel/passport",
139        "maps to larust_support::passport (this workspace, backed by the larust-passport \
140         crate) - a full OAuth2 authorization server: create_client(), \
141         create_authorization_code() + exchange_token() (Authorization Code with mandatory \
142         PKCE, Client Credentials, Refresh Token rotation), OAuthAuth<U>/OAuthClientAuth \
143         request extractors; see its own doc comment for what's deliberately out of scope \
144         (one redirect URI per client, no `passport:client`-equivalent interactive CLI, no \
145         scopes UI/consent-screen rendering - your own /oauth/authorize route owns that)",
146        Some("passport"),
147    ),
148    (
149        "laravel/pennant",
150        "maps to larust_support::pennant (this workspace, backed by the larust-pennant \
151         crate) - persisted, scope-aware boolean feature flags via active()/activate()/ \
152         deactivate()/forget()/purge(); see its own doc comment for what's deliberately out \
153         of scope (no Feature::define() resolver registry - active()'s own default argument \
154         replaces it, no @feature/@endfeature Blade directive - larust-view's directive set \
155         isn't an extensible registry, no non-boolean rich values)",
156        Some("pennant"),
157    ),
158    (
159        "laravel/scout",
160        "maps to larust_support::scout (this workspace, backed by the larust-scout crate) - \
161         full-text search via index()/search()/remove() against a Meilisearch instance; see \
162         its own doc comment for what's deliberately out of scope (Meilisearch only, no \
163         Algolia/database/collection drivers, no Searchable trait/automatic model-lifecycle \
164         indexing - explicit index()/remove() calls instead, no index configuration, \
165         filters, sorting, or facets)",
166        Some("scout"),
167    ),
168];
169
170/// The `larust-support` Cargo features `packages` implies, derived from
171/// [`TIER_1`]'s own third field - this is what turns `composer.json`'s own
172/// `require` block into the "required file" driving which optional Tier-1
173/// shim crates a converted app's generated `Cargo.toml` actually compiles
174/// in (see `xr convert`'s own doc comment/`docs/GOTCHAS.md`). Sorted and
175/// deduped so the generated `features = [...]` list is deterministic.
176pub fn required_features(packages: &[Package]) -> Vec<&'static str> {
177    let names: std::collections::HashSet<&str> = packages.iter().map(|p| p.name.as_str()).collect();
178    let mut features: Vec<&'static str> = TIER_1
179        .iter()
180        .filter_map(|(name, _, feature)| feature.filter(|_| names.contains(name)))
181        .collect();
182    features.sort_unstable();
183    features.dedup();
184    features
185}
186
187/// Parses `composer.json`'s `require` object into `(package, version)`
188/// pairs, in the order they appear in the file. Skips `php` itself (a
189/// runtime version constraint, not a package). Malformed JSON or a missing
190/// `require` object is a real error - this is called only after the
191/// caller has already confirmed the file exists.
192pub fn parse_require(source: &str) -> Result<Vec<Package>> {
193    let value: serde_json::Value =
194        serde_json::from_str(source).context("parsing composer.json as JSON")?;
195    let require = value
196        .get("require")
197        .and_then(|r| r.as_object())
198        .context("composer.json has no `require` object")?;
199
200    let mut packages = Vec::new();
201    for (name, version) in require {
202        if name == "php" {
203            continue;
204        }
205        let version = version.as_str().unwrap_or("*").to_string();
206        packages.push(Package {
207            name: name.clone(),
208            version,
209        });
210    }
211    // `serde_json::Value::Object` preserves insertion order (the `preserve_order`
212    // feature isn't enabled here, so it's a `BTreeMap` internally - sort
213    // explicitly so output is deterministic regardless of that).
214    packages.sort_by(|a, b| a.name.cmp(&b.name));
215    Ok(packages)
216}
217
218/// `true` if `packages` looks like a real Laravel application - used to
219/// fail `xr convert` fast on an unrelated directory rather than three
220/// minutes into a partial conversion.
221pub fn looks_like_laravel(packages: &[Package]) -> bool {
222    packages.iter().any(|p| p.name == "laravel/framework")
223}
224
225/// Splits `packages` into the two report tiers. `laravel/framework` itself
226/// is excluded - it isn't a third-party dependency to port, Larust *is*
227/// its wholesale replacement, so listing it as "no Larust equivalent;
228/// port manually" would be misleading noise rather than a real gap.
229pub fn classify(packages: &[Package]) -> (Vec<PackageNote>, Vec<PackageNote>) {
230    let tier_1: BTreeMap<&str, &str> = TIER_1
231        .iter()
232        .map(|(name, note, _)| (*name, *note))
233        .collect();
234    let mut mapped = Vec::new();
235    let mut unmapped = Vec::new();
236
237    for package in packages {
238        if package.name == "laravel/framework" {
239            continue;
240        }
241        if let Some(note) = tier_1.get(package.name.as_str()) {
242            mapped.push(PackageNote {
243                name: package.name.clone(),
244                version: package.version.clone(),
245                note: note.to_string(),
246            });
247        } else {
248            unmapped.push(PackageNote {
249                name: package.name.clone(),
250                version: package.version.clone(),
251                note: "no Larust equivalent; port manually".to_string(),
252            });
253        }
254    }
255
256    (mapped, unmapped)
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    const SAMPLE: &str = r#"{
264        "require": {
265            "php": "^8.2",
266            "laravel/framework": "^11.0",
267            "spatie/laravel-permission": "^6.0",
268            "spatie/laravel-activitylog": "^4.0"
269        }
270    }"#;
271
272    #[test]
273    fn parse_require_skips_php_and_extracts_the_rest() {
274        let packages = parse_require(SAMPLE).unwrap();
275        assert_eq!(packages.len(), 3);
276        assert!(packages
277            .iter()
278            .any(|p| p.name == "laravel/framework" && p.version == "^11.0"));
279        assert!(packages
280            .iter()
281            .any(|p| p.name == "spatie/laravel-permission" && p.version == "^6.0"));
282    }
283
284    #[test]
285    fn looks_like_laravel_checks_for_the_framework_package() {
286        let packages = parse_require(SAMPLE).unwrap();
287        assert!(looks_like_laravel(&packages));
288        assert!(!looks_like_laravel(&[]));
289    }
290
291    #[test]
292    fn classify_splits_mapped_and_unmapped_packages() {
293        // `spatie/laravel-permission` is a real TIER_1 entry (points at
294        // `larust-permissions`); `spatie/laravel-activitylog` has no
295        // mapping yet and stays unmapped - this is the mapped/unmapped
296        // split actually exercised, not just "everything's unmapped
297        // because the table happens to be empty."
298        let packages = parse_require(SAMPLE).unwrap();
299        let (mapped, unmapped) = classify(&packages);
300        assert_eq!(mapped.len(), 1);
301        assert_eq!(mapped[0].name, "spatie/laravel-permission");
302        assert!(mapped[0].note.contains("larust-permissions"));
303        assert_eq!(unmapped.len(), 1);
304        assert_eq!(unmapped[0].name, "spatie/laravel-activitylog");
305    }
306
307    #[test]
308    fn classify_maps_responsecache_too() {
309        let packages = [Package {
310            name: "spatie/laravel-responsecache".to_string(),
311            version: "^7.0".to_string(),
312        }];
313        let (mapped, unmapped) = classify(&packages);
314        assert_eq!(mapped.len(), 1);
315        assert_eq!(mapped[0].name, "spatie/laravel-responsecache");
316        assert!(mapped[0].note.contains("larust_http::responsecache"));
317        assert!(unmapped.is_empty());
318    }
319
320    #[test]
321    fn classify_maps_sanctum_too() {
322        let packages = [Package {
323            name: "laravel/sanctum".to_string(),
324            version: "^4.0".to_string(),
325        }];
326        let (mapped, unmapped) = classify(&packages);
327        assert_eq!(mapped.len(), 1);
328        assert_eq!(mapped[0].name, "laravel/sanctum");
329        assert!(mapped[0].note.contains("larust_support::sanctum"));
330        assert!(unmapped.is_empty());
331    }
332
333    #[test]
334    fn classify_maps_sitemap_too() {
335        let packages = [Package {
336            name: "spatie/laravel-sitemap".to_string(),
337            version: "^7.0".to_string(),
338        }];
339        let (mapped, unmapped) = classify(&packages);
340        assert_eq!(mapped.len(), 1);
341        assert_eq!(mapped[0].name, "spatie/laravel-sitemap");
342        assert!(mapped[0].note.contains("larust_support::sitemap"));
343        assert!(unmapped.is_empty());
344    }
345
346    #[test]
347    fn classify_maps_socialite_too() {
348        let packages = [Package {
349            name: "laravel/socialite".to_string(),
350            version: "^5.0".to_string(),
351        }];
352        let (mapped, unmapped) = classify(&packages);
353        assert_eq!(mapped.len(), 1);
354        assert_eq!(mapped[0].name, "laravel/socialite");
355        assert!(mapped[0].note.contains("larust_support::socialite"));
356        assert!(unmapped.is_empty());
357    }
358
359    #[test]
360    fn classify_maps_reverb_too() {
361        let packages = [Package {
362            name: "laravel/reverb".to_string(),
363            version: "^1.0".to_string(),
364        }];
365        let (mapped, unmapped) = classify(&packages);
366        assert_eq!(mapped.len(), 1);
367        assert_eq!(mapped[0].name, "laravel/reverb");
368        assert!(mapped[0].note.contains("larust_support::reverb"));
369        assert!(unmapped.is_empty());
370    }
371
372    #[test]
373    fn classify_maps_passport_too() {
374        let packages = [Package {
375            name: "laravel/passport".to_string(),
376            version: "^12.0".to_string(),
377        }];
378        let (mapped, unmapped) = classify(&packages);
379        assert_eq!(mapped.len(), 1);
380        assert_eq!(mapped[0].name, "laravel/passport");
381        assert!(mapped[0].note.contains("larust_support::passport"));
382        assert!(unmapped.is_empty());
383    }
384
385    #[test]
386    fn classify_maps_pennant_too() {
387        let packages = [Package {
388            name: "laravel/pennant".to_string(),
389            version: "^1.0".to_string(),
390        }];
391        let (mapped, unmapped) = classify(&packages);
392        assert_eq!(mapped.len(), 1);
393        assert_eq!(mapped[0].name, "laravel/pennant");
394        assert!(mapped[0].note.contains("larust_support::pennant"));
395        assert!(unmapped.is_empty());
396    }
397
398    #[test]
399    fn classify_maps_scout_too() {
400        let packages = [Package {
401            name: "laravel/scout".to_string(),
402            version: "^10.0".to_string(),
403        }];
404        let (mapped, unmapped) = classify(&packages);
405        assert_eq!(mapped.len(), 1);
406        assert_eq!(mapped[0].name, "laravel/scout");
407        assert!(mapped[0].note.contains("larust_support::scout"));
408        assert!(unmapped.is_empty());
409    }
410
411    #[test]
412    fn classify_maps_cashier_too() {
413        let packages = [Package {
414            name: "laravel/cashier".to_string(),
415            version: "^15.0".to_string(),
416        }];
417        let (mapped, unmapped) = classify(&packages);
418        assert_eq!(mapped.len(), 1);
419        assert_eq!(mapped[0].name, "laravel/cashier");
420        assert!(mapped[0].note.contains("larust_support::cashier"));
421        assert!(unmapped.is_empty());
422    }
423
424    #[test]
425    fn required_features_detects_every_tier_1_shim_sorted_and_deduped() {
426        let packages = [
427            Package {
428                name: "laravel/sanctum".to_string(),
429                version: "^4.0".to_string(),
430            },
431            Package {
432                name: "spatie/laravel-permission".to_string(),
433                version: "^6.0".to_string(),
434            },
435            Package {
436                name: "laravel/reverb".to_string(),
437                version: "^1.0".to_string(),
438            },
439            // A duplicate-feature package (there isn't a real second one
440            // mapping to "sanctum", so this just re-asserts sanctum is
441            // still present exactly once) - dedup is exercised by the
442            // sort_unstable/dedup call itself regardless.
443            Package {
444                name: "laravel/sanctum".to_string(),
445                version: "^4.0".to_string(),
446            },
447        ];
448        assert_eq!(
449            required_features(&packages),
450            vec!["permissions", "reverb", "sanctum"]
451        );
452    }
453
454    #[test]
455    fn required_features_is_empty_for_unmapped_or_feature_less_packages() {
456        let packages = [
457            Package {
458                name: "spatie/laravel-activitylog".to_string(),
459                version: "^4.0".to_string(),
460            },
461            Package {
462                name: "laravel/octane".to_string(),
463                version: "^2.0".to_string(),
464            },
465            Package {
466                name: "stripe/stripe-php".to_string(),
467                version: "^15.0".to_string(),
468            },
469            Package {
470                name: "spatie/laravel-responsecache".to_string(),
471                version: "^7.0".to_string(),
472            },
473        ];
474        assert!(required_features(&packages).is_empty());
475    }
476
477    #[test]
478    fn classify_excludes_laravel_framework_itself() {
479        let packages = parse_require(SAMPLE).unwrap();
480        let (_, unmapped) = classify(&packages);
481        assert!(!unmapped.iter().any(|p| p.name == "laravel/framework"));
482    }
483
484    #[test]
485    fn parse_require_rejects_missing_require_object() {
486        assert!(parse_require("{}").is_err());
487    }
488}