mirror of
https://github.com/usetrmnl/byos_laravel.git
synced 2026-01-13 15:07:49 +00:00
Compare commits
11 commits
41baff51a6
...
7489d85592
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7489d85592 | ||
|
|
22a24383b2 | ||
|
|
468e8a130d | ||
|
|
346f04a7af | ||
|
|
31a73ccc6e | ||
|
|
042654993a | ||
|
|
6c438ff4d4 | ||
|
|
b7ce0b6152 | ||
|
|
cdf477e2ed | ||
|
|
e63953dc13 | ||
|
|
a8f3232ccc |
14 changed files with 1005 additions and 91 deletions
|
|
@ -12,9 +12,14 @@ ENV APP_VERSION=${APP_VERSION}
|
|||
|
||||
ENV AUTORUN_ENABLED="true"
|
||||
|
||||
# Mark trmnl-liquid-cli as installed
|
||||
ENV TRMNL_LIQUID_ENABLED=1
|
||||
|
||||
# Switch to the root user so we can do root things
|
||||
USER root
|
||||
|
||||
COPY --chown=www-data:www-data --from=bnussbau/trmnl-liquid-cli:0.1.0 /usr/local/bin/trmnl-liquid-cli /usr/local/bin/
|
||||
|
||||
# Set the working directory
|
||||
WORKDIR /var/www/html
|
||||
|
||||
|
|
@ -48,6 +53,5 @@ FROM base AS production
|
|||
# Copy the assets from the assets image
|
||||
COPY --chown=www-data:www-data --from=assets /app/public/build /var/www/html/public/build
|
||||
COPY --chown=www-data:www-data --from=assets /app/node_modules /var/www/html/node_modules
|
||||
|
||||
# Drop back to the www-data user
|
||||
USER www-data
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ use App\Liquid\Filters\StandardFilters;
|
|||
use App\Liquid\Filters\StringMarkup;
|
||||
use App\Liquid\Filters\Uniqueness;
|
||||
use App\Liquid\Tags\TemplateTag;
|
||||
use App\Services\PluginImportService;
|
||||
use Exception;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
|
@ -19,6 +20,7 @@ use Illuminate\Support\Facades\App;
|
|||
use Illuminate\Support\Facades\Blade;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Str;
|
||||
use Keepsuit\LaravelLiquid\LaravelLiquidExtension;
|
||||
use Keepsuit\Liquid\Exceptions\LiquidException;
|
||||
|
|
@ -40,6 +42,7 @@ class Plugin extends Model
|
|||
'configuration_template' => 'json',
|
||||
'no_bleed' => 'boolean',
|
||||
'dark_mode' => 'boolean',
|
||||
'preferred_renderer' => 'string',
|
||||
];
|
||||
|
||||
protected static function boot()
|
||||
|
|
@ -127,9 +130,10 @@ class Plugin extends Model
|
|||
}
|
||||
}
|
||||
|
||||
// Split URLs by newline and filter out empty lines
|
||||
// Resolve Liquid variables in the entire polling_url field first, then split by newline
|
||||
$resolvedPollingUrls = $this->resolveLiquidVariables($this->polling_url);
|
||||
$urls = array_filter(
|
||||
array_map('trim', explode("\n", $this->polling_url)),
|
||||
array_map('trim', explode("\n", $resolvedPollingUrls)),
|
||||
fn ($url): bool => ! empty($url)
|
||||
);
|
||||
|
||||
|
|
@ -144,8 +148,8 @@ class Plugin extends Model
|
|||
$httpRequest = $httpRequest->withBody($resolvedBody);
|
||||
}
|
||||
|
||||
// Resolve Liquid variables in the polling URL
|
||||
$resolvedUrl = $this->resolveLiquidVariables($url);
|
||||
// URL is already resolved, use it directly
|
||||
$resolvedUrl = $url;
|
||||
|
||||
try {
|
||||
// Make the request based on the verb
|
||||
|
|
@ -180,8 +184,8 @@ class Plugin extends Model
|
|||
$httpRequest = $httpRequest->withBody($resolvedBody);
|
||||
}
|
||||
|
||||
// Resolve Liquid variables in the polling URL
|
||||
$resolvedUrl = $this->resolveLiquidVariables($url);
|
||||
// URL is already resolved, use it directly
|
||||
$resolvedUrl = $url;
|
||||
|
||||
try {
|
||||
// Make the request based on the verb
|
||||
|
|
@ -238,7 +242,7 @@ class Plugin extends Model
|
|||
try {
|
||||
// Attempt to parse it into JSON
|
||||
$json = $httpResponse->json();
|
||||
if($json !== null) {
|
||||
if ($json !== null) {
|
||||
return $json;
|
||||
}
|
||||
|
||||
|
|
@ -341,19 +345,48 @@ class Plugin extends Model
|
|||
return $template;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a template contains a Liquid for loop pattern
|
||||
*
|
||||
* @param string $template The template string to check
|
||||
* @return bool True if the template contains a for loop pattern
|
||||
*/
|
||||
private function containsLiquidForLoop(string $template): bool
|
||||
{
|
||||
return preg_match('/{%-?\s*for\s+/i', $template) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve Liquid variables in a template string using the Liquid template engine
|
||||
*
|
||||
* Uses the external trmnl-liquid renderer when:
|
||||
* - preferred_renderer is 'trmnl-liquid'
|
||||
* - External renderer is enabled in config
|
||||
* - Template contains a Liquid for loop pattern
|
||||
*
|
||||
* Otherwise uses the internal PHP-based Liquid renderer.
|
||||
*
|
||||
* @param string $template The template string containing Liquid variables
|
||||
* @return string The resolved template with variables replaced with their values
|
||||
*
|
||||
* @throws LiquidException
|
||||
* @throws Exception
|
||||
*/
|
||||
public function resolveLiquidVariables(string $template): string
|
||||
{
|
||||
// Get configuration variables - make them available at root level
|
||||
$variables = $this->configuration ?? [];
|
||||
|
||||
// Check if external renderer should be used
|
||||
$useExternalRenderer = $this->preferred_renderer === 'trmnl-liquid'
|
||||
&& config('services.trmnl.liquid_enabled')
|
||||
&& $this->containsLiquidForLoop($template);
|
||||
|
||||
if ($useExternalRenderer) {
|
||||
// Use external Ruby liquid renderer
|
||||
return $this->renderWithExternalLiquidRenderer($template, $variables);
|
||||
}
|
||||
|
||||
// Use the Liquid template engine to resolve variables
|
||||
$environment = App::make('liquid.environment');
|
||||
$environment->filterRegistry->register(StandardFilters::class);
|
||||
|
|
@ -363,6 +396,53 @@ class Plugin extends Model
|
|||
return $liquidTemplate->render($context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render template using external Ruby liquid renderer
|
||||
*
|
||||
* @param string $template The liquid template string
|
||||
* @param array $context The render context data
|
||||
* @return string The rendered HTML
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
private function renderWithExternalLiquidRenderer(string $template, array $context): string
|
||||
{
|
||||
$liquidPath = config('services.trmnl.liquid_path');
|
||||
|
||||
if (empty($liquidPath)) {
|
||||
throw new Exception('External liquid renderer path is not configured');
|
||||
}
|
||||
|
||||
// HTML encode the template
|
||||
$encodedTemplate = htmlspecialchars($template, ENT_QUOTES, 'UTF-8');
|
||||
|
||||
// Encode context as JSON
|
||||
$jsonContext = json_encode($context, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
if ($jsonContext === false) {
|
||||
throw new Exception('Failed to encode render context as JSON: '.json_last_error_msg());
|
||||
}
|
||||
|
||||
// Validate argument sizes
|
||||
app(PluginImportService::class)->validateExternalRendererArguments($encodedTemplate, $jsonContext, $liquidPath);
|
||||
|
||||
// Execute the external renderer
|
||||
$process = Process::run([
|
||||
$liquidPath,
|
||||
'--template',
|
||||
$encodedTemplate,
|
||||
'--context',
|
||||
$jsonContext,
|
||||
]);
|
||||
|
||||
if (! $process->successful()) {
|
||||
$errorOutput = $process->errorOutput() ?: $process->output();
|
||||
throw new Exception('External liquid renderer failed: '.$errorOutput);
|
||||
}
|
||||
|
||||
return $process->output();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the plugin's markup
|
||||
*
|
||||
|
|
@ -374,59 +454,67 @@ class Plugin extends Model
|
|||
$renderedContent = '';
|
||||
|
||||
if ($this->markup_language === 'liquid') {
|
||||
// Create a custom environment with inline templates support
|
||||
$inlineFileSystem = new InlineTemplatesFileSystem();
|
||||
$environment = new \Keepsuit\Liquid\Environment(
|
||||
fileSystem: $inlineFileSystem,
|
||||
extensions: [new StandardExtension(), new LaravelLiquidExtension()]
|
||||
);
|
||||
|
||||
// Register all custom filters
|
||||
$environment->filterRegistry->register(Data::class);
|
||||
$environment->filterRegistry->register(Date::class);
|
||||
$environment->filterRegistry->register(Localization::class);
|
||||
$environment->filterRegistry->register(Numbers::class);
|
||||
$environment->filterRegistry->register(StringMarkup::class);
|
||||
$environment->filterRegistry->register(Uniqueness::class);
|
||||
|
||||
// Register the template tag for inline templates
|
||||
$environment->tagRegistry->register(TemplateTag::class);
|
||||
|
||||
// Apply Liquid replacements (including 'with' syntax conversion)
|
||||
$processedMarkup = $this->applyLiquidReplacements($this->render_markup);
|
||||
|
||||
$template = $environment->parseString($processedMarkup);
|
||||
$context = $environment->newRenderContext(
|
||||
data: [
|
||||
'size' => $size,
|
||||
'data' => $this->data_payload,
|
||||
'config' => $this->configuration ?? [],
|
||||
...(is_array($this->data_payload) ? $this->data_payload : []),
|
||||
'trmnl' => [
|
||||
'system' => [
|
||||
'timestamp_utc' => now()->utc()->timestamp,
|
||||
],
|
||||
'user' => [
|
||||
'utc_offset' => '0',
|
||||
'name' => $this->user->name ?? 'Unknown User',
|
||||
'locale' => 'en',
|
||||
'time_zone_iana' => config('app.timezone'),
|
||||
],
|
||||
'plugin_settings' => [
|
||||
'instance_name' => $this->name,
|
||||
'strategy' => $this->data_strategy,
|
||||
'dark_mode' => $this->dark_mode ? 'yes' : 'no',
|
||||
'no_screen_padding' => $this->no_bleed ? 'yes' : 'no',
|
||||
'polling_headers' => $this->polling_header,
|
||||
'polling_url' => $this->polling_url,
|
||||
'custom_fields_values' => [
|
||||
...(is_array($this->configuration) ? $this->configuration : []),
|
||||
],
|
||||
// Build render context
|
||||
$context = [
|
||||
'size' => $size,
|
||||
'data' => $this->data_payload,
|
||||
'config' => $this->configuration ?? [],
|
||||
...(is_array($this->data_payload) ? $this->data_payload : []),
|
||||
'trmnl' => [
|
||||
'system' => [
|
||||
'timestamp_utc' => now()->utc()->timestamp,
|
||||
],
|
||||
'user' => [
|
||||
'utc_offset' => '0',
|
||||
'name' => $this->user->name ?? 'Unknown User',
|
||||
'locale' => 'en',
|
||||
'time_zone_iana' => config('app.timezone'),
|
||||
],
|
||||
'plugin_settings' => [
|
||||
'instance_name' => $this->name,
|
||||
'strategy' => $this->data_strategy,
|
||||
'dark_mode' => $this->dark_mode ? 'yes' : 'no',
|
||||
'no_screen_padding' => $this->no_bleed ? 'yes' : 'no',
|
||||
'polling_headers' => $this->polling_header,
|
||||
'polling_url' => $this->polling_url,
|
||||
'custom_fields_values' => [
|
||||
...(is_array($this->configuration) ? $this->configuration : []),
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$renderedContent = $template->render($context);
|
||||
],
|
||||
];
|
||||
|
||||
// Check if external renderer should be used
|
||||
if ($this->preferred_renderer === 'trmnl-liquid' && config('services.trmnl.liquid_enabled')) {
|
||||
// Use external Ruby renderer - pass raw template without preprocessing
|
||||
$renderedContent = $this->renderWithExternalLiquidRenderer($this->render_markup, $context);
|
||||
} else {
|
||||
// Use PHP keepsuit/liquid renderer
|
||||
// Create a custom environment with inline templates support
|
||||
$inlineFileSystem = new InlineTemplatesFileSystem();
|
||||
$environment = new \Keepsuit\Liquid\Environment(
|
||||
fileSystem: $inlineFileSystem,
|
||||
extensions: [new StandardExtension(), new LaravelLiquidExtension()]
|
||||
);
|
||||
|
||||
// Register all custom filters
|
||||
$environment->filterRegistry->register(Data::class);
|
||||
$environment->filterRegistry->register(Date::class);
|
||||
$environment->filterRegistry->register(Localization::class);
|
||||
$environment->filterRegistry->register(Numbers::class);
|
||||
$environment->filterRegistry->register(StringMarkup::class);
|
||||
$environment->filterRegistry->register(Uniqueness::class);
|
||||
|
||||
// Register the template tag for inline templates
|
||||
$environment->tagRegistry->register(TemplateTag::class);
|
||||
|
||||
// Apply Liquid replacements (including 'with' syntax conversion)
|
||||
$processedMarkup = $this->applyLiquidReplacements($this->render_markup);
|
||||
|
||||
$template = $environment->parseString($processedMarkup);
|
||||
$liquidContext = $environment->newRenderContext(data: $context);
|
||||
$renderedContent = $template->render($liquidContext);
|
||||
}
|
||||
} else {
|
||||
$renderedContent = Blade::render($this->render_markup, [
|
||||
'size' => $size,
|
||||
|
|
|
|||
|
|
@ -139,11 +139,13 @@ class PluginImportService
|
|||
* @param string $zipUrl The URL to the ZIP file
|
||||
* @param User $user The user importing the plugin
|
||||
* @param string|null $zipEntryPath Optional path to specific plugin in monorepo
|
||||
* @param string|null $preferredRenderer Optional preferred renderer (e.g., 'trmnl-liquid')
|
||||
* @param string|null $iconUrl Optional icon URL to set on the plugin
|
||||
* @return Plugin The created plugin instance
|
||||
*
|
||||
* @throws Exception If the ZIP file is invalid or required files are missing
|
||||
*/
|
||||
public function importFromUrl(string $zipUrl, User $user, ?string $zipEntryPath = null): Plugin
|
||||
public function importFromUrl(string $zipUrl, User $user, ?string $zipEntryPath = null, $preferredRenderer = null, ?string $iconUrl = null): Plugin
|
||||
{
|
||||
// Download the ZIP file
|
||||
$response = Http::timeout(60)->get($zipUrl);
|
||||
|
|
@ -232,6 +234,8 @@ class PluginImportService
|
|||
'render_markup' => $fullLiquid,
|
||||
'configuration_template' => $configurationTemplate,
|
||||
'data_payload' => json_decode($settings['static_data'] ?? '{}', true),
|
||||
'preferred_renderer' => $preferredRenderer,
|
||||
'icon_url' => $iconUrl,
|
||||
]);
|
||||
|
||||
if (! $plugin_updated) {
|
||||
|
|
@ -380,4 +384,58 @@ class PluginImportService
|
|||
'sharedLiquidPath' => $sharedLiquidPath,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that template and context are within command-line argument limits
|
||||
*
|
||||
* @param string $template The liquid template string
|
||||
* @param string $jsonContext The JSON-encoded context
|
||||
* @param string $liquidPath The path to the liquid renderer executable
|
||||
*
|
||||
* @throws Exception If the template or context exceeds argument limits
|
||||
*/
|
||||
public function validateExternalRendererArguments(string $template, string $jsonContext, string $liquidPath): void
|
||||
{
|
||||
// MAX_ARG_STRLEN on Linux is typically 131072 (128KB) for individual arguments
|
||||
// ARG_MAX is the total size of all arguments (typically 2MB on modern systems)
|
||||
$maxIndividualArgLength = 131072; // 128KB - MAX_ARG_STRLEN limit
|
||||
$maxTotalArgLength = $this->getMaxArgumentLength();
|
||||
|
||||
// Check individual argument sizes (template and context are the largest)
|
||||
if (mb_strlen($template) > $maxIndividualArgLength || mb_strlen($jsonContext) > $maxIndividualArgLength) {
|
||||
throw new Exception('Context too large for external liquid renderer. Reduce the size of the Payload or Template.');
|
||||
}
|
||||
|
||||
// Calculate total size of all arguments (path + flags + template + context)
|
||||
// Add overhead for path, flags, and separators (conservative estimate: ~200 bytes)
|
||||
$totalArgSize = mb_strlen($liquidPath) + mb_strlen('--template') + mb_strlen($template)
|
||||
+ mb_strlen('--context') + mb_strlen($jsonContext) + 200;
|
||||
|
||||
if ($totalArgSize > $maxTotalArgLength) {
|
||||
throw new Exception('Context too large for external liquid renderer. Reduce the size of the Payload or Template.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum argument length for command-line arguments
|
||||
*
|
||||
* @return int Maximum argument length in bytes
|
||||
*/
|
||||
private function getMaxArgumentLength(): int
|
||||
{
|
||||
// Try to get ARG_MAX from system using getconf
|
||||
$argMax = null;
|
||||
if (function_exists('shell_exec')) {
|
||||
$result = @shell_exec('getconf ARG_MAX 2>/dev/null');
|
||||
if ($result !== null && is_numeric(mb_trim($result))) {
|
||||
$argMax = (int) mb_trim($result);
|
||||
}
|
||||
}
|
||||
|
||||
// Use conservative fallback if ARG_MAX cannot be determined
|
||||
// ARG_MAX on macOS is typically 262144 (256KB), on Linux it's usually 2097152 (2MB)
|
||||
// We use 200KB as a conservative limit that works on both systems
|
||||
// Note: ARG_MAX includes environment variables, so we leave headroom
|
||||
return $argMax !== null ? min($argMax, 204800) : 204800;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -130,7 +130,7 @@ return [
|
|||
'force_https' => env('FORCE_HTTPS', false),
|
||||
'puppeteer_docker' => env('PUPPETEER_DOCKER', false),
|
||||
'puppeteer_mode' => env('PUPPETEER_MODE', 'local'),
|
||||
'puppeteer_wait_for_network_idle' => env('PUPPETEER_WAIT_FOR_NETWORK_IDLE', false),
|
||||
'puppeteer_wait_for_network_idle' => env('PUPPETEER_WAIT_FOR_NETWORK_IDLE', true),
|
||||
'puppeteer_window_size_strategy' => env('PUPPETEER_WINDOW_SIZE_STRATEGY', null),
|
||||
|
||||
'notifications' => [
|
||||
|
|
|
|||
|
|
@ -41,6 +41,8 @@ return [
|
|||
'proxy_refresh_cron' => env('TRMNL_PROXY_REFRESH_CRON'),
|
||||
'override_orig_icon' => env('TRMNL_OVERRIDE_ORIG_ICON', false),
|
||||
'image_url_timeout' => env('TRMNL_IMAGE_URL_TIMEOUT', 30), // 30 seconds; increase on low-powered devices
|
||||
'liquid_enabled' => env('TRMNL_LIQUID_ENABLED', false),
|
||||
'liquid_path' => env('TRMNL_LIQUID_PATH', '/usr/local/bin/trmnl-liquid-cli'),
|
||||
],
|
||||
|
||||
'webhook' => [
|
||||
|
|
|
|||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('plugins', function (Blueprint $table) {
|
||||
$table->string('preferred_renderer')->nullable()->after('markup_language');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('plugins', function (Blueprint $table) {
|
||||
$table->dropColumn('preferred_renderer');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
<?php
|
||||
|
||||
use App\Services\PluginImportService;
|
||||
use Livewire\Attributes\Lazy;
|
||||
use Livewire\Volt\Component;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
|
@ -8,7 +9,9 @@ use Illuminate\Support\Facades\Http;
|
|||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
new class extends Component {
|
||||
new
|
||||
#[Lazy]
|
||||
class extends Component {
|
||||
public array $catalogPlugins = [];
|
||||
public string $installingPlugin = '';
|
||||
|
||||
|
|
@ -17,13 +20,27 @@ new class extends Component {
|
|||
$this->loadCatalogPlugins();
|
||||
}
|
||||
|
||||
public function placeholder()
|
||||
{
|
||||
return <<<'HTML'
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center justify-center py-12">
|
||||
<div class="flex items-center space-x-2">
|
||||
<flux:icon.loading />
|
||||
<flux:text>Loading recipes...</flux:text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
HTML;
|
||||
}
|
||||
|
||||
private function loadCatalogPlugins(): void
|
||||
{
|
||||
$catalogUrl = config('app.catalog_url');
|
||||
|
||||
$this->catalogPlugins = Cache::remember('catalog_plugins', 43200, function () use ($catalogUrl) {
|
||||
try {
|
||||
$response = Http::get($catalogUrl);
|
||||
$response = Http::timeout(10)->get($catalogUrl);
|
||||
$catalogContent = $response->body();
|
||||
$catalog = Yaml::parse($catalogContent);
|
||||
|
||||
|
|
@ -83,7 +100,13 @@ new class extends Component {
|
|||
$this->installingPlugin = $pluginId;
|
||||
|
||||
try {
|
||||
$importedPlugin = $pluginImportService->importFromUrl($plugin['zip_url'], auth()->user(), $plugin['zip_entry_path'] ?? null);
|
||||
$importedPlugin = $pluginImportService->importFromUrl(
|
||||
$plugin['zip_url'],
|
||||
auth()->user(),
|
||||
$plugin['zip_entry_path'] ?? null,
|
||||
null,
|
||||
$plugin['logo_url'] ?? null
|
||||
);
|
||||
|
||||
$this->dispatch('plugin-installed');
|
||||
Flux::modal('import-from-catalog')->close();
|
||||
|
|
@ -113,7 +136,7 @@ new class extends Component {
|
|||
<div class="bg-white dark:bg-white/10 border border-zinc-200 dark:border-white/10 [:where(&)]:p-6 [:where(&)]:rounded-xl space-y-6">
|
||||
<div class="flex items-start space-x-4">
|
||||
@if($plugin['logo_url'])
|
||||
<img src="{{ $plugin['logo_url'] }}" alt="{{ $plugin['name'] }}" class="w-12 h-12 rounded-lg object-cover">
|
||||
<img src="{{ $plugin['logo_url'] }}" loading="lazy" alt="{{ $plugin['name'] }}" class="w-12 h-12 rounded-lg object-cover">
|
||||
@else
|
||||
<div class="w-12 h-12 bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-center">
|
||||
<flux:icon name="puzzle-piece" class="w-6 h-6 text-gray-400" />
|
||||
|
|
|
|||
236
resources/views/livewire/catalog/trmnl.blade.php
Normal file
236
resources/views/livewire/catalog/trmnl.blade.php
Normal file
|
|
@ -0,0 +1,236 @@
|
|||
<?php
|
||||
|
||||
use Livewire\Attributes\Lazy;
|
||||
use Livewire\Volt\Component;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use App\Services\PluginImportService;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
new
|
||||
#[Lazy]
|
||||
class extends Component {
|
||||
public array $recipes = [];
|
||||
public string $search = '';
|
||||
public bool $isSearching = false;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->loadNewest();
|
||||
}
|
||||
|
||||
public function placeholder()
|
||||
{
|
||||
return <<<'HTML'
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center justify-center py-12">
|
||||
<div class="flex items-center space-x-2">
|
||||
<flux:icon.loading />
|
||||
<flux:text>Loading recipes...</flux:text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
HTML;
|
||||
}
|
||||
|
||||
private function loadNewest(): void
|
||||
{
|
||||
try {
|
||||
$this->recipes = Cache::remember('trmnl_recipes_newest', 43200, function () {
|
||||
$response = Http::timeout(10)->get('https://usetrmnl.com/recipes.json', [
|
||||
'sort-by' => 'newest',
|
||||
]);
|
||||
|
||||
if (!$response->successful()) {
|
||||
throw new \RuntimeException('Failed to fetch TRMNL recipes');
|
||||
}
|
||||
|
||||
$json = $response->json();
|
||||
$data = $json['data'] ?? [];
|
||||
return $this->mapRecipes($data);
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('TRMNL catalog load error: ' . $e->getMessage());
|
||||
$this->recipes = [];
|
||||
}
|
||||
}
|
||||
|
||||
private function searchRecipes(string $term): void
|
||||
{
|
||||
$this->isSearching = true;
|
||||
try {
|
||||
$cacheKey = 'trmnl_recipes_search_' . md5($term);
|
||||
$this->recipes = Cache::remember($cacheKey, 300, function () use ($term) {
|
||||
$response = Http::get('https://usetrmnl.com/recipes.json', [
|
||||
'search' => $term,
|
||||
'sort-by' => 'newest',
|
||||
]);
|
||||
|
||||
if (!$response->successful()) {
|
||||
throw new \RuntimeException('Failed to search TRMNL recipes');
|
||||
}
|
||||
|
||||
$json = $response->json();
|
||||
$data = $json['data'] ?? [];
|
||||
return $this->mapRecipes($data);
|
||||
});
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('TRMNL catalog search error: ' . $e->getMessage());
|
||||
$this->recipes = [];
|
||||
} finally {
|
||||
$this->isSearching = false;
|
||||
}
|
||||
}
|
||||
|
||||
public function updatedSearch(): void
|
||||
{
|
||||
$term = trim($this->search);
|
||||
if ($term === '') {
|
||||
$this->loadNewest();
|
||||
return;
|
||||
}
|
||||
|
||||
if (strlen($term) < 2) {
|
||||
// Require at least 2 chars to avoid noisy calls
|
||||
return;
|
||||
}
|
||||
|
||||
$this->searchRecipes($term);
|
||||
}
|
||||
|
||||
public function installPlugin(string $recipeId, PluginImportService $pluginImportService): void
|
||||
{
|
||||
abort_unless(auth()->user() !== null, 403);
|
||||
|
||||
try {
|
||||
$zipUrl = "https://usetrmnl.com/api/plugin_settings/{$recipeId}/archive";
|
||||
|
||||
$recipe = collect($this->recipes)->firstWhere('id', $recipeId);
|
||||
|
||||
$plugin = $pluginImportService->importFromUrl(
|
||||
$zipUrl,
|
||||
auth()->user(),
|
||||
null,
|
||||
config('services.trmnl.liquid_enabled') ? 'trmnl-liquid' : null,
|
||||
$recipe['icon_url'] ?? null
|
||||
);
|
||||
|
||||
$this->dispatch('plugin-installed');
|
||||
Flux::modal('import-from-trmnl-catalog')->close();
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Plugin installation failed: ' . $e->getMessage());
|
||||
$this->addError('installation', 'Error installing plugin: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, array<string, mixed>> $items
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
private function mapRecipes(array $items): array
|
||||
{
|
||||
return collect($items)
|
||||
->map(function (array $item) {
|
||||
return [
|
||||
'id' => $item['id'] ?? null,
|
||||
'name' => $item['name'] ?? 'Untitled',
|
||||
'icon_url' => $item['icon_url'] ?? null,
|
||||
'screenshot_url' => $item['screenshot_url'] ?? null,
|
||||
'author_bio' => is_array($item['author_bio'] ?? null)
|
||||
? strip_tags($item['author_bio']['description'] ?? null)
|
||||
: null,
|
||||
'stats' => [
|
||||
'installs' => data_get($item, 'stats.installs'),
|
||||
'forks' => data_get($item, 'stats.forks'),
|
||||
],
|
||||
'detail_url' => isset($item['id']) ? ('https://usetrmnl.com/recipes/' . $item['id']) : null,
|
||||
];
|
||||
})
|
||||
->toArray();
|
||||
}
|
||||
}; ?>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex-1">
|
||||
<flux:input
|
||||
wire:model.live.debounce.400ms="search"
|
||||
placeholder="Search TRMNL recipes (min 2 chars)..."
|
||||
icon="magnifying-glass"
|
||||
/>
|
||||
</div>
|
||||
<flux:badge color="gray">Newest</flux:badge>
|
||||
</div>
|
||||
|
||||
@error('installation')
|
||||
<flux:callout variant="danger" icon="x-circle" heading="{{$message}}" />
|
||||
@enderror
|
||||
|
||||
@if(empty($recipes))
|
||||
<div class="text-center py-8">
|
||||
<flux:icon name="exclamation-triangle" class="mx-auto h-12 w-12 text-gray-400" />
|
||||
<flux:heading class="mt-2">No recipes found</flux:heading>
|
||||
<flux:subheading>Try a different search term</flux:subheading>
|
||||
</div>
|
||||
@else
|
||||
<div class="grid grid-cols-1 gap-4">
|
||||
@foreach($recipes as $recipe)
|
||||
<div class="bg-white dark:bg-white/10 border border-zinc-200 dark:border-white/10 [:where(&)]:p-6 [:where(&)]:rounded-xl space-y-6">
|
||||
<div class="flex items-start space-x-4">
|
||||
@php($thumb = $recipe['icon_url'] ?? $recipe['screenshot_url'])
|
||||
@if($thumb)
|
||||
<img src="{{ $thumb }}" loading="lazy" alt="{{ $recipe['name'] }}" class="w-12 h-12 rounded-lg object-cover">
|
||||
@else
|
||||
<div class="w-12 h-12 bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-center">
|
||||
<flux:icon name="puzzle-piece" class="w-6 h-6 text-gray-400" />
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="text-lg font-medium text-gray-900 dark:text-gray-100">{{ $recipe['name'] }}</h3>
|
||||
@if(data_get($recipe, 'stats.installs'))
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Installs: {{ data_get($recipe, 'stats.installs') }} · Forks: {{ data_get($recipe, 'stats.forks') }}</p>
|
||||
@endif
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
@if($recipe['detail_url'])
|
||||
<a href="{{ $recipe['detail_url'] }}" target="_blank" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
|
||||
<flux:icon name="arrow-top-right-on-square" class="w-5 h-5" />
|
||||
</a>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if($recipe['author_bio'])
|
||||
<p class="mt-2 text-sm text-gray-600 dark:text-gray-300">{{ $recipe['author_bio'] }}</p>
|
||||
@endif
|
||||
|
||||
<div class="mt-4 flex items-center space-x-3">
|
||||
@if($recipe['id'])
|
||||
<flux:button
|
||||
wire:click="installPlugin('{{ $recipe['id'] }}')"
|
||||
variant="primary">
|
||||
Install
|
||||
</flux:button>
|
||||
@endif
|
||||
|
||||
@if($recipe['detail_url'])
|
||||
<flux:button
|
||||
href="{{ $recipe['detail_url'] }}"
|
||||
target="_blank"
|
||||
variant="subtle">
|
||||
View on TRMNL
|
||||
</flux:button>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@endforeach
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
|
|
@ -156,6 +156,7 @@ new class extends Component {
|
|||
|
||||
<div class="py-12" x-data="{
|
||||
searchTerm: '',
|
||||
showFilters: false,
|
||||
filterPlugins(plugins) {
|
||||
if (this.searchTerm.length <= 1) return plugins;
|
||||
const search = this.searchTerm.toLowerCase();
|
||||
|
|
@ -165,28 +166,37 @@ new class extends Component {
|
|||
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
|
||||
<div class="flex justify-between items-center mb-6">
|
||||
<h2 class="text-2xl font-semibold dark:text-gray-100">Plugins & Recipes</h2>
|
||||
<div class="flex items-center space-x-2">
|
||||
<flux:button icon="funnel" variant="ghost" @click="showFilters = !showFilters"></flux:button>
|
||||
<flux:button.group>
|
||||
<flux:modal.trigger name="add-plugin">
|
||||
<flux:button icon="plus" variant="primary">Add Recipe</flux:button>
|
||||
</flux:modal.trigger>
|
||||
|
||||
<flux:button.group>
|
||||
<flux:modal.trigger name="add-plugin">
|
||||
<flux:button icon="plus" variant="primary">Add Recipe</flux:button>
|
||||
</flux:modal.trigger>
|
||||
|
||||
<flux:dropdown>
|
||||
<flux:button icon="chevron-down" variant="primary"></flux:button>
|
||||
<flux:menu>
|
||||
<flux:modal.trigger name="import-zip">
|
||||
<flux:menu.item icon="archive-box">Import Recipe Archive</flux:menu.item>
|
||||
</flux:modal.trigger>
|
||||
<flux:modal.trigger name="import-from-catalog">
|
||||
<flux:menu.item icon="book-open">Import from Catalog</flux:menu.item>
|
||||
</flux:modal.trigger>
|
||||
<flux:menu.item icon="beaker" wire:click="seedExamplePlugins">Seed Example Recipes</flux:menu.item>
|
||||
</flux:menu>
|
||||
</flux:dropdown>
|
||||
</flux:button.group>
|
||||
<flux:dropdown>
|
||||
<flux:button icon="chevron-down" variant="primary"></flux:button>
|
||||
<flux:menu>
|
||||
<flux:modal.trigger name="import-from-catalog">
|
||||
<flux:menu.item icon="book-open">Import from OSS Catalog</flux:menu.item>
|
||||
</flux:modal.trigger>
|
||||
@if(config('services.trmnl.liquid_enabled'))
|
||||
<flux:modal.trigger name="import-from-trmnl-catalog">
|
||||
<flux:menu.item icon="book-open">Import from TRMNL Catalog</flux:menu.item>
|
||||
</flux:modal.trigger>
|
||||
@endif
|
||||
<flux:separator />
|
||||
<flux:modal.trigger name="import-zip">
|
||||
<flux:menu.item icon="archive-box">Import Recipe Archive</flux:menu.item>
|
||||
</flux:modal.trigger>
|
||||
<flux:separator />
|
||||
<flux:menu.item icon="beaker" wire:click="seedExamplePlugins">Seed Example Recipes</flux:menu.item>
|
||||
</flux:menu>
|
||||
</flux:dropdown>
|
||||
</flux:button.group>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6 flex flex-col sm:flex-row gap-4">
|
||||
<div x-show="showFilters" class="mb-6 flex flex-col sm:flex-row gap-4" style="display: none;">
|
||||
<div class="flex-1">
|
||||
<flux:input
|
||||
x-model="searchTerm"
|
||||
|
|
@ -214,7 +224,7 @@ new class extends Component {
|
|||
<div class="space-y-6">
|
||||
<div>
|
||||
<flux:heading size="lg">Import Recipe
|
||||
<flux:badge color="yellow" class="ml-2">Alpha</flux:badge>
|
||||
<flux:badge color="blue" class="ml-2">Beta</flux:badge>
|
||||
</flux:heading>
|
||||
<flux:subheading>Upload a ZIP archive containing a TRMNL recipe — either exported from the cloud service or structured using the <a href="https://github.com/usetrmnl/trmnlp" target="_blank" class="underline">trmnlp</a> project structure.</flux:subheading>
|
||||
</div>
|
||||
|
|
@ -272,7 +282,7 @@ new class extends Component {
|
|||
<div class="space-y-6">
|
||||
<div>
|
||||
<flux:heading size="lg">Import from Catalog
|
||||
<flux:badge color="yellow" class="ml-2">Alpha</flux:badge>
|
||||
<flux:badge color="blue" class="ml-2">Beta</flux:badge>
|
||||
</flux:heading>
|
||||
<flux:subheading>Browse and install Recipes from the community. Add yours <a href="https://github.com/bnussbau/trmnl-recipe-catalog" class="underline" target="_blank">here</a>.</flux:subheading>
|
||||
</div>
|
||||
|
|
@ -280,6 +290,27 @@ new class extends Component {
|
|||
</div>
|
||||
</flux:modal>
|
||||
|
||||
<flux:modal name="import-from-trmnl-catalog">
|
||||
<div class="space-y-6">
|
||||
<div>
|
||||
<flux:heading size="lg">Import from TRMNL Recipe Catalog
|
||||
<flux:badge color="yellow" class="ml-2">Alpha</flux:badge>
|
||||
</flux:heading>
|
||||
<flux:callout class="mb-4 mt-4" color="yellow">
|
||||
<flux:heading size="sm">Limitations</flux:heading>
|
||||
<ul class="list-disc pl-5 mt-2">
|
||||
<li><flux:text>Only full view will be imported; shared markup will be prepended</flux:text></li>
|
||||
<li><flux:text>Requires <span class="font-mono">trmnl-liquid-cli</span> executable.</flux:text></li>
|
||||
<li><flux:text>API responses in formats other than <span class="font-mono">JSON</span> are not yet fully supported.</flux:text></li>
|
||||
<li><flux:text>There are limitations in payload size (Data Payload, Template).</flux:text></li>
|
||||
</ul>
|
||||
<flux:text class="mt-1">Please report issues, aside from the known limitations, on <a href="https://github.com/usetrmnl/byos_laravel/issues/new" target="_blank" class="underline">GitHub</a>. Include the recipe URL.</flux:text></li>
|
||||
</flux:callout>
|
||||
</div>
|
||||
<livewire:catalog.trmnl />
|
||||
</div>
|
||||
</flux:modal>
|
||||
|
||||
<flux:modal name="add-plugin" class="md:w-96">
|
||||
<div class="space-y-6">
|
||||
<div>
|
||||
|
|
@ -359,10 +390,14 @@ new class extends Component {
|
|||
x-show="searchTerm.length <= 1 || pluginName.includes(searchTerm.toLowerCase())"
|
||||
class="rounded-xl border bg-white dark:bg-stone-950 dark:border-stone-800 text-stone-800 shadow-xs">
|
||||
<a href="{{ ($plugin['detail_view_route']) ? route($plugin['detail_view_route']) : route('plugins.recipe', ['plugin' => $plugin['id']]) }}"
|
||||
class="block">
|
||||
<div class="flex items-center space-x-4 px-10 py-8">
|
||||
<flux:icon name="{{$plugin['flux_icon_name'] ?? 'puzzle-piece'}}"
|
||||
class="block h-full">
|
||||
<div class="flex items-center space-x-4 px-10 py-8 h-full">
|
||||
@isset($plugin['icon_url'])
|
||||
<img src="{{ $plugin['icon_url'] }}" class="h-6"/>
|
||||
@else
|
||||
<flux:icon name="{{$plugin['flux_icon_name'] ?? 'puzzle-piece'}}"
|
||||
class="text-4xl text-accent"/>
|
||||
@endif
|
||||
<h3 class="text-lg font-medium dark:text-zinc-200">{{$plugin['name']}}</h3>
|
||||
</div>
|
||||
</a>
|
||||
|
|
|
|||
|
|
@ -1082,7 +1082,7 @@ HTML;
|
|||
})"
|
||||
wire:ignore
|
||||
wire:key="cm-{{ $textareaId }}"
|
||||
class="max-w-2xl min-h-[300px] h-[500px] overflow-hidden resize-y"
|
||||
class="max-w-2xl min-h-[300px] h-[565px] overflow-hidden resize-y"
|
||||
>
|
||||
<!-- Loading state -->
|
||||
<div x-show="isLoading" class="flex items-center justify-center h-full">
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Livewire\Livewire;
|
||||
use Livewire\Volt\Volt;
|
||||
use Symfony\Component\Yaml\Yaml;
|
||||
|
||||
|
|
@ -16,6 +17,8 @@ it('can render catalog component', function (): void {
|
|||
config('app.catalog_url') => Http::response('', 200),
|
||||
]);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
$component = Volt::test('catalog.index');
|
||||
|
||||
$component->assertSee('No plugins available');
|
||||
|
|
@ -54,6 +57,8 @@ it('loads plugins from catalog URL', function (): void {
|
|||
config('app.catalog_url') => Http::response($yamlContent, 200),
|
||||
]);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
$component = Volt::test('catalog.index');
|
||||
|
||||
$component->assertSee('Test Plugin');
|
||||
|
|
@ -67,6 +72,8 @@ it('shows error when plugin not found', function (): void {
|
|||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
$component = Volt::test('catalog.index');
|
||||
|
||||
$component->call('installPlugin', 'non-existent-plugin');
|
||||
|
|
@ -97,6 +104,8 @@ it('shows error when zip_url is missing', function (): void {
|
|||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
$component = Volt::test('catalog.index');
|
||||
|
||||
$component->call('installPlugin', 'test-plugin');
|
||||
|
|
|
|||
|
|
@ -341,6 +341,53 @@ it('imports specific plugin from monorepo zip with zip_entry_path parameter', fu
|
|||
->and($plugin->render_markup)->toContain('<div class="plugin2-content">Plugin 2 content</div>');
|
||||
});
|
||||
|
||||
it('sets icon_url when importing from URL with iconUrl parameter', function (): void {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$zipContent = createMockZipFile([
|
||||
'src/settings.yml' => getValidSettingsYaml(),
|
||||
'src/full.liquid' => getValidFullLiquid(),
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://example.com/plugin.zip' => Http::response($zipContent, 200),
|
||||
]);
|
||||
|
||||
$pluginImportService = new PluginImportService();
|
||||
$plugin = $pluginImportService->importFromUrl(
|
||||
'https://example.com/plugin.zip',
|
||||
$user,
|
||||
null,
|
||||
null,
|
||||
'https://example.com/icon.png'
|
||||
);
|
||||
|
||||
expect($plugin)->toBeInstanceOf(Plugin::class)
|
||||
->and($plugin->icon_url)->toBe('https://example.com/icon.png');
|
||||
});
|
||||
|
||||
it('does not set icon_url when importing from URL without iconUrl parameter', function (): void {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$zipContent = createMockZipFile([
|
||||
'src/settings.yml' => getValidSettingsYaml(),
|
||||
'src/full.liquid' => getValidFullLiquid(),
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://example.com/plugin.zip' => Http::response($zipContent, 200),
|
||||
]);
|
||||
|
||||
$pluginImportService = new PluginImportService();
|
||||
$plugin = $pluginImportService->importFromUrl(
|
||||
'https://example.com/plugin.zip',
|
||||
$user
|
||||
);
|
||||
|
||||
expect($plugin)->toBeInstanceOf(Plugin::class)
|
||||
->and($plugin->icon_url)->toBeNull();
|
||||
});
|
||||
|
||||
// Helper methods
|
||||
function createMockZipFile(array $files): string
|
||||
{
|
||||
|
|
|
|||
154
tests/Feature/Volt/CatalogTrmnlTest.php
Normal file
154
tests/Feature/Volt/CatalogTrmnlTest.php
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Livewire\Livewire;
|
||||
use Livewire\Volt\Volt;
|
||||
|
||||
it('loads newest TRMNL recipes on mount', function () {
|
||||
Http::fake([
|
||||
'usetrmnl.com/recipes.json*' => Http::response([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 123,
|
||||
'name' => 'Weather Chum',
|
||||
'icon_url' => 'https://example.com/icon.png',
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 10, 'forks' => 2],
|
||||
],
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
Volt::test('catalog.trmnl')
|
||||
->assertSee('Weather Chum')
|
||||
->assertSee('Install')
|
||||
->assertSee('Installs: 10');
|
||||
});
|
||||
|
||||
it('searches TRMNL recipes when search term is provided', function () {
|
||||
Http::fake([
|
||||
// First call (mount -> newest)
|
||||
'usetrmnl.com/recipes.json?*' => Http::sequence()
|
||||
->push([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 1,
|
||||
'name' => 'Initial Recipe',
|
||||
'icon_url' => null,
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 1, 'forks' => 0],
|
||||
],
|
||||
],
|
||||
], 200)
|
||||
// Second call (search)
|
||||
->push([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 2,
|
||||
'name' => 'Weather Search Result',
|
||||
'icon_url' => null,
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 3, 'forks' => 1],
|
||||
],
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
Volt::test('catalog.trmnl')
|
||||
->assertSee('Initial Recipe')
|
||||
->set('search', 'weather')
|
||||
->assertSee('Weather Search Result')
|
||||
->assertSee('Install');
|
||||
});
|
||||
|
||||
it('installs plugin successfully when user is authenticated', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
Http::fake([
|
||||
'usetrmnl.com/recipes.json*' => Http::response([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 123,
|
||||
'name' => 'Weather Chum',
|
||||
'icon_url' => 'https://example.com/icon.png',
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 10, 'forks' => 2],
|
||||
],
|
||||
],
|
||||
], 200),
|
||||
'usetrmnl.com/api/plugin_settings/123/archive*' => Http::response('fake zip content', 200),
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
Volt::test('catalog.trmnl')
|
||||
->assertSee('Weather Chum')
|
||||
->call('installPlugin', '123')
|
||||
->assertSee('Error installing plugin'); // This will fail because we don't have a real zip file
|
||||
});
|
||||
|
||||
it('shows error when user is not authenticated', function () {
|
||||
Http::fake([
|
||||
'usetrmnl.com/recipes.json*' => Http::response([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 123,
|
||||
'name' => 'Weather Chum',
|
||||
'icon_url' => 'https://example.com/icon.png',
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 10, 'forks' => 2],
|
||||
],
|
||||
],
|
||||
], 200),
|
||||
]);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
Volt::test('catalog.trmnl')
|
||||
->assertSee('Weather Chum')
|
||||
->call('installPlugin', '123')
|
||||
->assertStatus(403); // This will return 403 because user is not authenticated
|
||||
});
|
||||
|
||||
it('shows error when plugin installation fails', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
Http::fake([
|
||||
'usetrmnl.com/recipes.json*' => Http::response([
|
||||
'data' => [
|
||||
[
|
||||
'id' => 123,
|
||||
'name' => 'Weather Chum',
|
||||
'icon_url' => 'https://example.com/icon.png',
|
||||
'screenshot_url' => null,
|
||||
'author_bio' => null,
|
||||
'stats' => ['installs' => 10, 'forks' => 2],
|
||||
],
|
||||
],
|
||||
], 200),
|
||||
'usetrmnl.com/api/plugin_settings/123/archive*' => Http::response('invalid zip content', 200),
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::withoutLazyLoading();
|
||||
|
||||
Volt::test('catalog.trmnl')
|
||||
->assertSee('Weather Chum')
|
||||
->call('installPlugin', '123')
|
||||
->assertSee('Error installing plugin'); // This will fail because the zip content is invalid
|
||||
});
|
||||
|
|
@ -357,3 +357,233 @@ test('resolveLiquidVariables handles empty configuration', function (): void {
|
|||
|
||||
expect($plugin->resolveLiquidVariables($template))->toBe($expected);
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables uses external renderer when preferred_renderer is trmnl-liquid and template contains for loop', function (): void {
|
||||
Illuminate\Support\Facades\Process::fake([
|
||||
'*' => Illuminate\Support\Facades\Process::result(
|
||||
output: 'https://api1.example.com/data\nhttps://api2.example.com/data',
|
||||
exitCode: 0
|
||||
),
|
||||
]);
|
||||
|
||||
config(['services.trmnl.liquid_enabled' => true]);
|
||||
config(['services.trmnl.liquid_path' => '/usr/local/bin/trmnl-liquid-cli']);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'configuration' => [
|
||||
'recipe_ids' => '1,2',
|
||||
],
|
||||
]);
|
||||
|
||||
$template = <<<'LIQUID'
|
||||
{% assign ids = recipe_ids | split: "," %}
|
||||
{% for id in ids %}
|
||||
https://api{{ id }}.example.com/data
|
||||
{% endfor %}
|
||||
LIQUID;
|
||||
|
||||
$result = $plugin->resolveLiquidVariables($template);
|
||||
|
||||
// Trim trailing newlines that may be added by the process
|
||||
expect(mb_trim($result))->toBe('https://api1.example.com/data\nhttps://api2.example.com/data');
|
||||
|
||||
Illuminate\Support\Facades\Process::assertRan(function ($process): bool {
|
||||
$command = is_array($process->command) ? implode(' ', $process->command) : $process->command;
|
||||
|
||||
return str_contains($command, 'trmnl-liquid-cli') &&
|
||||
str_contains($command, '--template') &&
|
||||
str_contains($command, '--context');
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables uses internal renderer when preferred_renderer is not trmnl-liquid', function (): void {
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'php',
|
||||
'configuration' => [
|
||||
'recipe_ids' => '1,2',
|
||||
],
|
||||
]);
|
||||
|
||||
$template = <<<'LIQUID'
|
||||
{% assign ids = recipe_ids | split: "," %}
|
||||
{% for id in ids %}
|
||||
https://api{{ id }}.example.com/data
|
||||
{% endfor %}
|
||||
LIQUID;
|
||||
|
||||
// Should use internal renderer even with for loop
|
||||
$result = $plugin->resolveLiquidVariables($template);
|
||||
|
||||
// Internal renderer should process the template
|
||||
expect($result)->toBeString();
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables uses internal renderer when external renderer is disabled', function (): void {
|
||||
config(['services.trmnl.liquid_enabled' => false]);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'configuration' => [
|
||||
'recipe_ids' => '1,2',
|
||||
],
|
||||
]);
|
||||
|
||||
$template = <<<'LIQUID'
|
||||
{% assign ids = recipe_ids | split: "," %}
|
||||
{% for id in ids %}
|
||||
https://api{{ id }}.example.com/data
|
||||
{% endfor %}
|
||||
LIQUID;
|
||||
|
||||
// Should use internal renderer when external is disabled
|
||||
$result = $plugin->resolveLiquidVariables($template);
|
||||
|
||||
expect($result)->toBeString();
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables uses internal renderer when template does not contain for loop', function (): void {
|
||||
config(['services.trmnl.liquid_enabled' => true]);
|
||||
config(['services.trmnl.liquid_path' => '/usr/local/bin/trmnl-liquid-cli']);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'configuration' => [
|
||||
'api_key' => 'test123',
|
||||
],
|
||||
]);
|
||||
|
||||
$template = 'https://api.example.com/data?key={{ api_key }}';
|
||||
|
||||
// Should use internal renderer when no for loop
|
||||
$result = $plugin->resolveLiquidVariables($template);
|
||||
|
||||
expect($result)->toBe('https://api.example.com/data?key=test123');
|
||||
|
||||
Illuminate\Support\Facades\Process::assertNothingRan();
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables detects for loop with standard opening tag', function (): void {
|
||||
Illuminate\Support\Facades\Process::fake([
|
||||
'*' => Illuminate\Support\Facades\Process::result(
|
||||
output: 'resolved',
|
||||
exitCode: 0
|
||||
),
|
||||
]);
|
||||
|
||||
config(['services.trmnl.liquid_enabled' => true]);
|
||||
config(['services.trmnl.liquid_path' => '/usr/local/bin/trmnl-liquid-cli']);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'configuration' => [],
|
||||
]);
|
||||
|
||||
// Test {% for pattern
|
||||
$template = '{% for item in items %}test{% endfor %}';
|
||||
$plugin->resolveLiquidVariables($template);
|
||||
|
||||
Illuminate\Support\Facades\Process::assertRan(function ($process): bool {
|
||||
$command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command;
|
||||
|
||||
return str_contains($command, 'trmnl-liquid-cli');
|
||||
});
|
||||
});
|
||||
|
||||
test('resolveLiquidVariables detects for loop with whitespace stripping tag', function (): void {
|
||||
Illuminate\Support\Facades\Process::fake([
|
||||
'*' => Illuminate\Support\Facades\Process::result(
|
||||
output: 'resolved',
|
||||
exitCode: 0
|
||||
),
|
||||
]);
|
||||
|
||||
config(['services.trmnl.liquid_enabled' => true]);
|
||||
config(['services.trmnl.liquid_path' => '/usr/local/bin/trmnl-liquid-cli']);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'configuration' => [],
|
||||
]);
|
||||
|
||||
// Test {%- for pattern (with whitespace stripping)
|
||||
$template = '{%- for item in items %}test{% endfor %}';
|
||||
$plugin->resolveLiquidVariables($template);
|
||||
|
||||
Illuminate\Support\Facades\Process::assertRan(function ($process): bool {
|
||||
$command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command;
|
||||
|
||||
return str_contains($command, 'trmnl-liquid-cli');
|
||||
});
|
||||
});
|
||||
|
||||
test('updateDataPayload resolves entire polling_url field first then splits by newline', function (): void {
|
||||
Http::fake([
|
||||
'https://api1.example.com/data' => Http::response(['data' => 'test1'], 200),
|
||||
'https://api2.example.com/data' => Http::response(['data' => 'test2'], 200),
|
||||
]);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'data_strategy' => 'polling',
|
||||
'polling_url' => "https://api1.example.com/data\nhttps://api2.example.com/data",
|
||||
'polling_verb' => 'get',
|
||||
'configuration' => [
|
||||
'recipe_ids' => '1,2',
|
||||
],
|
||||
]);
|
||||
|
||||
$plugin->updateDataPayload();
|
||||
|
||||
// Should have split the multi-line URL and generated two requests
|
||||
expect($plugin->data_payload)->toHaveKey('IDX_0');
|
||||
expect($plugin->data_payload)->toHaveKey('IDX_1');
|
||||
expect($plugin->data_payload['IDX_0'])->toBe(['data' => 'test1']);
|
||||
expect($plugin->data_payload['IDX_1'])->toBe(['data' => 'test2']);
|
||||
});
|
||||
|
||||
test('updateDataPayload handles multi-line polling_url with for loop using external renderer', function (): void {
|
||||
Illuminate\Support\Facades\Process::fake([
|
||||
'*' => Illuminate\Support\Facades\Process::result(
|
||||
output: "https://api1.example.com/data\nhttps://api2.example.com/data",
|
||||
exitCode: 0
|
||||
),
|
||||
]);
|
||||
|
||||
Http::fake([
|
||||
'https://api1.example.com/data' => Http::response(['data' => 'test1'], 200),
|
||||
'https://api2.example.com/data' => Http::response(['data' => 'test2'], 200),
|
||||
]);
|
||||
|
||||
config(['services.trmnl.liquid_enabled' => true]);
|
||||
config(['services.trmnl.liquid_path' => '/usr/local/bin/trmnl-liquid-cli']);
|
||||
|
||||
$plugin = Plugin::factory()->create([
|
||||
'data_strategy' => 'polling',
|
||||
'preferred_renderer' => 'trmnl-liquid',
|
||||
'polling_url' => <<<'LIQUID'
|
||||
{% assign ids = recipe_ids | split: "," %}
|
||||
{% for id in ids %}
|
||||
https://api{{ id }}.example.com/data
|
||||
{% endfor %}
|
||||
LIQUID
|
||||
,
|
||||
'polling_verb' => 'get',
|
||||
'configuration' => [
|
||||
'recipe_ids' => '1,2',
|
||||
],
|
||||
]);
|
||||
|
||||
$plugin->updateDataPayload();
|
||||
|
||||
// Should have used external renderer and generated two URLs
|
||||
expect($plugin->data_payload)->toHaveKey('IDX_0');
|
||||
expect($plugin->data_payload)->toHaveKey('IDX_1');
|
||||
expect($plugin->data_payload['IDX_0'])->toBe(['data' => 'test1']);
|
||||
expect($plugin->data_payload['IDX_1'])->toBe(['data' => 'test2']);
|
||||
|
||||
Illuminate\Support\Facades\Process::assertRan(function ($process): bool {
|
||||
$command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command;
|
||||
|
||||
return str_contains($command, 'trmnl-liquid-cli');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue