new DockerEnvironment, 'native' => new NativeEnvironment, 'herd' => new HerdEnvironment, 'lerd' => new LerdEnvironment, default => throw new \InvalidArgumentException("Unknown driver: {$name}"), }; } abstract public function name(): string; abstract public function label(): string; /** @return array Human-readable error messages for each unmet prerequisite; empty means all good. */ abstract public function missingPrerequisites(): array; public function run(InstallCommand $command): int { if (($result = $this->beforePrompts($command)) !== null) { return $result; } $command->promptForModules(); try { $result = $this->boot($command); if ($result === InstallCommand::SUCCESS) { $this->frontendBuilt = $this->buildFrontend($command); // Served only once built: a request before the build finds no manifest and 500s. $result = $this->serve($command); } // A module that doesn't fit the installed core installs fine and then breaks // every request, so "complete" waits until the app has actually booted. if ($result === InstallCommand::SUCCESS && ! $this->artisan($command, ['about', '--only=environment'])) { $result = $this->failWithReason($command, 'Checking the app boots'); } } catch (ProcessTimedOutException $e) { // Any step's command, on any driver: without this the install ends on a stack trace. $line = str_replace("'", '', $e->result->command()); $command->warn("`{$line}` ran longer than {$e->exceededTimeout()} seconds, so it was stopped."); $result = $this->fail("Running `{$line}`"); } if ($result === InstallCommand::SUCCESS) { $command->displaySuccess(array_merge($this->cdStep($command), $this->nextSteps($command), $this->demoStep($command))); } else { // Single exit point for every failing step in boot() — the install must // never end silently, since the app directory already exists by now. $command->displayFailure($this->failedStep, $this->resumeOptions()); } return $result; } /** * Builds the assets so the app's URL works before anyone runs Vite. Node isn't a * prerequisite, so without npm, or when the build fails, it stays a next step. */ protected function buildFrontend(InstallCommand $command): bool { if (! $this->commandExists('npm')) { return false; } $command->info('Building the frontend...'); if ($command->runProcess(['npm', 'install'], 600) && $command->runProcess(['npm', 'run', 'build'], 600)) { return true; } $command->warn('Building the frontend failed. Run `npm install && npm run build` in the app to see why.'); return false; } /** Makes the built app reachable (a site server's link). Nothing for most drivers. */ protected function serve(InstallCommand $command): int { return InstallCommand::SUCCESS; } /** @param string[] $args */ protected function artisan(InstallCommand $command, array $args): bool { return $command->runArtisan($args); } /** * An artisan command's output, or null when it fails. * * @param string[] $args */ protected function artisanOutput(InstallCommand $command, array $args): ?string { $result = Process::path($command->targetPath())->timeout(120)->run([PHP_BINARY, $command->path('artisan'), ...$args]); return $result->successful() ? $result->output() : null; } /** fail() after a command: its output says why, the failure box only names the step. */ protected function failWithReason(InstallCommand $command, string $step): int { $command->warnFailed($step); return $this->fail($step); } /** Record which step failed, then return FAILURE for boot() to propagate. */ protected function fail(string $step): int { $this->failedStep = $step; return InstallCommand::FAILURE; } /** * Resolved answers a resume run must carry, including ones that came from prompts * rather than options. * * @return array */ protected function resumeOptions(): array { return ['--driver' => $this->name()]; } /** @return string[] A `cd` step when the target app lives outside the current directory, empty otherwise. */ protected function cdStep(InstallCommand $command): array { $target = $this->normalizePath($command->targetPath()); $cwd = $this->normalizePath(getcwd()); if ($target === $cwd) { return []; } // Relative under the current directory, and quoted only where the shell would split it. $path = str_starts_with($target, $cwd.'/') ? substr($target, strlen($cwd) + 1) : $target; return ['cd '.(preg_match('#^[\w./-]+$#', $path) === 1 ? $path : ProcessUtils::escapeArgument($path))]; } private function normalizePath(string $path): string { $real = realpath($path); return rtrim($real !== false ? $real : $path, '/'); } /** @return string[] The demo password, once, when demo content was loaded. */ protected function demoStep(InstallCommand $command): array { $password = ($command->optionOrNull('demo') || $command->optionOrNull('template')) ? $this->readEnvValue($command, 'DEMO_PASSWORD') : null; // No demo accounts: with auth, the owner's own account has to become the admin. if ($password === null) { return is_dir($command->path('modules/auth')) ? ['Sign up, then make your account the admin: `'.$this->printedArtisan().' auth:make-admin you@example.com`'] : []; } // The state that was seeded: a template's demo is its `default`, a module demo the // `showcase`. Its seeders declare their accounts (#[DemoAccount]); the featured // ones are where to start. $state = $command->optionOrNull('state') ?: ($command->optionOrNull('demo') ? ($command->optionOrNull('template') ? 'default' : 'showcase') : null); $featured = $state === null ? [] : array_values(array_filter( json_decode((string) $this->artisanOutput($command, ['modules:demo-accounts', "--state={$state}", '--json']), true) ?: [], fn (array $account): bool => (bool) ($account['featured'] ?? false), )); if ($featured === []) { return ["Demo accounts use the password `{$password}`, saved in .env as DEMO_PASSWORD"]; } $accounts = implode(' or ', array_map(fn (array $account): string => "`{$account['email']}` ({$account['description']})", $featured)); return ["Sign in as {$accounts} with the password `{$password}`, saved in .env as DEMO_PASSWORD. Every demo account: `{$this->printedArtisan()} modules:demo-accounts --state={$state}`"]; } /** How the user runs artisan in the new app, for the commands printed at the end. */ protected function printedArtisan(): string { return 'php artisan'; } /** Hook: perform driver-specific steps before the module prompt. Return an exit code to abort, null to continue. */ protected function beforePrompts(InstallCommand $command): ?int { return null; } abstract protected function boot(InstallCommand $command): int; /** @return string[] Fully-qualified package names to install (e.g. ['saucebase/auth', 'saucebase/billing']). */ protected function resolveModules(InstallCommand $command): array { if ($command->option('all-modules')) { return $command->fetchAvailableModules(); } if ($raw = $command->option('modules')) { if ($raw === 'none') { return []; } return array_values(array_filter(array_map(function (string $name): string { $name = strtolower(trim($name)); if ($name === '' || str_contains($name, '/')) { return $name; } return "saucebase/{$name}"; }, explode(',', $raw)))); } return $command->getSelectedModules(); } /** @return string[] */ abstract protected function nextSteps(InstallCommand $command): array; protected function readEnvValue(InstallCommand $command, string $key): ?string { $env = @file_get_contents($command->path('.env')); if ($env === false) { return null; } if (preg_match('/^'.preg_quote($key, '/').'=(.+)$/m', $env, $m)) { return trim($m[1], "\"'"); } return null; } public function hasCommand(string $name): bool { return $this->commandExists($name); } protected function commandExists(string $name): bool { return trim(Process::run(['which', $name])->output()) !== ''; } }