|null */ private ?Collection $discovered = null; /** @var Collection|null */ private ?Collection $enabled = null; /** @var array in-memory discovery errors keyed by directory name */ private array $discoveryErrors = []; /** @var array */ private array $settings = []; /** @var array Provider failures in this application instance, retained across discovery refreshes. */ private array $failedProviders = []; public function __construct( private readonly ExtensionManifestValidator $validator, private readonly ExtensionAssetPublisher $assets, private readonly Dispatcher $events, private readonly ExtensionSettingsRegistry $settingsRegistry, private readonly ExtensionCompatibility $compatibility, ) {} public function directory(): string { return mb_rtrim(config()->string('extensions.directory'), '/\\'); } /** * @return Collection */ public function discovered(): Collection { if ($this->discovered instanceof Collection) { return $this->discovered; } $manifests = []; foreach (glob($this->directory().'/*/'.ExtensionManifest::FILENAME) ?: [] as $file) { $directory = dirname($file); try { $manifest = $this->validator->fromDirectory($directory); if ($manifest->id !== basename($directory)) { throw new InvalidExtensionException(sprintf('Extension directory "%s" must match its manifest id "%s".', basename($directory), $manifest->id)); } $manifests[$manifest->id] = $manifest; } catch (InvalidExtensionException $exception) { $this->discoveryErrors[basename($directory)] = $exception->getMessage(); Log::warning('[extensions] Skipping extension', ['directory' => $directory, 'exception' => $exception]); } } return $this->discovered = collect($manifests); } /** * @return array */ public function discoveryErrors(): array { return $this->discoveryErrors; } public function flushDiscovery(): void { $this->discovered = null; $this->enabled = null; $this->discoveryErrors = []; } /** * @return Collection */ public function records(): Collection { return rescue(function (): Collection { if (! Schema::hasTable('extensions')) { return $this->recordCollection([]); } $records = []; foreach (Extension::query()->get() as $extension) { $records[$extension->identifier] = $extension; } return $this->recordCollection($records); }, fn (): Collection => $this->recordCollection([])); } /** * @return Collection */ public function enabled(): Collection { if ($this->enabled instanceof Collection) { return $this->enabled; } $configured = $this->configuredEnabled()->reject(fn (ExtensionManifest $manifest): bool => isset($this->failedProviders[$manifest->id])); $result = $this->compatibility->resolve($configured); foreach ($result['errors'] as $identifier => $reason) { $this->recordFailure($identifier, $reason, phase: 'compatibility'); } return $this->enabled = $result['manifests']; } /** Whether an extension's runtime registrations may run right now. */ public function isAvailable(string $identifier): bool { return config('extensions.enabled') && $this->enabled()->has($identifier); } /** @return Collection */ public function configuredEnabled(): Collection { $discovered = $this->discovered(); if ($discovered->isEmpty()) { return $discovered; } $records = $this->records(); return $discovered->filter(function (ExtensionManifest $manifest) use ($records): bool { $record = $records->get($manifest->id); return $record !== null && $record->enabled; }); } /** * The enabled frontend extensions for the SPA to load. Signed-in users receive * each extension's frontend settings; everyone else only those marked ->public(). * * Guests only need what renders on the sign-in pages: the bundle, its styles and * translations, and public settings. Versions, screens and component claims are * left out so the login page does not describe the panel's extensions, and the * SPA skips screen and component registrations for an entry that has none. * * @return array, components?: list, development: array{url: string, version: string}|null}> */ public function frontendPayload(bool $authenticated): array { $enabled = $this->enabled()->filter(fn (ExtensionManifest $manifest): bool => $manifest->hasUi()); $configured = $authenticated ? $enabled : $enabled->filter(fn (ExtensionManifest $manifest): bool => ($this->settingsRegistry->get($manifest->id)?->publicConfigKeys() ?? []) !== []); if ($configured->isNotEmpty()) { rescue(fn () => ExtensionSettings::preload(array_values($configured->map(fn (ExtensionManifest $manifest): ExtensionSettings => $this->settings($manifest->id))->all())), report: false); } return $enabled->map(function (ExtensionManifest $manifest) use ($authenticated): array { $entry = [ 'id' => $manifest->id, 'entry' => $this->assets->entryUrl($manifest), 'prefix' => $manifest->uiPrefix, 'translations' => $this->translationsRevision($manifest), 'config' => (object) $this->frontendConfig($manifest->id, ! $authenticated), 'development' => $this->assets->developmentPayload($manifest->id), ]; if ($authenticated) { $entry['version'] = $manifest->version; $entry['screens'] = $manifest->screens; $entry['components'] = $manifest->components; } return $entry; }) ->values() ->all(); } public function recordFailure(string $identifier, string $reason, ?Throwable $exception = null, string $phase = 'runtime'): void { if (in_array($phase, ['register', 'boot'], true)) { $this->failedProviders[$identifier] = true; $this->enabled = null; } // A failure that repeats on every request (reading field values, for one) is written once. rescue(fn (): int => Extension::query() ->where('identifier', $identifier) ->where(fn (Builder $query): Builder => $query->whereNull('error')->orWhere('error', '<>', $reason)) ->update(['error' => $reason, 'error_phase' => $phase, 'errored_at' => now()]), report: false); $context = array_filter(['exception' => $exception]); $exception instanceof Throwable ? Log::error("[extensions] Failed to load \"{$identifier}\": {$reason}", $context) : Log::warning("[extensions] Skipping \"{$identifier}\": {$reason}", $context); rescue(fn () => $this->events->dispatch(new ExtensionLoadFailed($identifier, $phase, $reason, $exception))); } /** * Clears the load failures of extensions that have just loaded cleanly. Failures * at runtime are kept, so they are still there for an administrator to read. * * @param list $identifiers */ public function clearErrors(array $identifiers): void { if ($identifiers === []) { return; } foreach ($identifiers as $identifier) { if (! isset($this->failedProviders[$identifier])) { continue; } unset($this->failedProviders[$identifier]); $this->enabled = null; } // Runs on every boot, so it only writes when there is a load failure to clear. rescue(function () use ($identifiers): void { $loadFailures = Extension::query() ->whereIn('identifier', $identifiers) ->whereNotNull('error') ->where(fn (Builder $query): Builder => $query->whereNull('error_phase')->orWhereIn('error_phase', Extension::LOAD_PHASES)); if ($loadFailures->exists()) { $loadFailures->update(Extension::NO_ERROR); } }, report: false); } public function settings(string $identifier): ExtensionSettings { // One instance per extension per request so the per-instance row cache // in ExtensionSettings actually coalesces reads. return $this->settings[$identifier] ??= new ExtensionSettings($identifier); } /** * Changes whenever the extension's translation files do. The frontend puts it in the * URL it loads those translations from, which lets the browser cache them for as long * as core translations and still pick up an installed or upgraded extension at once. */ private function translationsRevision(ExtensionManifest $manifest): ?string { $directory = $manifest->path('resources', 'lang'); if (! is_dir($directory)) { return null; } $files = array_map( fn (SplFileInfo $file): string => implode("\0", [$file->getRelativePathname(), $file->getSize(), $file->getMTime()]), File::allFiles($directory), ); sort($files); return hash('xxh128', $manifest->version."\0".implode("\0", $files)); } /** * @param array $records * @return Collection */ private function recordCollection(array $records): Collection { return collect($records); } /** * The ->frontend()-marked settings for one extension, exposed to its bundle * as ctx.config; with $publicOnly just the ->public() ones, for guests. * Never allowed to break page rendering. * * @return array */ private function frontendConfig(string $identifier, bool $publicOnly): array { return rescue(fn (): array => $this->settingsRegistry->get($identifier)?->frontendConfig($publicOnly) ?? [], []); } }