From ae2da101aecb424d44811969668747ca5e507cbf Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:21:49 +0300 Subject: [PATCH 01/10] feat(cache): record cache, page cache and cache tools for public pages Lists ask the database only for IDs; each record comes from a per-record card, read for a whole page in one multi-get. Cards are plain arrays built from the admin fields (every language, link-field relations, SEO, pictures, the public URL, what extenders add) and are dropped on save, delete and restore, with version counters for related lists and cards. bulk() drops once after an import. Works on every Laravel store: tags on Redis and Memcached, version keys on the file and database stores. Catalog, news, pages, brands, stores, FAQ and reviews read their public lists through it, the theme keeps its record view in the card, and module settings are kept in it, so a warm list or product page runs no query. An optional page cache for visitors without a login (off by default) swaps the CSRF token on the way out, sends ETag, Last-Modified and Cache-Control for a CDN, and never keeps a page holding something made for one visitor, such as the image captcha's question. atrium:cache:warm, an admin screen with hit rate, size and clear, a debug line in local mode, the atrium.cache.stats filter for monitoring, a benchmark of 10 000 products with 40 properties on MySQL and PostgreSQL, and docs/cache.md in English and Russian. --- CHANGELOG.md | 4 + README.md | 1 + config/atrium.php | 53 ++ docs/cache.md | 273 +++++++ docs/cache.ru.md | 273 +++++++ docs/modules.md | 4 + docs/modules.ru.md | 4 + docs/readme/README.be.md | 1 + docs/readme/README.de.md | 1 + docs/readme/README.es.md | 1 + docs/readme/README.fr.md | 1 + docs/readme/README.it.md | 1 + docs/readme/README.ja.md | 1 + docs/readme/README.kk.md | 1 + docs/readme/README.pl.md | 1 + docs/readme/README.pt-BR.md | 1 + docs/readme/README.ru.md | 1 + docs/readme/README.tr.md | 1 + docs/readme/README.uk.md | 1 + docs/readme/README.uz.md | 1 + docs/readme/README.zh-CN.md | 1 + packages/admin/config/atrium.php | 53 ++ packages/admin/lang/be/cache.php | 32 + packages/admin/lang/be/menu.php | 1 + packages/admin/lang/de/cache.php | 32 + packages/admin/lang/de/menu.php | 1 + packages/admin/lang/en/cache.php | 32 + packages/admin/lang/en/menu.php | 1 + packages/admin/lang/es/cache.php | 32 + packages/admin/lang/es/menu.php | 1 + packages/admin/lang/fr/cache.php | 32 + packages/admin/lang/fr/menu.php | 1 + packages/admin/lang/it/cache.php | 32 + packages/admin/lang/it/menu.php | 1 + packages/admin/lang/ja/cache.php | 32 + packages/admin/lang/ja/menu.php | 1 + packages/admin/lang/kk/cache.php | 32 + packages/admin/lang/kk/menu.php | 1 + packages/admin/lang/pl/cache.php | 32 + packages/admin/lang/pl/menu.php | 1 + packages/admin/lang/pt_BR/cache.php | 32 + packages/admin/lang/pt_BR/menu.php | 1 + packages/admin/lang/ru/cache.php | 32 + packages/admin/lang/ru/menu.php | 1 + packages/admin/lang/tr/cache.php | 32 + packages/admin/lang/tr/menu.php | 1 + packages/admin/lang/uk/cache.php | 32 + packages/admin/lang/uk/menu.php | 1 + packages/admin/lang/uz/cache.php | 32 + packages/admin/lang/uz/menu.php | 1 + packages/admin/lang/zh_CN/cache.php | 32 + packages/admin/lang/zh_CN/menu.php | 1 + .../resources/js/Pages/Admin/Cache/Index.vue | 115 +++ packages/admin/routes/admin.php | 5 + packages/admin/src/AtriumServiceProvider.php | 82 ++ packages/admin/src/Auth/Permissions.php | 2 +- packages/admin/src/Cache/CacheStore.php | 221 ++++++ packages/admin/src/Cache/CachedIds.php | 25 + packages/admin/src/Cache/CachesRecords.php | 97 +++ packages/admin/src/Cache/Card.php | 247 ++++++ packages/admin/src/Cache/CardBuilder.php | 390 ++++++++++ packages/admin/src/Cache/RecordCache.php | 712 ++++++++++++++++++ packages/admin/src/Cache/TouchesOwner.php | 45 ++ packages/admin/src/Cache/Versions.php | 115 +++ packages/admin/src/Captcha/ImageCaptcha.php | 4 + .../src/Console/Commands/CacheWarmCommand.php | 147 ++++ .../Console/Commands/ModuleRemoveCommand.php | 1 + packages/admin/src/Contracts/Cacheable.php | 25 + .../src/Http/Controllers/AdminController.php | 4 + .../src/Http/Controllers/CacheController.php | 89 +++ .../admin/src/Http/Middleware/CacheDebug.php | 94 +++ .../admin/src/Http/Middleware/CachePages.php | 276 +++++++ packages/admin/src/Models/SeoMeta.php | 8 + packages/admin/src/Models/Slug.php | 8 + packages/admin/src/Modules/Settings.php | 24 +- .../admin/src/Support/ContentLanguages.php | 9 +- packages/admin/src/Support/PublicUrl.php | 18 +- packages/admin/src/Support/Sites.php | 5 +- .../tests/Feature/CacheContractsTest.php | 100 +++ .../admin/tests/Feature/CacheScreenTest.php | 98 +++ .../admin/tests/Feature/CacheTestCase.php | 129 ++++ .../admin/tests/Feature/PageCacheTest.php | 208 +++++ .../admin/tests/Feature/RecordCacheTest.php | 276 +++++++ .../tests/Feature/RecordCacheVersionsTest.php | 44 ++ packages/admin/tests/Fixtures/Cache/Book.php | 93 +++ packages/admin/tests/Fixtures/Cache/Shelf.php | 30 + packages/admin/tests/Fixtures/Cache/Tag.php | 19 + .../src/Commands/MigrateDataCommand.php | 7 + .../Commands/MigrateMediaLibraryCommand.php | 7 + .../bitrix/src/Commands/MigrateSeoCommand.php | 7 + .../src/Commands/MigrateSitesCommand.php | 7 + .../bitrix/src/Commands/SyncDataCommand.php | 7 + packages/brands/src/Models/Brand.php | 6 +- .../catalog/src/Models/CatalogSection.php | 6 +- packages/catalog/src/Models/Product.php | 6 +- packages/faq/src/Faq.php | 9 +- packages/faq/src/Models/Category.php | 6 +- packages/faq/src/Models/Question.php | 6 +- packages/news/src/Models/News.php | 6 +- .../src/Http/Controllers/PageController.php | 10 +- packages/pages/src/Models/Page.php | 6 +- packages/pages/src/PageTree.php | 36 +- packages/reviews/src/Models/Review.php | 6 +- packages/reviews/src/ReviewCounters.php | 4 + packages/reviews/src/Reviews.php | 13 +- packages/stores/src/Models/Store.php | 6 +- .../src/Http/Controllers/PageController.php | 54 +- packages/theme/src/Pages.php | 185 ++++- packages/theme/src/RecordView.php | 218 +++++- packages/theme/src/ThemeServiceProvider.php | 40 + packages/theme/tests/CacheBenchmarkTest.php | 274 +++++++ packages/theme/tests/CachedPagesTest.php | 149 ++++ packages/theme/tests/FileStoreCacheTest.php | 71 ++ .../theme/tests/Fixtures/BenchProduct.php | 122 +++ packages/theme/tests/Fixtures/Brand.php | 6 +- packages/theme/tests/Fixtures/Product.php | 6 +- .../theme/tests/Fixtures/ProductSection.php | 6 +- 117 files changed, 6141 insertions(+), 90 deletions(-) create mode 100644 docs/cache.md create mode 100644 docs/cache.ru.md create mode 100644 packages/admin/lang/be/cache.php create mode 100644 packages/admin/lang/de/cache.php create mode 100644 packages/admin/lang/en/cache.php create mode 100644 packages/admin/lang/es/cache.php create mode 100644 packages/admin/lang/fr/cache.php create mode 100644 packages/admin/lang/it/cache.php create mode 100644 packages/admin/lang/ja/cache.php create mode 100644 packages/admin/lang/kk/cache.php create mode 100644 packages/admin/lang/pl/cache.php create mode 100644 packages/admin/lang/pt_BR/cache.php create mode 100644 packages/admin/lang/ru/cache.php create mode 100644 packages/admin/lang/tr/cache.php create mode 100644 packages/admin/lang/uk/cache.php create mode 100644 packages/admin/lang/uz/cache.php create mode 100644 packages/admin/lang/zh_CN/cache.php create mode 100644 packages/admin/resources/js/Pages/Admin/Cache/Index.vue create mode 100644 packages/admin/src/Cache/CacheStore.php create mode 100644 packages/admin/src/Cache/CachedIds.php create mode 100644 packages/admin/src/Cache/CachesRecords.php create mode 100644 packages/admin/src/Cache/Card.php create mode 100644 packages/admin/src/Cache/CardBuilder.php create mode 100644 packages/admin/src/Cache/RecordCache.php create mode 100644 packages/admin/src/Cache/TouchesOwner.php create mode 100644 packages/admin/src/Cache/Versions.php create mode 100644 packages/admin/src/Console/Commands/CacheWarmCommand.php create mode 100644 packages/admin/src/Contracts/Cacheable.php create mode 100644 packages/admin/src/Http/Controllers/CacheController.php create mode 100644 packages/admin/src/Http/Middleware/CacheDebug.php create mode 100644 packages/admin/src/Http/Middleware/CachePages.php create mode 100644 packages/admin/tests/Feature/CacheContractsTest.php create mode 100644 packages/admin/tests/Feature/CacheScreenTest.php create mode 100644 packages/admin/tests/Feature/CacheTestCase.php create mode 100644 packages/admin/tests/Feature/PageCacheTest.php create mode 100644 packages/admin/tests/Feature/RecordCacheTest.php create mode 100644 packages/admin/tests/Feature/RecordCacheVersionsTest.php create mode 100644 packages/admin/tests/Fixtures/Cache/Book.php create mode 100644 packages/admin/tests/Fixtures/Cache/Shelf.php create mode 100644 packages/admin/tests/Fixtures/Cache/Tag.php create mode 100644 packages/theme/tests/CacheBenchmarkTest.php create mode 100644 packages/theme/tests/CachedPagesTest.php create mode 100644 packages/theme/tests/FileStoreCacheTest.php create mode 100644 packages/theme/tests/Fixtures/BenchProduct.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c47e17f3..6c22d859 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,10 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - Every source file starts with the Atrium copyright header. Pint adds it to PHP (`header_comment` in pint.json), `php scripts/copyright-header.php --fix` to Blade, Vue, JS, CSS, shell and YAML, and `tests/Unit/CopyrightHeaderTest.php` fails without it. - Docs module (`alveby/atrium-docs`): documentation pages made from the Markdown of a repository, the README, `docs/`, the changelog and every package's README, at `/docs/{version}/{page}` and `/{lang}/docs/…`. A sidebar, a contents list, GitHub's heading anchors, code coloured on the server by Phiki with light and dark themes at 4.5:1 or more, search in the language of the page with suggestions as you type, "Edit this page on GitHub". A page without a translation is shown in English with a notice, its canonical pointing to the English page and its hreflang listing only real translations. `atrium:docs:pull v0.2.0` copies a release out of git as one more version; the newest release is the default and older ones say so. Interface in 15 languages. - Module settings: a module names a `settings` class in its manifest (`extra.atrium.settings`), extending `Atrium\Admin\Modules\ModuleSettings`, with fields of the admin's own types, their rules and defaults, for all sites or for each (`$perSite`). The panel gets a **Modules** screen listing the installed modules and a settings screen for each; the `{key}.settings` permission is in the module's row of the role form. Values are read with `Setting::get('shop.currency')` (the current site's value, else the field's default) and kept in `admin_module_settings`. The manifest may set the module's `key` and `title`. The catalog has the first one: products on a page of a section, per site. +- Record cache: public pages stay fast with dozens of properties, relations, pictures and translations per record. A model that `implements Cacheable` and `use CachesRecords` gets a card per record, a plain cached array built from its admin fields (every language, the relations of its link fields, SEO, pictures with thumbnails, the public URL, and what extenders add). `Model::cached($id)` and `Model::cachedMany($ids)` read cards in one multi-get and build the missing ones together in a few queries. Lists ask only for IDs: `->cachedIds()` keeps the IDs and the total of a page under a hash of the SQL, the page, the site and the language, `->cachedPaginate()` and `->cachedCards()` return cards; `RecordCache::remember()` keeps any other value under the models it reads. Catalog, news, pages, brands, stores, FAQ and reviews read through it, and the theme keeps its ready record view in the card. A save, delete or restore through Eloquent drops the record's cards in every site and language and the cards of same-model records that show it, and bumps a version counter for its lists and for cards that depend on the model, so the admin's change is on the site at once; `bulk()` drops once at the end of an import (the Bitrix commands drop everything once). Works on every Laravel store: tags on Redis and Memcached, version keys on the file and database stores; Redis is recommended. Module settings are kept in it too. The `atrium.cache.stats` filter gives monitoring the hits and misses of the finished request. On a warm cache a list or product page runs no query. +- Page cache for visitors without a login (`ATRIUM_PAGE_CACHE=true`, off by default): whole pages keyed by the URL and the site, never for a signed-in admin, the CSRF token swapped for the visitor's on the way out, dropped by the same saves as the cards; `ETag`, `Last-Modified`, `304` and `Cache-Control` with `s-maxage` for a CDN (`private` when the page holds a form token). +- `atrium:cache:warm` opens the home page and the first page of every list of every site and language (`--records` also builds every card). **Admin → Cache** shows the hit rate, the store and its size, and clears one module, one site or everything. In local mode with `APP_DEBUG` a line under public pages and an `X-Atrium-Debug` header count queries and cache hits. +- A cache benchmark (`ATRIUM_BENCHMARK=1 vendor/bin/phpunit packages/theme/tests/CacheBenchmarkTest.php`): 10 000 products with 40 properties, list and product pages with the cache off, cold, warm and with the page cache. Guide: [docs/cache.md](docs/cache.md). - AI module (`alveby/atrium-ai`, on the Laravel AI SDK): a **Generate** link under text fields marked `->ai()` writes a description, a preview, the SEO title, description and keywords, or a picture's alt text, and **Translate** fills a translatable field's other languages. The text is offered in a dialog to edit or drop; nothing is saved until the editor saves. The SEO fields of `HasAdminSeo` have it already. Providers come in chains per kind of work (text, vision, embeddings) with fallback on a limit or a timeout; the defaults are free tiers (Gemini, Groq, OpenRouter) or a local Ollama, keys only from `.env`, and no key means no buttons. The provider is called after the response or by a queue worker, so the form never waits; prompts are Blade views; `ai_usage` logs task, provider, tokens and time without the texts; `atrium:ai:status` shows the chains and the usage. The same over `POST /api/v1/ai/generate` and the `generate_text` MCP tool. A module adds its own MCP tools through `atrium.mcp.tools`. - The AI module's helper: the Atrium arch in the corner of every admin page, animated, opens a chat that answers in the administrator's language from the guides and the module READMEs, and reads the records of the modules the administrator may view (tools `list_modules`, `describe_module`, `list_records`, `get_record`, `search_docs`), with links into the admin. It only reads. Other packages add tools in `atrium-ai.help.tools`; `ATRIUM_AI_HELP=false` turns it off. Interface in 15 languages. - `DisplayField`: read-only HTML on the edit form, drawn from the record by the server (`->html(fn (Model $record): string => …)`), for order lines, summaries and links. It is not on the create form and nothing is taken from the request for it. diff --git a/README.md b/README.md index 2c6c46c6..2e7afb52 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,7 @@ The Bitrix database is only read. The tabs, field order and list columns come ou - [SEO: titles, hreflang, sitemaps, schema.org, redirects, the SEO check](docs/seo.md) - [Your own module: fields, columns, tabs, permissions, languages, tests, a package](docs/modules.md) - [Custom fields: add fields to any module from the admin, filters and facets on 100 000 records](docs/custom-fields.md) +- [Cache: fast pages with dozens of properties, Redis, the page cache, CDN headers](docs/cache.md) - [Moving from 1C-Bitrix, step by step](docs/bitrix.md) - [Backups: databases and files to several places, schedules, health checks, restore](docs/backup.md) - [CDN: pictures, resized copies and WebP/AVIF, cache purge, uploads to S3](docs/cdn.md) diff --git a/config/atrium.php b/config/atrium.php index d0fd93a8..17292057 100644 --- a/config/atrium.php +++ b/config/atrium.php @@ -11,6 +11,7 @@ use Atrium\Admin\Dashboard\Gadgets\PerformanceGadget; use Atrium\Admin\Dashboard\Gadgets\SiteSpeedGadget; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Models\PageTiming; return [ /* @@ -209,6 +210,11 @@ 'route' => 'admin.api-tokens.index', 'icon' => 'settings', ], + [ + 'label' => 'atrium::menu.cache', + 'route' => 'admin.cache.index', + 'icon' => 'settings', + ], ], /* @@ -441,4 +447,51 @@ 'enabled' => (bool) env('ATRIUM_MCP_ENABLED', true), 'path' => 'mcp', ], + + /* + |-------------------------------------------------------------------------- + | Cache + |-------------------------------------------------------------------------- + | + | The record cache (docs/cache.md): lists answer with ids, records come + | from cards built once per language, and saving a record in the admin + | drops what showed it. Works on every Laravel store; Redis is the one to + | use in production (one MGET per list, tags free memory at once). + | + | store a store of config/cache.php, the default one when null + | strategy auto: tags where the store has them (Redis, Memcached), + | version keys elsewhere; versions: version keys everywhere + | ttl seconds: cards, lists of ids, full pages + | time_step lists that compare with "now" (active from/to) see time in + | steps of this many seconds, so their keys stay the same + | ignore models whose saves never touch the cache + | pages full-page cache for visitors who are not logged in to the + | admin; off by default (see docs/cache.md before turning on) + | debug a line under public pages with queries and cache hits, in + | the local environment with APP_DEBUG on + | + */ + 'cache' => [ + 'enabled' => (bool) env('ATRIUM_CACHE_ENABLED', true), + 'store' => env('ATRIUM_CACHE_STORE'), + 'strategy' => env('ATRIUM_CACHE_STRATEGY', 'auto'), + 'ttl' => [ + 'cards' => (int) env('ATRIUM_CACHE_TTL_CARDS', 86400), + 'lists' => (int) env('ATRIUM_CACHE_TTL_LISTS', 3600), + 'pages' => (int) env('ATRIUM_CACHE_TTL_PAGES', 600), + ], + 'time_step' => 60, + 'stats' => true, + 'ignore' => [ + PageTiming::class, + ], + 'pages' => [ + 'enabled' => (bool) env('ATRIUM_PAGE_CACHE', false), + // Seconds a CDN may keep a page without the session's form token. + 'shared_max_age' => (int) env('ATRIUM_PAGE_CACHE_SHARED_MAX_AGE', 60), + // Paths never cached, as Request::is() patterns. + 'except' => [], + ], + 'debug' => (bool) env('ATRIUM_CACHE_DEBUG', true), + ], ]; diff --git a/docs/cache.md b/docs/cache.md new file mode 100644 index 00000000..ce990dd7 --- /dev/null +++ b/docs/cache.md @@ -0,0 +1,273 @@ +# Cache + +Atrium keeps public pages fast even when a record has dozens of properties, relations, pictures and translations. The idea: + +- a list or a filter asks the database **only for IDs** (and the total), and keeps that answer; +- each record is drawn from its own **card**, a cached array with everything a page shows; the cards of a page come in **one multi-get**, and the missing ones are built together, in a few queries, whatever their number; +- a save drops exactly the cards and lists it touches, so an editor sees the change at once. + +On a warm cache a product page or a list page runs no query at all. A page cache for anonymous visitors (off by default) skips PHP's view work too. + +The cache works on every Laravel store. **Redis is recommended**. + +## Contents + +- [Stores](#stores) +- [Making a module cacheable](#making-a-module-cacheable) +- [Lists](#lists) +- [Reading cards](#reading-cards) +- [Other values: remember()](#other-values-remember) +- [When the cache is dropped](#when-the-cache-is-dropped) +- [Imports](#imports) +- [Page cache](#page-cache) +- [CDN](#cdn) +- [Warming, the admin screen and the debug line](#warming-the-admin-screen-and-the-debug-line) +- [Configuration](#configuration) +- [Benchmark](#benchmark) + +## Stores + +| Store | How a group is dropped | Notes | +|---|---|---| +| `redis` | tags | Recommended: fast multi-get, tags, sizes in the admin. | +| `memcached` | tags | Fine as well. | +| `file`, `database` | version keys | Works; each card is a file or a row. | +| `array` | tags | Tests only: lives one request. | + +The record cache uses the app's default store. To give it its own, set `ATRIUM_CACHE_STORE=redis` (a store from `config/cache.php`). For Redis: + +```dotenv +CACHE_STORE=redis +REDIS_CLIENT=phpredis +REDIS_HOST=127.0.0.1 +``` + +A store without tags gets **version keys** instead: every key carries a stamp made of a few counters (`all`, `site:{id}`, `card:{Class}`, `list:{Class}`), and dropping a group means bumping its counter. Old entries are never read again and expire with their TTL. `ATRIUM_CACHE_STRATEGY=versions` forces this on Redis too. + +## Making a module cacheable + +Add the `Cacheable` interface and the `CachesRecords` trait to the model: + +```php +use Atrium\Admin\Cache\CachesRecords; +use Atrium\Admin\Contracts\Cacheable; + +class Product extends Model implements Administrable, Cacheable +{ + use CachesRecords, HasAdminSeo, InteractsWithAdmin, Translatable; +} +``` + +That is all for most models. The card is built from the model's admin fields: + +- every column, with translations as they are (the card holds the record in every language); +- the relations behind `BelongsToField`, `BelongsToManyField` and the like, loaded for all missing cards at once; +- SEO meta, pictures and galleries (with thumbnails), the public URL; +- what extenders add (the theme puts in the ready view of the record). + +To name the relations yourself, override `cacheRelations()`: + +```php +public function cacheRelations(): array +{ + return ['brand', 'stores', 'section']; +} +``` + +A related model whose saves must reach the card is a **dependency**: the card stamp includes its list counter, so a brand renamed in the admin rebuilds the product cards that show it the next time they are read, not before. Relations to the same model (related products, a parent page) are not dependencies: a save drops the cards of the records that show it, found with one query. + +A row that belongs to another record through a morph pair (SEO meta, a slug) should use the `TouchesOwner` trait, so saving it drops the owner's cards. A model may also list owners in `cacheTouches()`. + +## Lists + +Ask for IDs, keep them, and draw the records from cards: + +```php +// IDs and the total of one page: one query on a miss, none on a hit. +$page = Product::query()->where('active', true)->orderBy('sort')->cachedIds(perPage: 20, page: 2); +$page->ids; // [12, 7, 31, …] +$page->total; // 4310 + +// The same, as a paginator of cards. +$products = Product::query()->where('active', true)->orderBy('sort')->cachedPaginate(20); + +// Every matching record, as cards (no paging). +$questions = Question::query()->where('category_id', $id)->orderBy('sort')->cachedCards(dependsOn: [Category::class]); +``` + +The list key is a hash of the SQL with its bindings, the page, the site and the language. It is dropped when any record of the model is saved, deleted or restored, and when a model listed in `dependsOn` changes (use it when the query joins or filters by another table). + +Times in a list query are rounded down to a minute (`RecordCache::now()`), so `active_from <= now()` gives the same key for 60 seconds. Use it instead of `now()` in public queries: + +```php +->where('active_from', '<=', app(RecordCache::class)->now()) +``` + +## Reading cards + +```php +$card = Product::cached(42); // one card, or null +$cards = Product::cachedMany([42, 7, 31]); // in the given order, missing ones left out + +$card->name; // in the current language, with fallback +$card->get('price'); +$card->relation('brand'); // a model or a collection, built from the card +$card->seo('title'); +$card->picture('preview_picture', 'detail_picture'); +$card->media('photos'); // [['url' => …, 'thumbnails' => …], …] +$card->url(); +$card->extra('theme'); // what an extender put in +$card->model(); // a model filled from the card, with its relations (no query) +``` + +The locale defaults to the current one; pass another as the second argument. + +Use `model()` where a view expects a model. It is never saved: it is built from the cache. + +## Other values: remember() + +For anything else drawn from the database (a menu, a tree, a summary of ratings), use `remember()` and name the models it reads: + +```php +$tree = app(RecordCache::class)->remember(Page::class, 'page-tree', fn () => $this->buildTree()); +$summary = app(RecordCache::class)->remember([Review::class, Product::class], 'summary:'.$id, fn () => …); +``` + +The value is dropped when any of those models changes. It is kept per site unless `perSite: false`. Keep values plain (arrays, scalars): models in a cache are slow to unpack and easy to get stale. + +A name that is not a model works too: `remember(Settings::class, 'settings:'.$module, …)` is dropped by `flushClass(Settings::class)`. Module settings are read this way, so a warm page asks the database nothing. + +## When the cache is dropped + +Saving, deleting or restoring a cacheable model through Eloquent (the admin, the API, MCP, your own code): + +- drops the record's cards in every site and language; +- drops the cards of records of the same model that show it (a related product, a child page); +- bumps the model's list counter: its lists, the `remember()` values naming it, and the cards that depend on it are rebuilt the next time they are read. + +Saving a site drops its cards (its domains are in every URL), saving a language drops everything. When a save runs inside a transaction, the cards are dropped once more after the commit, so a request in between cannot keep the old row. + +Code that writes past Eloquent (`DB::table()->update()`, `insert()`) must say so: + +```php +app(RecordCache::class)->flushClass(Product::class); // one model +app(RecordCache::class)->flushSite($siteId); // one site +app(RecordCache::class)->flushAll(); // everything +``` + +Cards also expire with their TTL (a day by default), so a missed drop heals itself. + +## Imports + +Thousands of saves in a row should not drop the cache thousands of times. Wrap the import: + +```php +app(RecordCache::class)->bulk(function () { + foreach ($rows as $row) { + Product::updateOrCreate(['xml_id' => $row['id']], $row); + } +}); +``` + +Inside `bulk()` saves only note the models they touched; at the end each of them is dropped once. An import that writes with `DB::table()` passes `everything: true`, and the whole cache is dropped once at the end. The Bitrix migrator does that. + +## Page cache + +For visitors who are not logged in, a whole page can be kept: the second visitor gets it from the store without running the controller. + +```dotenv +ATRIUM_PAGE_CACHE=true +``` + +- The key is the URL (scheme, host, path, sorted query) and the site; the language is in the URL. +- Only `GET` and `HEAD`, only `200` HTML answers, never the admin, never a signed-in admin or user, never Inertia or ajax, never a page that set its own cookie or flashed errors or old input, never paths in `atrium.cache.pages.except`. A response with `Cache-Control: no-store` or the `X-Atrium-No-Cache` header is not kept. +- **Form tokens**: the CSRF token in a kept page is swapped for the current visitor's on the way out, so forms keep working. +- A kept page is valid while the cards, lists and models it read stay the same: a save drops it at once. Models read in other ways can be named in `atrium.cache.pages.depends_on`. +- The answer carries `X-Atrium-Cache: HIT` or `MISS`. + +Turn it on after checking that no page shows something personal to a visitor without a login (a cart counter, "recently viewed"). Put such a page in `except`, or send the header from its controller: + +```php +return response()->view('cart')->header('X-Atrium-No-Cache', '1'); +``` + +A component that renders something for one visitor only, wherever it is placed, calls `app(RecordCache::class)->dontKeepPage()` instead. The built-in image captcha does: its question can be answered once, so a page that shows it is never kept. + +## CDN + +Kept pages are sent with `ETag` and `Last-Modified`; a request with a matching `If-None-Match` gets `304 Not Modified`. + +- A page without a form token: `Cache-Control: public, max-age=0, s-maxage=60`. A CDN may keep it for `ATRIUM_PAGE_CACHE_SHARED_MAX_AGE` seconds, the browser asks again every time. +- A page with a form token: `Cache-Control: private, no-cache`. A shared copy would hand one visitor's token to the next. + +Laravel's `web` group starts a session for every visitor, so every answer carries `Set-Cookie`, and most CDNs do not keep an answer that sets a cookie. Either have the CDN ignore the session cookie on public paths, or send public pages without the session. Purging a CDN after a save is not done by Atrium. The short `s-maxage` is the bound on staleness. + +## Warming, the admin screen and the debug line + +After a deploy or a cleared cache: + +```bash +php artisan atrium:cache:warm # home page and first page of every list, every site and language +php artisan atrium:cache:warm --records # also the card of every record of every cached module +php artisan atrium:cache:warm --site=main +``` + +A module adds its own pages with `app(RecordCache::class)->warmUsing(fn (string $language): iterable => [...])`. + +**Admin → Cache** (superadmins) shows the hit rate since the last reset, the store and whether it has tags, the number of entries and their size (Redis, file and database stores), and clears one module, one site or everything. + +In the local environment with `APP_DEBUG=true`, every public page gets an `X-Atrium-Debug` header and a line at the bottom of the screen: + +``` +queries=3 (2.1 ms); cache hits=21 misses=0; page cache=off; 18.4 ms +``` + +`ATRIUM_CACHE_DEBUG=false` hides it. + +## Configuration + +`config/atrium.php` → `cache`: + +| Key | Env | Default | | +|---|---|---|---| +| `enabled` | `ATRIUM_CACHE_ENABLED` | `true` | Off: cards are built on every read, nothing is kept. | +| `store` | `ATRIUM_CACHE_STORE` | default store | A store from `config/cache.php`. | +| `strategy` | `ATRIUM_CACHE_STRATEGY` | `auto` | `auto` (tags where the store has them) or `versions`. | +| `ttl.cards` | `ATRIUM_CACHE_TTL_CARDS` | `86400` | Seconds. | +| `ttl.lists` | `ATRIUM_CACHE_TTL_LISTS` | `3600` | Seconds; also for `remember()`. | +| `ttl.pages` | `ATRIUM_CACHE_TTL_PAGES` | `600` | Seconds. | +| `time_step` | | `60` | Seconds `RecordCache::now()` is rounded to. | +| `stats` | | `true` | Count hits and misses for the admin screen. | +| `ignore` | | | Models whose saves never touch the cache. | +| `pages.enabled` | `ATRIUM_PAGE_CACHE` | `false` | The page cache. | +| `pages.shared_max_age` | `ATRIUM_PAGE_CACHE_SHARED_MAX_AGE` | `60` | `s-maxage` for a CDN. | +| `pages.except` | | `[]` | Paths never kept, as `Request::is()` patterns. | +| `pages.depends_on` | | `[]` | Models whose saves drop every kept page. | +| `debug` | `ATRIUM_CACHE_DEBUG` | `true` | The debug line (local, with `APP_DEBUG`). | + +## Benchmark + +`packages/theme/tests/CacheBenchmarkTest.php` fills a catalog of 10 000 products with 40 properties each (16 lines, 10 numbers, 6 lists, 4 flags, 2 texts, 2 brand links), a translated name, code and text, three related products, three pictures and SEO, and opens a list page and a product page through the theme with the cache off, cold, warm and with the page cache: + +```bash +ATRIUM_BENCHMARK=1 vendor/bin/phpunit packages/theme/tests/CacheBenchmarkTest.php +``` + +`DB_CONNECTION` picks the database as for the rest of the suite, `ATRIUM_BENCHMARK_STORE` the store, `ATRIUM_BENCHMARK_PRODUCTS` the number of products. It fails if a list page costs more queries on page 250 than on page 1, a warm list or product page runs more than two queries, or a kept page runs any. + +Results on 2026-11-17 (PHP 8.4, MySQL 8.4 and PostgreSQL 17 in Docker, Redis 7, median of five requests; queries, then PHP CPU time): + +| Page | Cache off | Cold cache | Warm cache | Page cache | +|---|---|---|---|---| +| MySQL, list page 1 | 3 q, 6.8 ms | 7 q, 39.0 ms | **0 q**, 7.6 ms | **0 q**, 1.2 ms | +| MySQL, list page 250 | 3 q, 6.0 ms | 7 q, 38.9 ms | **0 q**, 8.2 ms | **0 q**, 1.2 ms | +| MySQL, product page | 6 q, 7.7 ms | 6 q, 11.0 ms | **0 q**, 4.9 ms | **0 q**, 1.4 ms | +| PostgreSQL, list page 1 | 3 q, 7.3 ms | 7 q, 48.3 ms | **0 q**, 12.1 ms | **0 q**, 1.3 ms | +| PostgreSQL, list page 250 | 3 q, 7.3 ms | 7 q, 46.9 ms | **0 q**, 15.7 ms | **0 q**, 1.7 ms | +| PostgreSQL, product page | 6 q, 13.7 ms | 6 q, 17.0 ms | **0 q**, 7.7 ms | **0 q**, 1.7 ms | + +"Cache off" is the theme reading the database directly, as before the cache. A cold list costs more queries than that because it builds the whole card (brands, related products, SEO), which the product page then reads for free. The count stays the same on page 1 and page 250. With the file store the counts are the same and CPU time is about twice as high. + +How to read it: the cache removes the database round trips. On a warm cache a page asks the database nothing, so the time no longer depends on the database's load or distance. A cold card costs about 2 ms of PHP per record, once. A warm list unpacks 20 cards and costs about the same PHP time as reading 20 rows. The page cache skips the controller and the views: about 1 ms. + +The test prints wall times too. They include the database and the store, so they move with the machine's load and are only comparable within one run. diff --git a/docs/cache.ru.md b/docs/cache.ru.md new file mode 100644 index 00000000..cc11b077 --- /dev/null +++ b/docs/cache.ru.md @@ -0,0 +1,273 @@ +# Кеш + +Atrium держит публичные страницы быстрыми, даже когда у записи десятки свойств, связей, картинок и переводов. Идея: + +- список или фильтр спрашивает у базы **только ID** (и общее число) и запоминает ответ; +- каждая запись рисуется из своей **карточки** — закешированного массива со всем, что показывает страница; карточки страницы приходят **одним multi-get**, а недостающие собираются вместе, за несколько запросов, сколько бы их ни было; +- сохранение сбрасывает ровно те карточки и списки, которых оно касается, поэтому редактор видит правку сразу. + +На тёплом кеше страница товара и страница списка не делают ни одного запроса. Кеш целых страниц для анонимных посетителей (по умолчанию выключен) пропускает ещё и работу шаблонов. + +Кеш работает на любом хранилище Laravel. **Рекомендуется Redis**. + +## Содержание + +- [Хранилища](#хранилища) +- [Как подключить модуль](#как-подключить-модуль) +- [Списки](#списки) +- [Чтение карточек](#чтение-карточек) +- [Другие значения: remember()](#другие-значения-remember) +- [Когда кеш сбрасывается](#когда-кеш-сбрасывается) +- [Импорт](#импорт) +- [Кеш страниц](#кеш-страниц) +- [CDN](#cdn) +- [Прогрев, экран в админке и строка отладки](#прогрев-экран-в-админке-и-строка-отладки) +- [Настройки](#настройки) +- [Замер](#замер) + +## Хранилища + +| Хранилище | Как сбрасывается группа | Заметки | +|---|---|---| +| `redis` | теги | Рекомендуется: быстрый multi-get, теги, размер в админке. | +| `memcached` | теги | Тоже подходит. | +| `file`, `database` | ключи версий | Работает; каждая карточка — файл или строка. | +| `array` | теги | Только для тестов: живёт один запрос. | + +Кеш записей берёт хранилище приложения по умолчанию. Чтобы дать ему своё, задайте `ATRIUM_CACHE_STORE=redis` (хранилище из `config/cache.php`). Для Redis: + +```dotenv +CACHE_STORE=redis +REDIS_CLIENT=phpredis +REDIS_HOST=127.0.0.1 +``` + +Хранилище без тегов получает **ключи версий**: в каждый ключ входит отметка из нескольких счётчиков (`all`, `site:{id}`, `card:{Class}`, `list:{Class}`), а сбросить группу — значит увеличить её счётчик. Старые записи больше не читаются и истекают по TTL. `ATRIUM_CACHE_STRATEGY=versions` включает этот способ и на Redis. + +## Как подключить модуль + +Добавьте модели интерфейс `Cacheable` и трейт `CachesRecords`: + +```php +use Atrium\Admin\Cache\CachesRecords; +use Atrium\Admin\Contracts\Cacheable; + +class Product extends Model implements Administrable, Cacheable +{ + use CachesRecords, HasAdminSeo, InteractsWithAdmin, Translatable; +} +``` + +Для большинства моделей этого достаточно. Карточка собирается по полям админки: + +- все колонки, переводы как есть (в карточке запись на всех языках); +- связи за `BelongsToField`, `BelongsToManyField` и похожими полями, загруженные сразу для всех недостающих карточек; +- SEO, картинки и галереи (с уменьшенными копиями), публичный адрес; +- то, что добавляют расширения (тема кладёт готовое представление записи). + +Чтобы назвать связи самому, переопределите `cacheRelations()`: + +```php +public function cacheRelations(): array +{ + return ['brand', 'stores', 'section']; +} +``` + +Связанная модель, сохранения которой должны доходить до карточки, — **зависимость**: в отметку карточки входит её счётчик списков, поэтому бренд, переименованный в админке, пересобирает карточки товаров с ним при следующем чтении, не раньше. Связи с той же моделью (похожие товары, родительская страница) зависимостями не считаются: сохранение сбрасывает карточки записей, которые её показывают, — их находит один запрос. + +Строке, которая принадлежит другой записи через morph-пару (SEO, slug), нужен трейт `TouchesOwner`: её сохранение сбросит карточки владельца. Модель может и сама перечислить владельцев в `cacheTouches()`. + +## Списки + +Спросите ID, запомните их и рисуйте записи из карточек: + +```php +// ID и общее число одной страницы: один запрос при промахе, ни одного при попадании. +$page = Product::query()->where('active', true)->orderBy('sort')->cachedIds(perPage: 20, page: 2); +$page->ids; // [12, 7, 31, …] +$page->total; // 4310 + +// То же самое пагинатором из карточек. +$products = Product::query()->where('active', true)->orderBy('sort')->cachedPaginate(20); + +// Все подходящие записи карточками (без страниц). +$questions = Question::query()->where('category_id', $id)->orderBy('sort')->cachedCards(dependsOn: [Category::class]); +``` + +Ключ списка — хеш SQL с параметрами, страницы, сайта и языка. Он сбрасывается, когда сохраняется, удаляется или восстанавливается любая запись модели, а также когда меняется модель из `dependsOn` (укажите её, если запрос соединяет или фильтрует по другой таблице). + +Время в запросе списка округляется вниз до минуты (`RecordCache::now()`), поэтому `active_from <= now()` даёт один ключ 60 секунд. Используйте его вместо `now()` в публичных запросах: + +```php +->where('active_from', '<=', app(RecordCache::class)->now()) +``` + +## Чтение карточек + +```php +$card = Product::cached(42); // одна карточка или null +$cards = Product::cachedMany([42, 7, 31]); // в заданном порядке, ненайденные пропущены + +$card->name; // на текущем языке, с запасным +$card->get('price'); +$card->relation('brand'); // модель или коллекция, собранная из карточки +$card->seo('title'); +$card->picture('preview_picture', 'detail_picture'); +$card->media('photos'); // [['url' => …, 'thumbnails' => …], …] +$card->url(); +$card->extra('theme'); // то, что положило расширение +$card->model(); // модель, заполненная из карточки, со связями (без запроса) +``` + +Язык по умолчанию — текущий; другой передаётся вторым аргументом. + +`model()` нужна там, где шаблон ждёт модель. Её не сохраняют: она собрана из кеша. + +## Другие значения: remember() + +Для всего остального, что берётся из базы (меню, дерево, сводка оценок), используйте `remember()` и назовите модели, которые оно читает: + +```php +$tree = app(RecordCache::class)->remember(Page::class, 'page-tree', fn () => $this->buildTree()); +$summary = app(RecordCache::class)->remember([Review::class, Product::class], 'summary:'.$id, fn () => …); +``` + +Значение сбрасывается, когда меняется любая из этих моделей. Оно хранится отдельно для каждого сайта, если не передать `perSite: false`. Храните простые значения (массивы, скаляры): модели в кеше медленно распаковываются и легко устаревают. + +Вместо модели можно назвать что угодно: `remember(Settings::class, 'settings:'.$module, …)` сбрасывается вызовом `flushClass(Settings::class)`. Так читаются настройки модулей, поэтому прогретая страница вообще не обращается к базе. + +## Когда кеш сбрасывается + +Сохранение, удаление или восстановление кешируемой модели через Eloquent (админка, API, MCP, ваш код): + +- сбрасывает карточки записи на всех сайтах и языках; +- сбрасывает карточки записей той же модели, которые её показывают (похожий товар, дочерняя страница); +- увеличивает счётчик списков модели: её списки, значения `remember()` с ней и зависящие от неё карточки пересоберутся при следующем чтении. + +Сохранение сайта сбрасывает его карточки (его домены есть в каждом адресе), сохранение языка — всё. Если сохранение идёт внутри транзакции, карточки сбрасываются ещё раз после коммита, чтобы запрос посередине не оставил старую строку. + +Код, который пишет в обход Eloquent (`DB::table()->update()`, `insert()`), должен сказать об этом сам: + +```php +app(RecordCache::class)->flushClass(Product::class); // одна модель +app(RecordCache::class)->flushSite($siteId); // один сайт +app(RecordCache::class)->flushAll(); // всё +``` + +Кроме того, карточки истекают по TTL (по умолчанию сутки), так что пропущенный сброс со временем исправляется сам. + +## Импорт + +Тысячи сохранений подряд не должны тысячи раз сбрасывать кеш. Оберните импорт: + +```php +app(RecordCache::class)->bulk(function () { + foreach ($rows as $row) { + Product::updateOrCreate(['xml_id' => $row['id']], $row); + } +}); +``` + +Внутри `bulk()` сохранения только отмечают затронутые модели; в конце каждая сбрасывается один раз. Импорт, который пишет через `DB::table()`, передаёт `everything: true`, и в конце один раз сбрасывается весь кеш. Так делает мигратор из Битрикса. + +## Кеш страниц + +Для посетителей без входа можно хранить страницу целиком: второй посетитель получает её из хранилища, контроллер не запускается. + +```dotenv +ATRIUM_PAGE_CACHE=true +``` + +- Ключ — адрес (схема, хост, путь, отсортированные параметры) и сайт; язык входит в адрес. +- Только `GET` и `HEAD`, только HTML-ответы `200`; никогда — админка, вошедший администратор или пользователь, Inertia и ajax, страница, поставившая свою куку или передавшая ошибки или старый ввод, пути из `atrium.cache.pages.except`. Ответ с `Cache-Control: no-store` или заголовком `X-Atrium-No-Cache` не хранится. +- **Токены форм**: CSRF-токен в сохранённой странице на выходе заменяется на токен текущего посетителя, формы продолжают работать. +- Сохранённая страница действительна, пока не изменились карточки, списки и модели, которые она читала: сохранение сбрасывает её сразу. Модели, прочитанные иначе, перечисляются в `atrium.cache.pages.depends_on`. +- В ответе есть `X-Atrium-Cache: HIT` или `MISS`. + +Включайте, проверив, что ни одна страница не показывает посетителю без входа что-то личное (счётчик корзины, «вы смотрели»). Такую страницу внесите в `except` или отправьте заголовок из её контроллера: + +```php +return response()->view('cart')->header('X-Atrium-No-Cache', '1'); +``` + +Компонент, который рисует что-то для одного посетителя, где бы он ни стоял, вызывает вместо этого `app(RecordCache::class)->dontKeepPage()`. Так делает встроенная капча-картинка: на её вопрос можно ответить один раз, поэтому страница с ней не сохраняется. + +## CDN + +Сохранённые страницы отдаются с `ETag` и `Last-Modified`; на запрос с совпавшим `If-None-Match` приходит `304 Not Modified`. + +- Страница без токена формы: `Cache-Control: public, max-age=0, s-maxage=60`. CDN может держать её `ATRIUM_PAGE_CACHE_SHARED_MAX_AGE` секунд, браузер каждый раз спрашивает заново. +- Страница с токеном формы: `Cache-Control: private, no-cache`. Общая копия отдала бы токен одного посетителя другому. + +Группа `web` в Laravel открывает сессию каждому посетителю, поэтому в каждом ответе есть `Set-Cookie`, а большинство CDN не хранят ответ, ставящий куку. Либо настройте CDN не обращать внимания на куку сессии на публичных путях, либо отдавайте публичные страницы без сессии. Atrium не очищает CDN после сохранения: границу устаревания задаёт короткий `s-maxage`. + +## Прогрев, экран в админке и строка отладки + +После выкладки или очистки кеша: + +```bash +php artisan atrium:cache:warm # главная и первая страница каждого списка, все сайты и языки +php artisan atrium:cache:warm --records # плюс карточка каждой записи каждого кешируемого модуля +php artisan atrium:cache:warm --site=main +``` + +Модуль добавляет свои страницы через `app(RecordCache::class)->warmUsing(fn (string $language): iterable => [...])`. + +**Админка → Кеш** (для суперадминов) показывает долю попаданий с последнего сброса, хранилище и есть ли у него теги, число записей и их размер (Redis, файлы и база) и очищает один модуль, один сайт или всё. + +В локальном окружении с `APP_DEBUG=true` у каждой публичной страницы есть заголовок `X-Atrium-Debug` и строка внизу экрана: + +``` +queries=3 (2.1 ms); cache hits=21 misses=0; page cache=off; 18.4 ms +``` + +`ATRIUM_CACHE_DEBUG=false` её скрывает. + +## Настройки + +`config/atrium.php` → `cache`: + +| Ключ | Env | По умолчанию | | +|---|---|---|---| +| `enabled` | `ATRIUM_CACHE_ENABLED` | `true` | Выключен: карточки собираются при каждом чтении, ничего не хранится. | +| `store` | `ATRIUM_CACHE_STORE` | хранилище по умолчанию | Хранилище из `config/cache.php`. | +| `strategy` | `ATRIUM_CACHE_STRATEGY` | `auto` | `auto` (теги, где они есть) или `versions`. | +| `ttl.cards` | `ATRIUM_CACHE_TTL_CARDS` | `86400` | Секунды. | +| `ttl.lists` | `ATRIUM_CACHE_TTL_LISTS` | `3600` | Секунды; и для `remember()`. | +| `ttl.pages` | `ATRIUM_CACHE_TTL_PAGES` | `600` | Секунды. | +| `time_step` | | `60` | До скольких секунд округляется `RecordCache::now()`. | +| `stats` | | `true` | Считать попадания и промахи для экрана в админке. | +| `ignore` | | | Модели, сохранения которых не трогают кеш. | +| `pages.enabled` | `ATRIUM_PAGE_CACHE` | `false` | Кеш страниц. | +| `pages.shared_max_age` | `ATRIUM_PAGE_CACHE_SHARED_MAX_AGE` | `60` | `s-maxage` для CDN. | +| `pages.except` | | `[]` | Пути, которые не хранятся, в виде шаблонов `Request::is()`. | +| `pages.depends_on` | | `[]` | Модели, сохранение которых сбрасывает все страницы. | +| `debug` | `ATRIUM_CACHE_DEBUG` | `true` | Строка отладки (локально, с `APP_DEBUG`). | + +## Замер + +`packages/theme/tests/CacheBenchmarkTest.php` заполняет каталог из 10 000 товаров по 40 свойств (16 строк, 10 чисел, 6 списков, 4 флажка, 2 текста, 2 ссылки на бренд), с переведёнными названием, кодом и текстом, тремя похожими товарами, тремя картинками и SEO, и открывает через тему страницу списка и страницу товара с выключенным, холодным и тёплым кешем и с кешем страниц: + +```bash +ATRIUM_BENCHMARK=1 vendor/bin/phpunit packages/theme/tests/CacheBenchmarkTest.php +``` + +`DB_CONNECTION` выбирает базу, как и для остальных тестов, `ATRIUM_BENCHMARK_STORE` — хранилище, `ATRIUM_BENCHMARK_PRODUCTS` — число товаров. Тест падает, если страница списка на 250-й странице стоит больше запросов, чем на первой, тёплая страница списка или товара делает больше двух запросов, а сохранённая страница — хотя бы один. + +Результаты на 17.11.2026 (PHP 8.4, MySQL 8.4 и PostgreSQL 17 в Docker, Redis 7, медиана пяти запросов; число запросов, затем процессорное время PHP): + +| Страница | Кеш выключен | Холодный кеш | Тёплый кеш | Кеш страниц | +|---|---|---|---|---| +| MySQL, список, стр. 1 | 3 запр., 6,8 мс | 7 запр., 39,0 мс | **0 запр.**, 7,6 мс | **0 запр.**, 1,2 мс | +| MySQL, список, стр. 250 | 3 запр., 6,0 мс | 7 запр., 38,9 мс | **0 запр.**, 8,2 мс | **0 запр.**, 1,2 мс | +| MySQL, товар | 6 запр., 7,7 мс | 6 запр., 11,0 мс | **0 запр.**, 4,9 мс | **0 запр.**, 1,4 мс | +| PostgreSQL, список, стр. 1 | 3 запр., 7,3 мс | 7 запр., 48,3 мс | **0 запр.**, 12,1 мс | **0 запр.**, 1,3 мс | +| PostgreSQL, список, стр. 250 | 3 запр., 7,3 мс | 7 запр., 46,9 мс | **0 запр.**, 15,7 мс | **0 запр.**, 1,7 мс | +| PostgreSQL, товар | 6 запр., 13,7 мс | 6 запр., 17,0 мс | **0 запр.**, 7,7 мс | **0 запр.**, 1,7 мс | + +«Кеш выключен» — это тема, которая читает базу напрямую, как до кеша. Холодный список стоит больше запросов, потому что собирает карточку целиком (бренды, похожие товары, SEO). Страница товара потом читает её даром. На 1-й и 250-й странице запросов столько же. С файловым хранилищем запросов столько же, а процессорного времени примерно вдвое больше. + +Как читать: кеш убирает походы в базу. На тёплом кеше страница не спрашивает у базы ничего, и время перестаёт зависеть от нагрузки на базу и от расстояния до неё. Холодная карточка стоит около 2 мс PHP на запись, один раз. Тёплый список распаковывает 20 карточек и тратит на PHP примерно столько же, сколько чтение 20 строк. Кеш страниц пропускает контроллер и шаблоны: около 1 мс. + +Тест печатает и полное время. В него входят база и хранилище, поэтому оно зависит от нагрузки на машину и сравнимо только внутри одного прогона. diff --git a/docs/modules.md b/docs/modules.md index e4efbe8c..638bb6da 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -236,6 +236,10 @@ $request->validate([ Leave the captcha's fields out of what goes back into the form: `->withInput($request->except(CaptchaManager::INPUTS))`. A captcha of another kind (Cloudflare Turnstile, hCaptcha, your own) is a class with `widget()` and `verify($request)` (`Atrium\Admin\Captcha\CaptchaDriver`), added with `app(CaptchaManager::class)->extend('turnstile', fn () => new Turnstile(...))` and chosen with `ATRIUM_CAPTCHA=turnstile`. +## Cache + +Public pages draw records from the record cache. Add `implements Cacheable` and `use CachesRecords` to the model, and read lists through `->cachedIds()` / `->cachedPaginate()` / `->cachedCards()` instead of `->get()`: a list then asks the database only for IDs, and each record comes from its card, one multi-get for a whole page. Saves through Eloquent drop what they touch; code that writes with `DB::table()` calls `app(RecordCache::class)->flushClass(Article::class)`, and an import runs inside `bulk()`. Everything else, step by step: [cache.md](cache.md). + ## Interface translations Labels may be plain text or translation keys. For a module that is used in more than one language, keep them in `lang/{language}/admin.php` and write `->label(__('admin.articles.name'))`. diff --git a/docs/modules.ru.md b/docs/modules.ru.md index 29e77c39..25793219 100644 --- a/docs/modules.ru.md +++ b/docs/modules.ru.md @@ -236,6 +236,10 @@ $request->validate([ Поля капчи не возвращайте в форму: `->withInput($request->except(CaptchaManager::INPUTS))`. Капча другого вида (Cloudflare Turnstile, hCaptcha, своя) — класс с `widget()` и `verify($request)` (`Atrium\Admin\Captcha\CaptchaDriver`), который добавляют через `app(CaptchaManager::class)->extend('turnstile', fn () => new Turnstile(...))` и выбирают `ATRIUM_CAPTCHA=turnstile`. +## Кеш + +Публичные страницы берут записи из кеша записей. Добавьте модели `implements Cacheable` и `use CachesRecords`, а списки читайте через `->cachedIds()` / `->cachedPaginate()` / `->cachedCards()` вместо `->get()`: тогда список спрашивает у базы только ID, а каждая запись приходит из своей карточки, одним multi-get на всю страницу. Сохранения через Eloquent сбрасывают то, чего касаются; код, который пишет через `DB::table()`, вызывает `app(RecordCache::class)->flushClass(Article::class)`, а импорт идёт внутри `bulk()`. Всё остальное по шагам: [cache.ru.md](cache.ru.md). + ## Переводы интерфейса Подписи могут быть обычным текстом или ключами перевода. Для модуля, которым пользуются на нескольких языках, держите их в `lang/{язык}/admin.php` и пишите `->label(__('admin.articles.name'))`. diff --git a/docs/readme/README.be.md b/docs/readme/README.be.md index 028f20c0..3b8de5e9 100644 --- a/docs/readme/README.be.md +++ b/docs/readme/README.be.md @@ -120,6 +120,7 @@ php artisan atrium:bitrix:parity - [ШІ-памочнік для тэкстаў: бясплатныя і платныя правайдары, апісанні, SEO, alt, пераклады](../ai.md) - [Свой модуль: палі, калонкі, укладкі, правы, мовы, тэсты, пакет](../modules.md) - [Свае палі: дадаць поле ў любы модуль з адмінкі, фільтры і фасеты на 100 000 запісаў](../custom-fields.md) +- [Кэш: хуткія старонкі з дзясяткамі ўласцівасцей, Redis, кэш старонак, загалоўкі для CDN](../cache.md) - [Пераезд з 1С-Бітрыкс крок за крокам](../bitrix.md) - [Рэзервовыя копіі: базы і файлы ў некалькі месцаў, расклад, праверкі, аднаўленне](../backup.md) - [CDN: выявы, паменшаныя копіі і WebP/AVIF, ачыстка кэша, загрузкі ў S3](../cdn.md) diff --git a/docs/readme/README.de.md b/docs/readme/README.de.md index 4eb3b841..52f1fb85 100644 --- a/docs/readme/README.de.md +++ b/docs/readme/README.de.md @@ -120,6 +120,7 @@ Die Bitrix-Datenbank wird nur gelesen. Tabs, Feldreihenfolge und Listenspalten k - [KI-Schreibhilfe: kostenlose und bezahlte Anbieter, Beschreibungen, SEO, Alt-Texte, Übersetzungen](../ai.md) - [Eigenes Modul: Felder, Spalten, Tabs, Rechte, Sprachen, Tests, als Paket](../modules.md) - [Eigene Felder: Felder für jedes Modul im Admin-Bereich anlegen, Filter und Facetten bei 100 000 Einträgen](../custom-fields.md) +- [Cache: schnelle Seiten mit Dutzenden Eigenschaften, Redis, Seiten-Cache, CDN-Header](../cache.md) - [Umzug von 1C-Bitrix, Schritt für Schritt](../bitrix.md) - [Backups: Datenbanken und Dateien an mehrere Orte, Zeitpläne, Prüfungen, Wiederherstellung](../backup.md) - [CDN: Bilder, verkleinerte Kopien und WebP/AVIF, Cache leeren, Uploads zu S3](../cdn.md) diff --git a/docs/readme/README.es.md b/docs/readme/README.es.md index 199e6a11..d085b75b 100644 --- a/docs/readme/README.es.md +++ b/docs/readme/README.es.md @@ -120,6 +120,7 @@ La base de datos de Bitrix solo se lee. Las pestañas, el orden de los campos y - [Ayuda de redacción con IA: proveedores gratuitos y de pago, descripciones, SEO, textos alt, traducciones](../ai.md) - [Tu propio módulo: campos, columnas, pestañas, permisos, idiomas, pruebas, paquete](../modules.md) - [Campos propios: añadir campos a cualquier módulo desde el panel, filtros y facetas con 100 000 registros](../custom-fields.md) +- [Caché: páginas rápidas con decenas de propiedades, Redis, caché de páginas, cabeceras para CDN](../cache.md) - [Migrar desde 1C-Bitrix, paso a paso](../bitrix.md) - [Copias de seguridad: bases de datos y archivos en varios destinos, horarios, comprobaciones, restauración](../backup.md) - [CDN: imágenes, copias redimensionadas y WebP/AVIF, purga de caché, subidas a S3](../cdn.md) diff --git a/docs/readme/README.fr.md b/docs/readme/README.fr.md index 541101f6..ae7ffd1f 100644 --- a/docs/readme/README.fr.md +++ b/docs/readme/README.fr.md @@ -120,6 +120,7 @@ La base de données Bitrix est uniquement lue. Les onglets, l'ordre des champs e - [Aide à la rédaction par IA : fournisseurs gratuits et payants, descriptions, SEO, textes alt, traductions](../ai.md) - [Votre module : champs, colonnes, onglets, droits, langues, tests, paquet](../modules.md) - [Champs personnalisés : ajouter des champs à tout module depuis l'administration, filtres et facettes sur 100 000 fiches](../custom-fields.md) +- [Cache : des pages rapides avec des dizaines de propriétés, Redis, cache de pages, en-têtes CDN](../cache.md) - [Migrer depuis 1C-Bitrix, pas à pas](../bitrix.md) - [Sauvegardes : bases de données et fichiers vers plusieurs destinations, planification, contrôles, restauration](../backup.md) - [CDN : images, copies redimensionnées et WebP/AVIF, purge du cache, envois vers S3](../cdn.md) diff --git a/docs/readme/README.it.md b/docs/readme/README.it.md index d49972ab..eaca51df 100644 --- a/docs/readme/README.it.md +++ b/docs/readme/README.it.md @@ -120,6 +120,7 @@ Il database di Bitrix viene solo letto. Le schede, l'ordine dei campi e le colon - [Aiuto alla scrittura con IA: fornitori gratuiti e a pagamento, descrizioni, SEO, testi alt, traduzioni](../ai.md) - [Il tuo modulo: campi, colonne, schede, permessi, lingue, test, pacchetto](../modules.md) - [Campi personalizzati: aggiungere campi a qualsiasi modulo dal pannello, filtri e faccette su 100 000 record](../custom-fields.md) +- [Cache: pagine veloci con decine di proprietà, Redis, cache delle pagine, intestazioni per CDN](../cache.md) - [Migrare da 1C-Bitrix, passo per passo](../bitrix.md) - [Backup: database e file in più destinazioni, pianificazione, controlli, ripristino](../backup.md) - [CDN: immagini, copie ridimensionate e WebP/AVIF, svuotamento della cache, caricamenti su S3](../cdn.md) diff --git a/docs/readme/README.ja.md b/docs/readme/README.ja.md index e33d16f7..2fc1a5b9 100644 --- a/docs/readme/README.ja.md +++ b/docs/readme/README.ja.md @@ -120,6 +120,7 @@ Bitrix のデータベースは読み取るだけです。タブ、フィール - [AI 文章アシスタント:無料・有料のプロバイダー、説明文、SEO、alt テキスト、翻訳](../ai.md) - [独自モジュール:フィールド、列、タブ、権限、言語、テスト、パッケージ化](../modules.md) - [カスタムフィールド:管理画面から任意のモジュールにフィールドを追加、10 万件でのフィルターとファセット](../custom-fields.md) +- [キャッシュ:数十のプロパティでも速いページ、Redis、ページキャッシュ、CDN ヘッダー](../cache.md) - [1C-Bitrix からの移行(手順)](../bitrix.md) - [バックアップ:データベースとファイルを複数の保存先へ、スケジュール、ヘルスチェック、復元](../backup.md) - [CDN:画像、リサイズしたコピーと WebP/AVIF、キャッシュの削除、S3 へのアップロード](../cdn.md) diff --git a/docs/readme/README.kk.md b/docs/readme/README.kk.md index 37ca91e1..fb3d80d7 100644 --- a/docs/readme/README.kk.md +++ b/docs/readme/README.kk.md @@ -120,6 +120,7 @@ php artisan atrium:bitrix:parity - [Мәтіндерге арналған ЖИ-көмекші: тегін және ақылы провайдерлер, сипаттамалар, SEO, alt, аудармалар](../ai.md) - [Өз модуліңіз: өрістер, бағандар, қойындылар, құқықтар, тілдер, тесттер, пакет](../modules.md) - [Өз өрістеріңіз: кез келген модульге әкімшілік панельден өріс қосу, 100 000 жазбадағы сүзгілер мен фасеттер](../custom-fields.md) +- [Кэш: ондаған қасиеті бар жылдам беттер, Redis, беттер кэші, CDN тақырыптары](../cache.md) - [1С-Битрикстен көшу, қадам-қадаммен](../bitrix.md) - [Сақтық көшірмелер: дерекқорлар мен файлдар бірнеше орынға, кесте, тексерулер, қалпына келтіру](../backup.md) - [CDN: суреттер, кішірейтілген көшірмелер және WebP/AVIF, кэшті тазалау, S3-ке жүктеу](../cdn.md) diff --git a/docs/readme/README.pl.md b/docs/readme/README.pl.md index bbb37d9e..ab332e4e 100644 --- a/docs/readme/README.pl.md +++ b/docs/readme/README.pl.md @@ -120,6 +120,7 @@ Baza danych Bitrixa jest tylko odczytywana. Karty, kolejność pól i kolumny li - [Pomoc AI w pisaniu: darmowi i płatni dostawcy, opisy, SEO, teksty alt, tłumaczenia](../ai.md) - [Własny moduł: pola, kolumny, zakładki, uprawnienia, języki, testy, pakiet](../modules.md) - [Własne pola: dodawanie pól do dowolnego modułu z panelu, filtry i fasety na 100 000 rekordów](../custom-fields.md) +- [Cache: szybkie strony z dziesiątkami właściwości, Redis, cache stron, nagłówki dla CDN](../cache.md) - [Przeprowadzka z 1C-Bitrix krok po kroku](../bitrix.md) - [Kopie zapasowe: bazy danych i pliki w kilku miejscach, harmonogram, kontrole, przywracanie](../backup.md) - [CDN: obrazy, pomniejszone kopie i WebP/AVIF, czyszczenie pamięci podręcznej, przesyłanie do S3](../cdn.md) diff --git a/docs/readme/README.pt-BR.md b/docs/readme/README.pt-BR.md index bca20643..6a9001b0 100644 --- a/docs/readme/README.pt-BR.md +++ b/docs/readme/README.pt-BR.md @@ -120,6 +120,7 @@ O banco de dados do Bitrix é apenas lido. As abas, a ordem dos campos e as colu - [Ajuda de redação com IA: provedores gratuitos e pagos, descrições, SEO, textos alt, traduções](../ai.md) - [Seu próprio módulo: campos, colunas, abas, permissões, idiomas, testes, pacote](../modules.md) - [Campos personalizados: adicionar campos a qualquer módulo pelo painel, filtros e facetas com 100 000 registros](../custom-fields.md) +- [Cache: páginas rápidas com dezenas de propriedades, Redis, cache de páginas, cabeçalhos para CDN](../cache.md) - [Migrar do 1C-Bitrix, passo a passo](../bitrix.md) - [Backups: bancos de dados e arquivos em vários destinos, agendamento, verificações, restauração](../backup.md) - [CDN: imagens, cópias redimensionadas e WebP/AVIF, limpeza de cache, uploads para S3](../cdn.md) diff --git a/docs/readme/README.ru.md b/docs/readme/README.ru.md index 9f498383..61cec146 100644 --- a/docs/readme/README.ru.md +++ b/docs/readme/README.ru.md @@ -118,6 +118,7 @@ php artisan atrium:bitrix:parity - [ИИ-помощник для текстов: бесплатные и платные провайдеры, описания, SEO, alt, переводы](../ai.ru.md) - [Свой модуль: поля, колонки, вкладки, права, языки, тесты, пакет](../modules.ru.md) - [Свои поля: добавить поле в любой модуль из админки, фильтры и фасеты на 100 000 записей](../custom-fields.ru.md) +- [Кеш: быстрые страницы с десятками свойств, Redis, кеш страниц, заголовки для CDN](../cache.ru.md) - [Переезд с 1С-Битрикс по шагам](../bitrix.ru.md) - [Резервные копии: базы и файлы в несколько мест, расписание, проверки, восстановление](../backup.ru.md) - [CDN: картинки, уменьшенные копии и WebP/AVIF, сброс кеша, загрузки в S3](../cdn.ru.md) diff --git a/docs/readme/README.tr.md b/docs/readme/README.tr.md index 0feb9305..0eb437c6 100644 --- a/docs/readme/README.tr.md +++ b/docs/readme/README.tr.md @@ -120,6 +120,7 @@ Bitrix veritabanından yalnızca okuma yapılır. Sekmeler, alan sırası ve lis - [Yapay zekâ yazım yardımı: ücretsiz ve ücretli sağlayıcılar, açıklamalar, SEO, alt metinleri, çeviriler](../ai.md) - [Kendi modülünüz: alanlar, sütunlar, sekmeler, yetkiler, diller, testler, paket](../modules.md) - [Özel alanlar: yönetim panelinden her modüle alan ekleme, 100 000 kayıtta filtreler ve faset sayıları](../custom-fields.md) +- [Önbellek: onlarca özellikli hızlı sayfalar, Redis, sayfa önbelleği, CDN başlıkları](../cache.md) - [1C-Bitrix’ten adım adım taşınma](../bitrix.md) - [Yedekler: veritabanları ve dosyalar birden çok yere, zamanlama, sağlık kontrolleri, geri yükleme](../backup.md) - [CDN: görseller, küçültülmüş kopyalar ve WebP/AVIF, önbellek temizleme, S3'e yükleme](../cdn.md) diff --git a/docs/readme/README.uk.md b/docs/readme/README.uk.md index 8e496faf..1cdeb7a6 100644 --- a/docs/readme/README.uk.md +++ b/docs/readme/README.uk.md @@ -120,6 +120,7 @@ php artisan atrium:bitrix:parity - [ШІ-помічник для текстів: безкоштовні й платні провайдери, описи, SEO, alt, переклади](../ai.md) - [Власний модуль: поля, колонки, вкладки, права, мови, тести, пакет](../modules.md) - [Власні поля: додати поле в будь-який модуль з адмінки, фільтри й фасети на 100 000 записів](../custom-fields.md) +- [Кеш: швидкі сторінки з десятками властивостей, Redis, кеш сторінок, заголовки для CDN](../cache.md) - [Переїзд з 1С-Бітрікс крок за кроком](../bitrix.md) - [Резервні копії: бази й файли в кілька місць, розклад, перевірки, відновлення](../backup.md) - [CDN: зображення, зменшені копії й WebP/AVIF, очищення кешу, завантаження в S3](../cdn.md) diff --git a/docs/readme/README.uz.md b/docs/readme/README.uz.md index 8b2e8fc4..869393de 100644 --- a/docs/readme/README.uz.md +++ b/docs/readme/README.uz.md @@ -120,6 +120,7 @@ Bitrix maʼlumotlar bazasi faqat oʻqiladi. Yorliqlar, maydonlar tartibi va roʻ - [Matnlar uchun SI-yordamchi: bepul va pullik provayderlar, tavsiflar, SEO, alt, tarjimalar](../ai.md) - [Oʻz modulingiz: maydonlar, ustunlar, yorliqlar, huquqlar, tillar, testlar, paket](../modules.md) - [Oʻz maydonlaringiz: istalgan modulga admin paneldan maydon qoʻshish, 100 000 yozuvda filtrlar va fasetlar](../custom-fields.md) +- [Kesh: oʻnlab xususiyatli tez sahifalar, Redis, sahifalar keshi, CDN sarlavhalari](../cache.md) - [1C-Bitrixdan koʻchish, qadamma-qadam](../bitrix.md) - [Zaxira nusxalar: bazalar va fayllar bir nechta joyga, jadval, tekshiruvlar, tiklash](../backup.md) - [CDN: rasmlar, kichraytirilgan nusxalar va WebP/AVIF, keshni tozalash, S3 ga yuklash](../cdn.md) diff --git a/docs/readme/README.zh-CN.md b/docs/readme/README.zh-CN.md index c4ec1873..19436d84 100644 --- a/docs/readme/README.zh-CN.md +++ b/docs/readme/README.zh-CN.md @@ -120,6 +120,7 @@ Bitrix 数据库只读不写。标签页、字段顺序和列表列会保持编 - [AI 写作助手:免费与付费服务商、描述、SEO、alt 文本、翻译](../ai.md) - [自定义模块:字段、列、标签页、权限、语言、测试、打包](../modules.md) - [自定义字段:在后台为任意模块添加字段,10 万条记录上的筛选与分面](../custom-fields.md) +- [缓存:带几十个属性也很快的页面、Redis、页面缓存、CDN 头](../cache.md) - [从 1C-Bitrix 迁移,分步说明](../bitrix.md) - [备份:数据库和文件同时存到多个位置、计划任务、健康检查、恢复](../backup.md) - [CDN:图片、缩放副本与 WebP/AVIF、清除缓存、上传到 S3](../cdn.md) diff --git a/packages/admin/config/atrium.php b/packages/admin/config/atrium.php index b87a5ac2..4211de6f 100644 --- a/packages/admin/config/atrium.php +++ b/packages/admin/config/atrium.php @@ -10,6 +10,7 @@ use Atrium\Admin\Dashboard\Gadgets\PerformanceGadget; use Atrium\Admin\Dashboard\Gadgets\SiteSpeedGadget; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Models\PageTiming; return [ /* @@ -213,6 +214,11 @@ 'route' => 'admin.api-tokens.index', 'icon' => 'settings', ], + [ + 'label' => 'atrium::menu.cache', + 'route' => 'admin.cache.index', + 'icon' => 'settings', + ], ], /* @@ -520,4 +526,51 @@ 'enabled' => (bool) env('ATRIUM_MCP_ENABLED', true), 'path' => 'mcp', ], + + /* + |-------------------------------------------------------------------------- + | Cache + |-------------------------------------------------------------------------- + | + | The record cache (docs/cache.md): lists answer with ids, records come + | from cards built once per language, and saving a record in the admin + | drops what showed it. Works on every Laravel store; Redis is the one to + | use in production (one MGET per list, tags free memory at once). + | + | store a store of config/cache.php, the default one when null + | strategy auto: tags where the store has them (Redis, Memcached), + | version keys elsewhere; versions: version keys everywhere + | ttl seconds: cards, lists of ids, full pages + | time_step lists that compare with "now" (active from/to) see time in + | steps of this many seconds, so their keys stay the same + | ignore models whose saves never touch the cache + | pages full-page cache for visitors who are not logged in to the + | admin; off by default (see docs/cache.md before turning on) + | debug a line under public pages with queries and cache hits, in + | the local environment with APP_DEBUG on + | + */ + 'cache' => [ + 'enabled' => (bool) env('ATRIUM_CACHE_ENABLED', true), + 'store' => env('ATRIUM_CACHE_STORE'), + 'strategy' => env('ATRIUM_CACHE_STRATEGY', 'auto'), + 'ttl' => [ + 'cards' => (int) env('ATRIUM_CACHE_TTL_CARDS', 86400), + 'lists' => (int) env('ATRIUM_CACHE_TTL_LISTS', 3600), + 'pages' => (int) env('ATRIUM_CACHE_TTL_PAGES', 600), + ], + 'time_step' => 60, + 'stats' => true, + 'ignore' => [ + PageTiming::class, + ], + 'pages' => [ + 'enabled' => (bool) env('ATRIUM_PAGE_CACHE', false), + // Seconds a CDN may keep a page without the session's form token. + 'shared_max_age' => (int) env('ATRIUM_PAGE_CACHE_SHARED_MAX_AGE', 60), + // Paths never cached, as Request::is() patterns. + 'except' => [], + ], + 'debug' => (bool) env('ATRIUM_CACHE_DEBUG', true), + ], ]; diff --git a/packages/admin/lang/be/cache.php b/packages/admin/lang/be/cache.php new file mode 100644 index 00000000..98956dbd --- /dev/null +++ b/packages/admin/lang/be/cache.php @@ -0,0 +1,32 @@ + 'Запісы чытаюцца з кэша, а не з базы. Захаванне запісу ў панэлі адразу абнаўляе кэш.', + 'hit_rate' => 'Трапленні ў кэш', + 'hits' => 'Трапленні', + 'misses' => 'Промахі', + 'size' => 'Памер', + 'entries' => 'Запісаў', + 'store' => 'Сховішча', + 'with_tags' => 'З тэгамі', + 'without_tags' => 'Без тэгаў (версіі)', + 'records' => 'Кэш запісаў', + 'pages' => 'Кэш старонак', + 'on' => 'Уключаны', + 'off' => 'Выключаны', + 'clear_hint' => 'Пасля захавання ў панэлі чысціць нічога не трэба. Гэта патрэбна, калі базу мянялі напрамую.', + 'module' => 'Модуль', + 'clear_module' => 'Ачысціць кэш модуля', + 'site' => 'Сайт', + 'clear_site' => 'Ачысціць кэш сайта', + 'clear_all' => 'Ачысціць увесь кэш', + 'reset_stats' => 'Скінуць статыстыку', + 'cleared' => 'Кэш ачышчаны.', +]; diff --git a/packages/admin/lang/be/menu.php b/packages/admin/lang/be/menu.php index a6760078..1a53a246 100644 --- a/packages/admin/lang/be/menu.php +++ b/packages/admin/lang/be/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Адміністратары', 'roles' => 'Ролі', 'api_tokens' => 'Токены API', + 'cache' => 'Кэш', 'languages' => 'Мовы', 'sites' => 'Сайты', 'modules' => 'Модулі', diff --git a/packages/admin/lang/de/cache.php b/packages/admin/lang/de/cache.php new file mode 100644 index 00000000..b20633c5 --- /dev/null +++ b/packages/admin/lang/de/cache.php @@ -0,0 +1,32 @@ + 'Datensätze werden aus dem Cache statt aus der Datenbank gelesen. Speichern im Panel aktualisiert ihn sofort.', + 'hit_rate' => 'Trefferquote', + 'hits' => 'Treffer', + 'misses' => 'Fehlgriffe', + 'size' => 'Größe', + 'entries' => 'Einträge', + 'store' => 'Speicher', + 'with_tags' => 'Mit Tags', + 'without_tags' => 'Ohne Tags (Versionen)', + 'records' => 'Datensatz-Cache', + 'pages' => 'Seiten-Cache', + 'on' => 'An', + 'off' => 'Aus', + 'clear_hint' => 'Nach dem Speichern im Panel ist kein Leeren nötig. Es hilft, wenn die Datenbank direkt geändert wurde.', + 'module' => 'Modul', + 'clear_module' => 'Modul-Cache leeren', + 'site' => 'Website', + 'clear_site' => 'Website-Cache leeren', + 'clear_all' => 'Gesamten Cache leeren', + 'reset_stats' => 'Statistik zurücksetzen', + 'cleared' => 'Der Cache wurde geleert.', +]; diff --git a/packages/admin/lang/de/menu.php b/packages/admin/lang/de/menu.php index 179cc122..c0416e3d 100644 --- a/packages/admin/lang/de/menu.php +++ b/packages/admin/lang/de/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administratoren', 'roles' => 'Rollen', 'api_tokens' => 'API-Tokens', + 'cache' => 'Cache', 'languages' => 'Sprachen', 'sites' => 'Websites', 'modules' => 'Module', diff --git a/packages/admin/lang/en/cache.php b/packages/admin/lang/en/cache.php new file mode 100644 index 00000000..354128db --- /dev/null +++ b/packages/admin/lang/en/cache.php @@ -0,0 +1,32 @@ + 'Records are read from the cache instead of the database. Saving a record in the panel updates it at once.', + 'hit_rate' => 'Hit rate', + 'hits' => 'Hits', + 'misses' => 'Misses', + 'size' => 'Size', + 'entries' => 'Entries', + 'store' => 'Store', + 'with_tags' => 'With tags', + 'without_tags' => 'Without tags (versions)', + 'records' => 'Record cache', + 'pages' => 'Page cache', + 'on' => 'On', + 'off' => 'Off', + 'clear_hint' => 'Clearing is never needed after saving in the panel. It helps after changing the database directly.', + 'module' => 'Module', + 'clear_module' => 'Clear module cache', + 'site' => 'Site', + 'clear_site' => 'Clear site cache', + 'clear_all' => 'Clear all cache', + 'reset_stats' => 'Reset statistics', + 'cleared' => 'The cache is cleared.', +]; diff --git a/packages/admin/lang/en/menu.php b/packages/admin/lang/en/menu.php index 349de9b6..05bf3699 100644 --- a/packages/admin/lang/en/menu.php +++ b/packages/admin/lang/en/menu.php @@ -12,6 +12,7 @@ 'administrators' => 'Administrators', 'roles' => 'Roles', 'api_tokens' => 'API tokens', + 'cache' => 'Cache', 'languages' => 'Languages', 'sites' => 'Sites', 'modules' => 'Modules', diff --git a/packages/admin/lang/es/cache.php b/packages/admin/lang/es/cache.php new file mode 100644 index 00000000..db43b2b6 --- /dev/null +++ b/packages/admin/lang/es/cache.php @@ -0,0 +1,32 @@ + 'Los registros se leen de la caché en lugar de la base de datos. Guardar en el panel la actualiza al instante.', + 'hit_rate' => 'Tasa de aciertos', + 'hits' => 'Aciertos', + 'misses' => 'Fallos', + 'size' => 'Tamaño', + 'entries' => 'Entradas', + 'store' => 'Almacén', + 'with_tags' => 'Con etiquetas', + 'without_tags' => 'Sin etiquetas (versiones)', + 'records' => 'Caché de registros', + 'pages' => 'Caché de páginas', + 'on' => 'Activada', + 'off' => 'Desactivada', + 'clear_hint' => 'Tras guardar en el panel no hace falta vaciar nada. Sirve si la base de datos se cambió directamente.', + 'module' => 'Módulo', + 'clear_module' => 'Vaciar caché del módulo', + 'site' => 'Sitio', + 'clear_site' => 'Vaciar caché del sitio', + 'clear_all' => 'Vaciar toda la caché', + 'reset_stats' => 'Restablecer estadísticas', + 'cleared' => 'La caché se ha vaciado.', +]; diff --git a/packages/admin/lang/es/menu.php b/packages/admin/lang/es/menu.php index 0e19fb71..a4b6d2fb 100644 --- a/packages/admin/lang/es/menu.php +++ b/packages/admin/lang/es/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administradores', 'roles' => 'Roles', 'api_tokens' => 'Tokens de API', + 'cache' => 'Caché', 'languages' => 'Idiomas', 'sites' => 'Sitios', 'modules' => 'Módulos', diff --git a/packages/admin/lang/fr/cache.php b/packages/admin/lang/fr/cache.php new file mode 100644 index 00000000..505084d7 --- /dev/null +++ b/packages/admin/lang/fr/cache.php @@ -0,0 +1,32 @@ + 'Les enregistrements sont lus depuis le cache plutôt que la base. Un enregistrement dans le panneau le met à jour aussitôt.', + 'hit_rate' => 'Taux de succès', + 'hits' => 'Succès', + 'misses' => 'Échecs', + 'size' => 'Taille', + 'entries' => 'Entrées', + 'store' => 'Stockage', + 'with_tags' => 'Avec étiquettes', + 'without_tags' => 'Sans étiquettes (versions)', + 'records' => 'Cache des enregistrements', + 'pages' => 'Cache des pages', + 'on' => 'Activé', + 'off' => 'Désactivé', + 'clear_hint' => 'Après un enregistrement dans le panneau, rien à vider. Utile si la base a été modifiée directement.', + 'module' => 'Module', + 'clear_module' => 'Vider le cache du module', + 'site' => 'Site', + 'clear_site' => 'Vider le cache du site', + 'clear_all' => 'Vider tout le cache', + 'reset_stats' => 'Réinitialiser les statistiques', + 'cleared' => 'Le cache est vidé.', +]; diff --git a/packages/admin/lang/fr/menu.php b/packages/admin/lang/fr/menu.php index 76426d10..cdbb1884 100644 --- a/packages/admin/lang/fr/menu.php +++ b/packages/admin/lang/fr/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administrateurs', 'roles' => 'Rôles', 'api_tokens' => 'Jetons API', + 'cache' => 'Cache', 'languages' => 'Langues', 'sites' => 'Sites', 'modules' => 'Modules', diff --git a/packages/admin/lang/it/cache.php b/packages/admin/lang/it/cache.php new file mode 100644 index 00000000..72aae0ad --- /dev/null +++ b/packages/admin/lang/it/cache.php @@ -0,0 +1,32 @@ + 'I record vengono letti dalla cache invece che dal database. Salvare nel pannello la aggiorna subito.', + 'hit_rate' => 'Percentuale di successo', + 'hits' => 'Successi', + 'misses' => 'Mancati', + 'size' => 'Dimensione', + 'entries' => 'Voci', + 'store' => 'Archivio', + 'with_tags' => 'Con tag', + 'without_tags' => 'Senza tag (versioni)', + 'records' => 'Cache dei record', + 'pages' => 'Cache delle pagine', + 'on' => 'Attiva', + 'off' => 'Disattiva', + 'clear_hint' => 'Dopo un salvataggio nel pannello non serve svuotare nulla. Serve se il database è stato modificato direttamente.', + 'module' => 'Modulo', + 'clear_module' => 'Svuota cache del modulo', + 'site' => 'Sito', + 'clear_site' => 'Svuota cache del sito', + 'clear_all' => 'Svuota tutta la cache', + 'reset_stats' => 'Azzera statistiche', + 'cleared' => 'La cache è stata svuotata.', +]; diff --git a/packages/admin/lang/it/menu.php b/packages/admin/lang/it/menu.php index 856d2206..bed6bedf 100644 --- a/packages/admin/lang/it/menu.php +++ b/packages/admin/lang/it/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Amministratori', 'roles' => 'Ruoli', 'api_tokens' => 'Token API', + 'cache' => 'Cache', 'languages' => 'Lingue', 'sites' => 'Siti', 'modules' => 'Moduli', diff --git a/packages/admin/lang/ja/cache.php b/packages/admin/lang/ja/cache.php new file mode 100644 index 00000000..b3db1504 --- /dev/null +++ b/packages/admin/lang/ja/cache.php @@ -0,0 +1,32 @@ + 'レコードはデータベースではなくキャッシュから読み込まれます。パネルで保存するとすぐに更新されます。', + 'hit_rate' => 'ヒット率', + 'hits' => 'ヒット', + 'misses' => 'ミス', + 'size' => 'サイズ', + 'entries' => 'エントリ', + 'store' => 'ストア', + 'with_tags' => 'タグあり', + 'without_tags' => 'タグなし(バージョン)', + 'records' => 'レコードキャッシュ', + 'pages' => 'ページキャッシュ', + 'on' => 'オン', + 'off' => 'オフ', + 'clear_hint' => 'パネルで保存した後にクリアする必要はありません。データベースを直接変更したときに使います。', + 'module' => 'モジュール', + 'clear_module' => 'モジュールのキャッシュをクリア', + 'site' => 'サイト', + 'clear_site' => 'サイトのキャッシュをクリア', + 'clear_all' => 'すべてのキャッシュをクリア', + 'reset_stats' => '統計をリセット', + 'cleared' => 'キャッシュをクリアしました。', +]; diff --git a/packages/admin/lang/ja/menu.php b/packages/admin/lang/ja/menu.php index 6454fddb..585c5f60 100644 --- a/packages/admin/lang/ja/menu.php +++ b/packages/admin/lang/ja/menu.php @@ -14,6 +14,7 @@ 'administrators' => '管理者', 'roles' => 'ロール', 'api_tokens' => 'API トークン', + 'cache' => 'キャッシュ', 'languages' => '言語', 'sites' => 'サイト', 'modules' => 'モジュール', diff --git a/packages/admin/lang/kk/cache.php b/packages/admin/lang/kk/cache.php new file mode 100644 index 00000000..8634b0d8 --- /dev/null +++ b/packages/admin/lang/kk/cache.php @@ -0,0 +1,32 @@ + 'Жазбалар дерекқордан емес, кэштен оқылады. Панельде сақтау оны бірден жаңартады.', + 'hit_rate' => 'Кэшке түсу үлесі', + 'hits' => 'Түсулер', + 'misses' => 'Түспеулер', + 'size' => 'Көлемі', + 'entries' => 'Жазбалар', + 'store' => 'Қойма', + 'with_tags' => 'Тегтермен', + 'without_tags' => 'Тегтерсіз (нұсқалар)', + 'records' => 'Жазбалар кэші', + 'pages' => 'Беттер кэші', + 'on' => 'Қосулы', + 'off' => 'Өшірулі', + 'clear_hint' => 'Панельде сақтағаннан кейін ештеңе тазалаудың қажеті жоқ. Дерекқор тікелей өзгертілгенде керек.', + 'module' => 'Модуль', + 'clear_module' => 'Модуль кэшін тазалау', + 'site' => 'Сайт', + 'clear_site' => 'Сайт кэшін тазалау', + 'clear_all' => 'Барлық кэшті тазалау', + 'reset_stats' => 'Статистиканы нөлдеу', + 'cleared' => 'Кэш тазаланды.', +]; diff --git a/packages/admin/lang/kk/menu.php b/packages/admin/lang/kk/menu.php index c1af57b8..eb6f69e0 100644 --- a/packages/admin/lang/kk/menu.php +++ b/packages/admin/lang/kk/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Әкімшілер', 'roles' => 'Рөлдер', 'api_tokens' => 'API токендері', + 'cache' => 'Кэш', 'languages' => 'Тілдер', 'sites' => 'Сайттар', 'modules' => 'Модульдер', diff --git a/packages/admin/lang/pl/cache.php b/packages/admin/lang/pl/cache.php new file mode 100644 index 00000000..6e89f978 --- /dev/null +++ b/packages/admin/lang/pl/cache.php @@ -0,0 +1,32 @@ + 'Rekordy są czytane z pamięci podręcznej zamiast z bazy. Zapis w panelu od razu ją aktualizuje.', + 'hit_rate' => 'Trafienia w cache', + 'hits' => 'Trafienia', + 'misses' => 'Chybienia', + 'size' => 'Rozmiar', + 'entries' => 'Wpisy', + 'store' => 'Magazyn', + 'with_tags' => 'Z tagami', + 'without_tags' => 'Bez tagów (wersje)', + 'records' => 'Cache rekordów', + 'pages' => 'Cache stron', + 'on' => 'Włączony', + 'off' => 'Wyłączony', + 'clear_hint' => 'Po zapisie w panelu nic nie trzeba czyścić. Pomaga, gdy baza była zmieniana bezpośrednio.', + 'module' => 'Moduł', + 'clear_module' => 'Wyczyść cache modułu', + 'site' => 'Strona', + 'clear_site' => 'Wyczyść cache strony', + 'clear_all' => 'Wyczyść cały cache', + 'reset_stats' => 'Wyzeruj statystyki', + 'cleared' => 'Cache wyczyszczony.', +]; diff --git a/packages/admin/lang/pl/menu.php b/packages/admin/lang/pl/menu.php index 8a66dc95..d7d49c18 100644 --- a/packages/admin/lang/pl/menu.php +++ b/packages/admin/lang/pl/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administratorzy', 'roles' => 'Role', 'api_tokens' => 'Tokeny API', + 'cache' => 'Cache', 'languages' => 'Języki', 'sites' => 'Witryny', 'modules' => 'Moduły', diff --git a/packages/admin/lang/pt_BR/cache.php b/packages/admin/lang/pt_BR/cache.php new file mode 100644 index 00000000..106961c5 --- /dev/null +++ b/packages/admin/lang/pt_BR/cache.php @@ -0,0 +1,32 @@ + 'Os registros são lidos do cache em vez do banco de dados. Salvar no painel o atualiza na hora.', + 'hit_rate' => 'Taxa de acertos', + 'hits' => 'Acertos', + 'misses' => 'Falhas', + 'size' => 'Tamanho', + 'entries' => 'Entradas', + 'store' => 'Armazenamento', + 'with_tags' => 'Com tags', + 'without_tags' => 'Sem tags (versões)', + 'records' => 'Cache de registros', + 'pages' => 'Cache de páginas', + 'on' => 'Ligado', + 'off' => 'Desligado', + 'clear_hint' => 'Depois de salvar no painel, não é preciso limpar nada. Ajuda quando o banco foi alterado diretamente.', + 'module' => 'Módulo', + 'clear_module' => 'Limpar cache do módulo', + 'site' => 'Site', + 'clear_site' => 'Limpar cache do site', + 'clear_all' => 'Limpar todo o cache', + 'reset_stats' => 'Zerar estatísticas', + 'cleared' => 'O cache foi limpo.', +]; diff --git a/packages/admin/lang/pt_BR/menu.php b/packages/admin/lang/pt_BR/menu.php index 58d4d891..63dcef2d 100644 --- a/packages/admin/lang/pt_BR/menu.php +++ b/packages/admin/lang/pt_BR/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administradores', 'roles' => 'Papéis', 'api_tokens' => 'Tokens de API', + 'cache' => 'Cache', 'languages' => 'Idiomas', 'sites' => 'Sites', 'modules' => 'Módulos', diff --git a/packages/admin/lang/ru/cache.php b/packages/admin/lang/ru/cache.php new file mode 100644 index 00000000..3b07967c --- /dev/null +++ b/packages/admin/lang/ru/cache.php @@ -0,0 +1,32 @@ + 'Записи читаются из кеша, а не из базы. Сохранение записи в панели сразу обновляет кеш.', + 'hit_rate' => 'Попадания в кеш', + 'hits' => 'Попадания', + 'misses' => 'Промахи', + 'size' => 'Размер', + 'entries' => 'Записей', + 'store' => 'Хранилище', + 'with_tags' => 'С тегами', + 'without_tags' => 'Без тегов (версии)', + 'records' => 'Кеш записей', + 'pages' => 'Кеш страниц', + 'on' => 'Включён', + 'off' => 'Выключен', + 'clear_hint' => 'После сохранения в панели чистить ничего не нужно. Это нужно, если база менялась напрямую.', + 'module' => 'Модуль', + 'clear_module' => 'Очистить кеш модуля', + 'site' => 'Сайт', + 'clear_site' => 'Очистить кеш сайта', + 'clear_all' => 'Очистить весь кеш', + 'reset_stats' => 'Сбросить статистику', + 'cleared' => 'Кеш очищен.', +]; diff --git a/packages/admin/lang/ru/menu.php b/packages/admin/lang/ru/menu.php index 7b44a1fb..02339ff8 100644 --- a/packages/admin/lang/ru/menu.php +++ b/packages/admin/lang/ru/menu.php @@ -12,6 +12,7 @@ 'administrators' => 'Администраторы', 'roles' => 'Роли', 'api_tokens' => 'API-токены', + 'cache' => 'Кеш', 'languages' => 'Языки', 'sites' => 'Сайты', 'modules' => 'Модули', diff --git a/packages/admin/lang/tr/cache.php b/packages/admin/lang/tr/cache.php new file mode 100644 index 00000000..47065260 --- /dev/null +++ b/packages/admin/lang/tr/cache.php @@ -0,0 +1,32 @@ + 'Kayıtlar veritabanı yerine önbellekten okunur. Panelde kaydetmek onu hemen günceller.', + 'hit_rate' => 'İsabet oranı', + 'hits' => 'İsabetler', + 'misses' => 'Iskalar', + 'size' => 'Boyut', + 'entries' => 'Girdiler', + 'store' => 'Depo', + 'with_tags' => 'Etiketli', + 'without_tags' => 'Etiketsiz (sürümler)', + 'records' => 'Kayıt önbelleği', + 'pages' => 'Sayfa önbelleği', + 'on' => 'Açık', + 'off' => 'Kapalı', + 'clear_hint' => 'Panelde kaydettikten sonra temizlemek gerekmez. Veritabanı doğrudan değiştirildiğinde işe yarar.', + 'module' => 'Modül', + 'clear_module' => 'Modül önbelleğini temizle', + 'site' => 'Site', + 'clear_site' => 'Site önbelleğini temizle', + 'clear_all' => 'Tüm önbelleği temizle', + 'reset_stats' => 'İstatistikleri sıfırla', + 'cleared' => 'Önbellek temizlendi.', +]; diff --git a/packages/admin/lang/tr/menu.php b/packages/admin/lang/tr/menu.php index f1370368..46229471 100644 --- a/packages/admin/lang/tr/menu.php +++ b/packages/admin/lang/tr/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Yöneticiler', 'roles' => 'Roller', 'api_tokens' => 'API tokenları', + 'cache' => 'Önbellek', 'languages' => 'Diller', 'sites' => 'Siteler', 'modules' => 'Modüller', diff --git a/packages/admin/lang/uk/cache.php b/packages/admin/lang/uk/cache.php new file mode 100644 index 00000000..e964bb31 --- /dev/null +++ b/packages/admin/lang/uk/cache.php @@ -0,0 +1,32 @@ + 'Записи читаються з кешу, а не з бази. Збереження запису в панелі одразу оновлює кеш.', + 'hit_rate' => 'Влучання в кеш', + 'hits' => 'Влучання', + 'misses' => 'Промахи', + 'size' => 'Розмір', + 'entries' => 'Записів', + 'store' => 'Сховище', + 'with_tags' => 'З тегами', + 'without_tags' => 'Без тегів (версії)', + 'records' => 'Кеш записів', + 'pages' => 'Кеш сторінок', + 'on' => 'Увімкнено', + 'off' => 'Вимкнено', + 'clear_hint' => 'Після збереження в панелі очищати нічого не треба. Це потрібно, якщо базу змінювали напряму.', + 'module' => 'Модуль', + 'clear_module' => 'Очистити кеш модуля', + 'site' => 'Сайт', + 'clear_site' => 'Очистити кеш сайту', + 'clear_all' => 'Очистити весь кеш', + 'reset_stats' => 'Скинути статистику', + 'cleared' => 'Кеш очищено.', +]; diff --git a/packages/admin/lang/uk/menu.php b/packages/admin/lang/uk/menu.php index 0c8e6c9c..b0742dbd 100644 --- a/packages/admin/lang/uk/menu.php +++ b/packages/admin/lang/uk/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Адміністратори', 'roles' => 'Ролі', 'api_tokens' => 'Токени API', + 'cache' => 'Кеш', 'languages' => 'Мови', 'sites' => 'Сайти', 'modules' => 'Модулі', diff --git a/packages/admin/lang/uz/cache.php b/packages/admin/lang/uz/cache.php new file mode 100644 index 00000000..c3c16241 --- /dev/null +++ b/packages/admin/lang/uz/cache.php @@ -0,0 +1,32 @@ + 'Yozuvlar maʼlumotlar bazasidan emas, keshdan oʻqiladi. Panelda saqlash uni darhol yangilaydi.', + 'hit_rate' => 'Keshga tushish ulushi', + 'hits' => 'Tushishlar', + 'misses' => 'Tushmasliklar', + 'size' => 'Hajmi', + 'entries' => 'Yozuvlar', + 'store' => 'Ombor', + 'with_tags' => 'Teglar bilan', + 'without_tags' => 'Teglarsiz (versiyalar)', + 'records' => 'Yozuvlar keshi', + 'pages' => 'Sahifalar keshi', + 'on' => 'Yoqilgan', + 'off' => 'Oʻchirilgan', + 'clear_hint' => 'Panelda saqlagandan keyin hech narsani tozalash shart emas. Bu bazani toʻgʻridan-toʻgʻri oʻzgartirganda kerak.', + 'module' => 'Modul', + 'clear_module' => 'Modul keshini tozalash', + 'site' => 'Sayt', + 'clear_site' => 'Sayt keshini tozalash', + 'clear_all' => 'Butun keshni tozalash', + 'reset_stats' => 'Statistikani nolga tushirish', + 'cleared' => 'Kesh tozalandi.', +]; diff --git a/packages/admin/lang/uz/menu.php b/packages/admin/lang/uz/menu.php index 878f9f38..392d85d1 100644 --- a/packages/admin/lang/uz/menu.php +++ b/packages/admin/lang/uz/menu.php @@ -14,6 +14,7 @@ 'administrators' => 'Administratorlar', 'roles' => 'Rollar', 'api_tokens' => 'API tokenlari', + 'cache' => 'Kesh', 'languages' => 'Tillar', 'sites' => 'Saytlar', 'modules' => 'Modullar', diff --git a/packages/admin/lang/zh_CN/cache.php b/packages/admin/lang/zh_CN/cache.php new file mode 100644 index 00000000..2e0fc9b6 --- /dev/null +++ b/packages/admin/lang/zh_CN/cache.php @@ -0,0 +1,32 @@ + '记录从缓存而不是数据库读取。在面板中保存会立即更新缓存。', + 'hit_rate' => '命中率', + 'hits' => '命中', + 'misses' => '未命中', + 'size' => '大小', + 'entries' => '条目', + 'store' => '存储', + 'with_tags' => '带标签', + 'without_tags' => '无标签(版本)', + 'records' => '记录缓存', + 'pages' => '页面缓存', + 'on' => '开启', + 'off' => '关闭', + 'clear_hint' => '在面板中保存后无需清除。仅在直接修改数据库后需要。', + 'module' => '模块', + 'clear_module' => '清除模块缓存', + 'site' => '站点', + 'clear_site' => '清除站点缓存', + 'clear_all' => '清除全部缓存', + 'reset_stats' => '重置统计', + 'cleared' => '缓存已清除。', +]; diff --git a/packages/admin/lang/zh_CN/menu.php b/packages/admin/lang/zh_CN/menu.php index ee0dcf49..d36dd574 100644 --- a/packages/admin/lang/zh_CN/menu.php +++ b/packages/admin/lang/zh_CN/menu.php @@ -14,6 +14,7 @@ 'administrators' => '管理员', 'roles' => '角色', 'api_tokens' => 'API 令牌', + 'cache' => '缓存', 'languages' => '语言', 'sites' => '站点', 'modules' => '模块', diff --git a/packages/admin/resources/js/Pages/Admin/Cache/Index.vue b/packages/admin/resources/js/Pages/Admin/Cache/Index.vue new file mode 100644 index 00000000..57d18f60 --- /dev/null +++ b/packages/admin/resources/js/Pages/Admin/Cache/Index.vue @@ -0,0 +1,115 @@ + + + diff --git a/packages/admin/routes/admin.php b/packages/admin/routes/admin.php index df324a1c..b51b54e9 100644 --- a/packages/admin/routes/admin.php +++ b/packages/admin/routes/admin.php @@ -10,6 +10,7 @@ use Atrium\Admin\Http\Controllers\AdminUserController; use Atrium\Admin\Http\Controllers\ApiTokenController; use Atrium\Admin\Http\Controllers\Auth\LoginController; +use Atrium\Admin\Http\Controllers\CacheController; use Atrium\Admin\Http\Controllers\DashboardController; use Atrium\Admin\Http\Controllers\FileManagerController; use Atrium\Admin\Http\Controllers\LocaleController; @@ -72,6 +73,10 @@ Route::post('api-tokens', [ApiTokenController::class, 'store'])->name('admin.api-tokens.store'); Route::delete('api-tokens/{id}', [ApiTokenController::class, 'destroy'])->whereNumber('id')->name('admin.api-tokens.destroy'); + // The record cache: hit rate, size, clearing — superadmins only + Route::get('cache', [CacheController::class, 'index'])->name('admin.cache.index'); + Route::post('cache/clear', [CacheController::class, 'clear'])->name('admin.cache.clear'); + // Admin Users (Administrators) Route::resource('users', AdminUserController::class)->except(['show'])->names([ 'index' => 'admin.users.index', diff --git a/packages/admin/src/AtriumServiceProvider.php b/packages/admin/src/AtriumServiceProvider.php index 3f54377b..6c06e124 100644 --- a/packages/admin/src/AtriumServiceProvider.php +++ b/packages/admin/src/AtriumServiceProvider.php @@ -12,12 +12,17 @@ use Atrium\Admin\Api\ApiResources; use Atrium\Admin\Auth\Permissions; use Atrium\Admin\Auth\SignIn; +use Atrium\Admin\Cache\CacheStore; +use Atrium\Admin\Cache\RecordCache; +use Atrium\Admin\Cache\Versions; use Atrium\Admin\Captcha\CaptchaManager; use Atrium\Admin\Contracts\Sitemapable; use Atrium\Admin\Hooks\Hooks; use Atrium\Admin\Http\Middleware\AdminAuthenticate; use Atrium\Admin\Http\Middleware\AuthenticateApiToken; use Atrium\Admin\Http\Middleware\AuthorizeAdminRoute; +use Atrium\Admin\Http\Middleware\CacheDebug; +use Atrium\Admin\Http\Middleware\CachePages; use Atrium\Admin\Http\Middleware\EnterSiteFolder; use Atrium\Admin\Http\Middleware\HandleAtriumRequests; use Atrium\Admin\Http\Middleware\RecordPageTiming; @@ -38,6 +43,9 @@ use Atrium\Admin\Support\Sites; use Closure; use Illuminate\Contracts\Http\Kernel as HttpKernel; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Queue\Events\JobProcessing; use Illuminate\Routing\Router; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Blade; @@ -99,6 +107,9 @@ public function register(): void return redirect()->intended(route(config('atrium.auth.redirect_after_login', 'admin.dashboard'))); }); }); + $this->app->singleton(CacheStore::class, fn (): CacheStore => CacheStore::fromConfig()); + $this->app->singleton(Versions::class, fn ($app): Versions => new Versions($app->make(CacheStore::class)->repository())); + $this->app->singleton(RecordCache::class); } public function boot(): void @@ -109,6 +120,7 @@ public function boot(): void $this->registerRoutes(); $this->registerLocalizedRoutes(); $this->registerSitemapFlush(); + $this->registerCache(); $this->registerCommands(); $this->registerCdnAssets(); } @@ -160,6 +172,12 @@ private function registerMiddleware(): void $this->app->make(HttpKernel::class)->pushMiddleware(EnterSiteFolder::class); $this->appendToWebGroup(ResolveSite::class); + // The full-page cache (off by default) wraps the page once the site + // is known; the debug line goes around everything to count hits too. + // Both check their settings on every request and step aside. + $this->appendToWebGroup(CachePages::class); + $this->app->make(HttpKernel::class)->pushMiddleware(CacheDebug::class); + // Page timings feed the dashboard gadgets. Added here so the gadgets // work right after install, without editing bootstrap/app.php. if (config('atrium.dashboard.timings.enabled', true)) { @@ -272,6 +290,69 @@ private function registerSitemapFlush(): void Event::listen('eloquent.deleted: *', $flush); } + /** + * The record cache: query macros, dropping what a saved record showed, + * a clean slate for every request and job. + */ + private function registerCache(): void + { + Builder::macro('cachedIds', function (?int $perPage = null, ?int $page = null, array $dependsOn = []) { + /** @var Builder $this */ + return app(RecordCache::class)->ids($this, $perPage, $page, $dependsOn); + }); + + Builder::macro('cachedPaginate', function (int $perPage = 20, string $pageName = 'page', ?int $page = null, ?string $locale = null, array $dependsOn = []) { + /** @var Builder $this */ + return app(RecordCache::class)->paginate($this, $perPage, $pageName, $page, $locale, $dependsOn); + }); + + Builder::macro('cachedCards', function (?string $locale = null, array $dependsOn = []) { + /** @var Builder $this */ + $cache = app(RecordCache::class); + + return $cache->cards($this->getModel()::class, $cache->ids($this, dependsOn: $dependsOn)->ids, $locale); + }); + + // A cached page depends on the class of every model it read. + Event::listen('eloquent.retrieved: *', function (string $event): void { + if (config('atrium.cache.pages.enabled', false)) { + $this->app->make(RecordCache::class)->markRead(['list:'.substr($event, 20)]); + } + }); + + $changed = function (string $event, array $payload): void { + if (($payload[0] ?? null) instanceof Model) { + $this->app->make(RecordCache::class)->changed($payload[0]); + } + }; + + foreach (['saved', 'deleted', 'restored', 'forceDeleted'] as $event) { + Event::listen('eloquent.'.$event.': *', $changed); + } + + $reset = function (): void { + if ($this->app->resolved(RecordCache::class)) { + $cache = $this->app->make(RecordCache::class); + $cache->persistStats(); + $cache->reset(); + } + }; + + $this->app->terminating($reset); + Event::listen(JobProcessing::class, $reset); + + // The monitoring module reads this request's hits and misses at the + // very end, after reset() may already have closed them. + $this->app->make(Hooks::class)->filter('atrium.cache.stats', function (array $stats): array { + $own = $this->app->make(RecordCache::class)->finishedStats(); + + return [ + 'hits' => (int) ($stats['hits'] ?? 0) + $own['hits'], + 'misses' => (int) ($stats['misses'] ?? 0) + $own['misses'], + ] + $stats; + }); + } + private function registerCommands(): void { if (! $this->app->runningInConsole()) { @@ -279,6 +360,7 @@ private function registerCommands(): void } $this->commands([ + Console\Commands\CacheWarmCommand::class, Console\Commands\CdnPurgeCommand::class, Console\Commands\CreateAdminCommand::class, Console\Commands\IndexMediaCommand::class, diff --git a/packages/admin/src/Auth/Permissions.php b/packages/admin/src/Auth/Permissions.php index 9b287f83..936a9a0a 100644 --- a/packages/admin/src/Auth/Permissions.php +++ b/packages/admin/src/Auth/Permissions.php @@ -242,7 +242,7 @@ private function routePermission(?string $routeName): ?string return null; } - if (str_starts_with($routeName, 'admin.roles.')) { + if (str_starts_with($routeName, 'admin.roles.') || str_starts_with($routeName, 'admin.cache.')) { return self::SUPERADMIN; } diff --git a/packages/admin/src/Cache/CacheStore.php b/packages/admin/src/Cache/CacheStore.php new file mode 100644 index 00000000..882a0a73 --- /dev/null +++ b/packages/admin/src/Cache/CacheStore.php @@ -0,0 +1,221 @@ + group => key prefix of its tagged entries */ + private array $prefixes = []; + + public function __construct( + private readonly Repository $repository, + private readonly bool $tags, + ) {} + + public static function fromConfig(): self + { + $repository = cache()->store(config('atrium.cache.store')); + $strategy = (string) config('atrium.cache.strategy', 'auto'); + $taggable = $repository instanceof CacheRepository && $repository->getStore() instanceof TaggableStore; + + return new self($repository, $taggable && $strategy !== 'versions'); + } + + public function repository(): Repository + { + return $this->repository; + } + + public function usesTags(): bool + { + return $this->tags; + } + + public function driver(): string + { + if (! $this->repository instanceof CacheRepository) { + return 'custom'; + } + + $store = $this->repository->getStore(); + + return strtolower((string) preg_replace('/Store$/', '', class_basename($store))); + } + + /** + * How much the store holds, where it can tell: the whole store (the + * record cache shares it with the application's own entries). + * + * @return array{entries:int|null,bytes:int|null} + */ + public function size(): array + { + $size = ['entries' => null, 'bytes' => null]; + + if (! $this->repository instanceof CacheRepository) { + return $size; + } + + $store = $this->repository->getStore(); + + try { + if ($store instanceof RedisStore) { + $connection = $store->connection(); + $size['entries'] = (int) $connection->command('dbsize'); + $info = (array) $connection->command('info', ['memory']); + $memory = $info['Memory'] ?? $info; + $size['bytes'] = isset($memory['used_memory']) ? (int) $memory['used_memory'] : null; + } elseif ($store instanceof FileStore) { + $entries = 0; + $bytes = 0; + + foreach ($store->getFilesystem()->allFiles($store->getDirectory()) as $file) { + $entries++; + $bytes += $file->getSize(); + } + + $size = ['entries' => $entries, 'bytes' => $bytes]; + } elseif ($store instanceof DatabaseStore) { + $size['entries'] = $store->getConnection()->table((string) config('cache.stores.'.config('atrium.cache.store', config('cache.default')).'.table', 'cache'))->count(); + } + } catch (Throwable) { + // A number on a screen is not worth an error. + } + + return $size; + } + + /** + * @param array $keys + * @return array key => value, null for a miss + */ + public function many(string $group, array $keys): array + { + if ($keys === []) { + return []; + } + + $raw = array_map(fn (string $key): string => $this->key($group, $key), $keys); + $values = $this->repository->many($raw); + $result = []; + + foreach ($keys as $i => $key) { + $result[$key] = $values[$raw[$i]] ?? null; + } + + return $result; + } + + public function get(string $group, string $key): mixed + { + return $this->many($group, [$key])[$key]; + } + + /** + * @param array $values + */ + public function putMany(string $group, array $values, int $ttl): void + { + if ($values === []) { + return; + } + + if ($this->tags) { + $this->repository->tags($this->tagsOf($group))->putMany($values, $ttl); + + return; + } + + $raw = []; + + foreach ($values as $key => $value) { + $raw[$this->key($group, (string) $key)] = $value; + } + + $this->repository->putMany($raw, $ttl); + } + + public function put(string $group, string $key, mixed $value, int $ttl): void + { + $this->putMany($group, [$key => $value], $ttl); + } + + /** + * @param array $keys + */ + public function forget(string $group, array $keys): void + { + foreach ($keys as $key) { + $this->repository->forget($this->key($group, $key)); + } + } + + /** + * Delete a group's entries where the store can; elsewhere they are + * already unreachable through bumped versions. + */ + public function flush(?string $group = null): void + { + if (! $this->tags) { + return; + } + + $this->repository->tags([$group === null ? 'atrium' : 'atrium:'.$group])->flush(); + $this->prefixes = []; + } + + public function reset(): void + { + $this->prefixes = []; + } + + private function key(string $group, string $key): string + { + if (! $this->tags) { + return 'atrium:'.$key; + } + + // Laravel's own tagged key: sha1(namespace of the tags).':'.$key. + $this->prefixes[$group] ??= $this->repository->tags($this->tagsOf($group))->taggedItemKey(''); + + return $this->prefixes[$group].$key; + } + + /** + * @return array + */ + private function tagsOf(string $group): array + { + return ['atrium', 'atrium:'.$group]; + } +} diff --git a/packages/admin/src/Cache/CachedIds.php b/packages/admin/src/Cache/CachedIds.php new file mode 100644 index 00000000..1c09d91a --- /dev/null +++ b/packages/admin/src/Cache/CachedIds.php @@ -0,0 +1,25 @@ + $ids + */ + public function __construct( + public readonly array $ids, + public readonly int $total, + ) {} +} diff --git a/packages/admin/src/Cache/CachesRecords.php b/packages/admin/src/Cache/CachesRecords.php new file mode 100644 index 00000000..46ba351a --- /dev/null +++ b/packages/admin/src/Cache/CachesRecords.php @@ -0,0 +1,97 @@ +where(...)->cachedPaginate(20); + * + * A card carries the relations named by cacheRelations(). By default these + * come from the admin form: a belongs-to-many field's relation, the relation + * behind a belongs-to or section field (`brand_id` → `brand()`), and the + * SEO meta. A relation to the model's own class (a parent section, related + * products) is left out: saving one of those records does not rebuild the + * cards that would show it, and it would copy whole records into each + * card. Override it to choose yourself. + * + * @mixin Model + */ +trait CachesRecords +{ + /** + * @return array + */ + public function cacheRelations(): array + { + $names = []; + // The trait may sit on a model that is not in the admin. + /** @phpstan-ignore function.alreadyNarrowedType */ + $fields = method_exists(static::class, 'getAdministrationFields') ? static::getAdministrationFields() : []; + + foreach ($fields as $field) { + $name = match ($field->getType()) { + 'belongsToMany' => $field->getName(), + 'belongsTo', 'treeSelect' => str_ends_with($field->getColumn(), '_id') ? Str::camel(Str::beforeLast($field->getColumn(), '_id')) : null, + default => null, + }; + + if ($name !== null && $this->isCacheRelation($name)) { + $names[] = $name; + } + } + + if ($this->isCacheRelation('seoMeta')) { + $names[] = 'seoMeta'; + } + + return array_values(array_unique($names)); + } + + /** + * @return array + */ + public static function cachedMany(iterable $ids, ?string $locale = null): array + { + return app(RecordCache::class)->cards(static::class, $ids, $locale); + } + + public static function cached(int|string $id, ?string $locale = null): ?Card + { + return app(RecordCache::class)->cards(static::class, [$id], $locale)[0] ?? null; + } + + private function isCacheRelation(string $name): bool + { + if (! method_exists($this, $name)) { + return false; + } + + try { + $relation = $this->{$name}(); + + return $relation instanceof Relation && $relation->getRelated()::class !== static::class; + } catch (Throwable) { + return false; + } + } +} diff --git a/packages/admin/src/Cache/Card.php b/packages/admin/src/Cache/Card.php new file mode 100644 index 00000000..2040c1e8 --- /dev/null +++ b/packages/admin/src/Cache/Card.php @@ -0,0 +1,247 @@ + null | {type, raw, relations} | list of them + * seo title, description, keywords, og_image + * media field => list of {url, path, name, thumbnails} + * url the record's public address (PublicUrl::forRecord) + * extra what modules added (RecordCache::extend()): the theme's + * page, custom field values … + * + * Read it as an array or through the methods. `$card->name` and + * `$card['name']` go through the model's casts and translations, exactly as + * `$model->name` would. `model()` gives the record back as a read-only + * Eloquent model with its declared relations set: templates that want a + * model get one without a query. + * + * @implements ArrayAccess + */ +final class Card implements ArrayAccess, JsonSerializable +{ + private ?Model $model = null; + + /** + * @param array $data + */ + public function __construct(private readonly array $data) {} + + public function id(): int|string + { + return $this->data['id']; + } + + /** + * @return class-string + */ + public function type(): string + { + return $this->data['type']; + } + + public function locale(): string + { + return (string) $this->data['locale']; + } + + /** + * An attribute through the model's casts and translations. + */ + public function get(string $attribute, mixed $default = null): mixed + { + return $this->model()->getAttribute($attribute) ?? $default; + } + + /** + * The row as the database returns it. + * + * @return array + */ + public function raw(): array + { + return $this->data['raw']; + } + + /** + * A declared relation as a model, a collection of models, or null. + * + * @return Model|Collection|null + */ + public function relation(string $name): Model|Collection|null + { + return $this->model()->getRelationValue($name); + } + + public function seo(string $key): ?string + { + $value = $this->data['seo'][$key] ?? null; + + return is_string($value) && $value !== '' ? $value : null; + } + + /** + * The pictures or files of a form field. + * + * @return array}> + */ + public function media(string $field): array + { + return $this->data['media'][$field] ?? []; + } + + /** + * The first picture of the first filled-in field. + */ + public function picture(string ...$fields): ?string + { + foreach ($fields as $field) { + if (($url = $this->media($field)[0]['url'] ?? null) !== null) { + return $url; + } + } + + return null; + } + + public function url(): ?string + { + $url = $this->data['url'] ?? null; + + return is_string($url) ? $url : null; + } + + /** + * What a module added to the card under its name. + */ + public function extra(string $name, mixed $default = null): mixed + { + return $this->data['extra'][$name] ?? $default; + } + + /** + * The record as an Eloquent model, its relations set from the card. + * Read it, never save it: it holds one language only. Name the class + * you expect to get it typed. + * + * @template T of Model + * + * @param class-string $as + * @return T + */ + public function model(string $as = Model::class): Model + { + $model = $this->model ??= self::hydrate($this->data, $this->locale()); + + if (! $model instanceof $as) { + throw new LogicException('The card holds a '.$model::class.', not a '.$as.'.'); + } + + return $model; + } + + /** + * @return array + */ + public function toArray(): array + { + return $this->data; + } + + /** + * @return array + */ + public function jsonSerialize(): array + { + return [ + 'id' => $this->id(), + 'type' => $this->type(), + 'locale' => $this->locale(), + 'attributes' => $this->model()->attributesToArray(), + 'seo' => $this->data['seo'] ?? [], + 'media' => $this->data['media'] ?? [], + 'url' => $this->url(), + 'extra' => $this->data['extra'] ?? [], + ]; + } + + public function __get(string $name): mixed + { + return $this->get($name); + } + + public function __isset(string $name): bool + { + return $this->get($name) !== null; + } + + public function offsetExists(mixed $offset): bool + { + return $this->get((string) $offset) !== null; + } + + public function offsetGet(mixed $offset): mixed + { + return $this->get((string) $offset); + } + + public function offsetSet(mixed $offset, mixed $value): void + { + throw new LogicException('A cached record is read-only.'); + } + + public function offsetUnset(mixed $offset): void + { + throw new LogicException('A cached record is read-only.'); + } + + /** + * @param array $data + */ + private static function hydrate(array $data, string $locale): Model + { + /** @var class-string $type */ + $type = $data['type']; + $model = (new $type)->newFromBuilder($data['raw']); + + // Translated attributes read in the card's language, whatever the + // app's language is now. + if (method_exists($model, 'setLocale')) { + $model->setLocale($locale); + } + + foreach ((array) ($data['relations'] ?? []) as $name => $related) { + if ($related === null) { + $model->setRelation($name, null); + } elseif (array_is_list($related)) { + $model->setRelation($name, (new $type)->newCollection(array_map(static fn (array $item): Model => self::hydrate($item, $locale), $related))); + } else { + $model->setRelation($name, self::hydrate($related, $locale)); + } + } + + return $model; + } +} diff --git a/packages/admin/src/Cache/CardBuilder.php b/packages/admin/src/Cache/CardBuilder.php new file mode 100644 index 00000000..223aa6c4 --- /dev/null +++ b/packages/admin/src/Cache/CardBuilder.php @@ -0,0 +1,390 @@ +> */ + private array $relations = []; + + /** @var array> */ + private array $dependencies = []; + + /** @var array>> */ + private array $mediaFields = []; + + /** @var array> */ + private array $fields = []; + + /** + * @param array,string):array> $extenders + */ + public function __construct( + private readonly array $extenders = [], + private readonly ?Closure $thumbnails = null, + ) {} + + /** + * @param class-string $class + * @param array $ids + * @return array> id => card data + */ + public function build(string $class, array $ids, string $locale, int $site): array + { + if ($ids === []) { + return []; + } + + $previous = app()->getLocale(); + app()->setLocale($locale); + + try { + /** @var Collection $models */ + $models = $class::query()->whereKey($ids)->with($this->relationsOf($class))->get(); + + $extra = []; + + foreach ($this->extenders as $name => $extender) { + // A module's broken extender costs its own data, not the page. + $extra[$name] = (array) ($this->safely(static fn (): mixed => $extender($models, $locale)) ?? []); + } + + $cards = []; + + foreach ($models as $model) { + $id = $model->getKey(); + $cards[$id] = [ + 'id' => $id, + 'type' => $class, + 'locale' => $locale, + 'site' => $site, + 'raw' => $this->raw($model, $locale), + 'relations' => $this->relationData($model, $locale), + 'seo' => $this->seo($model), + 'media' => $this->media($model), + 'url' => $this->safely(static fn (): ?string => PublicUrl::forRecord($model)), + 'extra' => array_filter(array_map(static fn (array $values): mixed => $values[$id] ?? null, $extra), static fn (mixed $value): bool => $value !== null), + ]; + } + + return $cards; + } finally { + app()->setLocale($previous); + } + } + + /** + * @param class-string $class + * @return array + */ + public function relationsOf(string $class): array + { + if (isset($this->relations[$class])) { + return $this->relations[$class]; + } + + $model = new $class; + + return $this->relations[$class] = $model instanceof Cacheable ? array_values($model->cacheRelations()) : []; + } + + /** + * The classes a card shows something of: saving any record of them + * makes the cards rebuild. Morph relations are owned by the record + * (its SEO meta, its pictures) and drop its card themselves. + * + * @param class-string $class + * @return array + */ + public function dependenciesOf(string $class): array + { + if (isset($this->dependencies[$class])) { + return $this->dependencies[$class]; + } + + $model = new $class; + $classes = []; + + foreach ($this->relationsOf($class) as $name) { + $relation = $this->safely(static fn (): mixed => $model->{$name}()); + + if ($relation instanceof Relation && ! $relation instanceof MorphOneOrMany && ! $relation instanceof MorphTo) { + $classes[] = $relation->getRelated()::class; + } + } + + // What the form links to: modules show the linked record's name. + foreach ($this->fieldsOf($class) as $field) { + if ($field instanceof BelongsToField && ($related = $field->getModelClass()) !== null) { + $classes[] = $related; + } + } + + // A record of its own class is dropped by referencing() instead: + // otherwise every save would rebuild every card of the class. + $classes = array_filter($classes, static fn (string $related): bool => $related !== $class); + + // The address is made of the sections' codes, its own class's too + // for a section: moving one moves the addresses below it. + $tree = PublicUrl::ruleFor($class)['tree'] ?? null; + + if (is_string($tree) && $tree !== '') { + $classes[] = $tree; + } + + return $this->dependencies[$class] = array_values(array_unique($classes)); + } + + /** + * Records of the same class whose cards show this one (related + * products, an analogue): their cards go when it is saved. + * + * @return array + */ + public function referencing(Model $record): array + { + $class = $record::class; + $ids = []; + + foreach ($this->fieldsOf($class) as $field) { + if (! $field instanceof BelongsToField || $field->getModelClass() !== $class) { + continue; + } + + $query = $class::query()->withoutGlobalScopes(); + $name = $field->getName(); + + if ($field->getType() === 'belongsToMany') { + if (! method_exists($record, $name) || ! $record->{$name}() instanceof BelongsToMany) { + continue; + } + + $query->whereHas($name, static fn ($related) => $related->withoutGlobalScopes()->whereKey($record->getKey())); + } else { + $value = $record->getAttribute($field->getValueColumn()); + + if ($value === null || $field->getColumn() === $record->getKeyName()) { + continue; + } + + $query->where($field->getColumn(), $value); + } + + $ids = [...$ids, ...$query->whereKeyNot($record->getKey())->pluck($record->getKeyName())->all()]; + } + + return array_values(array_unique($ids)); + } + + /** + * The row, a translated column reduced to the card's language and the + * default one: fifteen languages of a long text would make every card + * fifteen times bigger. + * + * @return array + */ + private function raw(Model $model, string $locale): array + { + $raw = $model->getAttributes(); + + if (! method_exists($model, 'getTranslatableAttributes') || ! method_exists($model, 'getTranslations')) { + return $raw; + } + + $default = app(ContentLanguages::class)->default(); + + foreach ($model->getTranslatableAttributes() as $attribute) { + if (! isset($raw[$attribute])) { + continue; + } + + $translations = (array) $model->getTranslations($attribute); + $kept = array_intersect_key($translations, array_flip([$locale, $default])); + $raw[$attribute] = json_encode($kept, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } + + return $raw; + } + + /** + * @return array + */ + private function relationData(Model $model, string $locale): array + { + $data = []; + + foreach ($model->getRelations() as $name => $value) { + if ($value instanceof Model) { + $data[$name] = $this->related($value, $locale); + } elseif ($value instanceof Collection) { + $data[$name] = $value->map(fn (Model $item): array => $this->related($item, $locale))->values()->all(); + } elseif ($value === null) { + $data[$name] = null; + } + } + + return $data; + } + + /** + * @return array + */ + private function related(Model $model, string $locale): array + { + return ['id' => $model->getKey(), 'type' => $model::class, 'raw' => $this->raw($model, $locale), 'relations' => []]; + } + + /** + * @return array + */ + private function seo(Model $model): array + { + if (! method_exists($model, 'getSeoTitle')) { + return []; + } + + return [ + 'title' => $this->safely(static fn (): string => (string) $model->getSeoTitle()), + 'description' => method_exists($model, 'getSeoDescription') ? $this->safely(static fn (): string => (string) $model->getSeoDescription()) : null, + 'keywords' => method_exists($model, 'getSeoKeywords') ? $this->safely(static fn (): ?string => $model->getSeoKeywords()) : null, + 'og_image' => method_exists($model, 'getOgImage') ? $this->safely(static fn (): ?string => $model->getOgImage()) : null, + ]; + } + + /** + * Pictures and files of the form's image, gallery and file fields, with + * their addresses worked out once. + * + * @return array}>> + */ + private function media(Model $model): array + { + $media = []; + + foreach ($this->mediaFieldsOf($model::class) as $column) { + $items = []; + + foreach ($this->list($model->getAttribute($column)) as $item) { + $url = MediaUrl::to($item); + + if ($url === null) { + continue; + } + + $path = is_array($item) ? (string) ($item['path'] ?? $item['url'] ?? '') : (string) $item; + $name = is_array($item) && isset($item['name']) ? (string) $item['name'] : rawurldecode(basename((string) parse_url($url, PHP_URL_PATH))); + + $items[] = [ + 'url' => $url, + 'path' => $path, + 'name' => $name, + 'thumbnails' => $this->thumbnails === null ? [] : (array) ($this->thumbnails)($path, $url), + ]; + } + + if ($items !== []) { + $media[$column] = $items; + } + } + + return $media; + } + + /** + * @return array + */ + private function mediaFieldsOf(string $class): array + { + if (isset($this->mediaFields[$class]['columns'])) { + return $this->mediaFields[$class]['columns']; + } + + $columns = []; + + foreach ($this->fieldsOf($class) as $field) { + if ($field instanceof Field && in_array($field->getType(), ['image', 'gallery', 'file'], true)) { + $columns[] = $field->getColumn(); + } + } + + return $this->mediaFields[$class]['columns'] = $columns; + } + + /** + * @return array + */ + private function fieldsOf(string $class): array + { + return $this->fields[$class] ??= method_exists($class, 'getAdministrationFields') ? array_values((array) $class::getAdministrationFields()) : []; + } + + /** + * A value that may be one item, a list, or a JSON list. + * + * @return array + */ + private function list(mixed $value): array + { + if ($value === null || $value === '' || $value === []) { + return []; + } + + if (is_string($value) && str_starts_with(ltrim($value), '[')) { + $decoded = json_decode($value, true); + + if (is_array($decoded)) { + return $decoded; + } + } + + if (is_array($value) && (array_is_list($value) || ! (isset($value['path']) || isset($value['url'])))) { + return $value; + } + + return [$value]; + } + + /** + * @template T + * + * @param Closure():T $callback + * @return T|null + */ + private function safely(Closure $callback): mixed + { + try { + return $callback(); + } catch (Throwable $e) { + report($e); + + return null; + } + } +} diff --git a/packages/admin/src/Cache/RecordCache.php b/packages/admin/src/Cache/RecordCache.php new file mode 100644 index 00000000..65684f36 --- /dev/null +++ b/packages/admin/src/Cache/RecordCache.php @@ -0,0 +1,712 @@ +where('section_id', 3)->orderBy('price')->cachedPaginate(20); + * $cards = Product::cachedMany([12, 7, 31]); + * + * Keys carry version counters (see Versions): + * + * all everything; "clear all" + * site:{id} one site's cards, lists and pages + * list:{class} any record of the class saved or deleted: its lists, + * and the cards of other classes that show it (a brand's + * name on its products) rebuild lazily + * card:{class} the class's cards; "clear this module" + * + * Saving a record drops its own cards in every language and site at once, + * and bumps its class's list version. + */ +final class RecordCache +{ + /** @var array,string):array> */ + private array $extenders = []; + + private ?Closure $thumbnails = null; + + private ?CardBuilder $builder = null; + + private int $bulk = 0; + + /** @var array */ + private array $bulkTouched = []; + + private bool $bulkEverything = false; + + /** @var array> */ + private array $warmers = []; + + /** @var array version names the current request has read through */ + private array $read = []; + + /** @var array{hits:int,misses:int} */ + private array $stats = ['hits' => 0, 'misses' => 0]; + + /** @var array */ + private array $changing = []; + + public function __construct( + private readonly CacheStore $store, + private readonly Versions $versions, + ) {} + + /** + * The read name of a request whose page must not be kept: it holds + * something made for one visitor only. + */ + public const NO_PAGE = 'no-page'; + + /** @var array{hits:int,misses:int} the counts of the request reset() last closed */ + private array $lastStats = ['hits' => 0, 'misses' => 0]; + + public function enabled(): bool + { + return (bool) config('atrium.cache.enabled', true); + } + + public function store(): CacheStore + { + return $this->store; + } + + public function versions(): Versions + { + return $this->versions; + } + + /** + * Cards of records in the order of the ids; ids with no record are + * left out. One multi-get, then one batch of queries for the misses. + * + * @param class-string $class + * @param iterable $ids + * @return array + */ + public function cards(string $class, iterable $ids, ?string $locale = null): array + { + $ids = array_values(array_unique(array_map(self::normalizeId(...), is_array($ids) ? $ids : iterator_to_array($ids, false)))); + + if ($ids === []) { + return []; + } + + $locale ??= app()->getLocale(); + $site = $this->site(); + // A cached page that shows the record is stale once any record of + // its class is saved (cards are dropped one by one, not versioned). + $this->markRead(['list:'.$class]); + + if (! $this->enabled() || ! is_subclass_of($class, Cacheable::class)) { + $data = $this->builder()->build($class, $ids, $locale, $site); + + return $this->ordered($ids, $data); + } + + $prefix = $this->cardPrefix($class, $site, $locale); + $keys = array_map(static fn (int|string $id): string => $prefix.$id, $ids); + $values = $this->store->many(self::group($class), $keys); + $data = []; + $missing = []; + + foreach ($ids as $i => $id) { + $value = $values[$keys[$i]] ?? null; + + if (is_array($value)) { + $data[$id] = $value; + } else { + $missing[] = $id; + } + } + + $this->stats['hits'] += count($data); + $this->stats['misses'] += count($missing); + + if ($missing !== []) { + $built = $this->builder()->build($class, $missing, $locale, $site); + $put = []; + + foreach ($built as $id => $card) { + $data[$id] = $card; + $put[$prefix.$id] = $card; + } + + $this->store->putMany(self::group($class), $put, $this->ttl('cards')); + } + + return $this->ordered($ids, $data); + } + + /** + * The ids a list query answers, cached by the query itself (its + * filters, order, page, the site and the language) until a record of + * its class changes. + * + * @param Builder $query + * @param array> $dependsOn other classes the query reads (a join, whereHas) + */ + public function ids(Builder $query, ?int $perPage = null, ?int $page = null, array $dependsOn = []): CachedIds + { + $model = $query->getModel(); + $class = $model::class; + + $run = static function () use ($query, $model, $perPage, $page): array { + $key = $model->getQualifiedKeyName(); + + if ($perPage === null) { + $ids = (clone $query)->toBase()->pluck($key)->all(); + + return ['ids' => $ids, 'total' => count($ids)]; + } + + $total = (clone $query)->toBase()->getCountForPagination(); + $ids = $total > 0 ? (clone $query)->forPage(max(1, (int) $page), $perPage)->toBase()->pluck($key)->all() : []; + + return ['ids' => $ids, 'total' => $total]; + }; + + if (! $this->enabled()) { + $result = $run(); + + return new CachedIds(array_map(self::normalizeId(...), $result['ids']), (int) $result['total']); + } + + $names = ['all', 'site:'.$this->site(), 'list:'.$class]; + + foreach ($dependsOn as $dependency) { + $names[] = 'list:'.$dependency; + } + + $this->markRead($names); + + $hash = hash('xxh128', implode("\n", [ + $class, + $query->toSql(), + json_encode(array_map(self::binding(...), $query->getBindings())), + (string) $perPage, + (string) $page, + app()->getLocale(), + ])); + $key = 'ids:'.$this->versions->stamp($names).':'.$hash; + $cached = $this->store->get(self::group($class), $key); + + if (is_array($cached)) { + $this->stats['hits']++; + } else { + $this->stats['misses']++; + $cached = $run(); + $this->store->put(self::group($class), $key, $cached, $this->ttl('lists')); + } + + return new CachedIds(array_map(self::normalizeId(...), $cached['ids']), (int) $cached['total']); + } + + /** + * A page of cards with the paginator the views know. + * + * @param Builder $query + * @param array> $dependsOn + * @return LengthAwarePaginator + */ + public function paginate(Builder $query, int $perPage = 20, string $pageName = 'page', ?int $page = null, ?string $locale = null, array $dependsOn = []): LengthAwarePaginator + { + $page ??= Paginator::resolveCurrentPage($pageName); + $result = $this->ids($query, $perPage, $page, $dependsOn); + + return new LengthAwarePaginator( + $this->cards($query->getModel()::class, $result->ids, $locale), + $result->total, + $perPage, + $page, + ['path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName], + ); + } + + /** + * Anything else worth keeping until a record of the given classes + * changes: a tree of sections, the counters of a block. + * + * @param string|array $classes model classes, or any name a writer drops with flushClass() + */ + public function remember(string|array $classes, string $key, Closure $callback, ?int $ttl = null, bool $perSite = true): mixed + { + if (! $this->enabled()) { + return $callback(); + } + + $classes = (array) $classes; + $names = ['all', ...array_map(static fn (string $class): string => 'list:'.$class, $classes)]; + + if ($perSite) { + $names[] = 'site:'.$this->site(); + } + + $this->markRead($names); + $group = self::group($classes[0] ?? 'remember'); + $full = 'r:'.$this->versions->stamp($names).':'.($perSite ? $this->site().':' : '').$key; + $cached = $this->store->get($group, $full); + + if (is_array($cached) && array_key_exists('v', $cached)) { + $this->stats['hits']++; + + return $cached['v']; + } + + $this->stats['misses']++; + $value = $callback(); + $this->store->put($group, $full, ['v' => $value], $ttl ?? $this->ttl('lists')); + + return $value; + } + + /** + * A record was saved, deleted or restored: drop its cards in every + * language and site, make its class's lists and the cards that show it + * stale, and pass the news to the records it belongs to. + */ + public function changed(Model $record): void + { + $class = $record::class; + + if (in_array($class, (array) config('atrium.cache.ignore', []), true)) { + return; + } + + if ($this->bulk > 0) { + $this->bulkTouched[$class] = true; + + return; + } + + $guard = $class.'#'.$record->getKey(); + + if (isset($this->changing[$guard])) { + return; + } + + $this->changing[$guard] = true; + + try { + $this->versions->bump('list:'.$class); + + // A site's domains and languages are in every address of its + // cards; a language is in every site's. + if ($record instanceof Site && $record->getKey() !== null) { + $this->flushSite((int) $record->getKey()); + } elseif ($record instanceof Language) { + $this->flushAll(); + } + + if ($record instanceof Cacheable && $record->getKey() !== null) { + $this->forgetCards($class, [$record->getKey(), ...$this->builder()->referencing($record)]); + } + + if (method_exists($record, 'cacheTouches')) { + foreach ((array) $record->cacheTouches() as $owner) { + if ($owner instanceof Model) { + $this->changed($owner); + } + } + } + } catch (Throwable $e) { + // A cache that is down must not fail the save. + report($e); + } finally { + unset($this->changing[$guard]); + } + } + + /** + * Drop a class's cards and lists (and those of the classes showing it), + * or the remember() values kept under a name of one's own. + * + * @param string $class a model class or a remember() name + */ + public function flushClass(string $class): void + { + $this->versions->bump('card:'.$class, 'list:'.$class); + $this->store->flush(self::group($class)); + } + + public function flushSite(int $site): void + { + $this->versions->bump('site:'.$site); + } + + public function flushAll(): void + { + $this->versions->bump('all'); + $this->store->flush(); + } + + /** + * Run an import without dropping cards record by record, then drop + * the classes it touched once. + * + * @template T + * + * Pass $everything for an import that writes past Eloquent (query + * builder inserts): no events tell which classes it touched, so the + * whole cache goes once at the end. + * + * @param Closure():T $callback + * @return T + */ + public function bulk(Closure $callback, bool $everything = false): mixed + { + $this->bulk++; + $this->bulkEverything = $this->bulkEverything || $everything; + + try { + return $callback(); + } finally { + if (--$this->bulk === 0) { + $touched = array_keys($this->bulkTouched); + $all = $this->bulkEverything; + $this->bulkTouched = []; + $this->bulkEverything = false; + + if ($all) { + $this->flushAll(); + } else { + foreach ($touched as $class) { + $this->flushClass($class); + } + } + } + } + } + + /** + * Add pages for atrium:cache:warm to open in a language: the theme adds + * its home page and the first page of every list. + * + * @param Closure(string):iterable $paths language => addresses or paths + */ + public function warmUsing(Closure $paths): void + { + $this->warmers[] = $paths; + } + + /** + * The paths atrium:cache:warm opens in a language, the site's home first. + * + * @return array + */ + public function warmPaths(string $language): array + { + $paths = ['/']; + + foreach ($this->warmers as $warmer) { + foreach ($warmer($language) as $url) { + $path = (string) parse_url((string) $url, PHP_URL_PATH); + $query = parse_url((string) $url, PHP_URL_QUERY); + $paths[] = '/'.ltrim($path, '/').(is_string($query) && $query !== '' ? '?'.$query : ''); + } + } + + return array_values(array_unique($paths)); + } + + /** + * Add a module's data to every card: called once per batch of records + * being built, in the card's language; returns id => data. + * + * @param Closure(Collection,string):array $extender + */ + public function extend(string $name, Closure $extender): void + { + $this->extenders[$name] = $extender; + $this->builder = null; + } + + /** + * How the cards get thumbnail addresses for their pictures: + * fn (string $path, string $url): array size => url. + */ + public function thumbnailsUsing(?Closure $resolver): void + { + $this->thumbnails = $resolver; + $this->builder = null; + } + + public function builder(): CardBuilder + { + return $this->builder ??= new CardBuilder($this->extenders, $this->thumbnails); + } + + /** + * The time list queries compare against, in steps (a minute by + * default): `now()` would make every query, and so every key, new. + */ + public function now(): Carbon + { + $step = max(1, (int) config('atrium.cache.time_step', 60)); + + return Carbon::createFromTimestamp(intdiv(Carbon::now()->getTimestamp(), $step) * $step, date_default_timezone_get()); + } + + /** + * @return array{hits:int,misses:int} + */ + public function requestStats(): array + { + return $this->stats; + } + + /** + * This request's counts, or, once the request has been closed by + * reset(), the counts it closed with: for whoever reads them at the very + * end (the monitoring module, through the atrium.cache.stats filter). + * + * @return array{hits:int,misses:int} + */ + public function finishedStats(): array + { + return $this->stats['hits'] + $this->stats['misses'] > 0 ? $this->stats : $this->lastStats; + } + + /** + * The version names read through during this request: a cached page + * stays valid while all of them stay the same. + * + * @return array + */ + public function readNames(): array + { + return array_keys($this->read); + } + + /** + * Keep the page cache off this request's page: a one-time token, a + * captcha question, anything made for this visitor alone. + */ + public function dontKeepPage(): void + { + $this->read[self::NO_PAGE] = true; + } + + public function pageKeepable(): bool + { + return ! isset($this->read[self::NO_PAGE]); + } + + /** + * @param array $names + */ + public function markRead(array $names): void + { + foreach ($names as $name) { + $this->read[$name] = true; + } + } + + /** + * Start afresh for the next request or job. + */ + public function reset(): void + { + if ($this->stats['hits'] + $this->stats['misses'] > 0) { + $this->lastStats = $this->stats; + } + + $this->read = []; + $this->stats = ['hits' => 0, 'misses' => 0]; + $this->versions->reset(); + $this->store->reset(); + } + + /** + * Add this request's hits and misses to the totals the admin shows. + */ + public function persistStats(): void + { + if (! config('atrium.cache.stats', true) || ($this->stats['hits'] + $this->stats['misses']) === 0) { + return; + } + + try { + $repository = $this->store->repository(); + + foreach ($this->stats as $name => $count) { + if ($count > 0 && $repository->increment('atrium:stats:'.$name, $count) === false) { + $repository->forever('atrium:stats:'.$name, $count); + } + } + } catch (Throwable) { + // Statistics are not worth an error page. + } + } + + /** + * @return array{hits:int,misses:int} + */ + public function totals(): array + { + $repository = $this->store->repository(); + + return [ + 'hits' => (int) $repository->get('atrium:stats:hits', 0), + 'misses' => (int) $repository->get('atrium:stats:misses', 0), + ]; + } + + public function resetTotals(): void + { + $this->store->repository()->forget('atrium:stats:hits'); + $this->store->repository()->forget('atrium:stats:misses'); + } + + public static function group(string $class): string + { + return str_replace('\\', '.', $class); + } + + /** + * @param class-string $class + * @param array $ids + */ + private function forgetCards(string $class, array $ids): void + { + $sites = $this->knownSites(); + $locales = $this->knownLocales(); + $keys = []; + + foreach ($sites as $site) { + foreach ($locales as $locale) { + $prefix = $this->cardPrefix($class, $site, $locale, false); + + foreach ($ids as $id) { + $keys[] = $prefix.$id; + } + } + } + + $this->store->forget(self::group($class), $keys); + + // Inside a transaction a request may build the card again from the + // old row before the commit: drop it once more after the commit. + if (DB::transactionLevel() > 0) { + DB::afterCommit(fn () => $this->store->forget(self::group($class), $keys)); + } + } + + /** + * @param class-string $class + */ + private function cardPrefix(string $class, int $site, string $locale, bool $markRead = true): string + { + $names = ['all', 'site:'.$site, 'card:'.$class]; + + foreach ($this->builder()->dependenciesOf($class) as $dependency) { + $names[] = 'list:'.$dependency; + } + + if ($markRead) { + $this->markRead($names); + } + + return 'card:'.$this->versions->stamp($names).':'.$site.':'.$locale.':'; + } + + /** + * @return array + */ + private function knownSites(): array + { + try { + $ids = app(Sites::class)->all()->pluck('id')->filter()->map(static fn (mixed $id): int => (int) $id)->all(); + } catch (Throwable) { + $ids = []; + } + + return array_values(array_unique([0, ...$ids])); + } + + /** + * @return array + */ + private function knownLocales(): array + { + try { + $codes = Language::query()->pluck('code')->all(); + } catch (Throwable) { + $codes = []; + } + + return array_values(array_unique([app()->getLocale(), (string) config('app.locale'), ...$codes])); + } + + private function site(): int + { + $sites = app(Sites::class); + + return $sites->isResolved() ? (int) $sites->current()->getKey() : 0; + } + + private function ttl(string $kind): int + { + return max(1, (int) config('atrium.cache.ttl.'.$kind, $kind === 'cards' ? 86400 : 3600)); + } + + /** + * @param array $ids + * @param array> $data + * @return array + */ + private function ordered(array $ids, array $data): array + { + $cards = []; + + foreach ($ids as $id) { + if (isset($data[$id])) { + $cards[] = new Card($data[$id]); + } + } + + return $cards; + } + + private static function normalizeId(mixed $id): int|string + { + return is_int($id) || (is_string($id) && ctype_digit($id) && strlen($id) < 19) ? (int) $id : (string) $id; + } + + private static function binding(mixed $value): mixed + { + return match (true) { + $value instanceof DateTimeInterface => $value->format('Y-m-d H:i:s.u'), + $value instanceof BackedEnum => $value->value, + is_object($value) && method_exists($value, '__toString') => (string) $value, + default => $value, + }; + } +} diff --git a/packages/admin/src/Cache/TouchesOwner.php b/packages/admin/src/Cache/TouchesOwner.php new file mode 100644 index 00000000..88f72fb7 --- /dev/null +++ b/packages/admin/src/Cache/TouchesOwner.php @@ -0,0 +1,45 @@ + + */ + public function cacheTouches(): array + { + $type = $this->getAttribute($this->ownerMorphName().'_type'); + $id = $this->getAttribute($this->ownerMorphName().'_id'); + $class = is_string($type) ? (Relation::getMorphedModel($type) ?? $type) : null; + + if ($class === null || $id === null || ! is_subclass_of($class, Model::class)) { + return []; + } + + $owner = new $class; + $owner->setRawAttributes([$owner->getKeyName() => $id], true); + $owner->exists = true; + + return [$owner]; + } + + abstract protected function ownerMorphName(): string; +} diff --git a/packages/admin/src/Cache/Versions.php b/packages/admin/src/Cache/Versions.php new file mode 100644 index 00000000..17e1d8f8 --- /dev/null +++ b/packages/admin/src/Cache/Versions.php @@ -0,0 +1,115 @@ + */ + private array $memo = []; + + public function __construct(private readonly Repository $store) {} + + /** + * @param array $names + * @return array name => version + */ + public function get(array $names): array + { + $names = array_values(array_unique($names)); + $missing = array_values(array_filter($names, fn (string $name): bool => ! isset($this->memo[$name]))); + + if ($missing !== []) { + $keys = array_map(static fn (string $name): string => self::PREFIX.$name, $missing); + $values = $this->store->many($keys); + + foreach ($missing as $i => $name) { + $value = $values[$keys[$i]] ?? null; + + if ($value === null || $value === false) { + $value = $this->start($name); + } + + $this->memo[$name] = (string) $value; + } + } + + return array_intersect_key($this->memo, array_flip($names)); + } + + /** + * One short string for a set of versions, to put into a key. + * + * @param array $names + */ + public function stamp(array $names): string + { + sort($names); + $versions = $this->get($names); + + return substr(hash('xxh128', implode('|', array_map(static fn (string $name): string => $name.'='.$versions[$name], $names))), 0, 16); + } + + public function bump(string ...$names): void + { + foreach (array_unique($names) as $name) { + $key = self::PREFIX.$name; + + // Redis and the array store create a missing counter at 1; + // ours never are 1, so that means it was not there. + $value = $this->store->increment($key); + + if ($value === false || (int) $value <= 1) { + $this->store->put($key, random_int(1, PHP_INT_MAX >> 1), self::TTL); + } + + unset($this->memo[$name]); + } + } + + /** + * Forget what was read: the next request (under Octane, in a queue + * worker) must see versions bumped by other processes. + */ + public function reset(): void + { + $this->memo = []; + } + + private function start(string $name): string + { + $key = self::PREFIX.$name; + $this->store->add($key, random_int(1, PHP_INT_MAX >> 1), self::TTL); + + return (string) $this->store->get($key); + } +} diff --git a/packages/admin/src/Captcha/ImageCaptcha.php b/packages/admin/src/Captcha/ImageCaptcha.php index 671a7b10..ff4e8cec 100644 --- a/packages/admin/src/Captcha/ImageCaptcha.php +++ b/packages/admin/src/Captcha/ImageCaptcha.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Captcha; +use Atrium\Admin\Cache\RecordCache; use Illuminate\Contracts\Cache\Repository as Cache; use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Contracts\Encryption\Encrypter; @@ -36,6 +37,9 @@ public function __construct(private readonly Encrypter $encrypter, private reado public function widget(): HtmlString { + // A question is used up on the first answer: a kept page would give + // every visitor the same one. + app(RecordCache::class)->dontKeepPage(); [$a, $b] = [random_int(1, 9), random_int(1, 9)]; $token = $this->encrypter->encrypt([ 'q' => "$a + $b", diff --git a/packages/admin/src/Console/Commands/CacheWarmCommand.php b/packages/admin/src/Console/Commands/CacheWarmCommand.php new file mode 100644 index 00000000..5b2c7ecf --- /dev/null +++ b/packages/admin/src/Console/Commands/CacheWarmCommand.php @@ -0,0 +1,147 @@ +warn('The record cache is off (ATRIUM_CACHE_ENABLED=false): nothing to warm.'); + + return self::SUCCESS; + } + + // Warming must not leave a session file behind per page. + config(['session.driver' => 'array']); + + $only = array_filter((array) $this->option('site')); + $pages = 0; + $cards = 0; + + foreach ($sites->all() as $site) { + if (! $site->active || ($only !== [] && ! in_array($site->code, $only, true))) { + continue; + } + + $sites->setCurrent($site); + $languages->flush(); + $codes = $languages->codes(); + $base = $this->base($site); + + foreach ($codes as $code) { + foreach ($cache->warmPaths($code) as $path) { + $status = $this->open($kernel, $base.$path); + $pages++; + $this->line(sprintf(' %s %s', $status, $base.$path), verbosity: $status === 200 ? 'v' : 'normal'); + } + } + + if ($this->option('records')) { + $cards += $this->buildCards($cache, $resources, $codes); + } + } + + $sites->forgetCurrent(); + $this->info($this->option('records') + ? sprintf('Opened %d pages and built %d cards.', $pages, $cards) + : sprintf('Opened %d pages.', $pages)); + + return self::SUCCESS; + } + + private function open(Kernel $kernel, string $url): int + { + try { + $request = Request::create($url, 'GET'); + $response = $kernel->handle($request); + $kernel->terminate($request, $response); + + return $response->getStatusCode(); + } catch (Throwable $e) { + report($e); + + return 500; + } + } + + /** + * @param array $codes + */ + private function buildCards(RecordCache $cache, ApiResources $resources, array $codes): int + { + $built = 0; + + // Modules of the panel, and the models the theme gives addresses to. + $classes = [...array_values($resources->modules()), ...array_keys((array) config('atrium.public_urls', []))]; + + foreach (array_unique($classes) as $class) { + if (! is_string($class) || ! class_exists($class)) { + continue; + } + + if (! is_subclass_of($class, Cacheable::class) || ! is_subclass_of($class, Model::class)) { + continue; + } + + $class::query()->select((new $class)->getQualifiedKeyName())->chunkById(500, function ($records) use ($cache, $class, $codes, &$built): void { + $ids = $records->modelKeys(); + + foreach ($codes as $code) { + $built += count($cache->cards($class, $ids, $code)); + } + + $cache->reset(); + }); + } + + return $built; + } + + /** + * Where the site is: its first domain (the app's URL when it has none) + * and its folder. + */ + private function base(Site $site): string + { + $url = rtrim((string) config('app.url', 'http://localhost'), '/'); + $scheme = (string) (parse_url($url, PHP_URL_SCHEME) ?: 'http'); + $domain = ((array) $site->domains)[0] ?? null; + $root = is_string($domain) && $domain !== '' ? $scheme.'://'.$domain : $url; + + return rtrim($root, '/').($site->folder ? '/'.trim((string) $site->folder, '/') : ''); + } +} diff --git a/packages/admin/src/Console/Commands/ModuleRemoveCommand.php b/packages/admin/src/Console/Commands/ModuleRemoveCommand.php index 883fc4c4..b6b117a1 100644 --- a/packages/admin/src/Console/Commands/ModuleRemoveCommand.php +++ b/packages/admin/src/Console/Commands/ModuleRemoveCommand.php @@ -69,6 +69,7 @@ public function handle(Modules $modules): int if (! $keep && Schema::hasTable(Settings::TABLE)) { DB::table(Settings::TABLE)->where('module', $module->key())->delete(); + $this->laravel->make(Settings::class)->flush(); } if (($keys !== [] || $own !== []) && Schema::hasTable('admin_roles')) { diff --git a/packages/admin/src/Contracts/Cacheable.php b/packages/admin/src/Contracts/Cacheable.php new file mode 100644 index 00000000..08524f9b --- /dev/null +++ b/packages/admin/src/Contracts/Cacheable.php @@ -0,0 +1,25 @@ + + */ + public function cacheRelations(): array; +} diff --git a/packages/admin/src/Http/Controllers/AdminController.php b/packages/admin/src/Http/Controllers/AdminController.php index 3c5fda56..3fcd88a0 100644 --- a/packages/admin/src/Http/Controllers/AdminController.php +++ b/packages/admin/src/Http/Controllers/AdminController.php @@ -11,6 +11,7 @@ use Atrium\Admin\Actions\CreateFromRecord; use Atrium\Admin\Auth\Permissions; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Contracts\Administrable; use Atrium\Admin\Facades\Hook; use Atrium\Admin\Fields\CheckboxField; @@ -429,6 +430,9 @@ protected function saveItem(Request $request, string $context, Model&Administrab return $record; }, attempts: 3); + // Pivot syncs and SEO rows fire no event of the record itself. + DB::afterCommit(static fn () => app(RecordCache::class)->changed($saved)); + // Listeners send mail and queue jobs: only for what was committed, // after the outermost transaction if the caller opened one. DB::afterCommit(static fn () => Hook::fire('atrium.record.saved', $saved, $context)); diff --git a/packages/admin/src/Http/Controllers/CacheController.php b/packages/admin/src/Http/Controllers/CacheController.php new file mode 100644 index 00000000..4d35f213 --- /dev/null +++ b/packages/admin/src/Http/Controllers/CacheController.php @@ -0,0 +1,89 @@ +cache->totals(); + $reads = $totals['hits'] + $totals['misses']; + + return Inertia::render('Admin/Cache/Index', [ + 'status' => [ + 'enabled' => (bool) config('atrium.cache.enabled', true), + 'pages' => (bool) config('atrium.cache.pages.enabled', false), + 'driver' => $this->store->driver(), + 'tags' => $this->store->usesTags(), + 'hits' => $totals['hits'], + 'misses' => $totals['misses'], + 'rate' => $reads > 0 ? round($totals['hits'] * 100 / $reads, 1) : null, + ...$this->store->size(), + ], + 'modules' => collect($this->modules()) + ->map(fn (string $class, string $key): array => ['key' => $key, 'label' => $this->resources->label($key)]) + ->sortBy('label') + ->values(), + 'sites' => $this->sites->all() + ->filter(fn (Site $site): bool => $site->exists) + ->map(fn (Site $site): array => ['id' => $site->getKey(), 'name' => (string) $site->name]) + ->values(), + ]); + } + + public function clear(Request $request): RedirectResponse + { + $validated = $request->validate([ + 'scope' => ['required', Rule::in(['all', 'module', 'site', 'stats'])], + 'module' => ['required_if:scope,module', 'nullable', Rule::in(array_keys($this->modules()))], + 'site' => ['required_if:scope,site', 'nullable', 'integer'], + ]); + + match ($validated['scope']) { + 'module' => $this->cache->flushClass($this->modules()[$validated['module']]), + 'site' => $this->cache->flushSite((int) $validated['site']), + 'stats' => $this->cache->resetTotals(), + default => $this->cache->flushAll(), + }; + + return redirect()->route('admin.cache.index')->with('success', __('atrium::cache.cleared')); + } + + /** + * @return array key => model class of every cached module + */ + private function modules(): array + { + return array_filter($this->resources->modules(), static fn (string $class): bool => is_subclass_of($class, Cacheable::class)); + } +} diff --git a/packages/admin/src/Http/Middleware/CacheDebug.php b/packages/admin/src/Http/Middleware/CacheDebug.php new file mode 100644 index 00000000..2042543f --- /dev/null +++ b/packages/admin/src/Http/Middleware/CacheDebug.php @@ -0,0 +1,94 @@ +cache->requestStats(); + $page = (string) $response->headers->get(CachePages::HEADER, 'off'); + $line = sprintf( + 'queries=%d (%.1f ms); cache hits=%d misses=%d; page cache=%s; %.1f ms', + self::$queries, + self::$queryMs, + $stats['hits'], + $stats['misses'], + strtolower($page), + (microtime(true) - $start) * 1000, + ); + + $response->headers->set(self::HEADER, $line); + $content = $response->getContent(); + + if (is_string($content) && str_contains((string) $response->headers->get('Content-Type'), 'text/html') && ($at = strripos($content, '')) !== false) { + $bar = '
Atrium: '.e($line).'
'; + $response->setContent(substr($content, 0, $at).$bar.substr($content, $at)); + } + + return $response; + } + + public static function enabled(): bool + { + return (bool) config('atrium.cache.debug', true) + && (bool) config('app.debug', false) + && app()->environment('local'); + } + + private static function listen(): void + { + if (self::$listening) { + return; + } + + self::$listening = true; + + DB::listen(static function ($query): void { + self::$queries++; + self::$queryMs += (float) $query->time; + }); + } +} diff --git a/packages/admin/src/Http/Middleware/CachePages.php b/packages/admin/src/Http/Middleware/CachePages.php new file mode 100644 index 00000000..61095618 --- /dev/null +++ b/packages/admin/src/Http/Middleware/CachePages.php @@ -0,0 +1,276 @@ +applies($request)) { + return $next($request); + } + + $key = $this->key($request); + $entry = $this->safely(fn (): mixed => $this->store->get('pages', $key)); + + if (is_array($entry) && $this->fresh($entry)) { + return $this->serve($request, $entry, 'HIT'); + } + + $response = $next($request); + + if (! $this->storable($response)) { + return $response; + } + + $entry = $this->entry($request, $response); + $this->safely(fn () => $this->store->put('pages', $key, $entry, max(1, (int) config('atrium.cache.ttl.pages', 600)))); + + return $this->serve($request, $entry, 'MISS', $response); + } + + private function applies(Request $request): bool + { + if (! config('atrium.cache.pages.enabled', false) || ! config('atrium.cache.enabled', true)) { + return false; + } + + if (! $request->isMethod('GET') && ! $request->isMethod('HEAD')) { + return false; + } + + if ($request->ajax() || $request->hasHeader('X-Inertia') || $request->hasHeader('X-Livewire')) { + return false; + } + + $admin = trim((string) config('atrium.prefix', 'admin'), '/'); + + if ($admin !== '' && $request->is($admin, $admin.'/*')) { + return false; + } + + foreach ((array) config('atrium.cache.pages.except', []) as $pattern) { + if ($request->is(ltrim((string) $pattern, '/'))) { + return false; + } + } + + // An admin sees the edit bar and unpublished things; a signed-in + // visitor sees their own name. + foreach (array_unique([(string) config('atrium.auth.guard', 'admin'), (string) config('auth.defaults.guard', 'web')]) as $guard) { + try { + if (auth()->guard($guard)->check()) { + return false; + } + } catch (Throwable) { + // A guard that is not configured signs nobody in. + } + } + + if ($request->hasSession()) { + $session = $request->session(); + + if ($session->has('errors') || (array) $session->get('_flash.old', []) !== [] || $session->hasOldInput()) { + return false; + } + } + + return true; + } + + private function key(Request $request): string + { + $query = $request->query(); + ksort($query); + + return 'page:'.$this->site().':'.hash('xxh128', $request->getSchemeAndHttpHost().'/'.trim($request->path(), '/').'?'.http_build_query($query)); + } + + /** + * @param array $entry + */ + private function fresh(array $entry): bool + { + $versions = (array) ($entry['versions'] ?? []); + + if ($versions === []) { + return false; + } + + $now = $this->safely(fn (): array => $this->versions->get(array_keys($versions))); + + return $now !== null && $now == $versions; + } + + private function storable(Response $response): bool + { + if ($response->getStatusCode() !== 200 || $response->headers->has('Content-Disposition')) { + return false; + } + + if (! str_contains((string) $response->headers->get('Content-Type'), 'text/html')) { + return false; + } + + // A page that must not be kept says so: Cache-Control no-store, or + // the X-Atrium-No-Cache header. + if ($response->headers->has('X-Atrium-No-Cache') || $response->headers->hasCacheControlDirective('no-store')) { + return false; + } + + // A page that holds something made for this visitor alone + // (dontKeepPage()). + if (! $this->cache->pageKeepable()) { + return false; + } + + // Cookies of the page's own (the session and form-token cookies are + // added later, by the middleware around this one). + if ($response->headers->getCookies() !== [] || Cookie::getQueuedCookies() !== []) { + return false; + } + + return is_string($response->getContent()) && $response->getContent() !== ''; + } + + /** + * @return array + */ + private function entry(Request $request, Response $response): array + { + $body = (string) $response->getContent(); + $token = $request->hasSession() ? (string) $request->session()->token() : ''; + $hasToken = $token !== '' && str_contains($body, $token); + + if ($hasToken) { + $body = str_replace($token, self::TOKEN, $body); + } + + $names = ['all', 'site:'.$this->site(), ...$this->cache->readNames()]; + + foreach ((array) config('atrium.cache.pages.depends_on', []) as $class) { + $names[] = 'list:'.$class; + } + + $names = array_values(array_unique($names)); + sort($names); + + return [ + 'body' => $body, + 'type' => (string) $response->headers->get('Content-Type'), + 'token' => $hasToken, + 'etag' => sha1($body), + 'time' => time(), + 'versions' => $this->versions->get($names), + ]; + } + + /** + * @param array $entry + */ + private function serve(Request $request, array $entry, string $state, ?Response $original = null): Response + { + $etag = '"'.$entry['etag'].'"'; + $response = $original ?? new Response('', 200, ['Content-Type' => $entry['type']]); + + if ($entry['token'] && $request->hasSession()) { + $response->setContent(str_replace(self::TOKEN, (string) $request->session()->token(), (string) $entry['body'])); + } elseif ($original === null) { + $response->setContent((string) $entry['body']); + } + + $response->headers->set('ETag', $etag); + $response->setLastModified((new DateTimeImmutable)->setTimestamp((int) $entry['time'])); + $response->headers->set(self::HEADER, $state); + + if ($entry['token']) { + $response->headers->set('Cache-Control', 'private, no-cache'); + } else { + $shared = max(0, (int) config('atrium.cache.pages.shared_max_age', 60)); + $response->headers->set('Cache-Control', 'public, max-age=0, s-maxage='.$shared); + } + + if (in_array($etag, $request->getETags(), true) || in_array('W/'.$etag, $request->getETags(), true)) { + $response->setNotModified(); + } + + return $response; + } + + private function site(): int + { + return $this->sites->isResolved() ? (int) $this->sites->current()->getKey() : 0; + } + + /** + * @template T + * + * @param Closure():T $callback + * @return T|null + */ + private function safely(Closure $callback): mixed + { + try { + return $callback(); + } catch (Throwable $e) { + report($e); + + return null; + } + } +} diff --git a/packages/admin/src/Models/SeoMeta.php b/packages/admin/src/Models/SeoMeta.php index 67022206..59ba8533 100644 --- a/packages/admin/src/Models/SeoMeta.php +++ b/packages/admin/src/Models/SeoMeta.php @@ -9,12 +9,15 @@ namespace Atrium\Admin\Models; +use Atrium\Admin\Cache\TouchesOwner; use Atrium\Admin\Support\MediaUrl; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; class SeoMeta extends Model { + use TouchesOwner; + protected $table = 'seo_meta'; protected $fillable = [ @@ -114,4 +117,9 @@ public function index(): self return $this; } + + protected function ownerMorphName(): string + { + return 'seoable'; + } } diff --git a/packages/admin/src/Models/Slug.php b/packages/admin/src/Models/Slug.php index 3999cc23..3cae805f 100644 --- a/packages/admin/src/Models/Slug.php +++ b/packages/admin/src/Models/Slug.php @@ -9,11 +9,14 @@ namespace Atrium\Admin\Models; +use Atrium\Admin\Cache\TouchesOwner; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; class Slug extends Model { + use TouchesOwner; + protected $table = 'slugs'; protected $fillable = [ @@ -78,4 +81,9 @@ public static function resolvePath(string $path, ?string $type = null): ?Model return $slugModel?->sluggable; } + + protected function ownerMorphName(): string + { + return 'sluggable'; + } } diff --git a/packages/admin/src/Modules/Settings.php b/packages/admin/src/Modules/Settings.php index 1ce119e1..ec2b4f99 100644 --- a/packages/admin/src/Modules/Settings.php +++ b/packages/admin/src/Modules/Settings.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Modules; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Models\Site; use Atrium\Admin\Support\Sites; use Illuminate\Database\QueryException; @@ -80,14 +81,22 @@ public function all(string $module, Site|int|null $site = null): array public function stored(string $module, int $siteId = 0): array { if (! isset($this->stored[$module])) { - $this->stored[$module] = []; - try { - foreach (DB::table(self::TABLE)->where('module', $module)->get(['site_id', 'values']) as $row) { - $this->stored[$module][(int) $row->site_id] = (array) json_decode((string) $row->values, true); - } + // Kept in the record cache: public pages read settings on + // every request. Not migrated yet throws past remember(), so + // an empty answer is never kept. + $this->stored[$module] = app(RecordCache::class)->remember(self::class, 'settings:'.$module, static function () use ($module): array { + $stored = []; + + foreach (DB::table(self::TABLE)->where('module', $module)->get(['site_id', 'values']) as $row) { + $stored[(int) $row->site_id] = (array) json_decode((string) $row->values, true); + } + + return $stored; + }, perSite: false); } catch (QueryException) { // Not migrated yet: nothing is saved. + $this->stored[$module] = []; } } @@ -123,6 +132,7 @@ public function save(string $module, array $values, Site|int|null $site = null): } $this->stored[$module][$siteId] = $values; + app(RecordCache::class)->flushClass(self::class); } /** @@ -163,5 +173,9 @@ public function siteId(ModuleSettings $declaration, Site|int|null $site = null): public function flush(): void { $this->stored = $this->declarations = $this->defaults = []; + + if (app()->resolved(RecordCache::class)) { + app(RecordCache::class)->flushClass(self::class); + } } } diff --git a/packages/admin/src/Support/ContentLanguages.php b/packages/admin/src/Support/ContentLanguages.php index da195361..2fd92b52 100644 --- a/packages/admin/src/Support/ContentLanguages.php +++ b/packages/admin/src/Support/ContentLanguages.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Support; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Models\Language; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; @@ -96,12 +97,16 @@ public function flush(): void private function load(): Collection { try { - $languages = Language::query() + $rows = app(RecordCache::class)->remember(Language::class, 'languages', static fn (): array => Language::query() ->where('active', true) ->orderByDesc('is_default') ->orderBy('sort') ->orderBy('id') - ->get(); + ->toBase() + ->get() + ->map(static fn (object $row): array => (array) $row) + ->all(), perSite: false); + $languages = Language::hydrate($rows); } catch (QueryException) { $languages = new Collection; } diff --git a/packages/admin/src/Support/PublicUrl.php b/packages/admin/src/Support/PublicUrl.php index 42181db1..6c93e257 100644 --- a/packages/admin/src/Support/PublicUrl.php +++ b/packages/admin/src/Support/PublicUrl.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Support; +use Atrium\Admin\Cache\RecordCache; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; @@ -109,7 +110,22 @@ public static function sectionPaths(string $treeClass, string $parentColumn = 'p return self::$pathCache[$cacheKey]; } + // Kept in the record cache until a section of the tree changes. + return self::$pathCache[$cacheKey] = app(RecordCache::class)->remember( + $treeClass, + 'section-paths:'.$parentColumn, + static fn (): array => self::buildSectionPaths($treeClass, $parentColumn), + perSite: false, + ); + } + + /** + * @return array + */ + private static function buildSectionPaths(string $treeClass, string $parentColumn): array + { $rows = $treeClass::query() + ->withoutGlobalScopes() ->get(['id', $parentColumn, 'code']) ->keyBy('id'); @@ -131,7 +147,7 @@ public static function sectionPaths(string $treeClass, string $parentColumn = 'p $paths[$id] = implode('/', $parts); } - return self::$pathCache[$cacheKey] = $paths; + return $paths; } /** diff --git a/packages/admin/src/Support/Sites.php b/packages/admin/src/Support/Sites.php index 12ce76a5..05681e34 100644 --- a/packages/admin/src/Support/Sites.php +++ b/packages/admin/src/Support/Sites.php @@ -9,6 +9,7 @@ namespace Atrium\Admin\Support; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Http\Middleware\EnterSiteFolder; use Atrium\Admin\Models\Site; use Illuminate\Database\QueryException; @@ -189,7 +190,9 @@ public function flush(): void private function load(): Collection { try { - $sites = Site::query()->orderByDesc('is_default')->orderBy('sort')->orderBy('id')->get(); + // Every request needs the sites: kept in the record cache until one is saved. + $rows = app(RecordCache::class)->remember(Site::class, 'sites', static fn (): array => Site::query()->orderByDesc('is_default')->orderBy('sort')->orderBy('id')->toBase()->get()->map(static fn (object $row): array => (array) $row)->all(), perSite: false); + $sites = Site::hydrate($rows); } catch (QueryException) { $sites = new Collection; } diff --git a/packages/admin/tests/Feature/CacheContractsTest.php b/packages/admin/tests/Feature/CacheContractsTest.php new file mode 100644 index 00000000..6e698d38 --- /dev/null +++ b/packages/admin/tests/Feature/CacheContractsTest.php @@ -0,0 +1,100 @@ +middleware('web')->get('/contact', function () { + return response('
'.app(CaptchaManager::class)->driver()->widget()->toHtml().'
'); + }); + + } + + public function test_a_page_with_a_captcha_question_is_never_kept(): void + { + config(['atrium.cache.pages.enabled' => true, 'atrium.captcha.driver' => 'image']); + + $first = $this->get('/contact')->assertOk()->assertHeaderMissing(CachePages::HEADER)->getContent(); + $second = $this->get('/contact')->assertOk()->assertHeaderMissing(CachePages::HEADER)->getContent(); + + // Each visitor gets a question of their own. + $this->assertNotSame($first, $second); + } + + public function test_a_page_with_the_captcha_off_is_kept(): void + { + config(['atrium.cache.pages.enabled' => true, 'atrium.captcha.driver' => 'none']); + + $this->get('/contact')->assertOk()->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('/contact')->assertOk()->assertHeader(CachePages::HEADER, 'HIT'); + } + + public function test_monitoring_reads_the_numbers_of_the_finished_request(): void + { + [$book] = $this->books(1); + $cache = $this->app->make(RecordCache::class); + Book::cached($book->id); + $this->resetRequest(); + + Book::cached($book->id); + $this->assertSame(['hits' => 1, 'misses' => 0], Hook::apply('atrium.cache.stats', ['hits' => 0, 'misses' => 0])); + + // What terminating() does at the end of the request. + $cache->reset(); + + $this->assertSame(['hits' => 1, 'misses' => 0], Hook::apply('atrium.cache.stats', ['hits' => 0, 'misses' => 0])); + } + + public function test_module_settings_are_read_without_a_query_and_saving_shows_at_once(): void + { + $settings = $this->app->make(Settings::class); + $settings->save('labels', ['color' => 'red']); + $this->assertSame(['color' => 'red'], $settings->stored('labels')); + + $this->forgetMemo($settings); + $this->assertSame(['color' => 'red'], $settings->stored('labels')); + $this->forgetMemo($settings); + [$queries, $stored] = $this->countQueries(fn () => $settings->stored('labels')); + + $this->assertSame(['color' => 'red'], $stored); + $this->assertSame(0, $queries); + + $settings->save('labels', ['color' => 'blue']); + $this->forgetMemo($settings); + + $this->assertSame(['color' => 'blue'], $settings->stored('labels')); + } + + /** + * What a new request starts with: the settings not yet read. + */ + private function forgetMemo(Settings $settings): void + { + (fn () => $this->stored = [])->call($settings); + } +} diff --git a/packages/admin/tests/Feature/CacheScreenTest.php b/packages/admin/tests/Feature/CacheScreenTest.php new file mode 100644 index 00000000..6be08056 --- /dev/null +++ b/packages/admin/tests/Feature/CacheScreenTest.php @@ -0,0 +1,98 @@ +books(1); + $cache = $this->app->make(RecordCache::class); + Book::cached($book->id); + $cache->persistStats(); + $this->resetRequest(); + Book::cached($book->id); + $cache->persistStats(); + // The panel's own request must not add to what is checked here. + config(['atrium.cache.stats' => false]); + ['hits' => $hits, 'misses' => $misses] = $cache->totals(); + $this->assertGreaterThan(0, $hits); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertOk() + ->assertInertia(fn (AssertableInertia $page) => $page + ->component('Admin/Cache/Index') + ->where('status.enabled', true) + ->where('status.driver', 'array') + ->where('status.hits', $hits) + ->where('status.misses', $misses) + ->where('status.rate', fn ($rate): bool => abs((float) $rate - $hits * 100 / ($hits + $misses)) < 0.1) + ->has('sites')); + } + + public function test_clearing_everything_rebuilds_the_cards(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + DB::table('cache_books')->update(['price' => 7]); + + $this->actingAs($this->admin(), 'admin') + ->post('/admin/cache/clear', ['scope' => 'all']) + ->assertRedirect('/admin/cache') + ->assertSessionHas('success'); + $this->resetRequest(); + + $this->assertSame(7, Book::cached($book->id)->price); + } + + public function test_resetting_the_counters_starts_them_from_zero(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + $cache = $this->app->make(RecordCache::class); + $cache->persistStats(); + $this->assertGreaterThan(0, $cache->totals()['misses']); + config(['atrium.cache.stats' => false]); + + $this->actingAs($this->admin(), 'admin')->post('/admin/cache/clear', ['scope' => 'stats'])->assertRedirect(); + + $this->assertSame(['hits' => 0, 'misses' => 0], $cache->totals()); + } + + public function test_an_unknown_scope_is_refused(): void + { + $this->actingAs($this->admin(), 'admin') + ->post('/admin/cache/clear', ['scope' => 'everything']) + ->assertSessionHasErrors('scope'); + } + + public function test_an_administrator_without_full_rights_cannot_open_it(): void + { + $editor = AdminUser::query()->create([ + 'name' => 'Editor', + 'email' => 'editor@example.com', + 'password' => 'secret-password', + 'is_active' => true, + ]); + + $this->actingAs($editor, 'admin')->get('/admin/cache')->assertForbidden(); + $this->actingAs($editor, 'admin')->post('/admin/cache/clear', ['scope' => 'all'])->assertForbidden(); + } +} diff --git a/packages/admin/tests/Feature/CacheTestCase.php b/packages/admin/tests/Feature/CacheTestCase.php new file mode 100644 index 00000000..8511797b --- /dev/null +++ b/packages/admin/tests/Feature/CacheTestCase.php @@ -0,0 +1,129 @@ +set('atrium.resources', [Post::class, Book::class]); + } + + protected function defineDatabaseMigrations(): void + { + parent::defineDatabaseMigrations(); + + Schema::create('cache_shelves', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + $table->timestamps(); + }); + + Schema::create('cache_tags', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->timestamps(); + }); + + Schema::create('cache_books', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + $table->boolean('active')->default(true); + $table->integer('price')->nullable(); + $table->foreignId('shelf_id')->nullable(); + $table->string('cover')->nullable(); + $table->json('photos')->nullable(); + $table->timestamps(); + }); + + Schema::create('cache_book_tag', function (Blueprint $table): void { + $table->foreignId('book_id'); + $table->foreignId('tag_id'); + }); + } + + protected function setUp(): void + { + parent::setUp(); + + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + } + + /** + * @return array + */ + protected function books(int $count, string $prefix = 'Book'): array + { + $books = []; + $red = Tag::query()->firstOrCreate(['name' => 'red']); + $blue = Tag::query()->firstOrCreate(['name' => 'blue']); + + for ($i = 1; $i <= $count; $i++) { + $shelf = Shelf::query()->create(['name' => ['en' => 'Shelf '.$i]]); + $book = Book::query()->create([ + 'name' => ['en' => $prefix.' '.$i], + 'price' => $i * 1000, + 'shelf_id' => $shelf->id, + 'cover' => 'books/cover-'.$i.'.jpg', + 'photos' => ['books/a.jpg', 'books/b.jpg'], + ]); + $book->tags()->attach([$red->id, $blue->id]); + $books[] = $book; + } + + return $books; + } + + /** + * What a new request starts with: nothing read yet. + */ + protected function resetRequest(): void + { + $this->app->make(RecordCache::class)->reset(); + } + + /** + * @template T + * + * @param callable():T $callback + * @return array{0:int,1:T} + */ + protected function countQueries(callable $callback): array + { + $count = 0; + DB::listen(function () use (&$count): void { + $count++; + }); + $before = $count; + $result = $callback(); + $queries = $count - $before; + // Further listeners keep counting; only this window matters. + $count = PHP_INT_MIN; + + return [$queries, $result]; + } +} diff --git a/packages/admin/tests/Feature/PageCacheTest.php b/packages/admin/tests/Feature/PageCacheTest.php new file mode 100644 index 00000000..b4bc3973 --- /dev/null +++ b/packages/admin/tests/Feature/PageCacheTest.php @@ -0,0 +1,208 @@ +middleware('web')->get('/books/{id}', function (int $id) { + return response('

'.e((string) Book::cached($id)?->name).'

'); + }); + + $router->middleware('web')->get('/order/{id}', function (int $id) { + return response('
'.e((string) Book::cached($id)?->name).''); + }); + + $router->middleware('web')->get('/posts', function () { + return response(''.e((string) Post::query()->orderBy('id')->first()?->name).''); + }); + + $router->middleware('web')->get('/cookie', function () { + return response('hi')->cookie('seen', '1'); + }); + + $router->middleware('web')->post('/books/{id}', fn () => response('posted')); + } + + protected function setUp(): void + { + parent::setUp(); + + config(['atrium.cache.pages.enabled' => true]); + } + + public function test_it_is_off_by_default(): void + { + config(['atrium.cache.pages.enabled' => false]); + [$book] = $this->books(1); + + $this->get('/books/'.$book->id)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get('/books/'.$book->id)->assertOk()->assertHeaderMissing(CachePages::HEADER); + } + + public function test_a_kept_page_is_served_without_a_query(): void + { + [$book] = $this->books(1); + + $this->get('/books/'.$book->id)->assertOk()->assertHeader(CachePages::HEADER, 'MISS')->assertSee('Book 1'); + + [$queries, $response] = $this->countQueries(fn () => $this->get('/books/'.$book->id)); + + $response->assertOk()->assertHeader(CachePages::HEADER, 'HIT')->assertSee('Book 1'); + $this->assertSame(0, $queries); + } + + public function test_a_save_makes_the_page_build_again(): void + { + [$book] = $this->books(1); + $this->get('/books/'.$book->id)->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('/books/'.$book->id)->assertHeader(CachePages::HEADER, 'HIT'); + + $book->setTranslation('name', 'en', 'Renamed')->save(); + + $this->get('/books/'.$book->id)->assertHeader(CachePages::HEADER, 'MISS')->assertSee('Renamed'); + } + + public function test_saving_a_model_the_page_read_directly_makes_it_build_again(): void + { + $post = Post::query()->create(['name' => 'First', 'active' => true]); + $this->get('/posts')->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('/posts')->assertHeader(CachePages::HEADER, 'HIT'); + + $post->update(['name' => 'Changed']); + + $this->get('/posts')->assertHeader(CachePages::HEADER, 'MISS')->assertSee('Changed'); + } + + public function test_clearing_a_module_clears_its_pages(): void + { + [$book] = $this->books(1); + $this->get('/books/'.$book->id); + DB::table('cache_books')->update(['name' => json_encode(['en' => 'Imported'])]); + + $this->app->make(RecordCache::class)->flushClass(Book::class); + + $this->get('/books/'.$book->id)->assertHeader(CachePages::HEADER, 'MISS')->assertSee('Imported'); + } + + public function test_a_kept_form_carries_the_current_visitors_token(): void + { + [$book] = $this->books(1); + + $first = $this->withSession(['_token' => 'token-of-the-first-visitor'])->get('/order/'.$book->id); + $first->assertHeader(CachePages::HEADER, 'MISS')->assertSee('token-of-the-first-visitor'); + $this->flushSession(); + + $second = $this->withSession(['_token' => 'token-of-the-second-visitor'])->get('/order/'.$book->id); + + $second->assertHeader(CachePages::HEADER, 'HIT') + ->assertSee('token-of-the-second-visitor') + ->assertDontSee('token-of-the-first-visitor') + ->assertDontSee(CachePages::TOKEN); + // A copy in a CDN would hand one visitor's token to the next. + $this->assertStringContainsString('private', (string) $second->headers->get('Cache-Control')); + } + + public function test_a_page_without_a_token_may_be_kept_by_a_cdn_and_answers_304(): void + { + [$book] = $this->books(1); + + $response = $this->get('/books/'.$book->id); + $etag = (string) $response->headers->get('ETag'); + + $this->assertNotSame('', $etag); + $this->assertNotNull($response->headers->get('Last-Modified')); + $this->assertStringContainsString('public', (string) $response->headers->get('Cache-Control')); + $this->assertStringContainsString('s-maxage=60', (string) $response->headers->get('Cache-Control')); + + $this->get('/books/'.$book->id, ['If-None-Match' => $etag])->assertStatus(304); + } + + public function test_an_admin_never_gets_a_kept_page(): void + { + [$book] = $this->books(1); + $this->get('/books/'.$book->id); + $admin = $this->admin(); + + $this->actingAs($admin, 'admin')->get('/books/'.$book->id)->assertOk()->assertHeaderMissing(CachePages::HEADER); + } + + public function test_posts_queries_and_own_cookies_are_handled_apart(): void + { + [$book] = $this->books(1); + + $this->post('/books/'.$book->id)->assertHeaderMissing(CachePages::HEADER); + $this->get('/books/'.$book->id.'?page=2')->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('/books/'.$book->id)->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('/books/'.$book->id.'?page=2')->assertHeader(CachePages::HEADER, 'HIT'); + $this->get('/cookie')->assertHeaderMissing(CachePages::HEADER); + $this->get('/cookie')->assertHeaderMissing(CachePages::HEADER); + } + + public function test_the_debug_line_counts_queries_and_hits_in_local_mode(): void + { + config(['atrium.cache.pages.enabled' => false, 'app.debug' => true]); + $this->app['env'] = 'local'; + [$book] = $this->books(1); + + $response = $this->get('/books/'.$book->id); + + $this->assertMatchesRegularExpression('/queries=\d+ .*cache hits=\d+ misses=[1-9]/', (string) $response->headers->get(CacheDebug::HEADER)); + $response->assertSee('data-atrium-debug', false); + + $this->app['env'] = 'testing'; + $this->get('/books/'.$book->id)->assertHeaderMissing(CacheDebug::HEADER); + } + + public function test_an_import_past_eloquent_drops_everything_once(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + + $this->app->make(RecordCache::class)->bulk(function (): void { + DB::table('cache_books')->update(['price' => 5]); + }, everything: true); + $this->resetRequest(); + + $this->assertSame(5, Book::cached($book->id)->price); + } + + public function test_saving_a_site_rebuilds_its_cards(): void + { + $site = Site::query()->firstOrCreate(['code' => 'main'], ['name' => 'Main', 'active' => true, 'is_default' => true]); + $this->app->make(Sites::class)->setCurrent($site); + [$book] = $this->books(1); + Book::cached($book->id); + DB::table('cache_books')->update(['price' => 9]); + + $site->update(['name' => 'Main site']); + $this->resetRequest(); + + $this->assertSame(9, Book::cached($book->id)->price); + } +} diff --git a/packages/admin/tests/Feature/RecordCacheTest.php b/packages/admin/tests/Feature/RecordCacheTest.php new file mode 100644 index 00000000..feeeeced --- /dev/null +++ b/packages/admin/tests/Feature/RecordCacheTest.php @@ -0,0 +1,276 @@ +books(3); + + $cards = Book::cachedMany([$c->id, 999, $a->id, $b->id]); + + $this->assertSame([$c->id, $a->id, $b->id], array_map(fn (Card $card): int|string => $card->id(), $cards)); + } + + public function test_a_warm_card_costs_no_query_and_one_cache_read(): void + { + $books = $this->books(5); + $ids = array_map(fn (Book $book): int => $book->id, $books); + + Book::cachedMany($ids); + $this->resetRequest(); + + $reads = 0; + $listener = function () use (&$reads): void { + $reads++; + }; + $this->app['events']->listen(RetrievingManyKeys::class, $listener); + + [$queries, $cards] = $this->countQueries(fn (): array => Book::cachedMany($ids)); + + $this->assertSame(0, $queries); + $this->assertCount(5, $cards); + // One multi-get of the versions, one of the cards. + $this->assertLessThanOrEqual(2, $reads); + $this->assertSame('Shelf 1', $cards[0]->relation('shelf')?->name); + } + + public function test_building_cards_costs_the_same_queries_for_ten_records_as_for_forty(): void + { + // Whatever is read once per request (the languages) is read first. + Book::cachedMany([$this->books(1)[0]->id]); + $ten = array_map(fn (Book $book): int => $book->id, $this->books(10)); + $forty = array_map(fn (Book $book): int => $book->id, $this->books(40)); + + [$few] = $this->countQueries(fn (): array => Book::cachedMany($ten)); + [$many] = $this->countQueries(fn (): array => Book::cachedMany($forty)); + + $this->assertSame($few, $many); + $this->assertLessThanOrEqual(5, $many); + } + + public function test_a_card_holds_the_record_in_its_language_with_relations_seo_and_pictures(): void + { + [$book] = $this->books(1); + $book->setTranslation('name', 'de', 'Buch 1')->save(); + $book->seoMeta()->create(['title' => 'Read Book 1']); + + $en = Book::cached($book->id, 'en'); + $de = Book::cached($book->id, 'de'); + + $this->assertSame('Book 1', $en->name); + $this->assertSame('Buch 1', $de->get('name')); + $this->assertSame('Read Book 1', $en->seo('title')); + $this->assertSame(['red', 'blue'], $en->relation('tags')->pluck('name')->all()); + $this->assertStringEndsWith('/storage/books/cover-1.jpg', (string) $en->picture('cover')); + $this->assertCount(2, $en->media('photos')); + $this->assertInstanceOf(Book::class, $en->model()); + $this->assertTrue($en->model()->relationLoaded('shelf')); + $this->assertSame(1000, $en['price']); + + // A card keeps the card's language and the default one, not all of them. + $this->assertSame(['en', 'de'], array_keys(json_decode($de->raw()['name'], true))); + } + + public function test_saving_a_record_drops_its_cards_in_every_language(): void + { + [$book] = $this->books(1); + Book::cached($book->id, 'en'); + Book::cached($book->id, 'de'); + + $book->setTranslation('name', 'en', 'Renamed')->setTranslation('name', 'de', 'Umbenannt')->save(); + $this->resetRequest(); + + $this->assertSame('Renamed', Book::cached($book->id, 'en')->name); + $this->assertSame('Umbenannt', Book::cached($book->id, 'de')->name); + } + + public function test_a_deleted_record_is_gone_from_cards_and_lists(): void + { + [$a, $b] = $this->books(2); + $this->assertSame([$a->id, $b->id], Book::query()->orderBy('id')->cachedIds()->ids); + Book::cachedMany([$a->id, $b->id]); + + $a->delete(); + $this->resetRequest(); + + $this->assertSame([$b->id], Book::query()->orderBy('id')->cachedIds()->ids); + $this->assertNull(Book::cached($a->id)); + } + + public function test_renaming_a_related_record_rebuilds_the_cards_that_show_it(): void + { + [$book] = $this->books(1); + $this->assertSame('Shelf 1', Book::cached($book->id)->relation('shelf')->name); + + $book->shelf->setTranslation('name', 'en', 'Moved shelf')->save(); + $this->resetRequest(); + + $this->assertSame('Moved shelf', Book::cached($book->id)->relation('shelf')->name); + } + + public function test_saving_seo_meta_drops_the_owners_card(): void + { + [$book] = $this->books(1); + $this->assertSame('Book 1', Book::cached($book->id)->seo('title')); + + SeoMeta::query()->create(['seoable_type' => Book::class, 'seoable_id' => $book->id, 'title' => 'New title']); + $this->resetRequest(); + + $this->assertSame('New title', Book::cached($book->id)->seo('title')); + } + + public function test_lists_are_cached_by_query_page_and_language(): void + { + $this->books(5); + + $first = Book::query()->orderByDesc('price')->cachedIds(2, 1); + $this->resetRequest(); + + [$queries, $again] = $this->countQueries(fn () => Book::query()->orderByDesc('price')->cachedIds(2, 1)); + $second = Book::query()->orderByDesc('price')->cachedIds(2, 2); + + $this->assertSame(0, $queries); + $this->assertSame($first->ids, $again->ids); + $this->assertSame(5, $again->total); + $this->assertNotSame($first->ids, $second->ids); + } + + public function test_a_new_record_shows_in_the_list_at_once(): void + { + $this->books(2); + $this->assertSame(2, Book::query()->cachedIds(10, 1)->total); + + $this->books(1, 'Extra'); + $this->resetRequest(); + + $this->assertSame(3, Book::query()->cachedIds(10, 1)->total); + } + + public function test_cached_paginate_gives_a_paginator_of_cards(): void + { + $this->books(5); + + $page = Book::query()->orderBy('id')->cachedPaginate(2, page: 3); + + $this->assertSame(5, $page->total()); + $this->assertCount(1, $page->items()); + $this->assertInstanceOf(Card::class, $page->items()[0]); + } + + public function test_an_admin_save_leaves_nothing_stale(): void + { + [$book] = $this->books(1); + $tag = Tag::query()->create(['name' => 'green']); + Book::cached($book->id); + Book::query()->where('price', '>', 500)->cachedIds(); + + $this->actingAs($this->admin(), 'admin') + ->put("/admin/books/{$book->id}", [ + 'name' => ['en' => 'Edited', 'de' => 'Bearbeitet'], + 'active' => true, + 'price' => 10, + 'shelf_id' => $book->shelf_id, + 'tags' => [$tag->id], + 'seo_title' => 'Edited title', + ]) + ->assertRedirect(); + + $this->resetRequest(); + $card = Book::cached($book->id); + + $this->assertSame('Edited', $card->name); + $this->assertSame(['green'], $card->relation('tags')->pluck('name')->all()); + $this->assertSame('Edited title', $card->seo('title')); + $this->assertSame([], Book::query()->where('price', '>', 500)->cachedIds()->ids); + } + + public function test_a_bulk_import_drops_the_cache_once_at_the_end(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + $cache = $this->app->make(RecordCache::class); + + $cache->bulk(function () use ($book): void { + $book->setTranslation('name', 'en', 'Imported')->save(); + $this->resetRequest(); + // Not dropped yet: the import is still running. + $this->assertSame('Book 1', Book::cached($book->id)->name); + }); + + $this->resetRequest(); + $this->assertSame('Imported', Book::cached($book->id)->name); + } + + public function test_remember_keeps_a_value_until_a_record_of_its_class_changes(): void + { + $cache = $this->app->make(RecordCache::class); + $calls = 0; + $count = function () use (&$calls): int { + $calls++; + + return Book::query()->count(); + }; + + $this->assertSame(0, $cache->remember(Book::class, 'count', $count)); + $this->assertSame(0, $cache->remember(Book::class, 'count', $count)); + $this->books(1); + $this->resetRequest(); + + $this->assertSame(1, $cache->remember(Book::class, 'count', $count)); + $this->assertSame(2, $calls); + } + + public function test_clearing_a_module_rebuilds_its_cards(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + DB::table('cache_books')->update(['price' => 1]); + + $this->app->make(RecordCache::class)->flushClass(Book::class); + $this->resetRequest(); + + $this->assertSame(1, Book::cached($book->id)->price); + } + + public function test_time_in_list_queries_moves_in_steps(): void + { + Carbon::setTestNow('2026-11-17 10:15:42'); + + $this->assertSame('2026-11-17 10:15:00', $this->app->make(RecordCache::class)->now()->format('Y-m-d H:i:s')); + + Carbon::setTestNow(); + } + + public function test_with_the_cache_off_everything_is_read_from_the_database(): void + { + config(['atrium.cache.enabled' => false]); + [$book] = $this->books(1); + Book::cached($book->id); + DB::table('cache_books')->update(['price' => 7]); + + $this->assertSame(7, Book::cached($book->id)->price); + } +} diff --git a/packages/admin/tests/Feature/RecordCacheVersionsTest.php b/packages/admin/tests/Feature/RecordCacheVersionsTest.php new file mode 100644 index 00000000..2fc136d9 --- /dev/null +++ b/packages/admin/tests/Feature/RecordCacheVersionsTest.php @@ -0,0 +1,44 @@ +directory = sys_get_temp_dir().'/atrium-cache-test-'.getmypid(); + $app['config']->set('cache.stores.cachefile', ['driver' => 'file', 'path' => $this->directory]); + $app['config']->set('atrium.cache.store', 'cachefile'); + } + + protected function tearDown(): void + { + File::deleteDirectory($this->directory); + + parent::tearDown(); + } + + public function test_the_file_store_uses_version_keys(): void + { + $this->assertFalse($this->app->make(CacheStore::class)->usesTags()); + $this->assertSame('file', $this->app->make(CacheStore::class)->driver()); + } +} diff --git a/packages/admin/tests/Fixtures/Cache/Book.php b/packages/admin/tests/Fixtures/Cache/Book.php new file mode 100644 index 00000000..c9f3834d --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Book.php @@ -0,0 +1,93 @@ + */ + public array $translatable = ['name']; + + protected function casts(): array + { + return ['active' => 'boolean', 'price' => 'integer', 'photos' => 'array']; + } + + /** + * @return BelongsTo + */ + public function shelf(): BelongsTo + { + return $this->belongsTo(Shelf::class, 'shelf_id'); + } + + /** + * @return BelongsToMany + */ + public function tags(): BelongsToMany + { + return $this->belongsToMany(Tag::class, 'cache_book_tag', 'book_id', 'tag_id'); + } + + public static function getAdminLabel(): string + { + return 'Books'; + } + + public static function getAdminRoutePrefix(): string + { + return 'books'; + } + + public static function getAdministrationFields(): array + { + return [ + TextField::make('name')->label('Name')->required(), + CheckboxField::make('active')->label('Active')->default(true), + NumberField::make('price')->label('Price'), + BelongsToField::make('shelf_id')->label('Shelf')->model(Shelf::class), + BelongsToManyField::make('tags')->label('Tags')->model(Tag::class), + ImageField::make('cover')->label('Cover'), + GalleryField::make('photos')->label('Photos'), + ]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } +} diff --git a/packages/admin/tests/Fixtures/Cache/Shelf.php b/packages/admin/tests/Fixtures/Cache/Shelf.php new file mode 100644 index 00000000..5a61621a --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Shelf.php @@ -0,0 +1,30 @@ + */ + public array $translatable = ['name']; +} diff --git a/packages/admin/tests/Fixtures/Cache/Tag.php b/packages/admin/tests/Fixtures/Cache/Tag.php new file mode 100644 index 00000000..f7578ded --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Tag.php @@ -0,0 +1,19 @@ +bulk(fn (): int => $this->import(), everything: true); + } + + private function import(): int { $this->info('Bitrix Data Migration'); $this->info('====================='); diff --git a/packages/bitrix/src/Commands/MigrateMediaLibraryCommand.php b/packages/bitrix/src/Commands/MigrateMediaLibraryCommand.php index 4073db93..dadbd6ee 100644 --- a/packages/bitrix/src/Commands/MigrateMediaLibraryCommand.php +++ b/packages/bitrix/src/Commands/MigrateMediaLibraryCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Bitrix\Commands; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Models\MediaCollection; use Atrium\Admin\Models\MediaItem; @@ -37,6 +38,12 @@ class MigrateMediaLibraryCommand extends AbstractBitrixCommand private const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']; public function handle(): int + { + // Rows go in past Eloquent: the record cache is dropped once, at the end. + return app(RecordCache::class)->bulk(fn (): int => $this->import(), everything: true); + } + + private function import(): int { if (! $this->verifyConnection()) { return self::FAILURE; diff --git a/packages/bitrix/src/Commands/MigrateSeoCommand.php b/packages/bitrix/src/Commands/MigrateSeoCommand.php index 6f186195..13c56c57 100644 --- a/packages/bitrix/src/Commands/MigrateSeoCommand.php +++ b/packages/bitrix/src/Commands/MigrateSeoCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Bitrix\Commands; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Traits\HasAdminSeo; use Atrium\Bitrix\Support\GeneratedPaths; use Illuminate\Database\Eloquent\Model; @@ -79,6 +80,12 @@ class MigrateSeoCommand extends AbstractBitrixCommand private array $missingTables = []; public function handle(): int + { + // Rows go in past Eloquent: the record cache is dropped once, at the end. + return app(RecordCache::class)->bulk(fn (): int => $this->import(), everything: true); + } + + private function import(): int { if (! $this->verifyConnection()) { return self::FAILURE; diff --git a/packages/bitrix/src/Commands/MigrateSitesCommand.php b/packages/bitrix/src/Commands/MigrateSitesCommand.php index 994942cd..60571df2 100644 --- a/packages/bitrix/src/Commands/MigrateSitesCommand.php +++ b/packages/bitrix/src/Commands/MigrateSitesCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Bitrix\Commands; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Models\Site; use Atrium\Bitrix\Support\BitrixSites; use Illuminate\Validation\ValidationException; @@ -27,6 +28,12 @@ class MigrateSitesCommand extends AbstractBitrixCommand protected $description = 'Move Bitrix sites (b_lang) with their folders and domains to Atrium'; public function handle(): int + { + // Rows go in past Eloquent: the record cache is dropped once, at the end. + return app(RecordCache::class)->bulk(fn (): int => $this->import(), everything: true); + } + + private function import(): int { if (! $this->verifyConnection()) { return self::FAILURE; diff --git a/packages/bitrix/src/Commands/SyncDataCommand.php b/packages/bitrix/src/Commands/SyncDataCommand.php index b5724ed8..75a90333 100644 --- a/packages/bitrix/src/Commands/SyncDataCommand.php +++ b/packages/bitrix/src/Commands/SyncDataCommand.php @@ -9,6 +9,7 @@ namespace Atrium\Bitrix\Commands; +use Atrium\Admin\Cache\RecordCache; use Atrium\Bitrix\Schema\IBlock; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; @@ -53,6 +54,12 @@ class SyncDataCommand extends MigrateDataCommand private array $report = []; public function handle(): int + { + // Rows go in past Eloquent: the record cache is dropped once, at the end. + return app(RecordCache::class)->bulk(fn (): int => $this->import(), everything: true); + } + + private function import(): int { $this->info('Catch-up transfer from Bitrix'); $this->info('=============================='); diff --git a/packages/brands/src/Models/Brand.php b/packages/brands/src/Models/Brand.php index 718ddecd..2e4f16e9 100644 --- a/packages/brands/src/Models/Brand.php +++ b/packages/brands/src/Models/Brand.php @@ -9,10 +9,12 @@ namespace Atrium\Brands\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\ImageColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\ColorField; use Atrium\Admin\Fields\ImageField; @@ -31,9 +33,9 @@ * @property string $name * @property string $code */ -class Brand extends Model implements Administrable +class Brand extends Model implements Administrable, Cacheable { - use InteractsWithAdmin; + use CachesRecords, InteractsWithAdmin; protected $table = 'brands'; diff --git a/packages/catalog/src/Models/CatalogSection.php b/packages/catalog/src/Models/CatalogSection.php index 8081c102..951b7129 100644 --- a/packages/catalog/src/Models/CatalogSection.php +++ b/packages/catalog/src/Models/CatalogSection.php @@ -9,9 +9,11 @@ namespace Atrium\Catalog\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\ContentField; use Atrium\Admin\Fields\ImageField; @@ -32,9 +34,9 @@ * @property string $name * @property string $code */ -class CatalogSection extends Model implements Administrable +class CatalogSection extends Model implements Administrable, Cacheable { - use InteractsWithAdmin; + use CachesRecords, InteractsWithAdmin; protected $table = 'catalog_sections'; diff --git a/packages/catalog/src/Models/Product.php b/packages/catalog/src/Models/Product.php index 0deecc88..71d98147 100644 --- a/packages/catalog/src/Models/Product.php +++ b/packages/catalog/src/Models/Product.php @@ -9,10 +9,12 @@ namespace Atrium\Catalog\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\ImageColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Fields\BelongsToManyField; use Atrium\Admin\Fields\CheckboxField; @@ -59,9 +61,9 @@ * @property string $name * @property string|null $code */ -class Product extends Model implements Administrable +class Product extends Model implements Administrable, Cacheable { - use HasAdminFiles, HasAdminSeo, HasAdminSlug, HasAdminTabs, HasSoftRelations, InteractsWithAdmin; + use CachesRecords, HasAdminFiles, HasAdminSeo, HasAdminSlug, HasAdminTabs, HasSoftRelations, InteractsWithAdmin; protected $table = 'catalog_products'; diff --git a/packages/faq/src/Faq.php b/packages/faq/src/Faq.php index 11e7bbba..e75f0c00 100644 --- a/packages/faq/src/Faq.php +++ b/packages/faq/src/Faq.php @@ -9,6 +9,7 @@ namespace Atrium\Faq; +use Atrium\Admin\Cache\Card; use Atrium\Faq\Models\Category; use Atrium\Faq\Models\Question; use Illuminate\Support\Collection; @@ -36,14 +37,16 @@ public function questions(?iterable $categories = null): Collection $query->whereKey(collect($categories)->map(fn (Category $category): mixed => $category->getKey())->all()); } - $order = $query->pluck('id')->flip(); + // Ids from the record cache, the questions from their cards. + $order = collect($query->cachedIds()->ids)->flip(); - return Question::query() + return collect(Question::query() ->whereIn('category_id', $order->keys()) ->where('active', true) ->orderBy('sort') ->orderBy('id') - ->get() + ->cachedCards(dependsOn: [Category::class])) + ->map(static fn (Card $card): Question => $card->model(Question::class)) ->filter(fn (Question $question): bool => $question->translated('question') !== '' && $question->translated('answer') !== '') ->sortBy(fn (Question $question): int => $order[$question->category_id], SORT_NUMERIC) ->values(); diff --git a/packages/faq/src/Models/Category.php b/packages/faq/src/Models/Category.php index ab39e2e3..cab264f4 100644 --- a/packages/faq/src/Models/Category.php +++ b/packages/faq/src/Models/Category.php @@ -9,9 +9,11 @@ namespace Atrium\Faq\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\NumberField; use Atrium\Admin\Fields\SlugField; @@ -31,9 +33,9 @@ * @property bool $active * @property int $sort */ -class Category extends Model implements Administrable +class Category extends Model implements Administrable, Cacheable { - use BelongsToSite, InteractsWithAdmin, Translatable; + use BelongsToSite, CachesRecords, InteractsWithAdmin, Translatable; protected $table = 'faq_categories'; diff --git a/packages/faq/src/Models/Question.php b/packages/faq/src/Models/Question.php index d2ca6a98..33ab0f30 100644 --- a/packages/faq/src/Models/Question.php +++ b/packages/faq/src/Models/Question.php @@ -9,9 +9,11 @@ namespace Atrium\Faq\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\ContentField; @@ -32,9 +34,9 @@ * @property bool $active * @property int $sort */ -class Question extends Model implements Administrable +class Question extends Model implements Administrable, Cacheable { - use BelongsToSite, InteractsWithAdmin, Translatable; + use BelongsToSite, CachesRecords, InteractsWithAdmin, Translatable; protected $table = 'faq_questions'; diff --git a/packages/news/src/Models/News.php b/packages/news/src/Models/News.php index 065ed5b2..3f713cc6 100644 --- a/packages/news/src/Models/News.php +++ b/packages/news/src/Models/News.php @@ -9,10 +9,12 @@ namespace Atrium\News\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\DateColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\ContentField; use Atrium\Admin\Fields\DateTimeField; @@ -32,9 +34,9 @@ * @property int $id * @property int|null $site_id */ -class News extends Model implements Administrable +class News extends Model implements Administrable, Cacheable { - use BelongsToSite, InteractsWithAdmin, Translatable; + use BelongsToSite, CachesRecords, InteractsWithAdmin, Translatable; protected $table = 'news'; diff --git a/packages/pages/src/Http/Controllers/PageController.php b/packages/pages/src/Http/Controllers/PageController.php index b7032750..2f2b1474 100644 --- a/packages/pages/src/Http/Controllers/PageController.php +++ b/packages/pages/src/Http/Controllers/PageController.php @@ -98,23 +98,23 @@ private function resolve(string $path): array $first = Str::before($path, '/'); if ($first !== $path && $first !== $default && $this->languages->has($first)) { - [$page, $old] = $this->find(Str::after($path, '/')); + [$page, $old] = $this->find(Str::after($path, '/'), $first); if ($page !== null) { return [$first, $page, $old]; } } - return [$default, ...$this->find($path)]; + return [$default, ...$this->find($path, $default)]; } /** * @return array{0:?Page,1:bool} */ - private function find(string $path): array + private function find(string $path, string $language): array { if (! str_ends_with($path, '.php')) { - return [$this->tree->find($path), false]; + return [$this->tree->find($path, $language), false]; } // Bitrix served /about/ from /about/index.php and /about/team/ from @@ -122,6 +122,6 @@ private function find(string $path): array $path = preg_replace('#(^|/)index\.php$#', '', $path) ?? $path; $path = preg_replace('#\.php$#', '', $path) ?? $path; - return [$path === '' ? null : $this->tree->find($path), true]; + return [$path === '' ? null : $this->tree->find($path, $language), true]; } } diff --git a/packages/pages/src/Models/Page.php b/packages/pages/src/Models/Page.php index 614ea3e0..8e77408f 100644 --- a/packages/pages/src/Models/Page.php +++ b/packages/pages/src/Models/Page.php @@ -10,10 +10,12 @@ namespace Atrium\Pages\Models; use Atrium\Admin\Actions\CreateFromRecord; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\DateColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Contracts\HasSeoFields; use Atrium\Admin\Contracts\Sitemapable; use Atrium\Admin\Fields\CheckboxField; @@ -54,9 +56,9 @@ * @property int $sort * @property string|null $source */ -class Page extends Model implements Administrable, HasSeoFields, Sitemapable +class Page extends Model implements Administrable, Cacheable, HasSeoFields, Sitemapable { - use BelongsToSite, HasAdminSeo, HasAdminTabs, InteractsWithAdmin, Translatable; + use BelongsToSite, CachesRecords, HasAdminSeo, HasAdminTabs, InteractsWithAdmin, Translatable; protected $table = 'pages'; diff --git a/packages/pages/src/PageTree.php b/packages/pages/src/PageTree.php index 223c1bed..014bdd74 100644 --- a/packages/pages/src/PageTree.php +++ b/packages/pages/src/PageTree.php @@ -9,6 +9,8 @@ namespace Atrium\Pages; +use Atrium\Admin\Cache\Card; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Support\ContentLanguages; use Atrium\Admin\Support\Sites; use Atrium\Pages\Models\Page; @@ -20,14 +22,15 @@ * * A page is visible when it and every page above it are active: hiding a * page hides its branch. The tree is read once (one query, no texts) and - * kept until a page is saved or deleted. + * kept in the record cache until a page is saved or deleted; the pages + * themselves come from their cards. */ final class PageTree { /** How many levels a path may have; also stops a loop in broken data. */ private const MAX_DEPTH = 20; - /** @var array,ids:array,parents:array,children:array>}> */ + /** @var array,ids:array,parents:array,children:array>,languages:array>}> */ private array $trees = []; public function __construct( @@ -36,13 +39,14 @@ public function __construct( ) {} /** - * The visible page at a path below the site root ("about/team"). + * The visible page at a path below the site root ("about/team"), read + * in a language (the current one by default). */ - public function find(string $path): ?Page + public function find(string $path, ?string $language = null): ?Page { $id = $this->tree()['ids'][trim($path, '/')] ?? null; - return $id === null ? null : Page::query()->find($id); + return $id === null ? null : $this->load([$id], $language)->first(); } /** @@ -62,7 +66,7 @@ public function url(Page $page, ?string $language = null): ?string $language ??= app()->getLocale(); $path = $this->path($page); - if ($path === null || ! $this->languages->has($language) || $page->getTranslation('name', $language, false) === '') { + if ($path === null || ! $this->languages->has($language) || ! in_array($language, $this->tree()['languages'][$page->getKey()] ?? [], true)) { return null; } @@ -125,41 +129,41 @@ public function flush(): void * @param array $ids * @return Collection */ - private function load(array $ids): Collection + private function load(array $ids, ?string $language = null): Collection { if ($ids === []) { return new Collection; } - $pages = Page::query()->whereKey($ids)->get()->keyBy('id'); - - return collect($ids)->map(fn (int $id): ?Page => $pages->get($id))->filter()->values(); + /** @var Collection */ + return collect(Page::cachedMany($ids, $language))->map(fn (Card $card): Page => $card->model(Page::class))->values(); } /** - * @return array{paths:array,ids:array,parents:array,children:array>} + * @return array{paths:array,ids:array,parents:array,children:array>,languages:array>} */ private function tree(): array { $key = $this->sites->isResolved() ? $this->sites->current()->getKey() : '*'; - return $this->trees[$key] ??= $this->build(); + return $this->trees[$key] ??= app(RecordCache::class)->remember(Page::class, 'page-tree', fn (): array => $this->build()); } /** - * @return array{paths:array,ids:array,parents:array,children:array>} + * @return array{paths:array,ids:array,parents:array,children:array>,languages:array>} */ private function build(): array { $rows = Page::query() ->orderBy('sort') ->orderBy('id') - ->get(['id', 'parent_id', 'code', 'active']) + ->get(['id', 'parent_id', 'code', 'active', 'name']) ->keyBy('id'); $paths = []; $parents = []; $children = []; + $languages = []; foreach ($rows as $id => $row) { $path = $this->pathOf($row, $rows); @@ -167,6 +171,8 @@ private function build(): array if ($path !== null) { $paths[$id] = $path; $parents[$id] = $row->parent_id; + // The languages the page has a name in: it has an address in those. + $languages[$id] = array_keys(array_filter((array) $row->getTranslations('name'), static fn (mixed $name): bool => (string) $name !== '')); } } @@ -184,7 +190,7 @@ private function build(): array $ids[$path] ??= $id; } - return ['paths' => $paths, 'ids' => $ids, 'parents' => $parents, 'children' => $children]; + return ['paths' => $paths, 'ids' => $ids, 'parents' => $parents, 'children' => $children, 'languages' => $languages]; } /** diff --git a/packages/reviews/src/Models/Review.php b/packages/reviews/src/Models/Review.php index 03c8b9b8..61b37bb2 100644 --- a/packages/reviews/src/Models/Review.php +++ b/packages/reviews/src/Models/Review.php @@ -9,9 +9,11 @@ namespace Atrium\Reviews\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\DateColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\DateTimeField; use Atrium\Admin\Fields\NumberField; use Atrium\Admin\Fields\SelectField; @@ -44,9 +46,9 @@ * @property Carbon|null $posted_at * @property Model|null $reviewable */ -class Review extends Model implements Administrable +class Review extends Model implements Administrable, Cacheable { - use BelongsToSite, HasSoftRelations, InteractsWithAdmin; + use BelongsToSite, CachesRecords, HasSoftRelations, InteractsWithAdmin; protected $table = 'reviews'; diff --git a/packages/reviews/src/ReviewCounters.php b/packages/reviews/src/ReviewCounters.php index ea42bf8b..b46bc7dd 100644 --- a/packages/reviews/src/ReviewCounters.php +++ b/packages/reviews/src/ReviewCounters.php @@ -9,6 +9,7 @@ namespace Atrium\Reviews; +use Atrium\Admin\Cache\RecordCache; use Atrium\Reviews\Models\Review; use Illuminate\Database\Connection; use Illuminate\Database\Query\Builder; @@ -108,6 +109,9 @@ public function rebuild(): int } }); + // Reviews changed behind Eloquent's back: what the cache shows of them is off too. + app(RecordCache::class)->flushClass(Review::class); + return $rows->count(); } diff --git a/packages/reviews/src/Reviews.php b/packages/reviews/src/Reviews.php index 0f5e3e90..b97d4f37 100644 --- a/packages/reviews/src/Reviews.php +++ b/packages/reviews/src/Reviews.php @@ -9,6 +9,8 @@ namespace Atrium\Reviews; +use Atrium\Admin\Cache\Card; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Contracts\Administrable; use Atrium\Admin\Modules\Soft; use Atrium\Admin\Support\Sites; @@ -123,7 +125,10 @@ public function summary(?Model $record = null): array $type = $record === null ? '' : $record->getMorphClass(); $id = $record === null ? 0 : $record->getKey(); - return $this->toSummary($this->counters()->where('reviewable_type', $type)->where('reviewable_id', $id)->first()); + // The counters change with the reviews: kept until a review is saved. + $row = app(RecordCache::class)->remember(Review::class, 'summary:'.$type.':'.$id, fn (): ?array => (array) ($this->counters()->where('reviewable_type', $type)->where('reviewable_id', $id)->first() ?? []) ?: null); + + return $this->toSummary($row === null ? null : (object) $row); } /** @@ -223,10 +228,12 @@ public function jsonLd(?Model $record, string $name, ?string $url, iterable $rev */ public function latest(?Model $record = null, ?int $limit = null): Collection { - return Review::query()->published()->about($record) + $cards = Review::query()->published()->about($record) ->orderByDesc('posted_at')->orderByDesc('id') ->limit($limit ?? config('atrium-reviews.per_page', 10)) - ->get(); + ->cachedCards(); + + return (new Review)->newCollection(array_map(static fn (Card $card): Review => $card->model(Review::class), $cards)); } /** diff --git a/packages/stores/src/Models/Store.php b/packages/stores/src/Models/Store.php index 8168dfd0..23c6bc2e 100644 --- a/packages/stores/src/Models/Store.php +++ b/packages/stores/src/Models/Store.php @@ -9,9 +9,11 @@ namespace Atrium\Stores\Models; +use Atrium\Admin\Cache\CachesRecords; use Atrium\Admin\Columns\BooleanColumn; use Atrium\Admin\Columns\TextColumn; use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\CheckboxField; use Atrium\Admin\Fields\ContentField; use Atrium\Admin\Fields\DateTimeField; @@ -34,9 +36,9 @@ * @property array|null $phones * @property array|null $location */ -class Store extends Model implements Administrable +class Store extends Model implements Administrable, Cacheable { - use InteractsWithAdmin; + use CachesRecords, InteractsWithAdmin; protected $table = 'stores'; diff --git a/packages/theme/src/Http/Controllers/PageController.php b/packages/theme/src/Http/Controllers/PageController.php index e6c50a71..b77ae238 100644 --- a/packages/theme/src/Http/Controllers/PageController.php +++ b/packages/theme/src/Http/Controllers/PageController.php @@ -9,6 +9,7 @@ namespace Atrium\Theme\Http\Controllers; +use Atrium\Admin\Cache\Card; use Atrium\Admin\Facades\Setting; use Atrium\Admin\Modules\Modules; use Atrium\Admin\Support\ContentLanguages; @@ -61,7 +62,7 @@ public function home(Skins $skins, HomeContent $content): View $modules[] = [ 'label' => $this->pages->label($class), 'url' => $this->pages->indexUrl($prefix), - 'records' => $this->views($this->pages->visible($class)->limit((int) config('atrium-theme.home_items', 3))->get()), + 'records' => $this->withUrls($this->pages->records($this->pages->visible($class)->limit((int) config('atrium-theme.home_items', 3)))), ]; } @@ -79,7 +80,7 @@ public function index(Request $request, string $prefix): View foreach ($this->pages->sectionModels($prefix) as $class) { $rule = $this->pages->module($prefix)[$class]; - $sections = [...$sections, ...$this->views($this->pages->visible($class)->whereNull($rule['parent_column'])->get())]; + $sections = [...$sections, ...$this->withUrls($this->pages->records($this->pages->visible($class)->whereNull($rule['parent_column'])))]; } $class = $this->pages->elementModels($prefix)[0] ?? null; @@ -104,20 +105,21 @@ public function show(Request $request, string $prefix, string $path): View|Redir abort_if($record === null, 404); - $url = $this->pages->url($record); + // From its card when the module is cached: no query. + $view = $this->pages->page($record); + $url = $view->url(); abort_if($url === null, 404); // Found by its code under another path: send the visitor and search // engines to where it lives now. - if ($this->pages->path($record) !== trim($path, '/')) { + if ($view->path() !== trim($path, '/')) { return redirect()->to($url, 301); } $rule = $this->pages->module($prefix)[$record::class]; - $urls = $this->pages->urls($record); + $urls = $view->urls(); $switch = $this->everyLanguage(fn (string $code): string => $urls[$code] ?? $this->pages->homeUrl($code)); - $view = new RecordView($record, $this->pages); $breadcrumbs = $this->breadcrumbs($prefix, $record, $rule); if ($this->pages->isSectionModel($record::class, $rule)) { @@ -141,7 +143,7 @@ public function show(Request $request, string $prefix, string $path): View|Redir private function section(Request $request, string $prefix, Model $section, RecordView $view, string $url, array $breadcrumbs, array $urls, array $switch): View { $rule = $this->pages->module($prefix)[$section::class]; - $children = $this->views($this->pages->visible($section::class)->where($rule['parent_column'], $section->getKey())->get()); + $children = $this->withUrls($this->pages->records($this->pages->visible($section::class)->where($rule['parent_column'], $section->getKey()))); $records = null; @@ -185,17 +187,17 @@ private function breadcrumbs(string $prefix, Model $record, array $rule): array $parentColumn = PublicUrl::ruleFor($tree)['parent_column']; for ($depth = 0; $parentId && $depth < self::MAX_DEPTH; $depth++) { - $section = $tree::query()->find($parentId); + $section = $this->pages->record($tree, $parentId); - if (! $section instanceof Model) { + if ($section === null) { break; } - if (($url = $this->pages->url($section)) !== null) { - array_unshift($crumbs, ['label' => (new RecordView($section, $this->pages))->title(), 'url' => $url]); + if (($url = $section->url()) !== null) { + array_unshift($crumbs, ['label' => $section->title(), 'url' => $url]); } - $parentId = $section->getAttribute($parentColumn); + $parentId = $section->record->getAttribute($parentColumn); } } @@ -205,27 +207,20 @@ private function breadcrumbs(string $prefix, Model $record, array $rule): array } /** - * @param iterable $records + * The pages a visitor can open. + * + * @param array $views * @return array */ - private function views(iterable $records): array + private function withUrls(array $views): array { - $views = []; - - foreach ($records as $record) { - $view = new RecordView($record, $this->pages); - - if ($view->url() !== null) { - $views[] = $view; - } - } - - return $views; + return array_values(array_filter($views, static fn (RecordView $view): bool => $view->url() !== null)); } /** * As many records a page as the module's `per_page` setting says, if it - * has one, or `atrium-theme.per_page`. + * has one, or `atrium-theme.per_page`. For a cached module the ids come + * from the cache, then the cards; the query itself otherwise. * * @param Builder $query */ @@ -234,6 +229,13 @@ private function paginate($query): LengthAwarePaginator $module = app(Modules::class)->ownerOf($query->getModel()::class); $perPage = (int) ($module === null ? null : Setting::get($module->key().'.per_page')) ?: (int) config('atrium-theme.per_page', 20); + if ($this->pages->isCached($query->getModel()::class)) { + $page = $query->cachedPaginate($perPage)->withQueryString(); + $page->setCollection($page->getCollection()->map(fn (Card $card): RecordView => RecordView::fromCard($card, $this->pages))); + + return $page; + } + $page = $query->paginate($perPage)->withQueryString(); $page->setCollection($page->getCollection()->map(fn (Model $record): RecordView => new RecordView($record, $this->pages))); diff --git a/packages/theme/src/Pages.php b/packages/theme/src/Pages.php index 31101849..a83176fc 100644 --- a/packages/theme/src/Pages.php +++ b/packages/theme/src/Pages.php @@ -9,14 +9,22 @@ namespace Atrium\Theme; +use Atrium\Admin\Cache\Card; +use Atrium\Admin\Cache\RecordCache; +use Atrium\Admin\Contracts\Administrable; +use Atrium\Admin\Contracts\Cacheable; +use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Support\ContentLanguages; use Atrium\Admin\Support\PublicUrl; use Atrium\Theme\Skins\Skins; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; +use WeakMap; /** * The modules that have pages on the site, read from @@ -32,9 +40,15 @@ final class Pages /** How many records one code may match before the lenient lookup gives up. */ private const MAX_CANDIDATES = 50; + /** @var array linked records, for preloadLinks() */ + private array $links = []; + /** @var array> */ private array $columns = []; + /** @var WeakMap|null the card each model from the cache came from */ + private ?WeakMap $cards = null; + /** * Prefix => [model class => rule], the longest prefix first, so that * `catalog/tours` is tried before `catalog`. @@ -150,17 +164,19 @@ public function visible(string $class): Builder { $query = $class::query(); $has = $this->columns($query->getModel()); + // Time in steps, not to the second: the cached lists keep their keys. + $now = app(RecordCache::class)->now(); if (isset($has['active'])) { $query->where('active', true); } if (isset($has['active_from'])) { - $query->where(fn (Builder $q) => $q->whereNull('active_from')->orWhere('active_from', '<=', now())); + $query->where(fn (Builder $q) => $q->whereNull('active_from')->orWhere('active_from', '<=', $now)); } if (isset($has['active_to'])) { - $query->where(fn (Builder $q) => $q->whereNull('active_to')->orWhere('active_to', '>=', now())); + $query->where(fn (Builder $q) => $q->whereNull('active_to')->orWhere('active_to', '>=', $now)); } if (isset($has['sort'])) { @@ -192,8 +208,23 @@ public function find(string $prefix, string $path): ?Model $query = $this->visible($class); $model = $query->getModel(); $column = $this->isTranslatable($model, 'code') ? 'code->'.app()->getLocale() : 'code'; + $query->where($column, $code)->limit(self::MAX_CANDIDATES); + + if ($this->isCached($class)) { + foreach ($query->cachedCards() as $card) { + $record = $this->remember($card); + + if ($this->page($record)->path() === $path) { + return $record; + } + + $fallback ??= $record; + } - foreach ($query->where($column, $code)->limit(self::MAX_CANDIDATES)->get() as $record) { + continue; + } + + foreach ($query->get() as $record) { if ($this->path($record) === $path) { return $record; } @@ -205,6 +236,70 @@ public function find(string $prefix, string $path): ?Model return $fallback; } + /** + * Whether a module's records come from the record cache. + */ + public function isCached(string $class): bool + { + return is_subclass_of($class, Cacheable::class) && app(RecordCache::class)->enabled(); + } + + /** + * Records of a query as pages: from their cards when the model is + * cached (one cache read, no query on a warm cache), from the + * database otherwise. + * + * @param Builder $query + * @return array + */ + public function records(Builder $query): array + { + $class = $query->getModel()::class; + + if (! $this->isCached($class)) { + return array_map(fn (Model $record): RecordView => new RecordView($record, $this), $query->get()->all()); + } + + return array_map(fn (Card $card): RecordView => RecordView::fromCard($card, $this), $query->cachedCards()); + } + + /** + * One record as a page, by id. + * + * @param class-string $class + */ + public function record(string $class, int|string $id): ?RecordView + { + if ($this->isCached($class)) { + $card = app(RecordCache::class)->cards($class, [$id])[0] ?? null; + + return $card === null ? null : RecordView::fromCard($card, $this); + } + + $record = $class::query()->find($id); + + return $record instanceof Model ? new RecordView($record, $this) : null; + } + + /** + * The page of a record: from its card when it came from the cache. + */ + public function page(Model $record): RecordView + { + $card = $this->cards?->offsetExists($record) ? $this->cards[$record] : null; + + return $card instanceof Card ? RecordView::fromCard($card, $this) : new RecordView($record, $this); + } + + private function remember(Card $card): Model + { + $this->cards ??= new WeakMap; + $model = $card->model(); + $this->cards[$model] = $card; + + return $model; + } + /** * The address of a record below its prefix: section path and code. */ @@ -224,6 +319,90 @@ public function path(Model $record, ?string $language = null): ?string return ltrim($parent.'/'.$code, '/'); } + /** + * Load the records a batch links to through its form's belongs-to + * fields and belongs-to-many relations, a query per field instead of + * one per record. + * + * @param EloquentCollection $records + */ + public function preloadLinks(EloquentCollection $records): void + { + $first = $records->first(); + + if (! $first instanceof Administrable) { + return; + } + + $relations = []; + + foreach ((array) $first::getAdministrationFields() as $field) { + if (! $field instanceof BelongsToField || ($class = $field->getModelClass()) === null) { + continue; + } + + if ($field->getType() === 'belongsToMany') { + if (method_exists($first, $field->getName()) && $first->{$field->getName()}() instanceof BelongsToMany) { + $relations[] = $field->getName(); + } + + continue; + } + + $values = $records->map(fn (Model $record): mixed => $record->getAttribute($field->getColumn())) + ->filter(fn (mixed $value): bool => is_scalar($value) && $value !== '') + ->unique() + ->reject(fn (mixed $value): bool => array_key_exists($this->linkKey($class, $field->getValueColumn(), $value), $this->links)) + ->values() + ->all(); + + if ($values === []) { + continue; + } + + foreach ($values as $value) { + $this->links[$this->linkKey($class, $field->getValueColumn(), $value)] = null; + } + + /** @var class-string $modelClass */ + $modelClass = $class; + + foreach ($modelClass::query()->whereIn($field->getValueColumn(), $values)->get() as $related) { + $this->links[$this->linkKey($class, $field->getValueColumn(), $related->getAttribute($field->getValueColumn()))] = $related; + } + } + + if ($relations !== []) { + $records->loadMissing($relations); + } + } + + /** + * The record a belongs-to field points at: from preloadLinks() while + * its batch is being drawn, a query otherwise. + * + * @param class-string $class + */ + public function linked(string $class, string $column, mixed $value): ?Model + { + $key = $this->linkKey($class, $column, $value); + + return array_key_exists($key, $this->links) ? $this->links[$key] : $class::query()->where($column, $value)->first(); + } + + /** + * Drop what preloadLinks() loaded: it holds for one batch only. + */ + public function forgetLinks(): void + { + $this->links = []; + } + + private function linkKey(string $class, string $column, mixed $value): string + { + return $class.'|'.$column.'|'.(string) $value; + } + /** * The record's page in a language, or null when it has none there: a * translated record needs its name and code in that language. diff --git a/packages/theme/src/RecordView.php b/packages/theme/src/RecordView.php index 9585f0d9..605054fc 100644 --- a/packages/theme/src/RecordView.php +++ b/packages/theme/src/RecordView.php @@ -9,6 +9,7 @@ namespace Atrium\Theme; +use Atrium\Admin\Cache\Card; use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Fields\BelongsToManyField; use Atrium\Admin\Fields\Field; @@ -28,6 +29,10 @@ * form: the picture, the text, then every other filled-in field by its type * — images as a gallery, files as links, the rest as a list of properties. * No template per module: whatever the form has, the page has. + * + * For a model in the record cache all of it is worked out once, when its + * card is built (toArray(), stored as the card's "theme" part), and the + * page reads it back with no query: fromCard(). */ final class RecordView { @@ -49,13 +54,111 @@ final class RecordView /** @var array|null */ private ?array $fields = null; + /** + * @param array|null $data what toArray() gave when the card was built + */ public function __construct( public readonly Model $record, private readonly Pages $pages, + private readonly ?array $data = null, ) {} + /** + * The page of a cached record: the card's model and the card's "theme" + * part. A card built before the theme was installed has none, and the + * page is worked out from the model then. + */ + public static function fromCard(Card $card, Pages $pages): self + { + $data = $card->extra('theme'); + + return new self($card->model(), $pages, is_array($data) ? $data : null); + } + + /** + * Everything the page shows, as plain values for the cache. Addresses + * on the current host are kept without it: the same card serves every + * domain of the site. + * + * @return array + */ + public function toArray(): array + { + $local = static fn (?string $url): ?string => self::local($url); + + return [ + 'title' => $this->title(), + 'seo_title' => $this->seoTitle(), + 'seo_description' => $this->seoDescription(), + 'seo_keywords' => $this->seoKeywords(), + 'og_image' => $local($this->ogImage()), + 'url' => $local($this->url()), + 'path' => $this->pages->path($this->record), + 'urls' => array_map($local, $this->pages->urls($this->record)), + 'date' => $this->date()?->toIso8601String(), + 'image' => $local($this->image()), + 'thumbnail' => $local($this->thumbnail()), + 'teaser' => $this->teaser()?->toHtml(), + 'body' => $this->body()?->toHtml(), + 'blocks' => array_map(static function (array $block) use ($local): array { + if (isset($block['html'])) { + $block['html'] = $block['html']->toHtml(); + } + + if (isset($block['images'])) { + $block['images'] = array_map($local, $block['images']); + } + + if (isset($block['files'])) { + $block['files'] = array_map(static fn (array $file): array => ['name' => $file['name'], 'url' => $local($file['url'])], $block['files']); + } + + if (isset($block['items'])) { + $block['items'] = array_map(static function (array $item) use ($local): array { + $item['url'] = $local($item['url'] ?? null); + $item['links'] = array_map(static fn (array $link): array => ['value' => $link['value'], 'url' => $local($link['url'] ?? null)], $item['links']); + + return $item; + }, $block['items']); + } + + return $block; + }, $this->blocks()), + ]; + } + + /** + * The path below the module's prefix (section path and code). + */ + public function path(): ?string + { + if ($this->data !== null) { + return $this->data['path'] ?? null; + } + + return $this->pages->path($this->record); + } + + /** + * The page in every language it is written in. + * + * @return array + */ + public function urls(): array + { + if ($this->data !== null) { + return array_filter(array_map(self::absolute(...), (array) ($this->data['urls'] ?? []))); + } + + return $this->pages->urls($this->record); + } + public function title(): string { + if ($this->data !== null) { + return (string) $this->data['title']; + } + foreach (['name', 'title'] as $attribute) { if (($text = $this->pages->text($this->record, $attribute)) !== '') { return $text; @@ -73,6 +176,10 @@ public function title(): string */ public function seoTitle(): string { + if ($this->data !== null) { + return (string) $this->data['seo_title']; + } + $title = method_exists($this->record, 'getSeoTitle') ? (string) $this->record->getSeoTitle() : ''; return $title !== '' ? $title : $this->title(); @@ -80,6 +187,10 @@ public function seoTitle(): string public function seoDescription(): string { + if ($this->data !== null) { + return (string) $this->data['seo_description']; + } + $description = method_exists($this->record, 'getSeoDescription') ? (string) $this->record->getSeoDescription() : ''; if ($description !== '') { @@ -93,11 +204,19 @@ public function seoDescription(): string public function seoKeywords(): ?string { + if ($this->data !== null) { + return $this->data['seo_keywords'] ?? null; + } + return method_exists($this->record, 'getSeoKeywords') ? $this->record->getSeoKeywords() : null; } public function ogImage(): ?string { + if ($this->data !== null) { + return self::absolute($this->data['og_image'] ?? null); + } + $image = method_exists($this->record, 'getOgImage') ? $this->record->getOgImage() : null; return is_string($image) && $image !== '' ? $image : $this->image(); @@ -105,11 +224,19 @@ public function ogImage(): ?string public function url(): ?string { + if ($this->data !== null) { + return self::absolute($this->data['url'] ?? null); + } + return $this->pages->url($this->record); } public function date(): ?Carbon { + if ($this->data !== null) { + return isset($this->data['date']) ? Carbon::parse($this->data['date'])->locale(app()->getLocale()) : null; + } + $value = $this->record->getAttribute('active_from'); return $value instanceof DateTimeInterface ? Carbon::instance($value)->locale(app()->getLocale()) : null; @@ -120,6 +247,10 @@ public function date(): ?Carbon */ public function image(): ?string { + if ($this->data !== null) { + return self::absolute($this->data['image'] ?? null); + } + return $this->media('detail_picture') ?? $this->media('picture') ?? $this->media('preview_picture'); } @@ -128,6 +259,10 @@ public function image(): ?string */ public function thumbnail(): ?string { + if ($this->data !== null) { + return self::absolute($this->data['thumbnail'] ?? null); + } + return $this->media('preview_picture') ?? $this->media('picture') ?? $this->media('detail_picture'); } @@ -136,6 +271,10 @@ public function thumbnail(): ?string */ public function teaser(): ?HtmlString { + if ($this->data !== null) { + return isset($this->data['teaser']) ? new HtmlString((string) $this->data['teaser']) : null; + } + return $this->html('preview_text'); } @@ -145,6 +284,10 @@ public function teaser(): ?HtmlString */ public function body(): ?HtmlString { + if ($this->data !== null) { + return isset($this->data['body']) ? new HtmlString((string) $this->data['body']) : null; + } + return $this->html('detail_text') ?? $this->html('preview_text') ?? $this->html('description'); } @@ -152,10 +295,14 @@ public function body(): ?HtmlString * Everything else that is filled in, in the form's order. Neighbouring * properties are grouped into one list. * - * @return array}|array{kind:'html',label:string,html:HtmlString}|array{kind:'images',label:string,images:array}|array{kind:'files',label:string,files:array}> + * @return array}>}|array{kind:'html',label:string,html:HtmlString}|array{kind:'images',label:string,images:array}|array{kind:'files',label:string,files:array}> */ public function blocks(): array { + if ($this->data !== null) { + return $this->cachedBlocks(); + } + $blocks = []; $skip = $this->skippedColumns(); @@ -273,8 +420,17 @@ private function linkProperty(Field $field, mixed $value): ?array return null; } + // The relation behind the field, when it is loaded (cards load it + // for every record at once); a query otherwise. + $relation = Str::camel(Str::beforeLast($field->getColumn(), '_id')); + $loaded = $field->getValueColumn() === 'id' && $relation !== $field->getColumn() && $this->record->relationLoaded($relation) + ? $this->record->getRelation($relation) + : false; + /** @var class-string $class */ - $related = $class::query()->where($field->getValueColumn(), $value)->first(); + $related = $loaded instanceof Model || $loaded === null + ? $loaded + : $this->pages->linked($class, $field->getValueColumn(), $value); if ($related === null) { return null; @@ -303,7 +459,9 @@ private function linksBlock(BelongsToManyField $field): ?array $items = []; - foreach ($relation->get() as $item) { + $related = $this->record->relationLoaded($name) ? $this->record->getRelation($name) : $relation->get(); + + foreach ($related as $item) { $text = $this->pages->text($item, $field->getDisplayColumn()); if ($text !== '') { @@ -422,4 +580,58 @@ private function fields(): array return $this->fields ??= array_filter($fields, static fn (mixed $field): bool => $field instanceof Field); } + + /** + * Blocks read back from the cache: texts become HTML again, addresses + * get the current host. + * + * @return array> + */ + private function cachedBlocks(): array + { + return array_map(static function (array $block): array { + if (isset($block['html'])) { + $block['html'] = new HtmlString((string) $block['html']); + } + + if (isset($block['images'])) { + $block['images'] = array_map(self::absolute(...), $block['images']); + } + + if (isset($block['files'])) { + $block['files'] = array_map(static fn (array $file): array => ['name' => $file['name'], 'url' => self::absolute($file['url'])], $block['files']); + } + + if (isset($block['items'])) { + $block['items'] = array_map(static function (array $item): array { + $item['url'] = self::absolute($item['url'] ?? null); + $item['links'] = array_map(static fn (array $link): array => ['value' => $link['value'], 'url' => self::absolute($link['url'] ?? null)], $item['links'] ?? []); + + return $item; + }, $block['items']); + } + + return $block; + }, (array) ($this->data['blocks'] ?? [])); + } + + private static function local(?string $url): ?string + { + if ($url === null) { + return null; + } + + $host = request()->getSchemeAndHttpHost(); + + return str_starts_with($url, $host.'/') || $url === $host ? substr($url, strlen($host)) ?: '/' : $url; + } + + private static function absolute(?string $url): ?string + { + if ($url === null || $url === '') { + return null; + } + + return str_starts_with($url, '/') && ! str_starts_with($url, '//') ? request()->getSchemeAndHttpHost().$url : $url; + } } diff --git a/packages/theme/src/ThemeServiceProvider.php b/packages/theme/src/ThemeServiceProvider.php index b6569256..7bd84218 100644 --- a/packages/theme/src/ThemeServiceProvider.php +++ b/packages/theme/src/ThemeServiceProvider.php @@ -9,6 +9,7 @@ namespace Atrium\Theme; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Contracts\Sitemapable; use Atrium\Admin\Support\ContentLanguages; use Atrium\Admin\Support\PublicUrl; @@ -19,6 +20,7 @@ use Atrium\Theme\Http\Controllers\PageController; use Atrium\Theme\Skins\Skin; use Atrium\Theme\Skins\Skins; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Routing\Route as RoutingRoute; use Illuminate\Support\Facades\Event; @@ -88,6 +90,44 @@ public function boot(): void ); }); + // A cached record's card carries its page, worked out once. + $this->callAfterResolving(RecordCache::class, function (RecordCache $cache): void { + // atrium:cache:warm opens the home page and the first page of every list. + $cache->warmUsing(function (string $language): array { + $pages = $this->app->make(Pages::class); + $urls = [$pages->homeUrl($language)]; + + foreach ($pages->prefixes() as $prefix) { + $urls[] = $pages->indexUrl($prefix, $language); + } + + return $urls; + }); + + $cache->extend('theme', function (Collection $models): array { + $pages = $this->app->make(Pages::class); + $first = $models->first(); + + // Only the modules whose pages the theme draws. + if ($first === null || ($rule = PublicUrl::ruleFor($first::class)) === null || $rule['prefix'] === '' || ! Route::has('atrium.theme.page')) { + return []; + } + + $data = []; + $pages->preloadLinks($models); + + try { + foreach ($models as $record) { + $data[$record->getKey()] = (new RecordView($record, $pages))->toArray(); + } + } finally { + $pages->forgetLinks(); + } + + return $data; + }); + }); + $flush = function (string $event, array $payload): void { $record = $payload[0] ?? null; diff --git a/packages/theme/tests/CacheBenchmarkTest.php b/packages/theme/tests/CacheBenchmarkTest.php new file mode 100644 index 00000000..0357bf22 --- /dev/null +++ b/packages/theme/tests/CacheBenchmarkTest.php @@ -0,0 +1,274 @@ +set('atrium.public_urls', [...(array) $config->get('atrium.public_urls'), BenchProduct::class => ['prefix' => 'bench']]); + + // The dashboard's page timing is written after the response is sent + // (a visitor does not wait for it): left out of the counts. + $config->set('atrium.dashboard.timings.enabled', false); + + $store = (string) (env('ATRIUM_BENCHMARK_STORE') ?: 'file'); + $config->set('atrium.cache.store', $store); + $config->set('cache.stores.file.path', sys_get_temp_dir().'/atrium-cache-benchmark'); + $config->set('database.redis.client', 'phpredis'); + $config->set('database.redis.cache.host', env('REDIS_HOST', '127.0.0.1')); + $config->set('database.redis.cache.port', (int) env('REDIS_PORT', 6379)); + $config->set('database.redis.cache.database', 1); + } + + public function test_the_catalog_benchmark(): void + { + if (! env('ATRIUM_BENCHMARK')) { + $this->markTestSkipped('Set ATRIUM_BENCHMARK=1 to run the cache benchmark.'); + } + + $count = (int) (env('ATRIUM_BENCHMARK_PRODUCTS') ?: 10000); + $this->seedCatalog($count); + $cache = $this->app->make(RecordCache::class); + $cache->flushAll(); + + $pages = [ + 'list, page 1' => '/bench', + 'list, page '.intdiv($count, 40) => '/bench?page='.intdiv($count, 40), + 'product page' => '/bench/product-'.intdiv($count, 2), + ]; + $rows = []; + + foreach ($pages as $label => $url) { + $this->get($url)->assertOk(); // the schema is read once per process + + config(['atrium.cache.enabled' => false, 'atrium.cache.pages.enabled' => false]); + $rows[$label]['off'] = $this->measure($url, fn () => null); + + config(['atrium.cache.enabled' => true]); + $rows[$label]['cold'] = $this->measure($url, function () use ($cache): void { + $cache->flushAll(); + PublicUrl::forgetPaths(); + }); + $rows[$label]['warm'] = $this->measure($url, fn () => null); + + config(['atrium.cache.pages.enabled' => true]); + $this->get($url); + $rows[$label]['page'] = $this->measure($url, fn () => null); + config(['atrium.cache.pages.enabled' => false]); + } + + $report = $this->report($count, $rows); + fwrite(STDERR, PHP_EOL.$report.PHP_EOL); + + if ($file = env('ATRIUM_BENCHMARK_REPORT')) { + file_put_contents((string) $file, $report.PHP_EOL, FILE_APPEND); + } + + // The targets: a list in the same few queries on any page, a warm + // product page in two at most, a kept page in none. + $this->assertSame($rows['list, page 1']['cold']['queries'], $rows['list, page '.intdiv($count, 40)]['cold']['queries']); + $this->assertLessThanOrEqual(2, $rows['list, page 1']['warm']['queries']); + $this->assertLessThanOrEqual(2, $rows['product page']['warm']['queries']); + $this->assertSame(0, $rows['product page']['page']['queries']); + } + + /** + * The median of a few runs: queries, wall time and this process's CPU + * time (the wall time includes the database and the cache store). + * + * @return array{queries:int,ms:float,cpu:float} + */ + private function measure(string $url, callable $before): array + { + $count = 0; + $listening = false; + DB::listen(function () use (&$count, &$listening): void { + if ($listening) { + $count++; + } + }); + $wall = []; + $cpu = []; + + for ($run = 0; $run < self::RUNS; $run++) { + $before(); + $count = 0; + $listening = true; + $usage = getrusage(); + $start = hrtime(true); + $this->get($url)->assertOk()->assertSee('Product'); + $wall[] = (hrtime(true) - $start) / 1e6; + $cpu[] = $this->cpu(getrusage()) - $this->cpu($usage); + $listening = false; + } + + sort($wall); + sort($cpu); + + return ['queries' => $count, 'ms' => round($wall[intdiv(self::RUNS, 2)], 1), 'cpu' => round($cpu[intdiv(self::RUNS, 2)], 1)]; + } + + /** + * @param array $usage + */ + private function cpu(array $usage): float + { + return $usage['ru_utime.tv_sec'] * 1000 + $usage['ru_utime.tv_usec'] / 1000 + $usage['ru_stime.tv_sec'] * 1000 + $usage['ru_stime.tv_usec'] / 1000; + } + + /** + * @param array> $rows + */ + private function report(int $count, array $rows): string + { + $lines = [ + sprintf('%d products × %d properties, %s, %s store (median of %d; queries, wall ms / PHP CPU ms)', $count, count(BenchProduct::properties()), DB::connection()->getDriverName(), config('atrium.cache.store'), self::RUNS), + '', + '| Page | Cache off | Cold cache | Warm cache | Page cache |', + '|---|---|---|---|---|', + ]; + + foreach ($rows as $label => $row) { + $cells = array_map(fn (array $cell): string => sprintf('%d q, %.1f / %.1f ms', $cell['queries'], $cell['ms'], $cell['cpu']), $row); + $lines[] = '| '.$label.' | '.implode(' | ', $cells).' |'; + } + + return implode(PHP_EOL, $lines); + } + + private function seedCatalog(int $count): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch']); + + Schema::create('bench_products', function (Blueprint $table): void { + $table->id(); + $table->boolean('active')->default(true); + $table->dateTime('active_from')->nullable(); + $table->dateTime('active_to')->nullable(); + $table->integer('sort')->default(500); + $table->json('name'); + $table->json('code'); + + foreach (BenchProduct::properties() as $column => $kind) { + match ($kind) { + 'number' => $table->decimal($column, 12, 2)->nullable(), + 'content' => $table->text($column)->nullable(), + 'brand' => $table->unsignedBigInteger($column)->nullable(), + default => $table->string($column)->nullable(), + }; + } + + $table->string('preview_picture')->nullable(); + $table->text('preview_text')->nullable(); + $table->string('detail_picture')->nullable(); + $table->json('detail_text')->nullable(); + $table->text('photos')->nullable(); + $table->string('meta_title')->nullable(); + $table->timestamps(); + }); + + Schema::create('bench_related', function (Blueprint $table): void { + $table->id(); + $table->foreignId('product_id')->index(); + $table->foreignId('related_id'); + }); + + $brands = []; + + for ($i = 1; $i <= 50; $i++) { + $brands[] = ['name' => 'Brand '.$i, 'xml_id' => 'brand-'.$i, 'created_at' => now(), 'updated_at' => now()]; + } + + Brand::query()->insert($brands); + + foreach (array_chunk(range(1, $count), 200) as $chunk) { + $products = []; + $related = []; + $seo = []; + + foreach ($chunk as $i) { + $products[] = $this->product($i); + + foreach ([1, 2, 3] as $step) { + $related[] = ['product_id' => $i, 'related_id' => ($i + $step * 7) % $count + 1]; + } + + $seo[] = ['seoable_type' => BenchProduct::class, 'seoable_id' => $i, 'title' => 'Buy product '.$i, 'description' => 'Product '.$i.' at the best price', 'created_at' => now(), 'updated_at' => now()]; + } + + DB::table('bench_products')->insert($products); + DB::table('bench_related')->insert($related); + DB::table('seo_meta')->insert($seo); + } + } + + /** + * @return array + */ + private function product(int $i): array + { + $row = [ + 'active' => true, + 'sort' => $i, + 'name' => json_encode(['en' => 'Product '.$i, 'de' => 'Produkt '.$i]), + 'code' => json_encode(['en' => 'product-'.$i, 'de' => 'produkt-'.$i]), + 'preview_picture' => '/upload/iblock/'.($i % 100).'/'.$i.'.jpg', + 'preview_text' => '

Short about product '.$i.'

', + 'detail_picture' => '/upload/iblock/'.($i % 100).'/'.$i.'-big.jpg', + 'detail_text' => json_encode(['en' => '

All about product '.$i.'

', 'de' => '

Alles über Produkt '.$i.'

']), + 'photos' => json_encode(['/upload/iblock/a/'.$i.'-1.jpg', '/upload/iblock/a/'.$i.'-2.jpg', '/upload/iblock/a/'.$i.'-3.jpg']), + 'meta_title' => 'Product '.$i, + 'created_at' => now(), + 'updated_at' => now(), + ]; + + foreach (BenchProduct::properties() as $column => $kind) { + $row[$column] = match ($kind) { + 'text' => 'Value '.$column.' '.$i, + 'number' => ($i * 13 % 1000) + 0.5, + 'list' => ['a', 'b', 'c'][$i % 3], + 'flag' => $i % 2 === 0 ? 'Y' : null, + 'content' => '

'.$column.' of product '.$i.'

', + default => $i % 50 + 1, + }; + } + + return $row; + } +} diff --git a/packages/theme/tests/CachedPagesTest.php b/packages/theme/tests/CachedPagesTest.php new file mode 100644 index 00000000..9c41235c --- /dev/null +++ b/packages/theme/tests/CachedPagesTest.php @@ -0,0 +1,149 @@ +create(['name' => 'Computers', 'code' => 'computers']); + $this->laptops = ProductSection::query()->create(['name' => 'Laptops', 'code' => 'laptops', 'parent_id' => $computers->id]); + } + + public function test_a_list_page_costs_the_same_queries_for_any_number_of_records(): void + { + $cache = $this->app->make(RecordCache::class); + $this->products(3); + $this->get('/catalog')->assertOk(); // the schema is read once per process + $cache->flushAll(); + PublicUrl::forgetPaths(); + $few = $this->queries(fn () => $this->get('/catalog')->assertOk()); + + $this->products(17, 'More'); + $cache->flushAll(); + PublicUrl::forgetPaths(); + $many = $this->queries(fn () => $this->get('/catalog')->assertOk()->assertSee('More 17')); + + $this->assertSame($few, $many); + } + + public function test_a_warm_product_page_runs_at_most_two_queries(): void + { + $this->products(1); + $url = '/catalog/computers/laptops/product-1'; + $this->get($url)->assertOk()->assertSee('Product 1'); + + $queries = $this->queries(fn () => $this->get($url)->assertOk()->assertSee('Product 1')); + + $this->assertLessThanOrEqual(2, $queries); + } + + public function test_a_warm_list_page_runs_at_most_two_queries(): void + { + $this->products(5); + $this->get('/catalog')->assertOk(); + + $queries = $this->queries(fn () => $this->get('/catalog')->assertOk()->assertSee('Product 5')); + + $this->assertLessThanOrEqual(2, $queries); + } + + public function test_a_save_shows_on_the_list_and_the_page_at_once(): void + { + [$product] = $this->products(1); + $brand = Brand::query()->create(['name' => 'Northwind', 'xml_id' => 'northwind']); + $product->update(['brand' => $brand->id]); + $this->get('/catalog')->assertSee('Product 1'); + $this->get('/catalog/computers/laptops/product-1')->assertSee('Product 1'); + + $product->update(['name' => 'Renamed']); + + $this->get('/catalog')->assertSee('Renamed')->assertDontSee('Product 1'); + $this->get('/catalog/computers/laptops/product-1')->assertSee('Renamed'); + } + + public function test_moving_a_section_moves_its_products_addresses(): void + { + $this->products(1); + $this->get('/catalog/computers/laptops/product-1')->assertOk(); + + $this->laptops->update(['code' => 'notebooks']); + + $this->get('/catalog/computers/notebooks/product-1')->assertOk()->assertSee('Product 1'); + } + + public function test_the_warm_command_fills_the_cache(): void + { + $this->products(3); + + $this->artisan('atrium:cache:warm', ['--records' => true]) + ->expectsOutputToContain('built 5 cards') // three products, two sections + ->assertSuccessful(); + + $cache = $this->app->make(RecordCache::class); + $cache->reset(); + $this->get('/catalog')->assertOk(); + + $this->assertSame(0, $cache->requestStats()['misses']); + } + + /** + * @return array + */ + private function products(int $count, string $prefix = 'Product'): array + { + $products = []; + + for ($i = 1; $i <= $count; $i++) { + $products[] = Product::query()->create([ + 'section_id' => $this->laptops->id, + 'name' => $prefix.' '.$i, + 'code' => strtolower($prefix).'-'.$i, + 'sort' => $i, + 'preview_picture' => '/upload/iblock/1/'.$i.'.jpg', + 'detail_text' => '

About '.$i.'

', + 'photos' => json_encode(['/upload/a.jpg', 'products/b.jpg']), + ]); + } + + return $products; + } + + private function queries(callable $request): int + { + $count = 0; + $counting = true; + DB::listen(function () use (&$count, &$counting): void { + if ($counting) { + $count++; + } + }); + $request(); + $counting = false; + + return $count; + } +} diff --git a/packages/theme/tests/FileStoreCacheTest.php b/packages/theme/tests/FileStoreCacheTest.php new file mode 100644 index 00000000..c4f37a20 --- /dev/null +++ b/packages/theme/tests/FileStoreCacheTest.php @@ -0,0 +1,71 @@ +path = sys_get_temp_dir().'/atrium-file-store-test-'.getmypid(); + $app['config']->set('cache.serializable_classes', false); + $app['config']->set('cache.stores.file.path', $this->path); + $app['config']->set('atrium.cache.store', 'file'); + } + + protected function tearDown(): void + { + File::deleteDirectory($this->path); + + parent::tearDown(); + } + + public function test_warm_pages_come_from_a_store_that_unpacks_no_objects(): void + { + $computers = ProductSection::query()->create(['name' => 'Computers', 'code' => 'computers']); + $laptops = ProductSection::query()->create(['name' => 'Laptops', 'code' => 'laptops', 'parent_id' => $computers->id]); + $brand = Brand::query()->create(['name' => 'Northwind', 'xml_id' => 'northwind']); + $product = Product::query()->create([ + 'section_id' => $laptops->id, + 'name' => 'Product 1', + 'code' => 'product-1', + 'brand' => $brand->id, + 'active_from' => now()->subDay(), + 'preview_picture' => '/upload/iblock/1/1.jpg', + 'photos' => json_encode(['/upload/a.jpg']), + ]); + $product->seoMeta()->create(['title' => 'Buy product 1']); + $cache = $this->app->make(RecordCache::class); + + foreach (['/catalog', '/catalog/computers/laptops/product-1'] as $url) { + $this->get($url)->assertOk(); + $cache->reset(); + + $this->get($url)->assertOk()->assertSee('Product 1'); + + $this->assertSame(0, $cache->requestStats()['misses'], $url); + $cache->reset(); + } + } +} diff --git a/packages/theme/tests/Fixtures/BenchProduct.php b/packages/theme/tests/Fixtures/BenchProduct.php new file mode 100644 index 00000000..76d17e0c --- /dev/null +++ b/packages/theme/tests/Fixtures/BenchProduct.php @@ -0,0 +1,122 @@ + */ + protected array $translatable = ['name', 'code', 'detail_text']; + + protected function casts(): array + { + return ['active' => 'boolean', 'active_from' => 'datetime', 'active_to' => 'datetime']; + } + + public static function getAdminLabel(): string + { + return 'Benchmark products'; + } + + /** + * @return BelongsToMany + */ + public function related(): BelongsToMany + { + return $this->belongsToMany(self::class, 'bench_related', 'product_id', 'related_id'); + } + + /** + * The 40 property columns: name => kind. + * + * @return array + */ + public static function properties(): array + { + $columns = []; + + foreach (['text' => self::TEXTS, 'number' => self::NUMBERS, 'list' => self::LISTS, 'flag' => self::FLAGS, 'content' => self::CONTENTS] as $kind => $count) { + for ($i = 1; $i <= $count; $i++) { + $columns[$kind.'_'.$i] = $kind; + } + } + + return $columns + ['brand_id' => 'brand', 'maker_id' => 'brand']; + } + + public static function getAdministrationFields(): array + { + $fields = [ + CheckboxField::make('active')->label('Active'), + TextField::make('name')->label('Name'), + SlugField::make('code')->label('Code'), + ]; + + foreach (self::properties() as $column => $kind) { + $label = ucfirst(str_replace('_', ' ', $column)); + $fields[] = match ($kind) { + 'text' => TextField::make($column)->label($label), + 'number' => NumberField::make($column)->label($label), + 'list' => SelectField::make($column)->label($label)->options(['a' => 'Option A', 'b' => 'Option B', 'c' => 'Option C']), + 'flag' => CheckboxField::make($column)->label($label)->checkedValue('Y'), + 'content' => ContentField::make($column)->label($label)->tab('detail'), + default => BelongsToField::make($column)->label($label)->model(Brand::class), + }; + } + + return [ + ...$fields, + BelongsToManyField::make('related')->label('Related')->model(self::class), + ImageField::make('preview_picture')->label('Preview picture')->tab('preview'), + ContentField::make('preview_text')->label('Preview text')->tab('preview'), + ImageField::make('detail_picture')->label('Detail picture')->tab('detail'), + ContentField::make('detail_text')->label('Detail text')->tab('detail'), + GalleryField::make('photos')->label('Photos')->tab('detail'), + TextField::make('meta_title')->label('Meta title')->tab('seo'), + ]; + } +} diff --git a/packages/theme/tests/Fixtures/Brand.php b/packages/theme/tests/Fixtures/Brand.php index d5311a53..dc0ba3eb 100644 --- a/packages/theme/tests/Fixtures/Brand.php +++ b/packages/theme/tests/Fixtures/Brand.php @@ -9,12 +9,16 @@ namespace Atrium\Theme\Tests\Fixtures; +use Atrium\Admin\Cache\CachesRecords; +use Atrium\Admin\Contracts\Cacheable; use Illuminate\Database\Eloquent\Model; /** * A highload directory: no page of its own. */ -class Brand extends Model +class Brand extends Model implements Cacheable { + use CachesRecords; + protected $guarded = []; } diff --git a/packages/theme/tests/Fixtures/Product.php b/packages/theme/tests/Fixtures/Product.php index 19fa16bd..6bbf930b 100644 --- a/packages/theme/tests/Fixtures/Product.php +++ b/packages/theme/tests/Fixtures/Product.php @@ -9,6 +9,8 @@ namespace Atrium\Theme\Tests\Fixtures; +use Atrium\Admin\Cache\CachesRecords; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Fields\BelongsToManyField; use Atrium\Admin\Fields\CheckboxField; @@ -29,9 +31,9 @@ /** * Shaped like a model the Bitrix migrator generates. */ -class Product extends Model +class Product extends Model implements Cacheable { - use HasAdminSeo; + use CachesRecords, HasAdminSeo; protected $guarded = []; diff --git a/packages/theme/tests/Fixtures/ProductSection.php b/packages/theme/tests/Fixtures/ProductSection.php index 385a5f2b..ddee0703 100644 --- a/packages/theme/tests/Fixtures/ProductSection.php +++ b/packages/theme/tests/Fixtures/ProductSection.php @@ -9,12 +9,16 @@ namespace Atrium\Theme\Tests\Fixtures; +use Atrium\Admin\Cache\CachesRecords; +use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\ContentField; use Atrium\Admin\Fields\TextField; use Illuminate\Database\Eloquent\Model; -class ProductSection extends Model +class ProductSection extends Model implements Cacheable { + use CachesRecords; + protected $guarded = []; protected function casts(): array From 4c13324c11a5ea123e55b128f227a57121f1a441 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:45:55 +0300 Subject: [PATCH 02/10] fix(cache): drop kept sites, languages and paths on flush, drop again after commit A save inside a transaction drops the record's cards a second time once committed, so a visitor who read between the save and the commit does not keep the old row. Sites::flush(), ContentLanguages::flush() and PublicUrl::forgetPaths() now drop what the record cache keeps too; switching the current site only forgets the picked languages. Cards hydrate their model on the default connection name, so is() holds. Pages::preloadLinks() reads the fields of any model that declares them. Adds the Dusk test of the cache screen. --- packages/admin/src/AtriumServiceProvider.php | 10 ++- packages/admin/src/Cache/Card.php | 4 +- .../src/Console/Commands/CacheWarmCommand.php | 2 +- .../admin/src/Support/ContentLanguages.php | 13 ++++ packages/admin/src/Support/PublicUrl.php | 5 +- packages/admin/src/Support/Sites.php | 5 +- .../admin/tests/Feature/RecordCacheTest.php | 39 +++++++++++ .../tests/Feature/SchemaTest.php | 2 + packages/theme/src/Pages.php | 6 +- .../theme/tests/ControllerInternalsTest.php | 2 +- tests/Browser/Admin/CacheTest.php | 70 +++++++++++++++++++ 11 files changed, 146 insertions(+), 12 deletions(-) create mode 100644 tests/Browser/Admin/CacheTest.php diff --git a/packages/admin/src/AtriumServiceProvider.php b/packages/admin/src/AtriumServiceProvider.php index 6c06e124..822afb1a 100644 --- a/packages/admin/src/AtriumServiceProvider.php +++ b/packages/admin/src/AtriumServiceProvider.php @@ -321,8 +321,14 @@ private function registerCache(): void }); $changed = function (string $event, array $payload): void { - if (($payload[0] ?? null) instanceof Model) { - $this->app->make(RecordCache::class)->changed($payload[0]); + $record = $payload[0] ?? null; + + if ($record instanceof Model) { + $cache = $this->app->make(RecordCache::class); + $cache->changed($record); + // Again once committed: a visitor who read between the save + // and the commit kept the old row under the new version. + $record->getConnection()->afterCommit(static fn () => $cache->changed($record)); } }; diff --git a/packages/admin/src/Cache/Card.php b/packages/admin/src/Cache/Card.php index 2040c1e8..fba0cded 100644 --- a/packages/admin/src/Cache/Card.php +++ b/packages/admin/src/Cache/Card.php @@ -224,7 +224,9 @@ private static function hydrate(array $data, string $locale): Model { /** @var class-string $type */ $type = $data['type']; - $model = (new $type)->newFromBuilder($data['raw']); + $prototype = new $type; + // Named like a model read by a query, so is() and the connection agree. + $model = $prototype->newFromBuilder($data['raw'], $prototype->getConnection()->getName()); // Translated attributes read in the card's language, whatever the // app's language is now. diff --git a/packages/admin/src/Console/Commands/CacheWarmCommand.php b/packages/admin/src/Console/Commands/CacheWarmCommand.php index 5b2c7ecf..58032318 100644 --- a/packages/admin/src/Console/Commands/CacheWarmCommand.php +++ b/packages/admin/src/Console/Commands/CacheWarmCommand.php @@ -58,7 +58,7 @@ public function handle(RecordCache $cache, Sites $sites, ContentLanguages $langu } $sites->setCurrent($site); - $languages->flush(); + $languages->forgetActive(); $codes = $languages->codes(); $base = $this->base($site); diff --git a/packages/admin/src/Support/ContentLanguages.php b/packages/admin/src/Support/ContentLanguages.php index 2fd92b52..1e13b29c 100644 --- a/packages/admin/src/Support/ContentLanguages.php +++ b/packages/admin/src/Support/ContentLanguages.php @@ -86,7 +86,20 @@ public function route(string $name, array $parameters = [], ?string $code = null return route('localized.'.$name, ['locale' => $code, ...$parameters], $absolute); } + /** + * The languages changed behind the models' back: read them anew. + */ public function flush(): void + { + $this->forgetActive(); + app(RecordCache::class)->flushClass(Language::class); + } + + /** + * Another site became current: its languages are picked anew from the + * kept list. + */ + public function forgetActive(): void { $this->active = null; } diff --git a/packages/admin/src/Support/PublicUrl.php b/packages/admin/src/Support/PublicUrl.php index 6c93e257..84f4ada5 100644 --- a/packages/admin/src/Support/PublicUrl.php +++ b/packages/admin/src/Support/PublicUrl.php @@ -112,8 +112,8 @@ public static function sectionPaths(string $treeClass, string $parentColumn = 'p // Kept in the record cache until a section of the tree changes. return self::$pathCache[$cacheKey] = app(RecordCache::class)->remember( - $treeClass, - 'section-paths:'.$parentColumn, + [$treeClass, self::class], + 'section-paths:'.$cacheKey, static fn (): array => self::buildSectionPaths($treeClass, $parentColumn), perSite: false, ); @@ -180,5 +180,6 @@ public static function forRecord(Model $record): ?string public static function forgetPaths(): void { self::$pathCache = []; + app(RecordCache::class)->flushClass(self::class); } } diff --git a/packages/admin/src/Support/Sites.php b/packages/admin/src/Support/Sites.php index 05681e34..d9ae72a8 100644 --- a/packages/admin/src/Support/Sites.php +++ b/packages/admin/src/Support/Sites.php @@ -162,7 +162,7 @@ public function setCurrent(Site $site): void $this->currentId = $site->id; $this->resolved = true; - app(ContentLanguages::class)->flush(); + app(ContentLanguages::class)->forgetActive(); } public function forgetCurrent(): void @@ -171,7 +171,7 @@ public function forgetCurrent(): void $this->resolved = false; $this->allowedIds = null; - app(ContentLanguages::class)->flush(); + app(ContentLanguages::class)->forgetActive(); } public function isMultisite(): bool @@ -182,6 +182,7 @@ public function isMultisite(): bool public function flush(): void { $this->all = null; + app(RecordCache::class)->flushClass(Site::class); } /** diff --git a/packages/admin/tests/Feature/RecordCacheTest.php b/packages/admin/tests/Feature/RecordCacheTest.php index feeeeced..ae094c67 100644 --- a/packages/admin/tests/Feature/RecordCacheTest.php +++ b/packages/admin/tests/Feature/RecordCacheTest.php @@ -207,6 +207,45 @@ public function test_an_admin_save_leaves_nothing_stale(): void $this->assertSame([], Book::query()->where('price', '>', 500)->cachedIds()->ids); } + public function test_a_save_in_a_transaction_drops_again_once_committed(): void + { + [$book] = $this->books(1); + $versions = $this->app->make(RecordCache::class)->versions(); + $name = 'list:'.Book::class; + $before = $versions->get([$name])[$name]; + $during = null; + + DB::transaction(function () use ($book, $versions, $name, &$during): void { + $book->update(['price' => 5]); + // The request that saves reads its own change at once. + $during = $versions->get([$name])[$name]; + }); + + $this->assertNotSame($before, $during); + // A visitor may have kept the old row between the save and the commit. + $this->assertNotSame($during, $versions->get([$name])[$name]); + } + + public function test_a_rolled_back_save_drops_nothing_more(): void + { + [$book] = $this->books(1); + $versions = $this->app->make(RecordCache::class)->versions(); + $name = 'list:'.Book::class; + $during = null; + + try { + DB::transaction(function () use ($book, $versions, $name, &$during): void { + $book->update(['price' => 5]); + $during = $versions->get([$name])[$name]; + + throw new \RuntimeException('rolled back'); + }); + } catch (\RuntimeException) { + } + + $this->assertSame($during, $versions->get([$name])[$name]); + } + public function test_a_bulk_import_drops_the_cache_once_at_the_end(): void { [$book] = $this->books(1); diff --git a/packages/custom-fields/tests/Feature/SchemaTest.php b/packages/custom-fields/tests/Feature/SchemaTest.php index a3dfd166..fc995d1c 100644 --- a/packages/custom-fields/tests/Feature/SchemaTest.php +++ b/packages/custom-fields/tests/Feature/SchemaTest.php @@ -80,7 +80,9 @@ public function test_without_a_site_the_values_belong_to_every_site(): void $this->assertSame($site->id, $this->fields()->site()); $this->assertGreaterThan(0, $site->id); + // A mass delete fires no model event: the kept list of sites is dropped by hand. Site::query()->delete(); + $this->app->make(Sites::class)->flush(); $this->app->forgetInstance(Sites::class); $this->assertSame(0, $this->fields()->site()); diff --git a/packages/theme/src/Pages.php b/packages/theme/src/Pages.php index a83176fc..0d8c6e3c 100644 --- a/packages/theme/src/Pages.php +++ b/packages/theme/src/Pages.php @@ -11,7 +11,6 @@ use Atrium\Admin\Cache\Card; use Atrium\Admin\Cache\RecordCache; -use Atrium\Admin\Contracts\Administrable; use Atrium\Admin\Contracts\Cacheable; use Atrium\Admin\Fields\BelongsToField; use Atrium\Admin\Support\ContentLanguages; @@ -330,13 +329,14 @@ public function preloadLinks(EloquentCollection $records): void { $first = $records->first(); - if (! $first instanceof Administrable) { + // Read like RecordView reads them: a model needs only the fields. + if ($first === null || ! method_exists($class = $first::class, 'getAdministrationFields')) { return; } $relations = []; - foreach ((array) $first::getAdministrationFields() as $field) { + foreach ((array) $class::getAdministrationFields() as $field) { if (! $field instanceof BelongsToField || ($class = $field->getModelClass()) === null) { continue; } diff --git a/packages/theme/tests/ControllerInternalsTest.php b/packages/theme/tests/ControllerInternalsTest.php index 53061d55..885f3d61 100644 --- a/packages/theme/tests/ControllerInternalsTest.php +++ b/packages/theme/tests/ControllerInternalsTest.php @@ -231,7 +231,7 @@ private function treeQueries(string $uri): array $queries = array_column(DB::getQueryLog(), 'query'); DB::disableQueryLog(); - return array_values(array_filter($queries, fn (string $sql): bool => str_contains($sql, 'product_sections') && str_ends_with($sql, 'limit 1'))); + return array_values(array_filter($queries, fn (string $sql): bool => str_contains($sql, '"product_sections" where'))); } public function test_a_record_that_stands_in_no_section_asks_the_tree_nothing(): void diff --git a/tests/Browser/Admin/CacheTest.php b/tests/Browser/Admin/CacheTest.php new file mode 100644 index 00000000..6010f5b5 --- /dev/null +++ b/tests/Browser/Admin/CacheTest.php @@ -0,0 +1,70 @@ +admin(); + $key = array_search(Product::class, app(ApiResources::class)->modules(), true); + $this->assertIsString($key); + $before = $this->versions(['list:'.Product::class, 'all']); + + $this->browse(function (Browser $browser) use ($admin, $key): void { + $browser->loginAs($admin, 'admin') + ->visit('/admin') + ->clickLink('Cache') + ->waitFor('[data-page-title="admin.cache"]') + ->assertPresent('[data-cache-stat="rate"]') + ->assertPresent('[data-cache-stat="size"]') + ->assertPresent('[data-cache-stat="store"]') + ->select('[data-cache-module]', $key) + ->click('[data-action="clear-module"]') + ->waitForText('The cache is cleared.'); + }); + + $afterModule = $this->versions(['list:'.Product::class, 'all']); + $this->assertNotSame($before['list:'.Product::class], $afterModule['list:'.Product::class]); + $this->assertSame($before['all'], $afterModule['all']); + + $this->browse(function (Browser $browser): void { + $browser->visit('/admin/cache') + ->waitFor('[data-action="clear-all"]') + ->click('[data-action="clear-all"]') + ->waitForText('The cache is cleared.'); + }); + + $this->assertNotSame($afterModule['all'], $this->versions(['all'])['all']); + } + + /** + * The version counters as the site reads them now. + * + * @param array $names + * @return array + */ + private function versions(array $names): array + { + $versions = app(RecordCache::class)->versions(); + $versions->reset(); + + return $versions->get($names); + } +} From a183b76628f231bdad3276c572289bcd31904d47 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:15:05 +0300 Subject: [PATCH 03/10] test(cache): every changed line of the admin cache tested both ways Tests for the record cache, its versions, cards and card builder, the cache store, the page cache, the debug line, the cache screen and the warm command, down to the last mutant. Redundant casts and wrappers that no test could tell apart are gone from the cache classes. CacheStore::size() looked up the database store as cache.stores..table when atrium.cache.store was not set; it now falls back to the default store. --- packages/admin/src/Cache/CacheStore.php | 6 +- packages/admin/src/Cache/Card.php | 2 +- packages/admin/src/Cache/CardBuilder.php | 14 +- packages/admin/src/Cache/RecordCache.php | 45 +- packages/admin/src/Cache/Versions.php | 13 +- .../src/Console/Commands/CacheWarmCommand.php | 9 +- .../src/Http/Controllers/CacheController.php | 2 +- .../admin/src/Http/Middleware/CacheDebug.php | 8 +- .../admin/src/Http/Middleware/CachePages.php | 24 +- .../Feature/Cache/AdminSaveCacheTest.php | 84 ++ .../Cache/CacheServiceProviderTest.php | 279 +++++++ .../tests/Feature/Cache/CacheStoreTest.php | 461 +++++++++++ .../tests/Feature/Cache/CachesRecordsTest.php | 165 ++++ .../tests/Feature/Cache/CardBuilderTest.php | 758 ++++++++++++++++++ .../admin/tests/Feature/Cache/CardTest.php | 298 +++++++ .../Feature/Cache/OwnerMorphNameTest.php | 95 +++ .../Feature/Cache/RecordCacheCardsTest.php | 286 +++++++ .../Feature/Cache/RecordCacheChangesTest.php | 680 ++++++++++++++++ .../Feature/Cache/RecordCacheListsTest.php | 371 +++++++++ .../RecordCacheOutsideTransactionTest.php | 86 ++ .../Feature/Cache/RecordCacheRememberTest.php | 336 ++++++++ .../Feature/Cache/RecordCacheRequestTest.php | 495 ++++++++++++ .../tests/Feature/Cache/SettingsCacheTest.php | 193 +++++ .../Cache/SiteAndLanguageCacheTest.php | 281 +++++++ .../admin/tests/Feature/CacheDebugTest.php | 242 ++++++ .../admin/tests/Feature/CacheScreenTest.php | 213 +++++ .../admin/tests/Feature/CacheTestCase.php | 32 + .../tests/Feature/CacheWarmCommandTest.php | 437 ++++++++++ .../tests/Feature/PageCacheRulesTest.php | 631 +++++++++++++++ .../admin/tests/Fixtures/Cache/Chapter.php | 116 +++ packages/admin/tests/Fixtures/Cache/Code.php | 31 + packages/admin/tests/Fixtures/Cache/Node.php | 36 + packages/admin/tests/Fixtures/Cache/Part.php | 56 ++ .../tests/Fixtures/Cache/SpyRepository.php | 138 ++++ .../tests/Fixtures/CacheScreen/Aardvark.php | 49 ++ .../tests/Fixtures/CacheScreen/Zebra.php | 49 ++ .../Fixtures/Cards/CountingImageField.php | 28 + .../tests/Fixtures/Cards/HalfTranslated.php | 33 + packages/admin/tests/Fixtures/Cards/Item.php | 167 ++++ packages/admin/tests/Fixtures/Cards/Label.php | 24 + packages/admin/tests/Fixtures/Cards/Owner.php | 30 + .../admin/tests/Fixtures/Cards/Section.php | 24 + .../admin/tests/Fixtures/Cards/SeoBroken.php | 45 ++ .../admin/tests/Fixtures/Cards/SeoLoose.php | 44 + .../tests/Fixtures/Cards/SeoTitleOnly.php | 29 + .../admin/tests/Fixtures/Clock/microtime.php | 30 + .../admin/tests/Fixtures/ScopedHandbook.php | 24 + packages/admin/tests/Fixtures/Unwarmable.php | 23 + .../admin/tests/Unit/Cache/VersionsTest.php | 245 ++++++ 49 files changed, 7704 insertions(+), 63 deletions(-) create mode 100644 packages/admin/tests/Feature/Cache/AdminSaveCacheTest.php create mode 100644 packages/admin/tests/Feature/Cache/CacheServiceProviderTest.php create mode 100644 packages/admin/tests/Feature/Cache/CacheStoreTest.php create mode 100644 packages/admin/tests/Feature/Cache/CachesRecordsTest.php create mode 100644 packages/admin/tests/Feature/Cache/CardBuilderTest.php create mode 100644 packages/admin/tests/Feature/Cache/CardTest.php create mode 100644 packages/admin/tests/Feature/Cache/OwnerMorphNameTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheCardsTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheChangesTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheListsTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheOutsideTransactionTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheRememberTest.php create mode 100644 packages/admin/tests/Feature/Cache/RecordCacheRequestTest.php create mode 100644 packages/admin/tests/Feature/Cache/SettingsCacheTest.php create mode 100644 packages/admin/tests/Feature/Cache/SiteAndLanguageCacheTest.php create mode 100644 packages/admin/tests/Feature/CacheDebugTest.php create mode 100644 packages/admin/tests/Feature/CacheWarmCommandTest.php create mode 100644 packages/admin/tests/Feature/PageCacheRulesTest.php create mode 100644 packages/admin/tests/Fixtures/Cache/Chapter.php create mode 100644 packages/admin/tests/Fixtures/Cache/Code.php create mode 100644 packages/admin/tests/Fixtures/Cache/Node.php create mode 100644 packages/admin/tests/Fixtures/Cache/Part.php create mode 100644 packages/admin/tests/Fixtures/Cache/SpyRepository.php create mode 100644 packages/admin/tests/Fixtures/CacheScreen/Aardvark.php create mode 100644 packages/admin/tests/Fixtures/CacheScreen/Zebra.php create mode 100644 packages/admin/tests/Fixtures/Cards/CountingImageField.php create mode 100644 packages/admin/tests/Fixtures/Cards/HalfTranslated.php create mode 100644 packages/admin/tests/Fixtures/Cards/Item.php create mode 100644 packages/admin/tests/Fixtures/Cards/Label.php create mode 100644 packages/admin/tests/Fixtures/Cards/Owner.php create mode 100644 packages/admin/tests/Fixtures/Cards/Section.php create mode 100644 packages/admin/tests/Fixtures/Cards/SeoBroken.php create mode 100644 packages/admin/tests/Fixtures/Cards/SeoLoose.php create mode 100644 packages/admin/tests/Fixtures/Cards/SeoTitleOnly.php create mode 100644 packages/admin/tests/Fixtures/Clock/microtime.php create mode 100644 packages/admin/tests/Fixtures/ScopedHandbook.php create mode 100644 packages/admin/tests/Fixtures/Unwarmable.php create mode 100644 packages/admin/tests/Unit/Cache/VersionsTest.php diff --git a/packages/admin/src/Cache/CacheStore.php b/packages/admin/src/Cache/CacheStore.php index 882a0a73..61a166a5 100644 --- a/packages/admin/src/Cache/CacheStore.php +++ b/packages/admin/src/Cache/CacheStore.php @@ -45,7 +45,7 @@ public function __construct( public static function fromConfig(): self { $repository = cache()->store(config('atrium.cache.store')); - $strategy = (string) config('atrium.cache.strategy', 'auto'); + $strategy = config('atrium.cache.strategy', 'auto'); $taggable = $repository instanceof CacheRepository && $repository->getStore() instanceof TaggableStore; return new self($repository, $taggable && $strategy !== 'versions'); @@ -92,7 +92,7 @@ public function size(): array if ($store instanceof RedisStore) { $connection = $store->connection(); $size['entries'] = (int) $connection->command('dbsize'); - $info = (array) $connection->command('info', ['memory']); + $info = $connection->command('info', ['memory']); $memory = $info['Memory'] ?? $info; $size['bytes'] = isset($memory['used_memory']) ? (int) $memory['used_memory'] : null; } elseif ($store instanceof FileStore) { @@ -106,7 +106,7 @@ public function size(): array $size = ['entries' => $entries, 'bytes' => $bytes]; } elseif ($store instanceof DatabaseStore) { - $size['entries'] = $store->getConnection()->table((string) config('cache.stores.'.config('atrium.cache.store', config('cache.default')).'.table', 'cache'))->count(); + $size['entries'] = $store->getConnection()->table((string) config('cache.stores.'.(config('atrium.cache.store') ?? config('cache.default')).'.table', 'cache'))->count(); } } catch (Throwable) { // A number on a screen is not worth an error. diff --git a/packages/admin/src/Cache/Card.php b/packages/admin/src/Cache/Card.php index fba0cded..23229268 100644 --- a/packages/admin/src/Cache/Card.php +++ b/packages/admin/src/Cache/Card.php @@ -234,7 +234,7 @@ private static function hydrate(array $data, string $locale): Model $model->setLocale($locale); } - foreach ((array) ($data['relations'] ?? []) as $name => $related) { + foreach ($data['relations'] ?? [] as $name => $related) { if ($related === null) { $model->setRelation($name, null); } elseif (array_is_list($related)) { diff --git a/packages/admin/src/Cache/CardBuilder.php b/packages/admin/src/Cache/CardBuilder.php index 223aa6c4..479afb7b 100644 --- a/packages/admin/src/Cache/CardBuilder.php +++ b/packages/admin/src/Cache/CardBuilder.php @@ -40,7 +40,7 @@ final class CardBuilder /** @var array>> */ private array $mediaFields = []; - /** @var array> */ + /** @var array> */ private array $fields = []; /** @@ -225,7 +225,7 @@ private function raw(Model $model, string $locale): array continue; } - $translations = (array) $model->getTranslations($attribute); + $translations = $model->getTranslations($attribute); $kept = array_intersect_key($translations, array_flip([$locale, $default])); $raw[$attribute] = json_encode($kept, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } @@ -298,7 +298,7 @@ private function media(Model $model): array continue; } - $path = is_array($item) ? (string) ($item['path'] ?? $item['url'] ?? '') : (string) $item; + $path = (string) (is_array($item) ? ($item['path'] ?? $item['url'] ?? '') : $item); $name = is_array($item) && isset($item['name']) ? (string) $item['name'] : rawurldecode(basename((string) parse_url($url, PHP_URL_PATH))); $items[] = [ @@ -338,11 +338,11 @@ private function mediaFieldsOf(string $class): array } /** - * @return array + * @return array */ private function fieldsOf(string $class): array { - return $this->fields[$class] ??= method_exists($class, 'getAdministrationFields') ? array_values((array) $class::getAdministrationFields()) : []; + return $this->fields[$class] ??= method_exists($class, 'getAdministrationFields') ? $class::getAdministrationFields() : []; } /** @@ -352,10 +352,6 @@ private function fieldsOf(string $class): array */ private function list(mixed $value): array { - if ($value === null || $value === '' || $value === []) { - return []; - } - if (is_string($value) && str_starts_with(ltrim($value), '[')) { $decoded = json_decode($value, true); diff --git a/packages/admin/src/Cache/RecordCache.php b/packages/admin/src/Cache/RecordCache.php index 65684f36..10c524c4 100644 --- a/packages/admin/src/Cache/RecordCache.php +++ b/packages/admin/src/Cache/RecordCache.php @@ -13,7 +13,6 @@ use Atrium\Admin\Models\Language; use Atrium\Admin\Models\Site; use Atrium\Admin\Support\Sites; -use BackedEnum; use Closure; use DateTimeInterface; use Illuminate\Database\Eloquent\Builder; @@ -57,7 +56,7 @@ final class RecordCache private int $bulk = 0; - /** @var array */ + /** @var array class => class: the classes saved during a bulk, as a set */ private array $bulkTouched = []; private bool $bulkEverything = false; @@ -65,13 +64,13 @@ final class RecordCache /** @var array> */ private array $warmers = []; - /** @var array version names the current request has read through */ + /** @var array name => name: the version names the current request has read through, as a set */ private array $read = []; /** @var array{hits:int,misses:int} */ private array $stats = ['hits' => 0, 'misses' => 0]; - /** @var array */ + /** @var array> class => keys of the records being changed right now */ private array $changing = []; public function __construct( @@ -113,7 +112,7 @@ public function versions(): Versions */ public function cards(string $class, iterable $ids, ?string $locale = null): array { - $ids = array_values(array_unique(array_map(self::normalizeId(...), is_array($ids) ? $ids : iterator_to_array($ids, false)))); + $ids = array_unique(array_map(self::normalizeId(...), is_array($ids) ? $ids : iterator_to_array($ids, false))); if ($ids === []) { return []; @@ -182,13 +181,13 @@ public function ids(Builder $query, ?int $perPage = null, ?int $page = null, arr $key = $model->getQualifiedKeyName(); if ($perPage === null) { - $ids = (clone $query)->toBase()->pluck($key)->all(); + $ids = $query->toBase()->pluck($key)->all(); return ['ids' => $ids, 'total' => count($ids)]; } - $total = (clone $query)->toBase()->getCountForPagination(); - $ids = $total > 0 ? (clone $query)->forPage(max(1, (int) $page), $perPage)->toBase()->pluck($key)->all() : []; + $total = $query->toBase()->getCountForPagination(); + $ids = $total > 0 ? (clone $query)->forPage((int) $page, $perPage)->toBase()->pluck($key)->all() : []; return ['ids' => $ids, 'total' => $total]; }; @@ -208,11 +207,10 @@ public function ids(Builder $query, ?int $perPage = null, ?int $page = null, arr $this->markRead($names); $hash = hash('xxh128', implode("\n", [ - $class, $query->toSql(), json_encode(array_map(self::binding(...), $query->getBindings())), - (string) $perPage, - (string) $page, + $perPage, + $page, app()->getLocale(), ])); $key = 'ids:'.$this->versions->stamp($names).':'.$hash; @@ -301,18 +299,18 @@ public function changed(Model $record): void } if ($this->bulk > 0) { - $this->bulkTouched[$class] = true; + $this->bulkTouched[$class] = $class; return; } - $guard = $class.'#'.$record->getKey(); + $key = $record->getKey(); - if (isset($this->changing[$guard])) { + if ($this->changing[$class][$key] ?? false) { return; } - $this->changing[$guard] = true; + $this->changing[$class][$key] = true; try { $this->versions->bump('list:'.$class); @@ -340,7 +338,7 @@ public function changed(Model $record): void // A cache that is down must not fail the save. report($e); } finally { - unset($this->changing[$guard]); + unset($this->changing[$class][$key]); } } @@ -389,7 +387,7 @@ public function bulk(Closure $callback, bool $everything = false): mixed return $callback(); } finally { if (--$this->bulk === 0) { - $touched = array_keys($this->bulkTouched); + $touched = $this->bulkTouched; $all = $this->bulkEverything; $this->bulkTouched = []; $this->bulkEverything = false; @@ -511,7 +509,7 @@ public function readNames(): array */ public function dontKeepPage(): void { - $this->read[self::NO_PAGE] = true; + $this->read[self::NO_PAGE] = self::NO_PAGE; } public function pageKeepable(): bool @@ -525,7 +523,7 @@ public function pageKeepable(): bool public function markRead(array $names): void { foreach ($names as $name) { - $this->read[$name] = true; + $this->read[$name] = $name; } } @@ -549,7 +547,7 @@ public function reset(): void */ public function persistStats(): void { - if (! config('atrium.cache.stats', true) || ($this->stats['hits'] + $this->stats['misses']) === 0) { + if (! config('atrium.cache.stats', true)) { return; } @@ -643,12 +641,12 @@ private function cardPrefix(string $class, int $site, string $locale, bool $mark private function knownSites(): array { try { - $ids = app(Sites::class)->all()->pluck('id')->filter()->map(static fn (mixed $id): int => (int) $id)->all(); + $ids = app(Sites::class)->all()->pluck('id')->filter()->all(); } catch (Throwable) { $ids = []; } - return array_values(array_unique([0, ...$ids])); + return array_unique([0, ...$ids]); } /** @@ -662,7 +660,7 @@ private function knownLocales(): array $codes = []; } - return array_values(array_unique([app()->getLocale(), (string) config('app.locale'), ...$codes])); + return array_unique([app()->getLocale(), ...$codes]); } private function site(): int @@ -704,7 +702,6 @@ private static function binding(mixed $value): mixed { return match (true) { $value instanceof DateTimeInterface => $value->format('Y-m-d H:i:s.u'), - $value instanceof BackedEnum => $value->value, is_object($value) && method_exists($value, '__toString') => (string) $value, default => $value, }; diff --git a/packages/admin/src/Cache/Versions.php b/packages/admin/src/Cache/Versions.php index 17e1d8f8..4105b530 100644 --- a/packages/admin/src/Cache/Versions.php +++ b/packages/admin/src/Cache/Versions.php @@ -34,6 +34,11 @@ final class Versions /** Counters live a month; one that expires restarts at a random number. */ private const TTL = 2592000; + /** A counter starts somewhere in 1 … START_MAX, never near the top: it only ever goes up. */ + private const START_MIN = 1; + + private const START_MAX = PHP_INT_MAX >> 1; + /** @var array */ private array $memo = []; @@ -45,7 +50,7 @@ public function __construct(private readonly Repository $store) {} */ public function get(array $names): array { - $names = array_values(array_unique($names)); + $names = array_unique($names); $missing = array_values(array_filter($names, fn (string $name): bool => ! isset($this->memo[$name]))); if ($missing !== []) { @@ -88,8 +93,8 @@ public function bump(string ...$names): void // ours never are 1, so that means it was not there. $value = $this->store->increment($key); - if ($value === false || (int) $value <= 1) { - $this->store->put($key, random_int(1, PHP_INT_MAX >> 1), self::TTL); + if ($value === false || $value <= 1) { + $this->store->put($key, random_int(self::START_MIN, self::START_MAX), self::TTL); } unset($this->memo[$name]); @@ -108,7 +113,7 @@ public function reset(): void private function start(string $name): string { $key = self::PREFIX.$name; - $this->store->add($key, random_int(1, PHP_INT_MAX >> 1), self::TTL); + $this->store->add($key, random_int(self::START_MIN, self::START_MAX), self::TTL); return (string) $this->store->get($key); } diff --git a/packages/admin/src/Console/Commands/CacheWarmCommand.php b/packages/admin/src/Console/Commands/CacheWarmCommand.php index 58032318..580a9a8d 100644 --- a/packages/admin/src/Console/Commands/CacheWarmCommand.php +++ b/packages/admin/src/Console/Commands/CacheWarmCommand.php @@ -58,7 +58,6 @@ public function handle(RecordCache $cache, Sites $sites, ContentLanguages $langu } $sites->setCurrent($site); - $languages->forgetActive(); $codes = $languages->codes(); $base = $this->base($site); @@ -106,7 +105,7 @@ private function buildCards(RecordCache $cache, ApiResources $resources, array $ $built = 0; // Modules of the panel, and the models the theme gives addresses to. - $classes = [...array_values($resources->modules()), ...array_keys((array) config('atrium.public_urls', []))]; + $classes = [...$resources->modules(), ...array_keys((array) config('atrium.public_urls', []))]; foreach (array_unique($classes) as $class) { if (! is_string($class) || ! class_exists($class)) { @@ -137,9 +136,9 @@ private function buildCards(RecordCache $cache, ApiResources $resources, array $ */ private function base(Site $site): string { - $url = rtrim((string) config('app.url', 'http://localhost'), '/'); - $scheme = (string) (parse_url($url, PHP_URL_SCHEME) ?: 'http'); - $domain = ((array) $site->domains)[0] ?? null; + $url = (string) config('app.url', 'http://localhost'); + $scheme = parse_url($url, PHP_URL_SCHEME) ?: 'http'; + $domain = ($site->domains)[0] ?? null; $root = is_string($domain) && $domain !== '' ? $scheme.'://'.$domain : $url; return rtrim($root, '/').($site->folder ? '/'.trim((string) $site->folder, '/') : ''); diff --git a/packages/admin/src/Http/Controllers/CacheController.php b/packages/admin/src/Http/Controllers/CacheController.php index 4d35f213..b111a4b9 100644 --- a/packages/admin/src/Http/Controllers/CacheController.php +++ b/packages/admin/src/Http/Controllers/CacheController.php @@ -56,7 +56,7 @@ public function index(): Response ->values(), 'sites' => $this->sites->all() ->filter(fn (Site $site): bool => $site->exists) - ->map(fn (Site $site): array => ['id' => $site->getKey(), 'name' => (string) $site->name]) + ->map(fn (Site $site): array => ['id' => $site->getKey(), 'name' => $site->name]) ->values(), ]); } diff --git a/packages/admin/src/Http/Middleware/CacheDebug.php b/packages/admin/src/Http/Middleware/CacheDebug.php index 2042543f..f648bac3 100644 --- a/packages/admin/src/Http/Middleware/CacheDebug.php +++ b/packages/admin/src/Http/Middleware/CacheDebug.php @@ -49,7 +49,7 @@ public function handle(Request $request, Closure $next): Response $response = $next($request); $stats = $this->cache->requestStats(); - $page = (string) $response->headers->get(CachePages::HEADER, 'off'); + $page = $response->headers->get(CachePages::HEADER, 'off'); $line = sprintf( 'queries=%d (%.1f ms); cache hits=%d misses=%d; page cache=%s; %.1f ms', self::$queries, @@ -73,8 +73,8 @@ public function handle(Request $request, Closure $next): Response public static function enabled(): bool { - return (bool) config('atrium.cache.debug', true) - && (bool) config('app.debug', false) + return config('atrium.cache.debug', true) + && config('app.debug', false) && app()->environment('local'); } @@ -88,7 +88,7 @@ private static function listen(): void DB::listen(static function ($query): void { self::$queries++; - self::$queryMs += (float) $query->time; + self::$queryMs += $query->time; }); } } diff --git a/packages/admin/src/Http/Middleware/CachePages.php b/packages/admin/src/Http/Middleware/CachePages.php index 61095618..89a46856 100644 --- a/packages/admin/src/Http/Middleware/CachePages.php +++ b/packages/admin/src/Http/Middleware/CachePages.php @@ -74,11 +74,13 @@ public function handle(Request $request, Closure $next): Response $response = $next($request); - if (! $this->storable($response)) { + $body = $response->getContent(); + + if (! is_string($body) || ! $this->storable($response, $body)) { return $response; } - $entry = $this->entry($request, $response); + $entry = $this->entry($request, $response, $body); $this->safely(fn () => $this->store->put('pages', $key, $entry, max(1, (int) config('atrium.cache.ttl.pages', 600)))); return $this->serve($request, $entry, 'MISS', $response); @@ -112,7 +114,7 @@ private function applies(Request $request): bool // An admin sees the edit bar and unpublished things; a signed-in // visitor sees their own name. - foreach (array_unique([(string) config('atrium.auth.guard', 'admin'), (string) config('auth.defaults.guard', 'web')]) as $guard) { + foreach ([config('atrium.auth.guard', 'admin'), config('auth.defaults.guard', 'web')] as $guard) { try { if (auth()->guard($guard)->check()) { return false; @@ -125,7 +127,7 @@ private function applies(Request $request): bool if ($request->hasSession()) { $session = $request->session(); - if ($session->has('errors') || (array) $session->get('_flash.old', []) !== [] || $session->hasOldInput()) { + if ($session->has('errors') || $session->get('_flash.old', []) !== [] || $session->hasOldInput()) { return false; } } @@ -146,9 +148,9 @@ private function key(Request $request): string */ private function fresh(array $entry): bool { - $versions = (array) ($entry['versions'] ?? []); + $versions = $entry['versions'] ?? []; - if ($versions === []) { + if (! is_array($versions) || $versions === []) { return false; } @@ -157,7 +159,7 @@ private function fresh(array $entry): bool return $now !== null && $now == $versions; } - private function storable(Response $response): bool + private function storable(Response $response, string $body): bool { if ($response->getStatusCode() !== 200 || $response->headers->has('Content-Disposition')) { return false; @@ -185,15 +187,14 @@ private function storable(Response $response): bool return false; } - return is_string($response->getContent()) && $response->getContent() !== ''; + return $body !== ''; } /** * @return array */ - private function entry(Request $request, Response $response): array + private function entry(Request $request, Response $response, string $body): array { - $body = (string) $response->getContent(); $token = $request->hasSession() ? (string) $request->session()->token() : ''; $hasToken = $token !== '' && str_contains($body, $token); @@ -207,12 +208,11 @@ private function entry(Request $request, Response $response): array $names[] = 'list:'.$class; } - $names = array_values(array_unique($names)); sort($names); return [ 'body' => $body, - 'type' => (string) $response->headers->get('Content-Type'), + 'type' => $response->headers->get('Content-Type'), 'token' => $hasToken, 'etag' => sha1($body), 'time' => time(), diff --git a/packages/admin/tests/Feature/Cache/AdminSaveCacheTest.php b/packages/admin/tests/Feature/Cache/AdminSaveCacheTest.php new file mode 100644 index 00000000..fa140f0f --- /dev/null +++ b/packages/admin/tests/Feature/Cache/AdminSaveCacheTest.php @@ -0,0 +1,84 @@ + + */ + private function form(Book $book, Tag $tag): array + { + return [ + 'name' => ['en' => 'Edited'], + 'active' => true, + 'price' => 10, + 'shelf_id' => $book->shelf_id, + 'tags' => [$tag->id], + 'seo_title' => 'Edited title', + ]; + } + + private function listVersion(): string + { + $name = 'list:'.Book::class; + + return $this->app->make(RecordCache::class)->versions()->get([$name])[$name]; + } + + public function test_a_save_from_the_panel_drops_the_record_even_when_model_events_are_muted(): void + { + [$book] = $this->books(1); + $tag = Tag::query()->create(['name' => 'green']); + Book::cached($book->id); + $this->resetRequest(); + $before = $this->listVersion(); + + Book::withoutEvents(fn () => $this->actingAs($this->admin(), 'admin') + ->put("/admin/books/{$book->id}", $this->form($book, $tag)) + ->assertRedirect() + ->assertSessionHasNoErrors()); + $this->resetRequest(); + + $this->assertNotSame($before, $this->listVersion()); + $card = Book::cached($book->id); + $this->assertSame('Edited', $card->name); + $this->assertSame(['green'], $card->relation('tags')->pluck('name')->all()); + $this->assertSame('Edited title', $card->seo('title')); + } + + public function test_a_save_that_failed_validation_drops_nothing(): void + { + [$book] = $this->books(1); + $tag = Tag::query()->create(['name' => 'green']); + Book::cached($book->id); + $this->resetRequest(); + $before = $this->listVersion(); + + Book::withoutEvents(fn () => $this->actingAs($this->admin(), 'admin') + ->from('/admin/books') + ->put("/admin/books/{$book->id}", [...$this->form($book, $tag), 'name' => ['en' => '']]) + ->assertSessionHasErrors()); + $this->resetRequest(); + + $this->assertSame($before, $this->listVersion()); + $this->assertSame('Book 1', Book::cached($book->id)->name); + } +} diff --git a/packages/admin/tests/Feature/Cache/CacheServiceProviderTest.php b/packages/admin/tests/Feature/Cache/CacheServiceProviderTest.php new file mode 100644 index 00000000..e07b4872 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/CacheServiceProviderTest.php @@ -0,0 +1,279 @@ +app->make(RecordCache::class); + } + + /** + * @return array + */ + private function twentyFiveBooks(): array + { + return $this->books(25); + } + + public function test_the_record_cache_is_one_for_the_whole_application_with_the_store_and_versions_it_shares(): void + { + $cache = $this->app->make(RecordCache::class); + + $this->assertSame($cache, $this->app->make(RecordCache::class)); + $this->assertSame($this->app->make(CacheStore::class), $this->app->make(CacheStore::class)); + $this->assertSame($this->app->make(Versions::class), $this->app->make(Versions::class)); + $this->assertSame($this->app->make(CacheStore::class), $cache->store()); + $this->assertSame($this->app->make(Versions::class), $cache->versions()); + } + + public function test_cached_ids_take_a_page_and_the_classes_the_list_depends_on(): void + { + $books = $this->books(5); + + $page = Book::query()->orderBy('id')->cachedIds(2, 2, [Shelf::class]); + + $this->assertSame([$books[2]->id, $books[3]->id], $page->ids); + $this->assertSame(5, $page->total); + $this->assertContains('list:'.Shelf::class, $this->cache()->readNames()); + } + + public function test_cached_ids_without_a_page_answer_all_of_them_and_depend_on_nothing_else(): void + { + $books = $this->books(3); + $this->resetRequest(); + + $all = Book::query()->orderBy('id')->cachedIds(); + + $this->assertSame(array_map(fn (Book $book): int => $book->id, $books), $all->ids); + $this->assertNotContains('list:'.Shelf::class, $this->cache()->readNames()); + } + + public function test_cached_paginate_pages_by_twenty_unless_told_otherwise(): void + { + $this->twentyFiveBooks(); + + $page = Book::query()->orderBy('id')->cachedPaginate(); + + $this->assertSame(20, $page->perPage()); + $this->assertSame(25, $page->total()); + $this->assertCount(20, $page->items()); + $this->assertSame('page', $page->getPageName()); + $this->assertSame(1, $page->currentPage()); + } + + public function test_cached_paginate_passes_its_page_name_page_language_and_classes_on(): void + { + $books = $this->books(5); + foreach ($books as $book) { + $book->setTranslation('name', 'de', 'Buch '.$book->id)->save(); + } + $this->resetRequest(); + + $page = Book::query()->orderBy('id')->cachedPaginate(2, 'seite', 2, 'de', [Shelf::class]); + + $this->assertSame(2, $page->perPage()); + $this->assertSame('seite', $page->getPageName()); + $this->assertSame(2, $page->currentPage()); + $this->assertSame([$books[2]->id, $books[3]->id], array_map(fn (Card $card): int|string => $card->id(), $page->items())); + $this->assertSame('de', $page->items()[0]->locale()); + $this->assertContains('list:'.Shelf::class, $this->cache()->readNames()); + } + + public function test_cached_cards_are_the_cards_of_the_query_in_a_language_of_choice(): void + { + $books = $this->books(3); + $this->resetRequest(); + + $cards = Book::query()->orderByDesc('id')->cachedCards('de', [Shelf::class]); + + $this->assertSame([$books[2]->id, $books[1]->id, $books[0]->id], array_map(fn (Card $card): int|string => $card->id(), $cards)); + $this->assertSame('de', $cards[0]->locale()); + $this->assertContains('list:'.Shelf::class, $this->cache()->readNames()); + } + + public function test_cached_cards_are_in_the_current_language_when_none_is_named(): void + { + $this->books(1); + $this->app->setLocale('de'); + + $cards = Book::query()->cachedCards(); + + $this->assertSame('de', $cards[0]->locale()); + } + + public function test_a_model_read_marks_its_class_as_read_while_the_page_cache_is_on(): void + { + $this->books(1); + config(['atrium.cache.pages.enabled' => true]); + $this->resetRequest(); + + Book::query()->get(); + + $this->assertSame(['list:'.Book::class], array_values(array_filter($this->cache()->readNames(), fn (string $name): bool => str_starts_with($name, 'list:'.Book::class)))); + } + + public function test_a_model_read_marks_nothing_while_the_page_cache_is_off(): void + { + $this->books(1); + config(['atrium.cache.pages.enabled' => false]); + $this->resetRequest(); + + Book::query()->get(); + + $this->assertSame([], $this->cache()->readNames()); + } + + public function test_the_page_cache_is_off_when_the_setting_is_missing(): void + { + $this->books(1); + $pages = config('atrium.cache.pages'); + unset($pages['enabled']); + config(['atrium.cache.pages' => $pages]); + $this->resetRequest(); + + Book::query()->get(); + + $this->assertSame([], $this->cache()->readNames()); + } + + /** + * @return array + */ + public static function modelEvents(): array + { + return [ + 'saved' => ['saved'], + 'deleted' => ['deleted'], + 'restored' => ['restored'], + 'forceDeleted' => ['forceDeleted'], + ]; + } + + #[DataProvider('modelEvents')] + public function test_every_event_that_changes_a_record_makes_its_lists_stale(string $event): void + { + $shelf = Shelf::query()->create(['name' => ['en' => 'Shelf']]); + $this->resetRequest(); + $before = $this->cache()->versions()->stamp(['list:'.Shelf::class]); + + Event::dispatch('eloquent.'.$event.': '.Shelf::class, [$shelf]); + $this->resetRequest(); + + $this->assertNotSame($before, $this->cache()->versions()->stamp(['list:'.Shelf::class])); + } + + public function test_an_event_with_no_record_in_it_is_left_alone(): void + { + $shelf = Shelf::query()->create(['name' => ['en' => 'Shelf']]); + $this->resetRequest(); + $before = $this->cache()->versions()->stamp(['list:'.Shelf::class]); + + Event::dispatch('eloquent.saved: '.Shelf::class, ['not a record']); + Event::dispatch('eloquent.deleted: '.Shelf::class, []); + $this->resetRequest(); + + $this->assertSame($before, $this->cache()->versions()->stamp(['list:'.Shelf::class])); + $this->assertNotNull($shelf->id); + } + + public function test_the_end_of_a_request_counts_it_into_the_totals_and_starts_afresh(): void + { + [$book] = $this->books(1); + $this->cache()->resetTotals(); + $this->resetRequest(); + + Book::cached($book->id); + $counted = $this->cache()->requestStats(); + $this->assertGreaterThan(0, $counted['misses']); + + $this->app->terminate(); + + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache()->requestStats()); + $this->assertSame($counted, $this->cache()->totals()); + } + + public function test_the_start_of_a_job_counts_the_last_one_and_starts_afresh(): void + { + [$book] = $this->books(1); + $this->cache()->resetTotals(); + $this->resetRequest(); + + Book::cached($book->id); + $counted = $this->cache()->requestStats(); + $this->assertGreaterThan(0, $counted['misses']); + $job = Mockery::mock(Job::class); + $job->shouldReceive('payload')->andReturn([]); + + Event::dispatch(new JobProcessing('sync', $job)); + + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache()->requestStats()); + $this->assertSame($counted, $this->cache()->totals()); + } + + public function test_monitoring_gets_the_numbers_of_this_request_on_top_of_its_own(): void + { + [$a, $b, $c] = $this->books(3); + Book::cached($a->id); + $this->resetRequest(); + Book::cachedMany([$a->id, $b->id, $c->id]); + $this->assertSame(['hits' => 1, 'misses' => 2], $this->cache()->requestStats()); + + $stats = Hook::apply('atrium.cache.stats', ['hits' => 10, 'misses' => 20, 'entries' => 7]); + + $this->assertSame(['hits' => 11, 'misses' => 22, 'entries' => 7], $stats); + } + + public function test_monitoring_gets_this_requests_numbers_alone_when_it_brought_none(): void + { + [$a, $b] = $this->books(2); + Book::cached($a->id); + $this->resetRequest(); + Book::cachedMany([$a->id, $b->id]); + + $this->assertSame(['hits' => 1, 'misses' => 1], Hook::apply('atrium.cache.stats', [])); + } + + public function test_the_numbers_monitoring_brought_are_read_as_numbers(): void + { + [$a] = $this->books(1); + Book::cached($a->id); + $this->resetRequest(); + Book::cached($a->id); + + $this->assertSame(['hits' => 6, 'misses' => 3], Hook::apply('atrium.cache.stats', ['hits' => '5', 'misses' => '3'])); + } + + public function test_the_warm_command_is_one_of_the_panels_commands(): void + { + $this->assertArrayHasKey('atrium:cache:warm', Artisan::all()); + } +} diff --git a/packages/admin/tests/Feature/Cache/CacheStoreTest.php b/packages/admin/tests/Feature/Cache/CacheStoreTest.php new file mode 100644 index 00000000..775f89f1 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/CacheStoreTest.php @@ -0,0 +1,461 @@ +}> */ + private array $asked = []; + + protected function setUp(): void + { + parent::setUp(); + + $this->directory = sys_get_temp_dir().'/atrium-cache-store-test-'.getmypid().'-'.bin2hex(random_bytes(4)); + } + + protected function tearDown(): void + { + File::deleteDirectory($this->directory); + + parent::tearDown(); + } + + private function tagged(): CacheStore + { + return new CacheStore(Cache::store('array'), true); + } + + private function plain(): CacheStore + { + return new CacheStore(Cache::store('array'), false); + } + + private function fileRepository(): CacheRepository + { + return new CacheRepository(new FileStore(new Filesystem, $this->directory)); + } + + /** + * A Redis store whose server answers what the test says. + * + * @param array $answers command => answer, or a Throwable to throw + */ + private function redis(array $answers): CacheRepository + { + $connection = Mockery::mock(RedisConnection::class); + $connection->shouldReceive('command')->andReturnUsing(function (string $command, array $arguments = []) use ($answers): mixed { + $this->asked[] = [$command, $arguments]; + $answer = $answers[$command] ?? null; + + if ($answer instanceof RuntimeException) { + throw $answer; + } + + return $answer; + }); + $factory = Mockery::mock(RedisFactory::class); + $factory->shouldReceive('connection')->andReturn($connection); + + return new CacheRepository(new RedisStore($factory)); + } + + private function databaseRepository(string $table): CacheRepository + { + Schema::create($table, function (Blueprint $blueprint): void { + $blueprint->string('key')->primary(); + $blueprint->mediumText('value'); + $blueprint->integer('expiration'); + }); + + return new CacheRepository(new DatabaseStore(DB::connection(), $table)); + } + + /** + * @return array + */ + public static function strategies(): array + { + return [ + 'a store with tags, chosen by itself' => ['array', 'auto', true], + 'a store with tags, strategy missing from the config' => ['array', null, true], + 'a store with tags, strategy forced to versions' => ['array', 'versions', false], + 'a store with tags, any other strategy' => ['array', 'tags', true], + 'a store without tags' => ['file', 'auto', false], + 'a store without tags, strategy forced to versions' => ['file', 'versions', false], + ]; + } + + #[DataProvider('strategies')] + public function test_tags_are_used_only_where_the_store_has_them_and_the_strategy_allows(?string $store, ?string $strategy, bool $tags): void + { + config([ + 'cache.stores.filed' => ['driver' => 'file', 'path' => $this->directory], + 'atrium.cache.store' => $store === 'file' ? 'filed' : $store, + ]); + $strategy === null ? config()->offsetUnset('atrium.cache.strategy') : config(['atrium.cache.strategy' => $strategy]); + + $this->assertSame($tags, CacheStore::fromConfig()->usesTags()); + } + + public function test_the_store_comes_from_the_config_and_hands_out_its_repository(): void + { + config(['atrium.cache.store' => 'array']); + + $store = CacheStore::fromConfig(); + + $this->assertSame(Cache::store('array'), $store->repository()); + } + + public function test_a_repository_that_is_not_laravels_never_has_tags(): void + { + config(['cache.stores.foreign' => ['driver' => 'foreign'], 'atrium.cache.store' => 'foreign', 'atrium.cache.strategy' => 'auto']); + Cache::extend('foreign', fn (): Repository => Mockery::mock(Repository::class)); + + $store = CacheStore::fromConfig(); + + $this->assertFalse($store->usesTags()); + $this->assertSame('custom', $store->driver()); + } + + public function test_the_driver_is_named_after_the_store(): void + { + $this->assertSame('array', $this->tagged()->driver()); + $this->assertSame('file', new CacheStore($this->fileRepository(), false)->driver()); + $this->assertSame('redis', new CacheStore($this->redis([]), true)->driver()); + $this->assertSame('database', new CacheStore($this->databaseRepository('driver_cache'), false)->driver()); + } + + public function test_the_size_of_a_store_that_cannot_tell_is_unknown(): void + { + $this->assertSame(['entries' => null, 'bytes' => null], $this->tagged()->size()); + } + + public function test_the_size_of_a_repository_that_is_not_laravels_is_unknown(): void + { + $store = new CacheStore(Mockery::mock(Repository::class), false); + + $this->assertSame(['entries' => null, 'bytes' => null], $store->size()); + } + + public function test_the_size_of_the_file_store_is_its_files(): void + { + $repository = $this->fileRepository(); + $repository->put('one', str_repeat('a', 100), 60); + $repository->put('two', str_repeat('b', 2000), 60); + $repository->put('three', 'c', 60); + + $bytes = 0; + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory, RecursiveDirectoryIterator::SKIP_DOTS)) as $file) { + $bytes += $file->getSize(); + } + + $size = new CacheStore($repository, false)->size(); + + $this->assertSame(['entries' => 3, 'bytes' => $bytes], $size); + $this->assertGreaterThan(2100, $bytes); + } + + public function test_the_size_of_an_empty_file_store_is_nothing(): void + { + mkdir($this->directory); + + $this->assertSame(['entries' => 0, 'bytes' => 0], new CacheStore($this->fileRepository(), false)->size()); + } + + public function test_a_file_store_without_its_directory_has_no_size_and_no_error(): void + { + $this->assertSame(['entries' => null, 'bytes' => null], new CacheStore($this->fileRepository(), false)->size()); + } + + public function test_the_size_of_the_database_store_counts_its_rows_in_the_table_of_the_configured_store(): void + { + $repository = $this->databaseRepository('atrium_kept'); + $repository->put('a', 1, 60); + $repository->put('b', 2, 60); + config(['cache.stores.kept' => ['driver' => 'database', 'table' => 'atrium_kept'], 'atrium.cache.store' => 'kept', 'cache.default' => 'array']); + + $this->assertSame(['entries' => 2, 'bytes' => null], new CacheStore($repository, false)->size()); + } + + public function test_the_size_of_the_database_store_uses_the_default_store_when_none_is_named(): void + { + $repository = $this->databaseRepository('atrium_default_kept'); + $repository->put('a', 1, 60); + config(['cache.stores.kept' => ['driver' => 'database', 'table' => 'atrium_default_kept'], 'atrium.cache.store' => null, 'cache.default' => 'kept']); + + $this->assertSame(['entries' => 1, 'bytes' => null], new CacheStore($repository, false)->size()); + } + + public function test_the_size_of_the_database_store_falls_back_to_the_table_named_cache(): void + { + $repository = $this->databaseRepository('cache'); + $repository->put('a', 1, 60); + $repository->put('b', 2, 60); + $repository->put('c', 3, 60); + config(['cache.stores.kept' => ['driver' => 'database'], 'atrium.cache.store' => 'kept']); + + $this->assertSame(['entries' => 3, 'bytes' => null], new CacheStore($repository, false)->size()); + } + + /** + * @return array,1:?int}> + */ + public static function memoryAnswers(): array + { + return [ + 'in sections, as predis answers' => [['Memory' => ['used_memory' => '1048576', 'used_memory_human' => '1M']], 1048576], + 'flat, as phpredis answers' => [['used_memory' => '2048', 'used_memory_peak' => '4096'], 2048], + 'a number already' => [['used_memory' => 512], 512], + 'no such figure' => [['used_memory_human' => '1M'], null], + 'an empty answer' => [[], null], + ]; + } + + /** + * @param array $info + */ + #[DataProvider('memoryAnswers')] + public function test_the_size_of_the_redis_store_is_its_keys_and_memory(array $info, ?int $bytes): void + { + $store = new CacheStore($this->redis(['dbsize' => '42', 'info' => $info]), false); + + $this->assertSame(['entries' => 42, 'bytes' => $bytes], $store->size()); + // The memory section of the server, and nothing else of its report. + $this->assertSame([['dbsize', []], ['info', ['memory']]], $this->asked); + } + + public function test_a_redis_that_does_not_answer_has_no_size_and_no_error(): void + { + $store = new CacheStore($this->redis(['dbsize' => new RuntimeException('connection refused')]), false); + + $this->assertSame(['entries' => null, 'bytes' => null], $store->size()); + } + + public function test_a_redis_that_stops_halfway_keeps_what_it_told(): void + { + $store = new CacheStore($this->redis(['dbsize' => 7, 'info' => new RuntimeException('connection lost')]), false); + + $this->assertSame(['entries' => 7, 'bytes' => null], $store->size()); + } + + public function test_entries_are_written_and_read_back_in_one_go_whatever_the_store(): void + { + foreach ([$this->tagged(), $this->plain()] as $store) { + $store->putMany('shelf', ['a' => 1, 'b' => ['x' => 2]], 60); + + $this->assertSame(['b' => ['x' => 2], 'missing' => null, 'a' => 1], $store->many('shelf', ['b', 'missing', 'a'])); + $this->assertSame(1, $store->get('shelf', 'a')); + $this->assertNull($store->get('shelf', 'missing')); + } + } + + public function test_nothing_asked_for_is_nothing_read(): void + { + $repository = Mockery::mock(CacheRepository::class); + $repository->shouldNotReceive('many'); + $repository->shouldNotReceive('tags'); + + $this->assertSame([], new CacheStore($repository, true)->many('shelf', [])); + } + + public function test_nothing_to_write_is_nothing_written(): void + { + $repository = Mockery::mock(CacheRepository::class); + $repository->shouldNotReceive('tags'); + $repository->shouldNotReceive('putMany'); + + foreach ([true, false] as $tags) { + new CacheStore($repository, $tags)->putMany('shelf', [], 60); + } + + $this->addToAssertionCount(1); + } + + public function test_a_plain_entry_sits_under_the_atrium_key_of_the_store(): void + { + $this->plain()->put('shelf', 'k', 'value', 60); + + $this->assertSame('value', Cache::store('array')->get('atrium:k')); + $this->assertNull(Cache::store('array')->get('k')); + } + + public function test_a_plain_entry_with_a_number_for_a_key_is_written(): void + { + $this->plain()->putMany('shelf', ['5' => 'five'], 60); + + $this->assertSame('five', Cache::store('array')->get('atrium:5')); + $this->assertSame(['5' => 'five'], $this->plain()->many('shelf', ['5'])); + } + + public function test_a_tagged_entry_is_the_one_laravel_keeps_under_the_group_and_atrium_tags(): void + { + $this->tagged()->put('shelf', 'k', 'value', 60); + + $this->assertSame('value', Cache::store('array')->tags(['atrium', 'atrium:shelf'])->get('k')); + $this->assertNull(Cache::store('array')->tags(['atrium', 'atrium:other'])->get('k')); + $this->assertNull(Cache::store('array')->get('atrium:k')); + } + + public function test_an_entry_lives_for_its_time_and_not_longer(): void + { + foreach ([$this->tagged(), $this->plain()] as $store) { + $store->put('shelf', 'k', 'value', 60); + + $this->travel(59)->seconds(); + $this->assertSame('value', $store->get('shelf', 'k')); + + $this->travel(2)->seconds(); + $this->assertNull($store->get('shelf', 'k')); + + $this->travelBack(); + } + } + + public function test_entries_are_forgotten_by_key_in_their_group_only(): void + { + foreach ([$this->tagged(), $this->plain()] as $store) { + $store->putMany('shelf', ['a' => 1, 'b' => 2, 'c' => 3], 60); + $store->put('other', 'a', 4, 60); + + $store->forget('shelf', ['a', 'c']); + + $this->assertSame(['a' => null, 'b' => 2, 'c' => null], $store->many('shelf', ['a', 'b', 'c'])); + $expected = $store->usesTags() ? 4 : null; + $this->assertSame($expected, $store->get('other', 'a')); + } + } + + public function test_flushing_a_group_deletes_its_entries_and_no_others(): void + { + $store = $this->tagged(); + $store->put('shelf', 'a', 1, 60); + $store->put('other', 'a', 2, 60); + Cache::store('array')->put('outside', 3, 60); + + $store->flush('shelf'); + + $this->assertNull($store->get('shelf', 'a')); + $this->assertSame(2, $store->get('other', 'a')); + $this->assertSame(3, Cache::store('array')->get('outside')); + } + + public function test_flushing_everything_deletes_every_group_and_leaves_the_rest_of_the_store(): void + { + $store = $this->tagged(); + $store->put('shelf', 'a', 1, 60); + $store->put('other', 'a', 2, 60); + Cache::store('array')->put('outside', 3, 60); + + $store->flush(); + + $this->assertNull($store->get('shelf', 'a')); + $this->assertNull($store->get('other', 'a')); + $this->assertSame(3, Cache::store('array')->get('outside')); + } + + public function test_a_flushed_group_is_written_and_read_again_under_its_new_tags(): void + { + $store = $this->tagged(); + $store->put('shelf', 'a', 1, 60); + $store->get('shelf', 'a'); + + $store->flush('shelf'); + $store->put('shelf', 'a', 2, 60); + + $this->assertSame(2, $store->get('shelf', 'a')); + } + + public function test_the_tags_of_a_group_are_worked_out_once_until_reset(): void + { + $repository = new class(Cache::store('array')->getStore()) extends CacheRepository + { + public int $tagged = 0; + + public function tags($names) + { + $this->tagged++; + + return parent::tags($names); + } + }; + $store = new CacheStore($repository, true); + + $store->many('shelf', ['a', 'b', 'c']); + $store->get('shelf', 'a'); + $this->assertSame(1, $repository->tagged); + + $store->many('other', ['a']); + $this->assertSame(2, $repository->tagged); + + $store->reset(); + $store->get('shelf', 'a'); + $this->assertSame(3, $repository->tagged); + } + + public function test_after_a_reset_the_tags_flushed_by_someone_else_are_taken_anew(): void + { + $store = $this->tagged(); + $store->put('shelf', 'a', 1, 60); + $store->get('shelf', 'a'); + + // Another process cleared the module's cache; this one still knows the old tags. + Cache::store('array')->tags(['atrium:shelf'])->flush(); + $store->put('shelf', 'a', 2, 60); + $this->assertSame(1, $store->get('shelf', 'a')); + + $store->reset(); + + $this->assertSame(2, $store->get('shelf', 'a')); + } + + public function test_a_store_without_tags_flushes_nothing_and_loses_nothing(): void + { + $repository = Mockery::mock(CacheRepository::class); + $repository->shouldNotReceive('tags'); + $repository->shouldReceive('putMany')->once()->with(['atrium:a' => 1], 60); + $repository->shouldReceive('many')->andReturn(['atrium:a' => 1]); + $store = new CacheStore($repository, false); + $store->put('shelf', 'a', 1, 60); + + $store->flush(); + $store->flush('shelf'); + + $this->assertSame(1, $store->get('shelf', 'a')); + } +} diff --git a/packages/admin/tests/Feature/Cache/CachesRecordsTest.php b/packages/admin/tests/Feature/Cache/CachesRecordsTest.php new file mode 100644 index 00000000..546bbe3f --- /dev/null +++ b/packages/admin/tests/Feature/Cache/CachesRecordsTest.php @@ -0,0 +1,165 @@ +assertSame(['shelf', 'tags', 'seoMeta'], (new Book)->cacheRelations()); + } + + public function test_a_form_field_is_a_relation_only_when_it_names_one_of_another_class(): void + { + // Said twice a relation counts once; a tree select counts like a belongs-to; "owner" has + // no "_id" to take the name from; "chapter" points to its own class; "fake" is not + // a relation; "broken" fails; "ghost" does not exist; the form has no SEO meta. + $this->assertSame(['shelf', 'section'], (new Chapter)->cacheRelations()); + } + + public function test_a_field_named_like_a_query_method_does_not_run_that_query(): void + { + $this->books(1); + + [$queries] = $this->countQueries(fn (): array => (new Chapter)->cacheRelations()); + + // "count_id" would be count(), asked of the table. + $this->assertSame(0, $queries); + } + + public function test_a_model_with_no_form_carries_no_relation(): void + { + $this->assertSame([], (new Shelf)->cacheRelations()); + } + + /** + * @return array + */ + public static function methods(): array + { + return ['cachedMany' => ['cachedMany'], 'cached' => ['cached']]; + } + + #[DataProvider('methods')] + public function test_the_ways_to_ask_for_cards_are_public_static_methods(string $method): void + { + $reflection = new ReflectionMethod(Book::class, $method); + + $this->assertTrue($reflection->isPublic()); + $this->assertTrue($reflection->isStatic()); + } + + public function test_cached_many_and_cached_give_cards_in_the_order_asked_for(): void + { + [$a, $b] = $this->books(2); + + $cards = Book::cachedMany([$b->id, $a->id]); + + $this->assertSame([$b->id, $a->id], array_map(fn (Card $card): int|string => $card->id(), $cards)); + $this->assertSame($a->id, Book::cached($a->id)?->id()); + $this->assertSame($a->id, Book::cached((string) $a->id)?->id()); + $this->assertNull(Book::cached(9999)); + } + + public function test_cached_speaks_the_language_asked_for(): void + { + [$book] = $this->books(1); + $book->setTranslation('name', 'de', 'Buch')->save(); + + $this->assertSame('Buch', Book::cached($book->id, 'de')?->name); + $this->assertSame('Book 1', Book::cachedMany([$book->id], 'en')[0]->name); + } + + /** + * @return array,1:array>}> + */ + public static function owners(): array + { + return [ + 'a class' => [['seoable_type' => Book::class, 'seoable_id' => 7], [Book::class]], + 'a number as text' => [['seoable_type' => Book::class, 'seoable_id' => '7'], [Book::class]], + 'a class that is not a model' => [['seoable_type' => 'stdClass', 'seoable_id' => 7], []], + 'a class that does not exist' => [['seoable_type' => 'Nowhere\\Nothing', 'seoable_id' => 7], []], + 'no type' => [['seoable_type' => null, 'seoable_id' => 7], []], + 'no id' => [['seoable_type' => Book::class, 'seoable_id' => null], []], + 'nothing at all' => [[], []], + ]; + } + + /** + * @param array $attributes + * @param array> $classes + */ + #[DataProvider('owners')] + public function test_a_row_names_the_owner_it_belongs_to_without_loading_it(array $attributes, array $classes): void + { + $row = new SeoMeta; + $row->setRawAttributes($attributes, true); + + [$queries, $owners] = $this->countQueries(fn (): array => $row->cacheTouches()); + + $this->assertSame(0, $queries); + $this->assertSame($classes, array_map(static fn (Model $owner): string => $owner::class, $owners)); + + foreach ($owners as $owner) { + $this->assertSame(7, (int) $owner->getKey()); + $this->assertTrue($owner->exists); + // Named, not changed: nothing to save. + $this->assertFalse($owner->isDirty()); + } + } + + public function test_a_row_may_name_its_owner_by_a_morph_alias(): void + { + Relation::morphMap(['book' => Book::class]); + + try { + $row = new SeoMeta; + $row->setRawAttributes(['seoable_type' => 'book', 'seoable_id' => 3], true); + + $owners = $row->cacheTouches(); + + $this->assertCount(1, $owners); + $this->assertInstanceOf(Book::class, $owners[0]); + $this->assertSame(3, (int) $owners[0]->getKey()); + } finally { + Relation::morphMap([], false); + } + } + + public function test_a_slug_names_its_owner_by_its_own_morph_pair(): void + { + $slug = new Slug; + $slug->setRawAttributes(['sluggable_type' => Tag::class, 'sluggable_id' => 4], true); + + $owners = $slug->cacheTouches(); + + $this->assertCount(1, $owners); + $this->assertInstanceOf(Tag::class, $owners[0]); + $this->assertSame(4, (int) $owners[0]->getKey()); + } +} diff --git a/packages/admin/tests/Feature/Cache/CardBuilderTest.php b/packages/admin/tests/Feature/Cache/CardBuilderTest.php new file mode 100644 index 00000000..40e97d64 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/CardBuilderTest.php @@ -0,0 +1,758 @@ +id(); + $table->json('name')->nullable(); + }); + + Schema::create('card_labels', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + }); + + Schema::create('card_sections', function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('parent_id')->nullable(); + $table->string('code')->nullable(); + }); + + Schema::create('card_items', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + $table->json('summary')->nullable(); + $table->string('code')->nullable(); + $table->unsignedBigInteger('owner_id')->nullable(); + $table->unsignedBigInteger('link_id')->nullable(); + $table->unsignedBigInteger('section_id')->nullable(); + $table->unsignedBigInteger('site_id')->nullable(); + $table->string('subject_type')->nullable(); + $table->unsignedBigInteger('subject_id')->nullable(); + $table->string('picture')->nullable(); + $table->text('files')->nullable(); + $table->text('docs')->nullable(); + }); + + Schema::create('card_item_label', function (Blueprint $table): void { + $table->unsignedBigInteger('item_id'); + $table->unsignedBigInteger('label_id'); + }); + + Schema::create('card_item_related', function (Blueprint $table): void { + $table->unsignedBigInteger('item_id'); + $table->unsignedBigInteger('related_id'); + }); + } + + protected function tearDown(): void + { + Item::forget(); + + parent::tearDown(); + } + + /** + * @param array $attributes + */ + private function item(array $attributes = []): Item + { + return Item::query()->create($attributes + ['name' => ['en' => 'Item']]); + } + + /** + * @param array $ids + * @return array> + */ + private function build(array $ids, string $locale = 'en', ?CardBuilder $builder = null): array + { + return ($builder ?? new CardBuilder)->build(Item::class, $ids, $locale, 1); + } + + private function url(string $path): string + { + return str_starts_with($path, 'http') ? $path : asset($path); + } + + public function test_nothing_asked_for_is_nothing_built_and_no_query_is_made(): void + { + $this->item(); + + [$queries, $cards] = $this->countQueries(fn (): array => $this->build([])); + + $this->assertSame([], $cards); + $this->assertSame(0, $queries); + } + + public function test_a_card_holds_the_row_the_relations_the_seo_the_pictures_and_the_address(): void + { + config(['atrium.public_urls.'.Item::class => ['prefix' => 'items']]); + Item::declare(['owner', 'tags', 'link', 'seoMeta']); + $owner = Owner::query()->create(['name' => ['en' => 'Ann', 'de' => 'Anna']]); + $red = Label::query()->create(['name' => 'red']); + $blue = Label::query()->create(['name' => 'blue']); + $item = $this->item([ + 'name' => ['en' => 'Hello', 'de' => 'Hallo'], + 'code' => 'hello', + 'owner_id' => $owner->id, + 'picture' => 'pics/a.jpg', + ]); + $item->tags()->attach([$red->id, $blue->id]); + $item->updateSeoMeta(['title' => 'SEO title', 'description' => 'SEO description', 'keywords' => 'one, two', 'og_image' => 'seo/og.png']); + + $cards = $this->build([$item->id], 'de'); + $card = $cards[$item->id]; + + $this->assertSame([$item->id], array_keys($cards)); + $this->assertSame($item->id, $card['id']); + $this->assertSame(Item::class, $card['type']); + $this->assertSame('de', $card['locale']); + $this->assertSame(1, $card['site']); + $this->assertSame(['id', 'type', 'locale', 'site', 'raw', 'relations', 'seo', 'media', 'url', 'extra'], array_keys($card)); + + $fresh = Item::query()->findOrFail($item->id)->getAttributes(); + $raw = $card['raw']; + $this->assertEquals(['en' => 'Hello', 'de' => 'Hallo'], json_decode((string) $raw['name'], true)); + unset($raw['name'], $fresh['name']); + $this->assertEquals($fresh, $raw); + + $this->assertSame(['owner', 'tags', 'link', 'seoMeta'], array_keys($card['relations'])); + $this->assertSame(['id', 'type', 'raw', 'relations'], array_keys($card['relations']['owner'])); + $this->assertSame($owner->id, $card['relations']['owner']['id']); + $this->assertSame(Owner::class, $card['relations']['owner']['type']); + $this->assertSame([], $card['relations']['owner']['relations']); + $this->assertEquals(['en' => 'Ann', 'de' => 'Anna'], json_decode((string) $card['relations']['owner']['raw']['name'], true)); + $this->assertEqualsCanonicalizing( + [['id' => $red->id, 'type' => Label::class, 'raw' => ['id' => $red->id, 'name' => 'red'], 'relations' => []], ['id' => $blue->id, 'type' => Label::class, 'raw' => ['id' => $blue->id, 'name' => 'blue'], 'relations' => []]], + $card['relations']['tags'], + ); + $this->assertTrue(array_is_list($card['relations']['tags'])); + $this->assertNull($card['relations']['link']); + $this->assertSame(SeoMeta::class, $card['relations']['seoMeta']['type']); + + $this->assertSame(['title' => 'SEO title', 'description' => 'SEO description', 'keywords' => 'one, two', 'og_image' => $this->url('/storage/seo/og.png')], $card['seo']); + $this->assertSame(['picture' => [['url' => $this->url('/storage/pics/a.jpg'), 'path' => 'pics/a.jpg', 'name' => 'a.jpg', 'thumbnails' => []]]], $card['media']); + $this->assertSame(app(Sites::class)->current()->url('items/hello'), $card['url']); + $this->assertSame([], $card['extra']); + } + + public function test_cards_are_keyed_by_id_and_records_that_are_missing_have_none(): void + { + [$a, $b] = [$this->item(), $this->item()]; + + $cards = $this->build([$b->id, 9999, $a->id]); + + $this->assertEqualsCanonicalizing([$a->id, $b->id], array_keys($cards)); + $this->assertSame($a->id, $cards[$a->id]['id']); + $this->assertSame($b->id, $cards[$b->id]['id']); + } + + public function test_the_relations_cost_one_query_each_however_many_cards_there_are(): void + { + Item::declare(['owner', 'tags', 'seoMeta']); + $owner = Owner::query()->create(['name' => ['en' => 'Ann']]); + $label = Label::query()->create(['name' => 'red']); + $ids = []; + + for ($i = 0; $i < 6; $i++) { + $item = $this->item(['owner_id' => $owner->id, 'code' => 'item-'.$i]); + $item->tags()->attach($label->id); + $ids[] = $item->id; + } + + $this->build($ids); + + [$queries, $cards] = $this->countQueries(fn (): array => $this->build($ids)); + + $this->assertCount(6, $cards); + // The items, the owners, the tags, the SEO meta. + $this->assertSame(4, $queries); + } + + public function test_a_card_is_built_in_its_own_language_and_the_application_gets_its_own_back(): void + { + $item = $this->item(['name' => ['en' => 'Hello', 'de' => 'Hallo']]); + $this->app->setLocale('fr'); + $seen = []; + $builder = new CardBuilder(['look' => function (Collection $models, string $locale) use (&$seen): array { + $seen[] = [$locale, app()->getLocale()]; + + return []; + }]); + + $cards = $this->build([$item->id], 'de', $builder); + + $this->assertSame([['de', 'de']], $seen); + $this->assertSame('fr', app()->getLocale()); + // The SEO title is the name, in the language the card is built in. + $this->assertSame('Hallo', $cards[$item->id]['seo']['title']); + } + + public function test_the_application_gets_its_language_back_when_the_build_fails(): void + { + $this->app->setLocale('fr'); + + try { + (new CardBuilder)->build('No\\Such\\Model', [1], 'de', 1); + $this->fail('A class that does not exist cannot be built.'); + } catch (Error) { + // expected + } + + $this->assertSame('fr', app()->getLocale()); + } + + public function test_a_module_adds_its_data_to_the_cards_and_a_broken_module_costs_only_its_own(): void + { + Exceptions::fake(); + [$a, $b, $c] = [$this->item(), $this->item(), $this->item()]; + $received = []; + $builder = new CardBuilder([ + 'stock' => function (Collection $models, string $locale) use (&$received, $a, $c): array { + $received[] = [$models->modelKeys(), $locale]; + + return [$a->id => 'in stock', $c->id => ['qty' => 3]]; + }, + 'broken' => function (): array { + throw new RuntimeException('the module is down'); + }, + 'nothing' => fn (): mixed => null, + 'object' => fn (): ArrayObject => new ArrayObject([$b->id => 'shared']), + 'empty' => fn (): array => [$a->id => null], + ]); + + $cards = $this->build([$a->id, $b->id, $c->id], 'de', $builder); + + $this->assertSame([[[$a->id, $b->id, $c->id], 'de']], $received); + $this->assertSame(['stock' => 'in stock'], $cards[$a->id]['extra']); + $this->assertSame(['object' => 'shared'], $cards[$b->id]['extra']); + $this->assertSame(['stock' => ['qty' => 3]], $cards[$c->id]['extra']); + Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'the module is down'); + Exceptions::assertReportedCount(1); + } + + public function test_the_pictures_get_their_thumbnails_from_the_resolver(): void + { + $item = $this->item(['picture' => 'pics/a.jpg']); + $given = []; + $builder = new CardBuilder([], function (string $path, string $url) use (&$given): array { + $given[] = [$path, $url]; + + return ['small' => $url.'?w=100']; + }); + + $card = $this->build([$item->id], 'en', $builder)[$item->id]; + + $this->assertSame([['pics/a.jpg', $this->url('/storage/pics/a.jpg')]], $given); + $this->assertSame(['small' => $this->url('/storage/pics/a.jpg').'?w=100'], $card['media']['picture'][0]['thumbnails']); + } + + public function test_a_resolver_that_has_nothing_to_give_leaves_the_thumbnails_empty(): void + { + $item = $this->item(['picture' => 'pics/a.jpg']); + $builder = new CardBuilder([], fn (): mixed => null); + + $card = $this->build([$item->id], 'en', $builder)[$item->id]; + + $this->assertSame([], $card['media']['picture'][0]['thumbnails']); + } + + public function test_an_address_that_cannot_be_worked_out_is_none_and_is_reported(): void + { + Exceptions::fake(); + config(['atrium.public_urls.'.Item::class => ['prefix' => 'items', 'parent' => 'section_id', 'tree' => 'No\\Such\\Tree']]); + $item = $this->item(['code' => 'hello']); + + $card = $this->build([$item->id])[$item->id]; + + $this->assertNull($card['url']); + Exceptions::assertReported(Error::class); + Exceptions::assertReportedCount(1); + } + + public function test_a_record_of_a_class_without_pages_has_no_address(): void + { + $item = $this->item(['code' => 'hello']); + + $this->assertNull($this->build([$item->id])[$item->id]['url']); + } + + public function test_the_row_of_a_translated_column_keeps_the_cards_language_and_the_default_one(): void + { + $item = $this->item([ + 'name' => ['en' => 'Hello/World', 'de' => 'Hallo', 'ru' => 'Привет', 'fr' => 'Bonjour'], + 'summary' => ['en' => 'Short', 'ru' => 'Кратко', 'fr' => 'Court'], + ]); + + $raw = $this->build([$item->id], 'ru')[$item->id]['raw']; + + // Readable, not escaped: the card is kept in the cache as it is. + $this->assertStringContainsString('"ru":"Привет"', $raw['name']); + $this->assertStringContainsString('"en":"Hello/World"', $raw['name']); + $this->assertEquals(['en' => 'Hello/World', 'ru' => 'Привет'], json_decode($raw['name'], true)); + $this->assertEquals(['en' => 'Short', 'ru' => 'Кратко'], json_decode($raw['summary'], true)); + } + + public function test_a_translated_column_with_nothing_in_it_stays_empty(): void + { + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"Hello"}', 'summary' => null]); + + $raw = $this->build([$id])[$id]['raw']; + + $this->assertNull($raw['summary']); + $this->assertEquals(['en' => 'Hello'], json_decode($raw['name'], true)); + } + + public function test_a_translated_column_with_nothing_in_it_does_not_stop_the_ones_after_it(): void + { + $id = DB::table('card_items')->insertGetId(['name' => null, 'summary' => '{"en":"Short","ru":"Кратко","fr":"Court"}']); + + $raw = $this->build([$id], 'ru')[$id]['raw']; + + $this->assertNull($raw['name']); + $this->assertEquals(['en' => 'Short', 'ru' => 'Кратко'], json_decode($raw['summary'], true)); + } + + public function test_a_row_that_is_not_translated_is_kept_as_it_is(): void + { + Item::declare(['tags', 'halfOwner']); + $label = Label::query()->create(['name' => 'red']); + $owner = Owner::query()->create(['name' => ['en' => 'Ann', 'de' => 'Anna', 'ru' => 'Анна']]); + $item = $this->item(['owner_id' => $owner->id]); + $item->tags()->attach($label->id); + + $relations = $this->build([$item->id], 'de')[$item->id]['relations']; + + $this->assertSame(['id' => $label->id, 'name' => 'red'], $relations['tags'][0]['raw']); + // Names its translated columns but cannot say what is in them. + $this->assertSame(['id' => $owner->id, 'name' => json_encode(['en' => 'Ann', 'de' => 'Anna', 'ru' => 'Анна'], JSON_UNESCAPED_UNICODE)], $this->normalizeName($relations['halfOwner']['raw'])); + } + + /** + * The JSON column comes back in the order the database keeps its keys. + * + * @param array $raw + * @return array + */ + private function normalizeName(array $raw): array + { + $name = json_decode((string) $raw['name'], true); + ksort($name); + $raw['name'] = json_encode(array_replace(['en' => null, 'de' => null, 'ru' => null], $name), JSON_UNESCAPED_UNICODE); + + return $raw; + } + + public function test_what_a_card_shows_of_the_seo_is_what_the_record_gives(): void + { + $with = $this->item(['name' => ['en' => 'Plain name']]); + $with->updateSeoMeta(['title' => 'Own title']); + $without = $this->item(['name' => ['en' => 'Plain name']]); + + $cards = $this->build([$with->id, $without->id]); + + $this->assertSame(['title' => 'Own title', 'description' => '', 'keywords' => null, 'og_image' => null], $cards[$with->id]['seo']); + $this->assertSame(['title' => 'Plain name', 'description' => '', 'keywords' => null, 'og_image' => null], $cards[$without->id]['seo']); + } + + public function test_a_record_with_no_seo_has_none_on_its_card(): void + { + $label = Label::query()->create(['name' => 'red']); + + $card = (new CardBuilder)->build(Label::class, [$label->id], 'en', 1)[$label->id]; + + $this->assertSame([], $card['seo']); + $this->assertSame([], $card['media']); + $this->assertSame(['id' => $label->id, 'name' => 'red'], $card['raw']); + $this->assertSame([], $card['relations']); + } + + public function test_the_seo_methods_of_a_record_may_answer_what_they_like(): void + { + Exceptions::fake(); + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"x"}']); + + $card = (new CardBuilder)->build(SeoLoose::class, [$id], 'en', 1)[$id]; + + $this->assertSame(['title' => '42', 'description' => '7', 'keywords' => 'kw', 'og_image' => 'og.png'], $card['seo']); + Exceptions::assertNothingReported(); + } + + public function test_a_record_that_knows_only_its_title_has_no_other_seo(): void + { + Exceptions::fake(); + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"x"}']); + + $card = (new CardBuilder)->build(SeoTitleOnly::class, [$id], 'en', 1)[$id]; + + $this->assertSame(['title' => 'Only a title', 'description' => null, 'keywords' => null, 'og_image' => null], $card['seo']); + Exceptions::assertNothingReported(); + } + + public function test_seo_that_fails_costs_only_the_part_that_failed(): void + { + Exceptions::fake(); + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"x"}']); + + $card = (new CardBuilder)->build(SeoBroken::class, [$id], 'en', 1)[$id]; + + $this->assertSame(['title' => null, 'description' => null, 'keywords' => null, 'og_image' => null], $card['seo']); + Exceptions::assertReportedCount(4); + } + + /** + * @return array}> + */ + public static function pictures(): array + { + return [ + 'nothing' => ['files', null, []], + 'an empty string' => ['files', '', []], + 'an empty list' => ['files', '[]', []], + 'a JSON list' => ['files', '["a.jpg","b.png"]', [['/storage/a.jpg', 'a.jpg', 'a.jpg'], ['/storage/b.png', 'b.png', 'b.png']]], + 'a JSON list after a space' => ['files', ' ["a.jpg"]', [['/storage/a.jpg', 'a.jpg', 'a.jpg']]], + 'a list that is not JSON is one value' => ['files', '[broken', [['/storage/[broken', '[broken', '[broken']]], + 'one path' => ['files', 'single.jpg', [['/storage/single.jpg', 'single.jpg', 'single.jpg']]], + 'an empty item is left out' => ['files', '["","a.jpg"]', [['/storage/a.jpg', 'a.jpg', 'a.jpg']]], + 'a full address' => ['files', 'https://cdn.example.com/dir/My%20Photo.jpg', [['https://cdn.example.com/dir/My%20Photo.jpg', 'https://cdn.example.com/dir/My%20Photo.jpg', 'My Photo.jpg']]], + 'a path from the web root' => ['files', '/upload/old/x.jpg', [['/upload/old/x.jpg', '/upload/old/x.jpg', 'x.jpg']]], + 'one item with a path and a name' => ['docs', '{"path":"p.pdf","name":"Spec"}', [['/storage/p.pdf', 'p.pdf', 'Spec']]], + 'one item with an address only' => ['docs', '{"url":"https://cdn.example.com/x.pdf"}', [['https://cdn.example.com/x.pdf', 'https://cdn.example.com/x.pdf', 'x.pdf']]], + 'one item with a path and an address' => ['docs', '{"path":"p.pdf","url":"https://cdn.example.com/u.pdf"}', [['https://cdn.example.com/u.pdf', 'p.pdf', 'u.pdf']]], + 'one item with a path and no name' => ['docs', '{"path":"p.pdf"}', [['/storage/p.pdf', 'p.pdf', 'p.pdf']]], + 'a list of items' => ['docs', '[{"path":"a.pdf","name":"A"},{"url":"https://cdn.example.com/b.pdf","name":7}]', [['/storage/a.pdf', 'a.pdf', 'A'], ['https://cdn.example.com/b.pdf', 'https://cdn.example.com/b.pdf', '7']]], + 'a list of paths as an object' => ['docs', '{"a":"x.pdf","b":"y.pdf"}', [['/storage/x.pdf', 'x.pdf', 'x.pdf'], ['/storage/y.pdf', 'y.pdf', 'y.pdf']]], + 'an item that has no address is left out' => ['docs', '[{"name":"nothing"}]', []], + 'a path that is not text' => ['docs', '{"url":"https://cdn.example.com/x.pdf","path":5}', [['https://cdn.example.com/x.pdf', '5', 'x.pdf']]], + ]; + } + + /** + * @param array $expected address, path, name + */ + #[DataProvider('pictures')] + public function test_pictures_and_files_are_listed_with_their_addresses(string $column, ?string $stored, array $expected): void + { + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"x"}', $column => $stored]); + + $media = $this->build([$id])[$id]['media']; + + $items = array_map(fn (array $item): array => [$item['url'], $item['path'], $item['name']], $media[$column] ?? []); + $expectedItems = array_map(fn (array $item): array => [$this->url($item[0]), $item[1], $item[2]], $expected); + $this->assertSame($expectedItems, $items); + $this->assertSame($expected === [] ? [] : [$column], array_keys($media)); + } + + public function test_only_the_pictures_and_files_of_the_form_are_pictures_and_files(): void + { + Item::declare(null, [TextField::make('name'), 'not a field', ImageField::make('picture'), TextField::make('files'), FileField::make('docs')]); + $id = DB::table('card_items')->insertGetId(['name' => '{"en":"x"}', 'picture' => 'a.jpg', 'files' => 'b.jpg', 'docs' => '["c.pdf"]']); + + $media = $this->build([$id])[$id]['media']; + + $this->assertSame(['picture', 'docs'], array_keys($media)); + } + + public function test_the_pictures_of_a_class_are_worked_out_once(): void + { + Item::declare(null, [CountingImageField::make('picture')]); + $builder = new CardBuilder; + $one = $this->item(['picture' => 'a.jpg']); + CountingImageField::$typeCalls = 0; + + $builder->build(Item::class, [$one->id], 'en', 1); + $worked = CountingImageField::$typeCalls; + $builder->build(Item::class, [$one->id], 'en', 1); + + $this->assertGreaterThan(0, $worked); + $this->assertSame($worked, CountingImageField::$typeCalls); + } + + public function test_the_fields_of_a_class_are_asked_for_once(): void + { + $builder = new CardBuilder; + $one = $this->item(['picture' => 'a.jpg']); + $two = $this->item(['picture' => 'b.jpg']); + Item::$fieldCalls = 0; + + $builder->build(Item::class, [$one->id, $two->id], 'en', 1); + $builder->build(Item::class, [$one->id], 'en', 1); + $builder->dependenciesOf(Item::class); + $builder->referencing($one); + + $this->assertSame(1, Item::$fieldCalls); + } + + public function test_a_class_without_a_form_has_no_pictures_and_shows_nothing_of_others(): void + { + $label = Label::query()->create(['name' => 'red']); + $builder = new CardBuilder; + + $this->assertSame([], $builder->dependenciesOf(Label::class)); + $this->assertSame([], $builder->referencing($label)); + $this->assertSame([], $builder->relationsOf(Label::class)); + } + + public function test_the_relations_of_a_class_are_what_it_declares_in_a_row(): void + { + Item::declare(['first' => 'owner', 'third' => 'tags']); + $builder = new CardBuilder; + + $this->assertSame(['owner', 'tags'], $builder->relationsOf(Item::class)); + } + + public function test_the_relations_of_a_class_are_asked_for_once(): void + { + $builder = new CardBuilder; + + $builder->relationsOf(Item::class); + $builder->relationsOf(Item::class); + $builder->dependenciesOf(Item::class); + + $this->assertSame(1, Item::$relationNameCalls); + } + + public function test_the_classes_a_card_shows_are_those_of_its_relations_and_its_form(): void + { + Exceptions::fake(); + Item::declare(['owner', 'link', 'seoMeta', 'subject', 'broken', 'notARelation', 'tags'], []); + + $classes = (new CardBuilder)->dependenciesOf(Item::class); + + // Not its own class, not the SEO meta (a morph relation of its own), + // not what a morph-to points at, and not what is no relation. + $this->assertSame([Owner::class, Label::class], $classes); + Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'no such relation'); + Exceptions::assertReportedCount(1); + } + + public function test_the_classes_the_form_links_to_count_once_and_not_the_class_itself(): void + { + Item::declare(['link', 'owner'], [ + TextField::make('name'), + 'not a field', + BelongsToField::make('owner_id')->model(Owner::class), + BelongsToField::make('section_id')->model(Section::class), + BelongsToField::make('nothing_id'), + BelongsToManyField::make('related')->model(Item::class), + ]); + + $this->assertSame([Owner::class, Section::class], (new CardBuilder)->dependenciesOf(Item::class)); + } + + /** + * @return array,1:array}> + */ + public static function trees(): array + { + return [ + 'no rule' => [null, [Owner::class]], + 'a rule without a tree' => [['prefix' => 'items'], [Owner::class]], + 'an empty tree' => [['prefix' => 'items', 'tree' => ''], [Owner::class]], + 'a tree that is no class name' => [['prefix' => 'items', 'tree' => 12], [Owner::class]], + 'a tree of sections' => [['prefix' => 'items', 'parent' => 'section_id', 'tree' => Section::class], [Owner::class, Section::class]], + 'a tree of its own class' => [['prefix' => 'items', 'parent' => 'link_id', 'tree' => Item::class], [Owner::class, Item::class]], + ]; + } + + /** + * @param array|null $rule + * @param array $expected + */ + #[DataProvider('trees')] + public function test_the_tree_the_address_is_made_of_is_shown_too(?array $rule, array $expected): void + { + Item::declare(['owner'], []); + $rule === null || config(['atrium.public_urls.'.Item::class => $rule]); + + $this->assertSame($expected, (new CardBuilder)->dependenciesOf(Item::class)); + } + + public function test_the_classes_a_card_shows_are_worked_out_once(): void + { + Item::declare(['owner'], []); + $builder = new CardBuilder; + + $this->assertSame([Owner::class], $builder->dependenciesOf(Item::class)); + + config(['atrium.public_urls.'.Item::class => ['prefix' => 'items', 'parent' => 'section_id', 'tree' => Section::class]]); + + $this->assertSame([Owner::class], $builder->dependenciesOf(Item::class)); + $this->assertSame([Owner::class, Section::class], (new CardBuilder)->dependenciesOf(Item::class)); + } + + /** + * @return array{0:Item,1:Item,2:Item} + */ + private function links(): array + { + Owner::query()->create(['name' => ['en' => 'Ann']]); + $target = $this->item(['name' => ['en' => 'Target']]); + $both = $this->item(['link_id' => $target->id]); + $both->related()->attach($target->id); + $linked = $this->item(['link_id' => $target->id]); + $this->item(['name' => ['en' => 'Stranger']]); + + return [$target, $both, $linked]; + } + + public function test_the_records_that_show_this_one_are_found_through_every_field_that_points_at_it(): void + { + [$target, $both, $linked] = $this->links(); + Item::declare(null, [ + TextField::make('name'), + BelongsToField::make('owner_id')->model(Owner::class), + BelongsToManyField::make('related')->model(Item::class), + BelongsToField::make('link_id')->model(Item::class), + ]); + + $ids = (new CardBuilder)->referencing($target); + + // Each once, in a list. + $this->assertSame([$both->id, $linked->id], $ids); + } + + public function test_a_field_that_is_not_a_relation_of_the_class_finds_nothing(): void + { + [$target] = $this->links(); + // Owner 1 is also the owner of the first item: a relation that is not + // a many-to-many must not be asked as one. + Item::query()->whereKey($target->id + 1)->update(['owner_id' => $target->id]); + Item::declare(null, [ + BelongsToManyField::make('ghost')->model(Item::class), + BelongsToManyField::make('owner')->model(Item::class), + ]); + + $this->assertSame([], (new CardBuilder)->referencing($target)); + } + + public function test_a_field_may_point_through_another_column_and_a_value_it_has_not_set_points_nowhere(): void + { + $record = $this->item(['section_id' => 7]); + $pointing = $this->item(['link_id' => 7]); + $this->item(['link_id' => null]); + Item::declare(null, [BelongsToField::make('link_id')->model(Item::class)->valueColumn('section_id')]); + + $this->assertSame([$pointing->id], (new CardBuilder)->referencing($record)); + + // The record has no owner: nothing points at it through its absence. + Item::declare(null, [BelongsToField::make('link_id')->model(Item::class)->valueColumn('owner_id')]); + $this->assertSame([], (new CardBuilder)->referencing($record)); + } + + public function test_a_field_on_the_key_itself_finds_nothing(): void + { + $other = $this->item(); + $record = $this->item(['link_id' => $other->id]); + Item::declare(null, [BelongsToField::make('id')->model(Item::class)->valueColumn('link_id')]); + + $this->assertSame([], (new CardBuilder)->referencing($record)); + } + + public function test_a_record_that_points_at_itself_does_not_show_itself(): void + { + $record = $this->item(); + $record->forceFill(['link_id' => $record->id])->save(); + Item::declare(null, [BelongsToField::make('link_id')->model(Item::class)]); + + $this->assertSame([], (new CardBuilder)->referencing($record)); + } + + /** + * @return array + */ + public static function fieldsThatPointNowhere(): array + { + return [ + 'a many-to-many that is not a relation of the class' => [BelongsToManyField::make('ghost')->model(Item::class)], + 'a many-to-one asked as a many-to-many' => [BelongsToManyField::make('owner')->model(Item::class)], + 'a field the record has no value for' => [BelongsToField::make('link_id')->model(Item::class)->valueColumn('owner_id')], + 'a field on the key itself' => [BelongsToField::make('id')->model(Item::class)->valueColumn('link_id')], + ]; + } + + #[DataProvider('fieldsThatPointNowhere')] + public function test_a_field_that_finds_nothing_does_not_stop_the_fields_after_it(BelongsToField $nowhere): void + { + $other = $this->item(); + $target = $this->item(['link_id' => $other->id]); + $linked = $this->item(['link_id' => $target->id]); + Item::declare(null, [$nowhere, BelongsToField::make('link_id')->model(Item::class)]); + + $this->assertSame([$linked->id], (new CardBuilder)->referencing($target)); + } + + public function test_the_ids_found_through_each_field_are_all_there(): void + { + $target = $this->item(); + $related = $this->item(); + $related->related()->attach($target->id); + $linked = $this->item(['link_id' => $target->id]); + Item::declare(null, [ + BelongsToManyField::make('related')->model(Item::class), + BelongsToField::make('link_id')->model(Item::class), + ]); + + $this->assertSame([$related->id, $linked->id], (new CardBuilder)->referencing($target)); + } + + public function test_the_ids_found_through_two_fields_are_each_there_once(): void + { + Owner::query()->create(['name' => ['en' => 'Ann']]); + $target = $this->item(); + $both = $this->item(['link_id' => $target->id]); + $both->related()->attach($target->id); + $linked = $this->item(['link_id' => $target->id]); + Item::declare(null, [ + BelongsToManyField::make('related')->model(Item::class), + BelongsToField::make('link_id')->model(Item::class), + ]); + + $this->assertSame([$both->id, $linked->id], (new CardBuilder)->referencing($target)); + } +} diff --git a/packages/admin/tests/Feature/Cache/CardTest.php b/packages/admin/tests/Feature/Cache/CardTest.php new file mode 100644 index 00000000..11d4a787 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/CardTest.php @@ -0,0 +1,298 @@ + $overrides + */ + private function card(array $overrides = []): Card + { + return new Card($overrides + [ + 'id' => 5, + 'type' => Book::class, + 'locale' => 'de', + 'site' => 0, + 'raw' => ['id' => 5, 'name' => json_encode(['en' => 'Book', 'de' => 'Buch']), 'price' => '1000', 'active' => 1, 'shelf_id' => 1], + 'relations' => [], + 'seo' => ['title' => 'Read it', 'description' => '', 'keywords' => null], + 'media' => ['cover' => [['url' => '/storage/a.jpg', 'path' => 'a.jpg', 'name' => 'a.jpg', 'thumbnails' => []]], 'photos' => []], + 'url' => '/books/book', + 'extra' => ['stars' => 4, 'empty' => null], + ]); + } + + public function test_a_card_tells_what_it_was_built_from(): void + { + $card = $this->card(); + + $this->assertSame(5, $card->id()); + $this->assertSame(Book::class, $card->type()); + $this->assertSame('de', $card->locale()); + $this->assertSame(['id' => 5, 'name' => json_encode(['en' => 'Book', 'de' => 'Buch']), 'price' => '1000', 'active' => 1, 'shelf_id' => 1], $card->raw()); + } + + public function test_an_id_may_be_a_string(): void + { + $this->assertSame('abc', $this->card(['id' => 'abc'])->id()); + } + + public function test_an_attribute_comes_through_the_casts_and_the_cards_language(): void + { + $card = $this->card(); + + $this->assertSame(1000, $card->get('price')); + $this->assertTrue($card->get('active')); + // The card is German whatever the app speaks now. + $this->assertSame('en', app()->getLocale()); + $this->assertSame('Buch', $card->get('name')); + } + + public function test_a_missing_attribute_gives_the_default_and_a_present_one_does_not(): void + { + $card = $this->card(); + + $this->assertNull($card->get('nothing')); + $this->assertSame('fallback', $card->get('nothing', 'fallback')); + $this->assertSame(1000, $card->get('price', 'fallback')); + } + + public function test_a_record_without_translations_is_read_as_it_is(): void + { + $card = new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'de', 'raw' => ['id' => 1, 'name' => 'red']]); + + $this->assertSame('red', $card->get('name')); + $this->assertInstanceOf(Tag::class, $card->model()); + } + + /** + * @return array,1:?string}> + */ + public static function seoValues(): array + { + return [ + 'a title' => [['title' => 'Read it'], 'Read it'], + 'an empty one' => [['title' => ''], null], + 'nothing' => [['title' => null], null], + 'a number' => [['title' => 5], null], + 'a list' => [['title' => ['a']], null], + 'a missing key' => [[], null], + ]; + } + + /** + * @param array $seo + */ + #[DataProvider('seoValues')] + public function test_seo_gives_a_filled_in_string_or_nothing(array $seo, ?string $expected): void + { + $this->assertSame($expected, $this->card(['seo' => $seo])->seo('title')); + } + + public function test_seo_of_a_card_that_has_none_is_nothing(): void + { + $card = new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'en', 'raw' => []]); + + $this->assertNull($card->seo('title')); + } + + public function test_the_pictures_of_a_field_or_none(): void + { + $card = $this->card(); + + $this->assertSame('/storage/a.jpg', $card->media('cover')[0]['url']); + $this->assertSame([], $card->media('photos')); + $this->assertSame([], $card->media('unknown')); + $this->assertSame([], (new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'en', 'raw' => []]))->media('cover')); + } + + public function test_the_picture_is_the_first_one_of_the_first_filled_in_field(): void + { + $card = $this->card(); + + $this->assertSame('/storage/a.jpg', $card->picture('cover')); + $this->assertSame('/storage/a.jpg', $card->picture('photos', 'unknown', 'cover')); + $this->assertNull($card->picture('photos', 'unknown')); + $this->assertNull($card->picture()); + } + + public function test_the_address_is_a_string_or_nothing(): void + { + $this->assertSame('/books/book', $this->card()->url()); + $this->assertNull($this->card(['url' => null])->url()); + $this->assertNull($this->card(['url' => 5])->url()); + $this->assertNull((new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'en', 'raw' => []]))->url()); + } + + public function test_what_a_module_added_or_the_default(): void + { + $card = $this->card(); + + $this->assertSame(4, $card->extra('stars')); + $this->assertSame(4, $card->extra('stars', 'none')); + $this->assertNull($card->extra('unknown')); + $this->assertSame('none', $card->extra('unknown', 'none')); + $this->assertSame('none', $card->extra('empty', 'none')); + $this->assertSame('none', (new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'en', 'raw' => []]))->extra('stars', 'none')); + } + + public function test_the_model_is_one_object_that_reads_like_the_record_a_query_gives(): void + { + [$book] = $this->books(1); + $card = Book::cached($book->id); + + $model = $card->model(); + + $this->assertInstanceOf(Book::class, $model); + $this->assertSame($model, $card->model()); + // Named like a model read by a query: it is the same record. + $this->assertSame(Book::query()->find($book->id)?->getConnectionName(), $model->getConnectionName()); + $this->assertTrue($model->is(Book::query()->find($book->id))); + $this->assertTrue($model->exists); + } + + public function test_the_model_may_be_asked_for_by_its_class(): void + { + [$book] = $this->books(1); + $card = Book::cached($book->id); + + $this->assertInstanceOf(Book::class, $card->model(Book::class)); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The card holds a '.Book::class.', not a '.Shelf::class.'.'); + + $card->model(Shelf::class); + } + + public function test_relations_come_from_the_card_with_no_query(): void + { + [$book] = $this->books(1); + $card = Book::cached($book->id); + + [$queries, $relations] = $this->countQueries(fn (): array => [ + $card->relation('shelf'), + $card->relation('tags'), + $card->relation('seoMeta'), + $card->model()->relationLoaded('tags'), + ]); + + $this->assertSame(0, $queries); + $this->assertInstanceOf(Shelf::class, $relations[0]); + $this->assertSame('Shelf 1', $relations[0]->name); + $this->assertCount(2, $relations[1]); + $this->assertContainsOnlyInstancesOf(Tag::class, $relations[1]); + $this->assertSame(['red', 'blue'], $relations[1]->pluck('name')->all()); + // A relation the record has none of is known to be empty, not looked up. + $this->assertNull($relations[2]); + $this->assertTrue($relations[3]); + } + + public function test_a_relation_that_is_empty_in_the_card_is_not_loaded_from_the_database(): void + { + $shelf = Shelf::query()->create(['name' => ['en' => 'Real']]); + $card = $this->card([ + 'raw' => ['id' => 5, 'name' => '{}', 'shelf_id' => $shelf->id], + 'relations' => ['shelf' => null, 'tags' => []], + ]); + + [$queries, $found] = $this->countQueries(fn (): array => [$card->relation('shelf'), $card->relation('tags')]); + + $this->assertSame(0, $queries); + $this->assertNull($found[0]); + $this->assertCount(0, $found[1]); + } + + public function test_a_card_is_read_only(): void + { + $card = $this->card(); + + foreach ([ + fn () => $card['price'] = 1, + function () use ($card): void { + unset($card['price']); + }, + ] as $write) { + try { + $write(); + $this->fail('A card must not be written to.'); + } catch (LogicException $e) { + $this->assertSame('A cached record is read-only.', $e->getMessage()); + } + } + } + + public function test_a_card_reads_like_an_array_and_like_an_object(): void + { + $card = $this->card(); + + $this->assertSame(1000, $card['price']); + $this->assertSame(1000, $card->price); + $this->assertTrue(isset($card['price'])); + $this->assertTrue(isset($card->price)); + $this->assertFalse(isset($card['nothing'])); + $this->assertFalse(isset($card->nothing)); + $this->assertNull($card['nothing']); + } + + public function test_a_card_is_its_data_as_an_array(): void + { + $card = $this->card(); + + $this->assertSame(5, $card->toArray()['id']); + $this->assertSame(Book::class, $card->toArray()['type']); + $this->assertSame(['title' => 'Read it', 'description' => '', 'keywords' => null], $card->toArray()['seo']); + } + + public function test_a_card_is_written_as_json_with_its_attributes(): void + { + $card = $this->card(); + + $this->assertSame([ + 'id' => 5, + 'type' => Book::class, + 'locale' => 'de', + 'attributes' => $card->model()->attributesToArray(), + 'seo' => ['title' => 'Read it', 'description' => '', 'keywords' => null], + 'media' => $card->toArray()['media'], + 'url' => '/books/book', + 'extra' => ['stars' => 4, 'empty' => null], + ], $card->jsonSerialize()); + $this->assertSame(json_encode($card->jsonSerialize()), json_encode($card)); + } + + public function test_a_card_without_seo_pictures_address_and_extras_is_written_with_empty_ones(): void + { + $card = new Card(['id' => 1, 'type' => Tag::class, 'locale' => 'en', 'raw' => ['id' => 1, 'name' => 'red']]); + + $this->assertSame([ + 'id' => 1, + 'type' => Tag::class, + 'locale' => 'en', + 'attributes' => ['id' => 1, 'name' => 'red'], + 'seo' => [], + 'media' => [], + 'url' => null, + 'extra' => [], + ], $card->jsonSerialize()); + } +} diff --git a/packages/admin/tests/Feature/Cache/OwnerMorphNameTest.php b/packages/admin/tests/Feature/Cache/OwnerMorphNameTest.php new file mode 100644 index 00000000..25ade9d3 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/OwnerMorphNameTest.php @@ -0,0 +1,95 @@ +,1:string}> + */ + public static function owned(): array + { + return [ + 'SEO meta' => [SeoMeta::class, 'seoable'], + 'a slug' => [Slug::class, 'sluggable'], + ]; + } + + public function test_a_model_that_extends_the_seo_row_can_read_the_name_of_its_pair(): void + { + $row = new class extends SeoMeta + { + public function name(): string + { + return $this->ownerMorphName(); + } + }; + + $this->assertSame('seoable', $row->name()); + } + + public function test_a_model_that_extends_the_slug_row_can_read_the_name_of_its_pair(): void + { + $row = new class extends Slug + { + public function name(): string + { + return $this->ownerMorphName(); + } + }; + + $this->assertSame('sluggable', $row->name()); + } + + /** + * @param class-string $class + */ + #[DataProvider('owned')] + public function test_a_row_names_its_owner_without_loading_it(string $class, string $name): void + { + $row = new $class([$name.'_type' => Book::class, $name.'_id' => 7]); + $row->forceFill([$name.'_type' => Book::class, $name.'_id' => 7]); + + $touched = $row->cacheTouches(); + + $this->assertCount(1, $touched); + $this->assertInstanceOf(Book::class, $touched[0]); + $this->assertSame(7, $touched[0]->getKey()); + $this->assertTrue($touched[0]->exists); + } + + /** + * @param class-string $class + */ + #[DataProvider('owned')] + public function test_a_row_with_no_owner_touches_nothing(string $class, string $name): void + { + $row = new $class; + $this->assertSame([], $row->cacheTouches()); + + $row->forceFill([$name.'_type' => Book::class]); + $this->assertSame([], $row->cacheTouches()); + + $row->forceFill([$name.'_type' => 'not a class', $name.'_id' => 7]); + $this->assertSame([], $row->cacheTouches()); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheCardsTest.php b/packages/admin/tests/Feature/Cache/RecordCacheCardsTest.php new file mode 100644 index 00000000..f853c5a1 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheCardsTest.php @@ -0,0 +1,286 @@ +cache = $this->app->make(RecordCache::class); + } + + /** + * What a request starts with once the records are in the database: the + * sites and languages loaded, nothing read, nothing counted. + * + * @return array + */ + private function freshBooks(int $count): array + { + $books = $this->books($count); + $this->app->make(ContentLanguages::class)->default(); + $this->resetRequest(); + + return $books; + } + + /** + * @param array $cards + * @return array + */ + private function ids(array $cards): array + { + return array_map(static fn (Card $card): int|string => $card->id(), $cards); + } + + /** + * @return array + */ + private function cardNames(string $class, int $site = 0): array + { + return ['all', 'site:'.$site, 'card:'.$class, ...array_map(static fn (string $dependency): string => 'list:'.$dependency, $this->cache->builder()->dependenciesOf($class))]; + } + + public function test_ids_may_come_from_a_generator_whose_keys_repeat(): void + { + [$a, $b] = $this->freshBooks(2); + + $cards = $this->cache->cards(Book::class, (function () use ($a, $b) { + yield 'same' => $a->id; + yield 'same' => $b->id; + })()); + + $this->assertSame([$a->id, $b->id], $this->ids($cards)); + } + + public function test_ids_may_come_from_an_array_with_any_keys(): void + { + [$a, $b] = $this->freshBooks(2); + + $cards = $this->cache->cards(Book::class, ['x' => $b->id, 7 => $a->id]); + + $this->assertSame([$b->id, $a->id], $this->ids($cards)); + } + + public function test_a_record_asked_for_twice_is_built_and_counted_once(): void + { + [$a, $b] = $this->freshBooks(2); + + $cards = $this->cache->cards(Book::class, [$a->id, $a->id, $b->id, $a->id]); + + $this->assertSame([$a->id, $b->id], $this->ids($cards)); + $this->assertSame(['hits' => 0, 'misses' => 2], $this->cache->requestStats()); + } + + public function test_an_id_written_another_way_is_the_same_record(): void + { + [$a, $b] = $this->freshBooks(2); + + $cards = $this->cache->cards(Book::class, [$a->id, '0'.$a->id, (string) $a->id, $b->id]); + + $this->assertSame([$a->id, $b->id], $this->ids($cards)); + $this->assertSame(['hits' => 0, 'misses' => 2], $this->cache->requestStats()); + } + + public function test_no_ids_give_no_cards_and_read_nothing(): void + { + $this->freshBooks(1); + + $this->assertSame([], $this->cache->cards(Book::class, [])); + $this->assertSame([], $this->cache->cards(Book::class, (fn () => yield from [])())); + $this->assertSame([], $this->cache->readNames()); + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->requestStats()); + } + + public function test_cards_tell_the_page_what_it_depends_on(): void + { + [$book] = $this->freshBooks(1); + + $this->cache->cards(Book::class, [$book->id]); + + $this->assertSame(['list:'.Book::class, 'all', 'site:0', 'card:'.Book::class, 'list:'.Shelf::class, 'list:'.Tag::class], $this->cache->readNames()); + } + + public function test_with_the_cache_off_a_page_depends_on_the_class_only(): void + { + [$book] = $this->freshBooks(1); + config(['atrium.cache.enabled' => false]); + + $this->cache->cards(Book::class, [$book->id]); + + $this->assertSame(['list:'.Book::class], $this->cache->readNames()); + } + + public function test_a_class_that_is_not_cacheable_is_built_every_time_and_depends_on_its_class_only(): void + { + [$cache, $repository] = $this->spyCache(); + $red = Tag::query()->firstOrCreate(['name' => 'red']); + $this->resetRequest(); + + $cards = $cache->cards(Tag::class, [$red->id]); + + $this->assertSame([$red->id], $this->ids($cards)); + $this->assertSame('red', $cards[0]->name); + $this->assertSame([], $repository->calls); + $this->assertSame(['list:'.Tag::class], $cache->readNames()); + $this->assertSame(['hits' => 0, 'misses' => 0], $cache->requestStats()); + } + + public function test_with_the_cache_off_nothing_is_read_from_or_written_to_it(): void + { + [$cache, $repository] = $this->spyCache(); + [$book] = $this->freshBooks(1); + config(['atrium.cache.enabled' => false]); + + $cards = $cache->cards(Book::class, [$book->id]); + + $this->assertSame([$book->id], $this->ids($cards)); + $this->assertSame([], $repository->calls); + $this->assertSame(['hits' => 0, 'misses' => 0], $cache->requestStats()); + } + + public function test_hits_and_misses_add_up_over_the_calls_of_a_request(): void + { + [$a, $b, $c] = $this->freshBooks(3); + + $this->cache->cards(Book::class, [$a->id, $b->id]); + $this->assertSame(['hits' => 0, 'misses' => 2], $this->cache->requestStats()); + + $this->cache->cards(Book::class, [$a->id, $b->id, $c->id]); + $this->assertSame(['hits' => 2, 'misses' => 3], $this->cache->requestStats()); + + $this->cache->cards(Book::class, [$a->id, $c->id]); + $this->assertSame(['hits' => 4, 'misses' => 3], $this->cache->requestStats()); + } + + public function test_cards_are_kept_under_a_key_of_the_class_site_language_and_id_for_a_day(): void + { + [$cache, $repository] = $this->spyCache(); + [$book] = $this->freshBooks(1); + + $cache->cards(Book::class, [$book->id], 'de'); + + $key = 'atrium:card:'.$cache->versions()->stamp($this->cardNames(Book::class)).':0:de:'.$book->id; + $this->assertContains([$key], array_map(static fn (array $call): array => $call[0], $repository->callsTo('many'))); + $this->assertSame([$key], array_keys($repository->callsTo('putMany')[0][0])); + $this->assertSame(86400, $repository->callsTo('putMany')[0][1]); + $this->assertSame($book->id, $repository->callsTo('putMany')[0][0][$key]['id']); + $this->assertSame('de', $repository->callsTo('putMany')[0][0][$key]['locale']); + } + + public function test_a_warm_card_is_read_back_and_nothing_is_written(): void + { + [$cache, $repository] = $this->spyCache(); + [$book] = $this->freshBooks(1); + $cache->cards(Book::class, [$book->id]); + $writes = count($repository->callsTo('putMany')); + + $cards = $cache->cards(Book::class, [$book->id]); + + $this->assertSame([$book->id], $this->ids($cards)); + $this->assertCount($writes, $repository->callsTo('putMany')); + $this->assertSame(['hits' => 1, 'misses' => 1], $cache->requestStats()); + } + + public function test_cards_speak_the_language_of_the_app_unless_asked_for_another(): void + { + [$book] = $this->freshBooks(1); + $book->setTranslation('name', 'de', 'Buch')->save(); + $this->app->setLocale('de'); + + $this->assertSame('de', $this->cache->cards(Book::class, [$book->id])[0]->locale()); + $this->assertSame('en', $this->cache->cards(Book::class, [$book->id], 'en')[0]->locale()); + $this->assertSame('Buch', $this->cache->cards(Book::class, [$book->id])[0]->name); + } + + public function test_cards_of_a_site_are_kept_apart_from_the_cards_of_another(): void + { + [$cache, $repository] = $this->spyCache(); + $site = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'active' => true]); + $this->app->make(Sites::class)->flush(); + $this->app->make(Sites::class)->setCurrent($site); + [$book] = $this->freshBooks(1); + + $cache->cards(Book::class, [$book->id]); + + $key = 'atrium:card:'.$cache->versions()->stamp($this->cardNames(Book::class, (int) $site->id)).':'.$site->id.':en:'.$book->id; + $this->assertSame([$key], array_keys($repository->callsTo('putMany')[0][0])); + $this->assertContains('site:'.$site->id, $cache->readNames()); + $this->assertNotContains('site:0', $cache->readNames()); + } + + /** + * @return array,1:int}> + */ + public static function cardLifetimes(): array + { + return [ + 'a day by default' => [[], 86400], + 'what is configured' => [['cards' => 120], 120], + 'a string from the environment' => [['cards' => '300'], 300], + 'zero is one second' => [['cards' => 0], 1], + 'negative is one second' => [['cards' => -5], 1], + 'only the lists configured' => [['lists' => 5], 86400], + ]; + } + + /** + * @param array $ttl + */ + #[DataProvider('cardLifetimes')] + public function test_cards_live_as_long_as_the_configuration_says(array $ttl, int $seconds): void + { + config(['atrium.cache.ttl' => $ttl]); + [$cache, $repository] = $this->spyCache(); + [$book] = $this->freshBooks(1); + + $cache->cards(Book::class, [$book->id]); + + $this->assertSame($seconds, $repository->callsTo('putMany')[0][1]); + } + + public function test_a_key_may_be_anything_that_prints_as_one(): void + { + Code::query()->create(['code' => 'abc']); + $key = new class implements Stringable + { + public function __toString(): string + { + return 'abc'; + } + }; + + $cards = $this->cache->cards(Code::class, [$key, 'abc']); + + $this->assertCount(1, $cards); + $this->assertSame('abc', $cards[0]->id()); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheChangesTest.php b/packages/admin/tests/Feature/Cache/RecordCacheChangesTest.php new file mode 100644 index 00000000..1e475e57 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheChangesTest.php @@ -0,0 +1,680 @@ +cache, $this->store] = $this->spyCache(); + $this->app->make(ContentLanguages::class)->default(); + Node::$told = 0; + } + + /** + * The version counters bumped, in order. + * + * @return array + */ + private function bumped(): array + { + return array_map(static fn (array $call): string => substr((string) $call[0], strlen('atrium:v:')), $this->store->callsTo('increment')); + } + + /** + * The keys forgotten, in order. + * + * @return array + */ + private function forgotten(): array + { + return array_map(static fn (array $call): string => (string) $call[0], $this->store->callsTo('forget')); + } + + /** + * @param array $dependencies + */ + private function cardKey(string $class, array $dependencies, int $site, string $locale, int|string $id): string + { + $names = ['all', 'site:'.$site, 'card:'.$class, ...array_map(static fn (string $dependency): string => 'list:'.$dependency, $dependencies)]; + + return 'atrium:card:'.$this->cache->versions()->stamp($names).':'.$site.':'.$locale.':'.$id; + } + + private function book(int $id): Book + { + $book = new Book; + $book->setAttribute('id', $id); + + return $book; + } + + /** + * Make the application know these sites, without saving any. + * + * @param array $ids + */ + private function knowSites(array $ids): void + { + $sites = new Collection(array_map(static fn (int|string|null $id): Site => (new Site)->setRawAttributes(['id' => $id], true), $ids)); + (new ReflectionProperty(Sites::class, 'all'))->setValue($this->app->make(Sites::class), $sites); + } + + public function test_saving_a_book_makes_the_lists_of_its_class_stale_and_nothing_else(): void + { + $this->cache->changed($this->book(5)); + + $this->assertSame(['list:'.Book::class], $this->bumped()); + } + + public function test_saving_a_record_that_is_not_cacheable_makes_its_lists_stale_and_drops_no_card(): void + { + $tag = new Tag; + $tag->setAttribute('id', 5); + + $this->cache->changed($tag); + + $this->assertSame(['list:'.Tag::class], $this->bumped()); + $this->assertSame([], $this->forgotten()); + } + + public function test_saving_a_site_makes_that_sites_pages_stale(): void + { + $site = new Site; + $site->setAttribute('id', 3); + + $this->cache->changed($site); + + $this->assertSame(['list:'.Site::class, 'site:3'], $this->bumped()); + } + + public function test_a_site_that_has_no_key_yet_makes_no_site_stale(): void + { + $this->cache->changed(new Site); + + $this->assertSame(['list:'.Site::class], $this->bumped()); + } + + /** + * @return array + */ + public static function languageKeys(): array + { + return [ + 'a saved language' => [4], + 'one with no key yet' => [null], + ]; + } + + #[DataProvider('languageKeys')] + public function test_saving_a_language_makes_everything_stale(?int $key): void + { + $language = new Language; + $language->setAttribute('id', $key); + + $this->cache->changed($language); + + $this->assertSame(['list:'.Language::class, 'all'], $this->bumped()); + } + + public function test_saving_a_language_drops_the_entries_of_the_store_where_it_can(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->changed(new Language); + + $this->assertContains([['atrium']], $repository->callsTo('tags')); + } + + public function test_saving_a_book_leaves_the_store_alone_beyond_its_own_cards(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->changed($this->book(5)); + + $this->assertNotContains([['atrium']], $repository->callsTo('tags')); + } + + public function test_a_record_of_a_class_that_is_ignored_changes_nothing(): void + { + config(['atrium.cache.ignore' => [Book::class]]); + + $this->cache->changed($this->book(5)); + $this->assertSame([], $this->store->calls); + + $tag = new Tag; + $tag->setAttribute('id', 5); + $this->cache->changed($tag); + $this->assertSame(['list:'.Tag::class], $this->bumped()); + } + + public function test_a_record_that_has_no_key_drops_no_card_and_a_record_that_has_one_drops_them(): void + { + $this->cache->changed(new Book); + $this->assertSame([], $this->forgotten()); + + $this->cache->changed($this->book(5)); + $this->assertNotSame([], $this->forgotten()); + } + + public function test_saving_a_record_drops_its_card_in_every_site_and_language(): void + { + $this->knowSites([3, 5]); + $this->app->setLocale('fr'); + + $this->cache->changed($this->book(7)); + + $expected = []; + + foreach ([0, 3, 5] as $site) { + foreach (['fr', 'de', 'en'] as $locale) { + $expected[] = $this->cardKey(Book::class, [Shelf::class, Tag::class], $site, $locale, 7); + } + } + + $forgotten = $this->forgotten(); + $this->assertEqualsCanonicalizing($expected, array_unique($forgotten)); + // Dropped again once committed: the test runs inside a transaction. + $this->assertCount(count($expected) * 2, $forgotten); + } + + public function test_a_site_or_a_language_listed_twice_is_dropped_once(): void + { + $this->knowSites([3, 3]); + $this->app->setLocale('de'); + + $this->cache->changed($this->book(7)); + + $keys = $this->forgotten(); + // Sites 0 and 3, languages de and en, each key twice for the second drop. + $this->assertCount(8, $keys); + $this->assertCount(4, array_unique($keys)); + } + + public function test_the_first_site_is_always_known_and_a_site_without_a_key_adds_none(): void + { + $this->knowSites([null]); + $this->app->setLocale('en'); + + $this->cache->changed($this->book(7)); + + $this->assertEqualsCanonicalizing( + [ + $this->cardKey(Book::class, [Shelf::class, Tag::class], 0, 'en', 7), + $this->cardKey(Book::class, [Shelf::class, Tag::class], 0, 'de', 7), + ], + array_unique($this->forgotten()), + ); + } + + public function test_a_site_that_has_no_key_does_not_hide_the_others(): void + { + $this->knowSites([3, null, 5]); + + $this->cache->changed($this->book(7)); + + $forgotten = $this->forgotten(); + $this->assertContains($this->cardKey(Book::class, [Shelf::class, Tag::class], 3, 'en', 7), $forgotten); + $this->assertContains($this->cardKey(Book::class, [Shelf::class, Tag::class], 5, 'en', 7), $forgotten); + $this->assertContains($this->cardKey(Book::class, [Shelf::class, Tag::class], 0, 'en', 7), $forgotten); + } + + public function test_the_key_of_a_site_that_comes_as_text_is_a_number(): void + { + $this->knowSites(['5']); + + $this->cache->changed($this->book(7)); + + $this->assertContains($this->cardKey(Book::class, [Shelf::class, Tag::class], 5, 'en', 7), $this->forgotten()); + } + + public function test_when_the_sites_cannot_be_read_the_main_one_is_dropped_and_nothing_is_reported(): void + { + Exceptions::fake(); + $this->app->instance(Sites::class, new class + { + public function all(): never + { + throw new RuntimeException('No sites.'); + } + + public function isResolved(): bool + { + return false; + } + }); + + $this->cache->changed($this->book(7)); + + Exceptions::assertNothingReported(); + $this->assertContains($this->cardKey(Book::class, [Shelf::class, Tag::class], 0, 'en', 7), $this->forgotten()); + $this->assertCount(2, array_unique($this->forgotten())); + } + + public function test_when_the_languages_cannot_be_read_those_of_the_application_are_dropped_and_nothing_is_reported(): void + { + Exceptions::fake(); + $this->knowSites([]); + $this->app->setLocale('fr'); + DB::listen(static function ($query): void { + if (str_contains($query->sql, (new Language)->getTable())) { + throw new RuntimeException('No languages.'); + } + }); + + $this->cache->changed($this->book(7)); + + Exceptions::assertNothingReported(); + $this->assertEqualsCanonicalizing( + [ + $this->cardKey(Book::class, [Shelf::class, Tag::class], 0, 'fr', 7), + ], + array_unique($this->forgotten()), + ); + } + + public function test_saving_a_record_drops_the_cards_of_the_records_of_its_class_that_point_at_it(): void + { + $one = Part::query()->create(['name' => 'one']); + $child = Part::query()->create(['name' => 'child', 'parent_id' => $one->id]); + $other = Part::query()->create(['name' => 'other', 'parent_id' => $one->id + 100]); + $this->store->calls = []; + + $this->cache->changed($one); + + $forgotten = $this->forgotten(); + $this->assertContains($this->cardKey(Part::class, [], 0, 'en', $one->id), $forgotten); + $this->assertContains($this->cardKey(Part::class, [], 0, 'en', $child->id), $forgotten); + $this->assertNotContains($this->cardKey(Part::class, [], 0, 'en', $other->id), $forgotten); + } + + public function test_dropping_cards_is_not_reading_them(): void + { + $this->cache->changed($this->book(7)); + + $this->assertSame([], $this->cache->readNames()); + } + + public function test_a_save_in_a_transaction_drops_the_cards_again_once_committed_and_only_then(): void + { + $this->knowSites([]); + $this->app->setLocale('en'); + $during = null; + + DB::transaction(function () use (&$during): void { + $this->store->calls = []; + $this->cache->changed($this->book(7)); + $during = count($this->forgotten()); + }); + + $this->assertSame(2, $during); + $this->assertSame(4, count($this->forgotten())); + $this->assertSame(array_slice($this->forgotten(), 0, 2), array_slice($this->forgotten(), 2)); + } + + public function test_a_save_in_a_transaction_that_is_rolled_back_drops_nothing_more(): void + { + $this->knowSites([]); + + try { + DB::transaction(function (): void { + $this->cache->changed($this->book(7)); + + throw new RuntimeException('rolled back'); + }); + } catch (RuntimeException) { + } + + $this->assertCount(2, $this->forgotten()); + } + + public function test_a_cache_that_is_down_is_reported_and_the_save_goes_on(): void + { + Exceptions::fake(); + $this->store->failing = 'increment'; + + $this->cache->changed($this->book(7)); + + Exceptions::assertReported(static fn (RuntimeException $e): bool => $e->getMessage() === 'The cache is down.'); + } + + public function test_a_record_is_not_reported_when_the_cache_is_up(): void + { + Exceptions::fake(); + + $this->cache->changed($this->book(7)); + $this->cache->changed(new Node); + + Exceptions::assertNothingReported(); + } + + public function test_a_record_that_failed_to_save_the_cache_may_be_saved_again(): void + { + $handler = new class implements ExceptionHandler + { + public function report(Throwable $e): void + { + throw new LogicException('The handler is down too.'); + } + + public function shouldReport(Throwable $e): bool + { + return true; + } + + public function render($request, Throwable $e): never + { + throw $e; + } + + public function renderForConsole($output, Throwable $e): void {} + }; + $this->app->instance(ExceptionHandler::class, $handler); + $this->store->failing = 'increment'; + + try { + $this->cache->changed($this->book(7)); + $this->fail('The handler was meant to throw.'); + } catch (LogicException) { + } + + $this->store->failing = null; + $this->store->calls = []; + $this->cache->changed($this->book(7)); + + $this->assertSame(['list:'.Book::class], $this->bumped()); + } + + public function test_the_same_record_is_not_saved_again_while_it_is_being_saved(): void + { + $one = Node::query()->create(['name' => 'one']); + $two = Node::query()->create(['name' => 'two']); + $one->tells = [$two]; + $two->tells = [$one]; + Node::$told = 0; + + $this->cache->changed($one); + + // One after the other once each, not for ever. + $this->assertSame(['list:'.Node::class, 'list:'.Node::class], $this->bumped()); + $this->assertLessThan(50, Node::$told); + } + + public function test_a_record_that_tells_another_of_its_class_makes_both_stale(): void + { + $one = Node::query()->create(['name' => 'one']); + $two = Node::query()->create(['name' => 'two']); + $one->tells = [$two]; + + $this->cache->changed($one); + + $this->assertSame(['list:'.Node::class, 'list:'.Node::class], $this->bumped()); + } + + public function test_a_record_that_tells_one_of_another_class_with_the_same_key_makes_both_stale(): void + { + $node = Node::query()->create(['name' => 'node']); + $book = $this->book((int) $node->getKey()); + $node->tells = [$book]; + + $this->cache->changed($node); + + $this->assertSame(['list:'.Node::class, 'list:'.Book::class], $this->bumped()); + } + + public function test_a_record_may_be_saved_again_once_its_save_is_done(): void + { + $this->cache->changed($this->book(7)); + $this->cache->changed($this->book(7)); + + $this->assertSame(['list:'.Book::class, 'list:'.Book::class], $this->bumped()); + } + + public function test_a_record_with_no_key_is_saved_each_time_it_is_asked_to(): void + { + $this->cache->changed(new Node); + $this->cache->changed(new Node); + + $this->assertSame(['list:'.Node::class, 'list:'.Node::class], $this->bumped()); + } + + /** + * @return array what the record answers, the lists made stale + */ + public static function whoToTell(): array + { + return [ + 'nobody' => [[], 1], + 'nothing' => [null, 1], + 'one record' => [[new Book], 2], + 'something that is not a record' => [[new stdClass, 'text', 5], 1], + 'a record after something that is not' => [[new stdClass, new Book], 2], + 'one record not in a list' => [new Book, 1], + ]; + } + + #[DataProvider('whoToTell')] + public function test_only_records_are_told_about_a_save(mixed $answer, int $lists): void + { + Exceptions::fake(); + $node = new Node; + $node->setAttribute('id', 1); + $node->tells = $answer; + + $this->cache->changed($node); + + Exceptions::assertNothingReported(); + $this->assertCount($lists, $this->bumped()); + } + + public function test_the_class_flush_makes_cards_and_lists_stale_and_drops_the_group_of_the_store(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->flushClass(Book::class); + + $this->assertSame(['card:'.Book::class, 'list:'.Book::class], array_map(static fn (array $call): string => substr((string) $call[0], strlen('atrium:v:')), $repository->callsTo('increment'))); + $this->assertSame([[['atrium:Atrium.Admin.Tests.Fixtures.Cache.Book']]], $repository->callsTo('tags')); + } + + public function test_the_class_flush_of_a_name_of_ones_own_works_the_same(): void + { + $this->cache->flushClass('my-block'); + + $this->assertSame(['card:my-block', 'list:my-block'], $this->bumped()); + } + + public function test_the_flush_of_a_site_makes_only_that_site_stale(): void + { + $this->cache->flushSite(4); + + $this->assertSame(['site:4'], $this->bumped()); + } + + public function test_the_flush_of_everything_makes_everything_stale_and_drops_what_the_store_holds(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->flushAll(); + + $this->assertSame(['atrium:v:all'], array_map(static fn (array $call): string => (string) $call[0], $repository->callsTo('increment'))); + $this->assertSame([[['atrium']]], $repository->callsTo('tags')); + } + + public function test_a_store_without_tags_is_not_asked_to_drop_anything(): void + { + $this->cache->flushAll(); + $this->cache->flushClass(Book::class); + + $this->assertSame([], $this->store->callsTo('tags')); + } + + public function test_nothing_is_dropped_while_an_import_runs(): void + { + $this->cache->bulk(function (): void { + $this->cache->changed($this->book(1)); + $this->cache->changed($this->book(2)); + $this->cache->changed(new Language); + + $this->assertSame([], $this->store->calls); + }); + } + + public function test_an_import_drops_each_class_it_touched_once_at_the_end(): void + { + $tag = new Tag; + $tag->setAttribute('id', 1); + + $this->cache->bulk(function () use ($tag): void { + $this->cache->changed($this->book(1)); + $this->cache->changed($tag); + $this->cache->changed($this->book(2)); + $this->cache->changed($this->book(1)); + }); + + $this->assertSame(['card:'.Book::class, 'list:'.Book::class, 'card:'.Tag::class, 'list:'.Tag::class], $this->bumped()); + $this->assertSame([], $this->forgotten()); + } + + public function test_an_import_that_touched_nothing_drops_nothing(): void + { + $this->cache->bulk(static fn (): null => null); + + $this->assertSame([], $this->store->calls); + } + + public function test_an_import_that_writes_past_the_models_drops_everything_once_and_not_by_class(): void + { + $this->cache->bulk(function (): void { + $this->cache->changed($this->book(1)); + }, everything: true); + + $this->assertSame(['all'], $this->bumped()); + } + + public function test_an_import_that_does_not_say_so_does_not_drop_everything(): void + { + $this->cache->bulk(static fn (): null => null, everything: false); + + $this->assertNotContains('all', $this->bumped()); + } + + public function test_an_import_inside_an_import_waits_for_the_outer_one(): void + { + $this->cache->bulk(function (): void { + $this->cache->bulk(function (): void { + $this->cache->changed($this->book(1)); + }); + + $this->assertSame([], $this->store->calls, 'the inner one ended'); + + $this->cache->changed($this->book(2)); + }); + + $this->assertSame(['card:'.Book::class, 'list:'.Book::class], $this->bumped()); + } + + /** + * @return array whether the inner and the outer ask for everything + */ + public static function nestedImports(): array + { + return [ + 'the inner one' => [true, false], + 'the outer one' => [false, true], + 'both' => [true, true], + ]; + } + + #[DataProvider('nestedImports')] + public function test_everything_goes_when_any_of_the_nested_imports_asks_for_it(bool $inner, bool $outer): void + { + $this->cache->bulk(function () use ($inner): void { + $this->cache->bulk(static fn (): null => null, $inner); + $this->assertSame([], $this->store->calls); + }, $outer); + + $this->assertSame(['all'], $this->bumped()); + } + + public function test_the_next_import_starts_afresh(): void + { + $this->cache->bulk(function (): void { + $this->cache->changed($this->book(1)); + }, everything: true); + $this->store->calls = []; + + $this->cache->bulk(function (): void { + $this->cache->changed(new Node); + }); + + $this->assertSame(['card:'.Node::class, 'list:'.Node::class], $this->bumped()); + } + + public function test_an_import_gives_back_what_its_callback_returns(): void + { + $this->assertSame(42, $this->cache->bulk(static fn (): int => 42)); + $this->assertSame('x', $this->cache->bulk(static fn (): string => 'x', everything: true)); + } + + public function test_an_import_that_fails_still_drops_what_it_touched_and_lets_the_error_through(): void + { + try { + $this->cache->bulk(function (): void { + $this->cache->changed($this->book(1)); + + throw new RuntimeException('Import failed.'); + }); + $this->fail('The error must come through.'); + } catch (RuntimeException $e) { + $this->assertSame('Import failed.', $e->getMessage()); + } + + $this->assertSame(['card:'.Book::class, 'list:'.Book::class], $this->bumped()); + + // And saving works again: the import is over. + $this->store->calls = []; + $this->cache->changed($this->book(1)); + $this->assertSame(['list:'.Book::class], $this->bumped()); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheListsTest.php b/packages/admin/tests/Feature/Cache/RecordCacheListsTest.php new file mode 100644 index 00000000..a3220679 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheListsTest.php @@ -0,0 +1,371 @@ +cache = $this->app->make(RecordCache::class); + } + + /** + * @return array + */ + private function freshBooks(int $count): array + { + $books = $this->books($count); + $this->app->make(ContentLanguages::class)->default(); + $this->resetRequest(); + + return $books; + } + + public function test_the_ids_of_text_keys_come_back_as_numbers_where_they_are_numbers(): void + { + foreach (['12', '123456789012345678', '1234567890123456789', '12abc', 'abc'] as $code) { + Code::query()->create(['code' => $code]); + } + $this->resetRequest(); + + $first = $this->cache->ids(Code::query()->orderBy('code')); + $this->resetRequest(); + $again = $this->cache->ids(Code::query()->orderBy('code')); + + foreach ([$first, $again] as $result) { + $this->assertCount(5, $result->ids); + $this->assertSame(5, $result->total); + // Up to eighteen digits it is a number; longer would not fit; the rest is text. + $this->assertContains(12, $result->ids, 'twelve'); + $this->assertContains(123456789012345678, $result->ids, 'eighteen digits'); + $this->assertContains('1234567890123456789', $result->ids, 'nineteen digits'); + $this->assertContains('12abc', $result->ids, 'digits and letters'); + $this->assertContains('abc', $result->ids, 'letters'); + } + } + + public function test_with_the_cache_off_the_ids_come_straight_from_the_database(): void + { + foreach (['12', 'abc'] as $code) { + Code::query()->create(['code' => $code]); + } + [$cache, $repository] = $this->spyCache(); + config(['atrium.cache.enabled' => false]); + + $all = $cache->ids(Code::query()->orderBy('code')); + $page = $cache->ids(Code::query()->orderBy('code'), 1, 2); + + $this->assertSame([12, 'abc'], $all->ids); + $this->assertSame(2, $all->total); + $this->assertSame(['abc'], $page->ids); + $this->assertSame(2, $page->total); + $this->assertSame([], $repository->calls); + $this->assertSame([], $cache->readNames()); + $this->assertSame(['hits' => 0, 'misses' => 0], $cache->requestStats()); + } + + public function test_a_list_tells_the_page_what_it_depends_on(): void + { + $this->freshBooks(1); + + $this->cache->ids(Book::query()); + + $this->assertSame(['all', 'site:0', 'list:'.Book::class], $this->cache->readNames()); + } + + public function test_a_list_that_reads_other_classes_depends_on_them_too(): void + { + $this->freshBooks(1); + + $this->cache->ids(Book::query(), dependsOn: [Shelf::class, Code::class]); + + $this->assertSame(['all', 'site:0', 'list:'.Book::class, 'list:'.Shelf::class, 'list:'.Code::class], $this->cache->readNames()); + } + + public function test_a_list_goes_stale_when_a_class_it_depends_on_changes_and_not_otherwise(): void + { + [$book] = $this->freshBooks(1); + $withShelf = fn (array $dependsOn) => $this->cache->ids(Book::query()->whereHas('shelf', fn ($shelves) => $shelves->whereNotNull('name')), dependsOn: $dependsOn); + $this->assertSame([$book->id], $withShelf([Shelf::class])->ids); + $this->assertSame([$book->id], $withShelf([])->ids); + + DB::table('cache_shelves')->update(['name' => null]); + $this->cache->changed(Shelf::query()->firstOrFail()); + $this->resetRequest(); + + $this->assertSame([], $withShelf([Shelf::class])->ids); + // Not told about the shelves, it keeps what it had. + $this->assertSame([$book->id], $withShelf([])->ids); + } + + public function test_a_page_of_a_list_is_cut_by_its_size_and_number(): void + { + $books = $this->freshBooks(5); + $ids = array_map(fn (Book $book): int => $book->id, $books); + + $first = $this->cache->ids(Book::query()->orderBy('id'), 2, 1); + $second = $this->cache->ids(Book::query()->orderBy('id'), 2, 2); + $last = $this->cache->ids(Book::query()->orderBy('id'), 2, 3); + $beyond = $this->cache->ids(Book::query()->orderBy('id'), 2, 4); + + $this->assertSame(array_slice($ids, 0, 2), $first->ids); + $this->assertSame(array_slice($ids, 2, 2), $second->ids); + $this->assertSame(array_slice($ids, 4, 2), $last->ids); + $this->assertSame([], $beyond->ids); + $this->assertSame([5, 5, 5, 5], [$first->total, $second->total, $last->total, $beyond->total]); + } + + public function test_no_page_number_means_the_first_page(): void + { + $books = $this->freshBooks(3); + + $result = $this->cache->ids(Book::query()->orderBy('id'), 2); + + $this->assertSame([$books[0]->id, $books[1]->id], $result->ids); + } + + public function test_a_list_without_a_page_size_gives_every_id(): void + { + $books = $this->freshBooks(3); + + $result = $this->cache->ids(Book::query()->orderBy('id')); + + $this->assertSame(array_map(fn (Book $book): int => $book->id, $books), $result->ids); + $this->assertSame(3, $result->total); + } + + public function test_an_empty_page_costs_one_query_for_the_count_and_none_for_the_ids(): void + { + $this->freshBooks(2); + + [$queries, $result] = $this->countQueries(fn () => $this->cache->ids(Book::query()->where('price', '>', 999999), 5, 1)); + + $this->assertSame(1, $queries); + $this->assertSame([], $result->ids); + $this->assertSame(0, $result->total); + } + + public function test_the_query_of_the_caller_is_left_as_it_was(): void + { + $this->freshBooks(3); + $query = Book::query()->where('price', '>', 500)->orderBy('id'); + $sql = $query->toSql(); + $bindings = $query->getBindings(); + + $this->cache->ids($query, 2, 2); + $this->cache->ids($query); + $this->cache->ids($query, 1, 1); + + $this->assertSame($sql, $query->toSql()); + $this->assertSame($bindings, $query->getBindings()); + $this->assertCount(3, $query->get()); + } + + public function test_a_list_is_read_back_from_the_cache_with_no_query(): void + { + $books = $this->freshBooks(3); + $first = $this->cache->ids(Book::query()->orderBy('id'), 2, 1); + $this->resetRequest(); + + [$queries, $again] = $this->countQueries(fn () => $this->cache->ids(Book::query()->orderBy('id'), 2, 1)); + + $this->assertSame(0, $queries); + $this->assertSame($first->ids, $again->ids); + $this->assertSame(3, $again->total); + $this->assertSame($books[0]->id, $again->ids[0]); + } + + public function test_misses_and_hits_are_counted_once_each(): void + { + $this->freshBooks(2); + + $this->cache->ids(Book::query()); + $this->assertSame(['hits' => 0, 'misses' => 1], $this->cache->requestStats()); + + $this->cache->ids(Book::query()); + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->requestStats()); + } + + public function test_a_list_is_kept_apart_for_each_filter_page_size_page_and_language(): void + { + $this->freshBooks(5); + $kept = function (callable $query): int { + $before = $this->cache->requestStats()['misses']; + $query(); + + return $this->cache->requestStats()['misses'] - $before; + }; + + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 2, 1))); + $this->assertSame(0, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 2, 1)), 'the same list'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 2000), 2, 1)), 'another filter'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 3, 1)), 'another page size'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 2, 2)), 'another page'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 2)), 'no page'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000))), 'no page size'); + + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '<', 1000), 2, 1)), 'the same value in another comparison'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->orderBy('id'))), 'an order and no value at all'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->orderByDesc('id'))), 'another order'); + + $this->app->setLocale('de'); + $this->assertSame(1, $kept(fn () => $this->cache->ids(Book::query()->where('price', '>', 1000), 2, 1)), 'another language'); + } + + public function test_a_time_in_a_filter_is_told_apart_to_the_microsecond(): void + { + $this->freshBooks(1); + $before = fn (string $time) => $this->cache->ids(Book::query()->where('created_at', '<', Carbon::parse($time))); + + $before('2031-01-01 00:00:00.100000'); + $before('2031-01-01 00:00:00.200000'); + $this->assertSame(['hits' => 0, 'misses' => 2], $this->cache->requestStats()); + + $before('2031-01-01 00:00:00.100000'); + $this->assertSame(['hits' => 1, 'misses' => 2], $this->cache->requestStats()); + } + + public function test_a_filter_with_a_value_that_prints_as_text_is_told_apart_by_that_text(): void + { + $this->freshBooks(3); + $amount = fn (string $text): Stringable => new class($text) implements Stringable + { + public function __construct(private readonly string $text) {} + + public function __toString(): string + { + return $this->text; + } + }; + $over = fn (string $text) => $this->cache->ids(Book::query()->whereRaw('price > ?', [$amount($text)])); + + $this->assertCount(2, $over('1000')->ids); + $this->assertCount(1, $over('2000')->ids); + $this->assertCount(2, $over('1000')->ids); + $this->assertSame(['hits' => 1, 'misses' => 2], $this->cache->requestStats()); + } + + public function test_a_list_is_kept_under_a_key_of_its_versions_and_query_for_an_hour(): void + { + [$cache, $repository] = $this->spyCache(); + $this->freshBooks(1); + + $cache->ids(Book::query()); + + $stamp = $cache->versions()->stamp(['all', 'site:0', 'list:'.Book::class]); + $put = $repository->callsTo('putMany'); + $this->assertCount(1, $put); + $this->assertCount(1, $put[0][0]); + $this->assertMatchesRegularExpression('/^atrium:ids:'.$stamp.':[0-9a-f]{32}$/', (string) array_key_first($put[0][0])); + $this->assertSame(3600, $put[0][1]); + } + + /** + * @return array,1:int}> + */ + public static function listLifetimes(): array + { + return [ + 'an hour by default' => [[], 3600], + 'what is configured' => [['lists' => 90], 90], + 'a string from the environment' => [['lists' => '45'], 45], + 'zero is one second' => [['lists' => 0], 1], + 'only the cards configured' => [['cards' => 5], 3600], + ]; + } + + /** + * @param array $ttl + */ + #[DataProvider('listLifetimes')] + public function test_lists_live_as_long_as_the_configuration_says(array $ttl, int $seconds): void + { + config(['atrium.cache.ttl' => $ttl]); + [$cache, $repository] = $this->spyCache(); + $this->freshBooks(1); + + $cache->ids(Book::query()); + + $this->assertSame($seconds, $repository->callsTo('putMany')[0][1]); + } + + public function test_a_paginator_holds_the_cards_of_the_page_twenty_to_a_page_unless_told_otherwise(): void + { + $this->freshBooks(25); + + $page = $this->cache->paginate(Book::query()->orderBy('id')); + + $this->assertSame(20, $page->perPage()); + $this->assertSame(25, $page->total()); + $this->assertSame(1, $page->currentPage()); + $this->assertSame(2, $page->lastPage()); + $this->assertCount(20, $page->items()); + $this->assertContainsOnlyInstancesOf(Card::class, $page->items()); + } + + public function test_a_paginator_knows_its_page_its_size_its_name_and_its_path(): void + { + $this->freshBooks(5); + Paginator::currentPathResolver(fn (): string => '/books'); + + $page = $this->cache->paginate(Book::query()->orderBy('id'), 2, 'p', 3); + + $this->assertSame(2, $page->perPage()); + $this->assertSame(3, $page->currentPage()); + $this->assertSame('p', $page->getPageName()); + $this->assertSame('/books', $page->path()); + $this->assertSame('/books?p=2', $page->url(2)); + $this->assertCount(1, $page->items()); + } + + public function test_a_paginator_takes_its_page_from_the_request_under_its_own_name(): void + { + $books = $this->freshBooks(5); + Paginator::currentPageResolver(fn (string $name): int => $name === 'p' ? 2 : 1); + + $page = $this->cache->paginate(Book::query()->orderBy('id'), 2, 'p'); + + $this->assertSame(2, $page->currentPage()); + $this->assertSame([$books[2]->id, $books[3]->id], array_map(fn (Card $card): int|string => $card->id(), $page->items())); + } + + public function test_a_paginator_hands_the_language_and_the_dependencies_on(): void + { + [$book] = $this->freshBooks(1); + $book->setTranslation('name', 'de', 'Buch')->save(); + $this->resetRequest(); + + $page = $this->cache->paginate(Book::query()->whereHas('shelf', fn ($shelves) => $shelves->whereNotNull('name')), 5, 'page', 1, 'de', [Shelf::class]); + + $this->assertSame('Buch', $page->items()[0]->name); + $this->assertContains('list:'.Shelf::class, $this->cache->readNames()); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheOutsideTransactionTest.php b/packages/admin/tests/Feature/Cache/RecordCacheOutsideTransactionTest.php new file mode 100644 index 00000000..3610d75c --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheOutsideTransactionTest.php @@ -0,0 +1,86 @@ + 0) { + DB::rollBack(); + } + + // What an application has: the framework's own manager for tests + // runs the callbacks of the first transaction at once. + DB::connection()->setTransactionManager(new DatabaseTransactionsManager); + + $sites = new Collection([(new Site)->setRawAttributes(['id' => null], true)]); + (new ReflectionProperty(Sites::class, 'all'))->setValue($this->app->make(Sites::class), $sites); + } + + private function book(): Book + { + $book = new Book; + $book->setAttribute('id', 7); + + return $book; + } + + public function test_a_save_with_no_transaction_drops_the_cards_once(): void + { + [$cache, $store] = $this->spyCache(); + $this->assertSame(0, DB::transactionLevel()); + + $cache->changed($this->book()); + + // The main site in the language of the application: one key. + $this->assertCount(1, $store->callsTo('forget')); + } + + public function test_a_save_in_a_transaction_drops_the_cards_again_once_it_is_committed(): void + { + [$cache, $store] = $this->spyCache(); + + DB::transaction(function () use ($cache, $store): void { + $cache->changed($this->book()); + + $this->assertCount(1, $store->callsTo('forget')); + }); + + $this->assertCount(2, $store->callsTo('forget')); + } + + public function test_a_save_in_a_transaction_that_is_rolled_back_drops_the_cards_once(): void + { + [$cache, $store] = $this->spyCache(); + + DB::beginTransaction(); + $cache->changed($this->book()); + DB::rollBack(); + + $this->assertCount(1, $store->callsTo('forget')); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheRememberTest.php b/packages/admin/tests/Feature/Cache/RecordCacheRememberTest.php new file mode 100644 index 00000000..33026a91 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheRememberTest.php @@ -0,0 +1,336 @@ +cache = $this->app->make(RecordCache::class); + $this->app->make(ContentLanguages::class)->default(); + $this->resetRequest(); + } + + /** + * @return array{0:callable():int,1:callable():int} a callback that counts its runs, and the count + */ + private function counter(mixed $value = 'value'): array + { + $runs = 0; + + return [ + function () use (&$runs, $value): mixed { + $runs++; + + return $value; + }, + function () use (&$runs): int { + return $runs; + }, + ]; + } + + public function test_a_value_is_made_once_and_read_back_after_that(): void + { + [$make, $runs] = $this->counter(['a' => 1]); + + $first = $this->cache->remember(Book::class, 'k', $make); + $second = $this->cache->remember(Book::class, 'k', $make); + + $this->assertSame(['a' => 1], $first); + $this->assertSame(['a' => 1], $second); + $this->assertSame(1, $runs()); + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->requestStats()); + } + + public function test_a_value_that_is_nothing_is_kept_too(): void + { + [$make, $runs] = $this->counter(null); + + $this->assertNull($this->cache->remember(Book::class, 'k', $make)); + $this->assertNull($this->cache->remember(Book::class, 'k', $make)); + + $this->assertSame(1, $runs()); + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->requestStats()); + } + + public function test_the_same_name_under_another_key_or_class_is_another_value(): void + { + [$make, $runs] = $this->counter(); + + $this->cache->remember(Book::class, 'a', $make); + $this->cache->remember(Book::class, 'b', $make); + $this->cache->remember(Shelf::class, 'a', $make); + + $this->assertSame(3, $runs()); + } + + public function test_something_else_under_the_key_is_not_a_value_of_ours(): void + { + [$cache, $repository] = $this->spyCache(); + [$make, $runs] = $this->counter('mine'); + $cache->remember(Book::class, 'k', $make); + $key = (string) array_key_first($repository->callsTo('putMany')[0][0]); + + foreach ([['no v here' => 1], 'text', 5, null] as $other) { + $repository->put($key, $other, 60); + + $this->assertSame('mine', $cache->remember(Book::class, 'k', $make)); + } + + $this->assertSame(5, $runs()); + } + + public function test_with_the_cache_off_the_value_is_made_every_time_and_the_store_is_left_alone(): void + { + [$cache, $repository] = $this->spyCache(); + config(['atrium.cache.enabled' => false]); + [$make, $runs] = $this->counter(); + + $this->assertSame('value', $cache->remember(Book::class, 'k', $make)); + $this->assertSame('value', $cache->remember(Book::class, 'k', $make)); + + $this->assertSame(2, $runs()); + $this->assertSame([], $repository->calls); + $this->assertSame([], $cache->readNames()); + $this->assertSame(['hits' => 0, 'misses' => 0], $cache->requestStats()); + } + + public function test_a_value_is_kept_under_its_versions_and_the_site_it_is_for(): void + { + [$cache, $repository] = $this->spyCache(); + + $cache->remember(Book::class, 'k', fn (): string => 'v'); + + $stamp = $cache->versions()->stamp(['all', 'list:'.Book::class, 'site:0']); + $put = $repository->callsTo('putMany'); + $this->assertSame(['atrium:r:'.$stamp.':0:k' => ['v' => 'v']], $put[0][0]); + $this->assertSame(3600, $put[0][1]); + } + + public function test_a_value_for_every_site_has_no_site_in_its_key(): void + { + [$cache, $repository] = $this->spyCache(); + + $cache->remember([Book::class, Shelf::class], 'k', fn (): string => 'v', perSite: false); + + $stamp = $cache->versions()->stamp(['all', 'list:'.Book::class, 'list:'.Shelf::class]); + $this->assertSame(['atrium:r:'.$stamp.':k' => ['v' => 'v']], $repository->callsTo('putMany')[0][0]); + $this->assertSame(['all', 'list:'.Book::class, 'list:'.Shelf::class], $cache->readNames()); + } + + public function test_a_value_for_a_site_is_for_that_site_by_default(): void + { + [$cache] = $this->spyCache(); + + $cache->remember(Book::class, 'k', fn (): string => 'v'); + + $this->assertSame(['all', 'list:'.Book::class, 'site:0'], $cache->readNames()); + } + + public function test_a_page_that_reads_a_value_learns_every_class_it_depends_on(): void + { + $this->cache->remember([Book::class, Shelf::class], 'k', fn (): string => 'v'); + + $this->assertSame(['all', 'list:'.Book::class, 'list:'.Shelf::class, 'site:0'], $this->cache->readNames()); + } + + public function test_a_single_class_may_be_named_alone(): void + { + $this->cache->remember(Shelf::class, 'k', fn (): string => 'v'); + + $this->assertSame(['all', 'list:'.Shelf::class, 'site:0'], $this->cache->readNames()); + } + + public function test_a_value_of_a_site_is_made_again_for_another_site(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember(Book::class, 'k', $make); + $shop = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'active' => true]); + $sites = $this->app->make(Sites::class); + $sites->flush(); + $sites->setCurrent($shop); + $this->resetRequest(); + + $this->cache->remember(Book::class, 'k', $make); + $this->cache->remember(Book::class, 'k', $make); + + $this->assertSame(2, $runs()); + $this->assertContains('site:'.$shop->id, $this->cache->readNames()); + } + + public function test_a_value_for_every_site_is_not_made_again_for_another_site(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember(Book::class, 'k', $make, perSite: false); + $shop = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'active' => true]); + $sites = $this->app->make(Sites::class); + $sites->flush(); + $sites->setCurrent($shop); + $this->resetRequest(); + + $this->cache->remember(Book::class, 'k', $make, perSite: false); + + $this->assertSame(1, $runs()); + } + + public function test_a_current_site_that_is_not_saved_yet_is_site_zero(): void + { + $sites = $this->app->make(Sites::class); + $unsaved = new Site; + (new ReflectionProperty(Sites::class, 'all'))->setValue($sites, new Collection([$unsaved])); + $sites->setCurrent($unsaved); + + $this->cache->remember(Book::class, 'k', fn (): string => 'v'); + + $this->assertContains('site:0', $this->cache->readNames()); + } + + /** + * @return array,1:?int,2:int}> + */ + public static function valueLifetimes(): array + { + return [ + 'the lists lifetime by default' => [[], null, 3600], + 'what is configured for lists' => [['lists' => 90], null, 90], + 'what the call asks for' => [['lists' => 90], 15, 15], + 'what the call asks for beats the default' => [[], 7200, 7200], + ]; + } + + /** + * @param array $config + */ + #[DataProvider('valueLifetimes')] + public function test_a_value_lives_as_long_as_it_was_told_or_as_lists_do(array $config, ?int $ttl, int $seconds): void + { + config(['atrium.cache.ttl' => $config]); + [$cache, $repository] = $this->spyCache(); + + $cache->remember(Book::class, 'k', fn (): string => 'v', $ttl); + + $this->assertSame($seconds, $repository->callsTo('putMany')[0][1]); + } + + public function test_a_value_is_made_again_when_a_class_it_depends_on_changes_and_not_otherwise(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember([Book::class, Shelf::class], 'k', $make); + [$book] = $this->books(1); + $this->resetRequest(); + $this->assertSame(2, $this->remembered($make, $runs, [Book::class, Shelf::class]), 'a book was saved'); + + $tag = new Tag(['name' => 'green']); + $tag->save(); + $this->resetRequest(); + + $this->assertSame(2, $this->remembered($make, $runs, [Book::class, Shelf::class]), 'a tag is not a dependency'); + + $book->save(); + $this->cache->changed($book); + $this->resetRequest(); + + $this->assertSame(3, $this->remembered($make, $runs, [Book::class, Shelf::class])); + } + + /** + * @param callable():mixed $make + * @param callable():int $runs + * @param array $classes + */ + private function remembered(callable $make, callable $runs, array $classes): int + { + $this->cache->remember($classes, 'k', $make(...)); + + return $runs(); + } + + public function test_flushing_a_name_of_ones_own_makes_its_values_again(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember('my-block', 'k', $make); + $this->cache->remember('my-block', 'k', $make); + $this->assertSame(1, $runs()); + + $this->cache->flushClass('my-block'); + $this->resetRequest(); + $this->cache->remember('my-block', 'k', $make); + + $this->assertSame(2, $runs()); + } + + public function test_flushing_everything_makes_values_again(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember(Book::class, 'k', $make); + + $this->cache->flushAll(); + $this->resetRequest(); + $this->cache->remember(Book::class, 'k', $make); + + $this->assertSame(2, $runs()); + } + + public function test_flushing_one_site_makes_only_its_values_again(): void + { + [$make, $runs] = $this->counter(); + $this->cache->remember(Book::class, 'k', $make); + $this->cache->remember(Book::class, 'k', $make, perSite: false); + + $this->cache->flushSite(0); + $this->resetRequest(); + $this->cache->remember(Book::class, 'k', $make); + $this->cache->remember(Book::class, 'k', $make, perSite: false); + + $this->assertSame(3, $runs()); + } + + public function test_the_entries_of_a_value_go_in_the_group_of_the_first_class(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->remember([Book::class, Shelf::class], 'k', fn (): string => 'v'); + + $group = 'atrium:'.str_replace('\\', '.', Book::class); + $this->assertContains([['atrium', $group]], $repository->callsTo('tags')); + $this->assertNotContains([['atrium', 'atrium:'.str_replace('\\', '.', Shelf::class)]], $repository->callsTo('tags')); + } + + public function test_the_entries_of_a_value_with_no_class_go_in_the_group_called_remember(): void + { + [$cache, $repository] = $this->spyCache(true); + + $cache->remember([], 'k', fn (): string => 'v'); + + $this->assertContains([['atrium', 'atrium:remember']], $repository->callsTo('tags')); + $this->assertSame(['all', 'site:0'], $cache->readNames()); + } +} diff --git a/packages/admin/tests/Feature/Cache/RecordCacheRequestTest.php b/packages/admin/tests/Feature/Cache/RecordCacheRequestTest.php new file mode 100644 index 00000000..d5a19172 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/RecordCacheRequestTest.php @@ -0,0 +1,495 @@ +cache, $this->store] = $this->spyCache(); + $this->timezone = date_default_timezone_get(); + $this->app->make(ContentLanguages::class)->default(); + } + + protected function tearDown(): void + { + Carbon::setTestNow(); + date_default_timezone_set($this->timezone); + + parent::tearDown(); + } + + /** + * One miss and one hit of a value kept. + */ + private function missAndHit(RecordCache $cache): void + { + $cache->remember(Book::class, 'k', fn (): int => 1); + $cache->remember(Book::class, 'k', fn (): int => 1); + } + + public function test_the_cache_hands_out_the_store_and_the_versions_it_was_made_with(): void + { + $repository = new SpyRepository; + $store = new CacheStore($repository, false); + $versions = new Versions($repository); + + $cache = new RecordCache($store, $versions); + + $this->assertSame($store, $cache->store()); + $this->assertSame($versions, $cache->versions()); + } + + /** + * @return array,1:bool}> + */ + public static function enabledSettings(): array + { + return [ + 'on when nothing is said' => [[], true], + 'on' => [['enabled' => true], true], + 'off' => [['enabled' => false], false], + 'off as zero' => [['enabled' => 0], false], + 'off as text zero' => [['enabled' => '0'], false], + 'on as one' => [['enabled' => 1], true], + ]; + } + + /** + * @param array $setting + */ + #[DataProvider('enabledSettings')] + public function test_the_cache_is_on_unless_the_configuration_turns_it_off(array $setting, bool $enabled): void + { + config(['atrium.cache' => $setting]); + + $this->assertSame($enabled, $this->cache->enabled()); + } + + public function test_a_group_is_a_class_name_with_dots_for_backslashes(): void + { + $this->assertSame('Atrium.Admin.Models.Site', RecordCache::group('Atrium\\Admin\\Models\\Site')); + $this->assertSame('my-block', RecordCache::group('my-block')); + } + + /** + * @return array,1:int}> the setting, the timestamp the time comes down to + */ + public static function timeSteps(): array + { + return [ + 'a minute when nothing is said' => [[], 1800000120], + 'a minute' => [['time_step' => 60], 1800000120], + 'a hundred seconds' => [['time_step' => 100], 1800000100], + 'twenty-five seconds' => [['time_step' => 25], 1800000125], + 'a step from the environment' => [['time_step' => '45'], 1800000135], + 'a second' => [['time_step' => 1], 1800000137], + 'none is a second' => [['time_step' => 0], 1800000137], + 'less than none is a second' => [['time_step' => -5], 1800000137], + ]; + } + + /** + * @param array $setting + */ + #[DataProvider('timeSteps')] + public function test_the_time_of_lists_moves_in_steps(array $setting, int $expected): void + { + Carbon::setTestNow(Carbon::createFromTimestamp(1800000137)); + config(['atrium.cache' => $setting]); + + $this->assertSame($expected, $this->cache->now()->getTimestamp()); + } + + public function test_the_time_of_lists_is_in_the_time_zone_of_the_application(): void + { + Carbon::setTestNow(Carbon::createFromTimestamp(1800000137)); + date_default_timezone_set('Asia/Tokyo'); + + $this->assertSame('Asia/Tokyo', $this->cache->now()->getTimezone()->getName()); + + date_default_timezone_set('America/New_York'); + + $this->assertSame('America/New_York', $this->cache->now()->getTimezone()->getName()); + } + + public function test_a_request_counts_its_hits_and_misses(): void + { + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->requestStats()); + + $this->missAndHit($this->cache); + + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->requestStats()); + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->finishedStats()); + } + + /** + * @return array misses, hits + */ + public static function countsOfARequest(): array + { + return [ + 'only misses' => [3, 0], + 'only hits' => [0, 3], + 'both' => [2, 4], + ]; + } + + #[DataProvider('countsOfARequest')] + public function test_the_counts_of_a_request_that_did_anything_are_its_own_whichever_they_are(int $misses, int $hits): void + { + for ($i = 0; $i < $misses; $i++) { + $this->cache->remember(Book::class, 'k'.$i, fn (): int => 1); + } + + for ($i = 0; $i < $hits; $i++) { + $this->cache->remember(Book::class, 'k0', fn (): int => 1); + } + + $own = $this->cache->requestStats(); + $this->cache->reset(); + // A request that did nothing since reset: the counts it closed with. + $this->assertSame($own, $this->cache->finishedStats()); + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->requestStats()); + } + + public function test_the_counts_of_a_request_that_did_something_after_a_reset_replace_the_closed_ones(): void + { + $this->missAndHit($this->cache); + $this->cache->reset(); + $this->cache->remember(Book::class, 'other', fn (): int => 1); + + $this->assertSame(['hits' => 0, 'misses' => 1], $this->cache->finishedStats()); + } + + public function test_a_request_that_counted_nothing_leaves_the_counts_that_were_closed_before(): void + { + $this->missAndHit($this->cache); + $this->cache->reset(); + $this->cache->reset(); + + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->finishedStats()); + } + + public function test_a_cache_that_never_counted_anything_finishes_with_zeros(): void + { + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->finishedStats()); + } + + public function test_a_request_starts_afresh_after_a_reset(): void + { + $this->cache->remember(Book::class, 'k', fn (): int => 1); + $this->cache->dontKeepPage(); + $this->assertNotSame([], $this->cache->readNames()); + $this->assertFalse($this->cache->pageKeepable()); + + $this->cache->reset(); + + $this->assertSame([], $this->cache->readNames()); + $this->assertTrue($this->cache->pageKeepable()); + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->requestStats()); + } + + public function test_a_reset_makes_the_next_read_see_the_versions_another_process_bumped(): void + { + $name = 'list:'.Book::class; + $before = $this->cache->versions()->get([$name])[$name]; + $this->store->put('atrium:v:'.$name, 123456, 60); + + $this->assertSame($before, $this->cache->versions()->get([$name])[$name]); + + $this->cache->reset(); + + $this->assertSame('123456', $this->cache->versions()->get([$name])[$name]); + } + + public function test_a_reset_makes_the_store_work_out_its_tagged_keys_again(): void + { + [$cache, $repository] = $this->spyCache(true); + $cache->store()->many('group', ['a']); + $cache->store()->many('group', ['b']); + $before = count($repository->callsTo('tags')); + + $cache->reset(); + $cache->store()->many('group', ['a']); + + $this->assertSame($before + 1, count($repository->callsTo('tags'))); + } + + public function test_a_page_is_kept_unless_something_made_for_one_visitor_was_on_it(): void + { + $this->assertTrue($this->cache->pageKeepable()); + + $this->cache->markRead(['all', 'list:'.Book::class]); + $this->assertTrue($this->cache->pageKeepable()); + + $this->cache->dontKeepPage(); + $this->assertFalse($this->cache->pageKeepable()); + $this->assertContains(RecordCache::NO_PAGE, $this->cache->readNames()); + } + + public function test_the_names_a_request_read_are_listed_once_each_in_the_order_they_came(): void + { + $this->cache->markRead(['b', 'a']); + $this->cache->markRead(['a', 'c']); + + $this->assertSame(['b', 'a', 'c'], $this->cache->readNames()); + } + + public function test_the_numbers_of_a_request_are_added_to_the_totals(): void + { + $this->missAndHit($this->cache); + $this->cache->persistStats(); + + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->totals()); + + $this->cache->reset(); + $this->cache->remember(Book::class, 'other', fn (): int => 1); + $this->cache->persistStats(); + + $this->assertSame(['hits' => 1, 'misses' => 2], $this->cache->totals()); + } + + public function test_a_count_of_zero_is_not_written_down(): void + { + $this->cache->remember(Book::class, 'k', fn (): int => 1); + + $this->cache->persistStats(); + + $this->assertSame([['atrium:stats:misses', 1]], array_values(array_filter($this->store->callsTo('increment'), static fn (array $call): bool => str_starts_with((string) $call[0], 'atrium:stats:')))); + $this->assertSame(['hits' => 0, 'misses' => 1], $this->cache->totals()); + } + + public function test_a_store_that_cannot_increment_a_missing_total_starts_it(): void + { + $this->store->memcached = true; + $this->missAndHit($this->cache); + $this->store->calls = []; + + $this->cache->persistStats(); + + $this->assertSame([['atrium:stats:hits', 1], ['atrium:stats:misses', 1]], $this->store->callsTo('increment')); + $this->assertSame([['atrium:stats:hits', 1], ['atrium:stats:misses', 1]], $this->store->callsTo('forever')); + $this->assertSame(['hits' => 1, 'misses' => 1], $this->cache->totals()); + } + + public function test_a_store_that_increments_does_not_start_the_total_again(): void + { + $this->missAndHit($this->cache); + $this->store->calls = []; + + $this->cache->persistStats(); + + $this->assertSame([], $this->store->callsTo('forever')); + } + + public function test_with_the_counts_turned_off_nothing_is_written(): void + { + config(['atrium.cache.stats' => false]); + $this->missAndHit($this->cache); + $this->store->calls = []; + + $this->cache->persistStats(); + + $this->assertSame([], $this->store->calls); + } + + public function test_a_cache_that_is_down_costs_the_request_no_error_for_its_counts(): void + { + Exceptions::fake(); + $this->missAndHit($this->cache); + $this->store->failing = 'increment'; + + $this->cache->persistStats(); + + Exceptions::assertNothingReported(); + $this->assertSame(1, count($this->store->callsTo('increment'))); + } + + public function test_a_request_that_did_nothing_writes_nothing(): void + { + $this->cache->persistStats(); + + $this->assertSame([], $this->store->callsTo('increment')); + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->totals()); + } + + public function test_the_totals_are_numbers_whatever_the_store_kept(): void + { + $this->store->put('atrium:stats:hits', '5', 60); + $this->store->put('atrium:stats:misses', '7.0', 60); + + $this->assertSame(['hits' => 5, 'misses' => 7], $this->cache->totals()); + } + + public function test_the_totals_start_at_zero(): void + { + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->totals()); + } + + public function test_clearing_the_totals_clears_both(): void + { + $this->missAndHit($this->cache); + $this->cache->persistStats(); + + $this->cache->resetTotals(); + + $this->assertSame(['hits' => 0, 'misses' => 0], $this->cache->totals()); + $this->assertSame([['atrium:stats:hits'], ['atrium:stats:misses']], $this->store->callsTo('forget')); + } + + public function test_the_pages_to_warm_start_with_the_home_page(): void + { + $this->assertSame(['/'], $this->cache->warmPaths('en')); + } + + public function test_the_pages_to_warm_are_made_of_the_paths_and_queries_of_what_modules_add(): void + { + $this->cache->warmUsing(static fn (): array => [ + 'https://example.com/books?page=2', + '/news/', + 'about', + 'https://example.com', + 'https://example.com//double', + '/empty?', + '/books?page=2', + '/', + ]); + + $this->assertSame(['/', '/books?page=2', '/news/', '/about', '/double', '/empty'], $this->cache->warmPaths('en')); + } + + public function test_the_pages_to_warm_may_be_given_as_anything_that_prints_as_an_address(): void + { + $this->cache->warmUsing(static fn (): array => [new class implements Stringable + { + public function __toString(): string + { + return 'https://example.com/shop?tab=1'; + } + }]); + + $this->assertSame(['/', '/shop?tab=1'], $this->cache->warmPaths('en')); + } + + public function test_the_pages_to_warm_may_come_from_a_generator(): void + { + $this->cache->warmUsing(static function (): iterable { + yield '/a'; + yield '/b'; + }); + + $this->assertSame(['/', '/a', '/b'], $this->cache->warmPaths('en')); + } + + public function test_every_module_is_asked_for_the_pages_in_the_language_and_in_the_order_it_came(): void + { + $asked = []; + $this->cache->warmUsing(static function (string $language) use (&$asked): array { + $asked[] = 'first:'.$language; + + return ['/one']; + }); + $this->cache->warmUsing(static function (string $language) use (&$asked): array { + $asked[] = 'second:'.$language; + + return ['/two']; + }); + + $this->assertSame(['/', '/one', '/two'], $this->cache->warmPaths('de')); + $this->assertSame(['first:de', 'second:de'], $asked); + } + + private function cardsWithNoCache(): RecordCache + { + config(['atrium.cache.enabled' => false]); + + return $this->cache; + } + + public function test_the_builder_is_made_once_and_made_again_when_a_module_adds_to_the_cards(): void + { + $first = $this->cache->builder(); + + $this->assertSame($first, $this->cache->builder()); + + $this->cache->extend('stars', static fn (): array => []); + + $second = $this->cache->builder(); + $this->assertNotSame($first, $second); + $this->assertSame($second, $this->cache->builder()); + + $this->cache->thumbnailsUsing(null); + + $this->assertNotSame($second, $this->cache->builder()); + } + + public function test_what_a_module_adds_shows_in_the_cards_built_after_it_was_added(): void + { + [$book] = $this->books(1); + $cache = $this->cardsWithNoCache(); + $this->assertNull($cache->cards(Book::class, [$book->id])[0]->extra('stars')); + + $cache->extend('stars', static fn (Collection $books, string $locale): array => $books->mapWithKeys(static fn (Book $book): array => [$book->getKey() => 'stars of '.$book->getKey().' in '.$locale])->all()); + $this->assertSame('stars of '.$book->id.' in en', $cache->cards(Book::class, [$book->id])[0]->extra('stars')); + + // Added again under the same name: replaced. + $cache->extend('stars', static fn (): array => [$book->id => 'replaced']); + $this->assertSame('replaced', $cache->cards(Book::class, [$book->id])[0]->extra('stars')); + + // Another name: both are there. + $cache->extend('hearts', static fn (): array => [$book->id => 'loved']); + $card = $cache->cards(Book::class, [$book->id])[0]; + $this->assertSame('replaced', $card->extra('stars')); + $this->assertSame('loved', $card->extra('hearts')); + } + + public function test_the_thumbnails_of_the_pictures_come_from_what_the_module_gave(): void + { + [$book] = $this->books(1); + $cache = $this->cardsWithNoCache(); + $this->assertSame([], $cache->cards(Book::class, [$book->id])[0]->media('cover')[0]['thumbnails']); + + $cache->thumbnailsUsing(static fn (string $path, string $url): array => ['small' => $url.'?w=100', 'path' => $path]); + $thumbnails = $cache->cards(Book::class, [$book->id])[0]->media('cover')[0]['thumbnails']; + + $this->assertSame('books/cover-1.jpg', $thumbnails['path']); + $this->assertStringEndsWith('?w=100', $thumbnails['small']); + + $cache->thumbnailsUsing(null); + $this->assertSame([], $cache->cards(Book::class, [$book->id])[0]->media('cover')[0]['thumbnails']); + } +} diff --git a/packages/admin/tests/Feature/Cache/SettingsCacheTest.php b/packages/admin/tests/Feature/Cache/SettingsCacheTest.php new file mode 100644 index 00000000..1f7781f3 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/SettingsCacheTest.php @@ -0,0 +1,193 @@ +resolving(Modules::class, static fn (Modules $modules) => $modules->add(Label::module())); + + $this->root = sys_get_temp_dir().'/atrium-settings-cache-'.uniqid(); + mkdir($this->root.'/config', 0777, true); + copy(dirname(__DIR__, 3).'/config/atrium.php', $this->root.'/config/atrium.php'); + $app->useConfigPath($this->root.'/config'); + } + + protected function tearDown(): void + { + (new Filesystem)->deleteDirectory($this->root); + + parent::tearDown(); + } + + private function settings(): Settings + { + return $this->app->make(Settings::class); + } + + /** + * What a new request starts with: the settings not yet read. + */ + private function forgetMemo(): void + { + (fn () => $this->stored = [])->call($this->settings()); + } + + /** + * What the record cache holds under a name, or the given marker. + */ + private function kept(string $key, bool $perSite = false): mixed + { + return $this->app->make(RecordCache::class)->remember(Settings::class, $key, static fn (): string => 'nothing kept', perSite: $perSite); + } + + public function test_the_settings_of_a_module_are_kept_under_its_name_for_all_sites(): void + { + $this->settings()->save('labels', ['color' => 'blue']); + $this->forgetMemo(); + + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->assertSame([0 => ['color' => 'blue']], $this->kept('settings:labels')); + } + + public function test_every_module_has_a_name_of_its_own_in_the_cache(): void + { + $this->settings()->save('labels', ['color' => 'blue']); + $this->settings()->save('banners', ['size' => 'big']); + $this->forgetMemo(); + + $this->assertSame(['size' => 'big'], $this->settings()->stored('banners')); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->assertSame([0 => ['size' => 'big']], $this->kept('settings:banners')); + $this->assertSame('nothing kept', $this->kept('settings:')); + $this->assertSame('nothing kept', $this->kept('labels')); + $this->assertSame('nothing kept', $this->kept('labelssettings:')); + } + + public function test_the_cache_holds_the_values_of_every_site_of_the_module(): void + { + DB::table(Settings::TABLE)->insert([ + ['module' => 'labels', 'site_id' => null, 'values' => '{"color":"red"}', 'created_at' => now(), 'updated_at' => now()], + ['module' => 'labels', 'site_id' => 7, 'values' => '{"color":"blue"}', 'created_at' => now(), 'updated_at' => now()], + ]); + + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels', 7)); + $this->assertSame(['color' => 'red'], $this->settings()->stored('labels')); + $this->assertSame([], $this->settings()->stored('labels', 8)); + } + + public function test_a_row_with_something_else_than_a_list_of_values_reads_as_an_array(): void + { + DB::table(Settings::TABLE)->insert(['module' => 'labels', 'site_id' => null, 'values' => '"damaged"', 'created_at' => now(), 'updated_at' => now()]); + + $this->assertIsArray($this->settings()->stored('labels')); + } + + public function test_a_row_with_nothing_in_it_reads_as_no_values(): void + { + DB::table(Settings::TABLE)->insert(['module' => 'labels', 'site_id' => null, 'values' => 'null', 'created_at' => now(), 'updated_at' => now()]); + + $this->assertSame([], $this->settings()->stored('labels')); + $this->assertSame([0 => []], $this->kept('settings:labels')); + } + + public function test_flushing_makes_the_settings_be_read_anew(): void + { + $this->settings()->save('labels', ['color' => 'blue']); + $this->forgetMemo(); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + // Changed behind the cache's back. + DB::table(Settings::TABLE)->where('module', 'labels')->update(['values' => '{"color":"red"}']); + $this->forgetMemo(); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->settings()->flush(); + + $this->assertSame(['color' => 'red'], $this->settings()->stored('labels')); + } + + public function test_flushing_forgets_what_was_read_and_what_modules_declared(): void + { + $this->settings()->save('labels', ['color' => 'blue']); + DB::table(Settings::TABLE)->where('module', 'labels')->update(['values' => '{"color":"red"}']); + + $this->settings()->flush(); + + $this->assertSame(['color' => 'red'], $this->settings()->stored('labels')); + } + + public function test_saving_makes_the_settings_show_at_once(): void + { + $this->settings()->save('labels', ['color' => 'blue']); + $this->forgetMemo(); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->settings()->save('labels', ['color' => 'red']); + $this->forgetMemo(); + + $this->assertSame(['color' => 'red'], $this->settings()->stored('labels')); + } + + public function test_removing_a_module_with_its_data_drops_its_settings_from_the_cache_too(): void + { + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-labels'])->assertSuccessful(); + $this->settings()->save('labels', ['color' => 'blue']); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->artisan('atrium:module:remove', ['package' => 'acme/atrium-labels', '--delete-data' => true])->assertSuccessful(); + + $this->assertSame([], $this->settings()->stored('labels')); + } + + public function test_the_settings_are_gone_from_the_cache_even_when_the_config_file_cannot_be_edited(): void + { + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-labels'])->assertSuccessful(); + $this->settings()->save('labels', ['color' => 'blue']); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + unlink(config_path('atrium.php')); + + $this->artisan('atrium:module:remove', ['package' => 'acme/atrium-labels', '--delete-data' => true])->assertFailed(); + + $this->assertSame(0, DB::table(Settings::TABLE)->count()); + $this->assertSame([], $this->settings()->stored('labels')); + } + + public function test_removing_a_module_and_keeping_its_data_keeps_its_settings(): void + { + $this->artisan('atrium:module:install', ['package' => 'acme/atrium-labels'])->assertSuccessful(); + $this->settings()->save('labels', ['color' => 'blue']); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + + $this->artisan('atrium:module:remove', ['package' => 'acme/atrium-labels', '--keep-data' => true])->assertSuccessful(); + + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels')); + $this->assertSame(1, DB::table(Settings::TABLE)->count()); + } +} diff --git a/packages/admin/tests/Feature/Cache/SiteAndLanguageCacheTest.php b/packages/admin/tests/Feature/Cache/SiteAndLanguageCacheTest.php new file mode 100644 index 00000000..ffbd6c21 --- /dev/null +++ b/packages/admin/tests/Feature/Cache/SiteAndLanguageCacheTest.php @@ -0,0 +1,281 @@ +app->make(Sites::class); + } + + private function languages(): ContentLanguages + { + return $this->app->make(ContentLanguages::class); + } + + private function addGerman(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + } + + private function addGermanSite(): Site + { + $this->addGerman(); + + return Site::query()->create(['code' => 'de', 'name' => 'Deutschland', 'domains' => ['example.de'], 'languages' => ['de']]); + } + + /** + * What the record cache holds under a name, or the given marker. + */ + private function kept(string|array $classes, string $key): mixed + { + return $this->app->make(RecordCache::class)->remember($classes, $key, static fn (): string => 'nothing kept', perSite: false); + } + + /** + * A request that starts afresh: nothing read yet, nothing remembered. + */ + private function forgetInRequest(): void + { + $this->app->make(RecordCache::class)->reset(); + $this->sites()->forgetCurrent(); + (new ReflectionProperty(Sites::class, 'all'))->setValue($this->sites(), null); + } + + public function test_the_sites_are_kept_for_every_site_and_come_back_as_sites(): void + { + $this->addGermanSite(); + $this->forgetInRequest(); + + $all = $this->sites()->all(); + + $this->assertSame(['main', 'de'], $all->pluck('code')->all()); + $this->assertSame(['example.de'], $all->last()->domains); + $this->assertTrue($all->last()->exists); + $kept = $this->kept(Site::class, 'sites'); + $this->assertIsArray($kept); + $this->assertSame(['main', 'de'], array_column($kept, 'code')); + } + + public function test_the_sites_are_read_from_the_cache_while_nothing_has_changed(): void + { + $this->addGermanSite(); + $this->forgetInRequest(); + $this->sites()->all(); + $this->forgetInRequest(); + + $queries = 0; + DB::listen(function () use (&$queries): void { + $queries++; + }); + + $this->sites()->all(); + + $this->assertSame(0, $queries); + } + + public function test_flushing_the_sites_reads_them_anew_from_the_database(): void + { + $this->forgetInRequest(); + $this->assertSame('main', $this->sites()->all()->first()->code); + + // Changed behind the models' back. + DB::table((new Site)->getTable())->where('code', 'main')->update(['name' => 'Renamed']); + $this->forgetInRequest(); + $this->assertNotSame('Renamed', $this->sites()->all()->first()->name); + + $this->sites()->flush(); + + $this->assertSame('Renamed', $this->sites()->all()->first()->name); + } + + public function test_the_languages_are_kept_for_every_site_and_come_back_as_languages(): void + { + $this->addGerman(); + $this->languages()->flush(); + + $codes = $this->languages()->codes(); + + $this->assertSame(['en', 'de'], $codes); + $this->assertTrue($this->languages()->all()->first()->exists); + $this->assertTrue($this->languages()->all()->first()->is_default); + $kept = $this->kept(Language::class, 'languages'); + $this->assertIsArray($kept); + $this->assertSame(['en', 'de'], array_column($kept, 'code')); + } + + public function test_flushing_the_languages_reads_them_anew_from_the_database(): void + { + $this->assertSame(['en'], $this->languages()->codes()); + + // Added behind the models' back. + DB::table((new Language)->getTable())->insert(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200, 'active' => true, 'is_default' => false, 'created_at' => now(), 'updated_at' => now()]); + $this->languages()->forgetActive(); + + // Forgotten for the request, but the cache still has what it had. + $this->assertSame(['en'], $this->languages()->codes()); + + $this->languages()->flush(); + + $this->assertSame(['en', 'de'], $this->languages()->codes()); + } + + public function test_another_site_becoming_current_picks_its_languages_from_the_kept_ones(): void + { + $german = $this->addGermanSite(); + $this->languages()->flush(); + $this->assertSame(['en', 'de'], $this->languages()->codes()); + + $this->sites()->setCurrent($german); + + $this->assertSame(['de'], $this->languages()->codes()); + + $this->sites()->forgetCurrent(); + + $this->assertSame(['en', 'de'], $this->languages()->codes()); + } + + public function test_switching_sites_does_not_flush_what_is_kept(): void + { + $german = $this->addGermanSite(); + $this->languages()->flush(); + $this->languages()->codes(); + DB::table((new Language)->getTable())->where('code', 'de')->update(['name' => 'Changed behind the back']); + + $this->sites()->setCurrent($german); + $this->sites()->forgetCurrent(); + + $this->assertSame('Deutsch', $this->languages()->find('de')->name); + } + + public function test_section_paths_are_kept_for_every_site_under_the_name_of_the_tree(): void + { + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $italy = Handbook::query()->create(['name' => 'Italy', 'code' => 'italy', 'parent_id' => $tours->id]); + + $paths = PublicUrl::sectionPaths(Handbook::class); + + $this->assertSame('tours/italy', $paths[$italy->id]); + $kept = $this->kept([Handbook::class, PublicUrl::class], 'section-paths:'.Handbook::class.'|parent_id'); + $this->assertSame($paths, $kept); + $this->assertSame('nothing kept', $this->kept([Handbook::class, PublicUrl::class], 'section-paths:')); + $this->assertSame('nothing kept', $this->kept([Handbook::class, PublicUrl::class], Handbook::class.'|parent_id')); + $this->assertSame('nothing kept', $this->kept([Handbook::class, PublicUrl::class], Handbook::class.'|parent_idsection-paths:')); + } + + public function test_section_paths_read_twice_in_a_request_ask_the_cache_once(): void + { + Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $this->app->make(RecordCache::class)->reset(); + + PublicUrl::sectionPaths(Handbook::class); + $asked = $this->app->make(RecordCache::class)->requestStats(); + PublicUrl::sectionPaths(Handbook::class); + + $this->assertSame(1, $asked['hits'] + $asked['misses']); + $this->assertSame($asked, $this->app->make(RecordCache::class)->requestStats()); + } + + public function test_section_paths_are_dropped_when_a_section_of_the_tree_is_saved(): void + { + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + $this->forgetPathsOfThisRequest(); + + // The cache holds the tree until a section of it is saved. + DB::table('articles')->where('id', $tours->id)->update(['code' => 'trips']); + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + $this->forgetPathsOfThisRequest(); + + $tours->refresh()->update(['name' => 'Trips']); + $this->app->make(RecordCache::class)->reset(); + + $this->assertSame('trips', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + } + + public function test_section_paths_stay_while_a_record_of_another_class_is_saved(): void + { + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + DB::table('articles')->where('id', $tours->id)->update(['code' => 'trips']); + + Post::query()->create(['name' => 'Elsewhere']); + $this->forgetPathsOfThisRequest(); + + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + } + + public function test_forgetting_the_paths_drops_the_kept_ones_too(): void + { + $tours = Handbook::query()->create(['name' => 'Tours', 'code' => 'tours']); + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + DB::table('articles')->where('id', $tours->id)->update(['code' => 'trips']); + $this->forgetPathsOfThisRequest(); + $this->assertSame('tours', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + + PublicUrl::forgetPaths(); + + $this->assertSame('trips', PublicUrl::sectionPaths(Handbook::class)[$tours->id]); + } + + public function test_the_sections_a_scope_hides_are_still_in_the_paths_of_their_children(): void + { + $secret = ScopedHandbook::query()->withoutGlobalScopes()->create(['name' => 'Secret', 'code' => 'secret']); + $child = ScopedHandbook::query()->withoutGlobalScopes()->create(['name' => 'Child', 'code' => 'child', 'parent_id' => $secret->id]); + + $paths = PublicUrl::sectionPaths(ScopedHandbook::class); + + $this->assertSame('secret/child', $paths[$child->id]); + $this->assertSame('secret', $paths[$secret->id]); + } + + /** + * What a new request starts with: the paths of the last one forgotten + * (the cache keeps its own). + */ + private function forgetPathsOfThisRequest(): void + { + (new ReflectionProperty(PublicUrl::class, 'pathCache'))->setValue(null, []); + $this->app->make(RecordCache::class)->reset(); + } +} diff --git a/packages/admin/tests/Feature/CacheDebugTest.php b/packages/admin/tests/Feature/CacheDebugTest.php new file mode 100644 index 00000000..ddb0da53 --- /dev/null +++ b/packages/admin/tests/Feature/CacheDebugTest.php @@ -0,0 +1,242 @@ +middleware('web')->get('/queries', function () { + DB::table('cache_books')->count(); + DB::table('cache_books')->count(); + DB::table('cache_books')->count(); + + return response('counted'); + }); + + $router->middleware('web')->get('/timed', function () { + $connection = DB::connection(); + $events = $this->app['events']; + $events->dispatch(new QueryExecuted('select 1', [], 12.5, $connection)); + $events->dispatch(new QueryExecuted('select 2', [], 7.5, $connection)); + + return response('timed'); + }); + + $router->middleware('web')->get('/quiet', fn () => response('quiet')); + $router->middleware('web')->get('/books/{id}', fn (int $id) => response(''.e((string) Book::cached($id)?->name).'')); + $router->middleware('web')->get('/two-bodies', fn () => response('')); + $router->middleware('web')->get('/upper', fn () => response('shout')); + $router->middleware('web')->get('/fragment', fn () => response('

no body here

')); + $router->middleware('web')->get('/data', fn () => response('{"html":""}', 200, ['Content-Type' => 'application/json'])); + $router->middleware('web')->get('/stream', fn () => response()->stream(function (): void { + echo 'streamed'; + }, 200, ['Content-Type' => 'text/html'])); + } + + protected function setUp(): void + { + parent::setUp(); + + // The listener is added once for the process; a new application needs its own. + (new ReflectionProperty(CacheDebug::class, 'listening'))->setValue(null, false); + Clock::$instants = []; + config(['app.debug' => true, 'atrium.cache.debug' => true]); + $this->app['env'] = 'local'; + } + + protected function tearDown(): void + { + Clock::$instants = []; + + parent::tearDown(); + } + + private function line(string $uri): string + { + return (string) $this->get($uri)->assertOk()->headers->get(CacheDebug::HEADER); + } + + /** + * @return array + */ + public static function modes(): array + { + return [ + 'local, debugging, on' => [true, true, 'local', true], + 'switched off' => [false, true, 'local', false], + 'not debugging' => [true, false, 'local', false], + 'not local' => [true, true, 'production', false], + 'nothing of it' => [false, false, 'production', false], + 'only debugging' => [false, true, 'production', false], + 'only the switch' => [true, false, 'production', false], + 'local but off and not debugging' => [false, false, 'local', false], + ]; + } + + #[DataProvider('modes')] + public function test_the_debug_line_is_only_for_local_development(bool $switch, bool $debug, string $environment, bool $expected): void + { + config(['atrium.cache.debug' => $switch, 'app.debug' => $debug]); + $this->app['env'] = $environment; + + $this->assertSame($expected, CacheDebug::enabled()); + + $response = $this->get('/quiet')->assertOk(); + + if ($expected) { + $response->assertHeader(CacheDebug::HEADER)->assertSee('data-atrium-debug', false); + } else { + $response->assertHeaderMissing(CacheDebug::HEADER)->assertDontSee('data-atrium-debug', false); + } + } + + public function test_the_switch_and_the_debug_mode_may_be_given_as_numbers(): void + { + config(['atrium.cache.debug' => 1, 'app.debug' => '1']); + + $this->assertTrue(CacheDebug::enabled()); + + config(['atrium.cache.debug' => 0]); + + $this->assertFalse(CacheDebug::enabled()); + } + + public function test_the_debug_line_is_on_by_default_in_local_debugging(): void + { + $atrium = (array) config('atrium.cache'); + unset($atrium['debug']); + config(['atrium.cache' => $atrium]); + + $this->assertTrue(CacheDebug::enabled()); + } + + public function test_the_debug_line_is_off_when_the_debug_mode_is_not_set_at_all(): void + { + $app = (array) config('app'); + unset($app['debug']); + config(['app' => $app]); + + $this->assertFalse(CacheDebug::enabled()); + } + + public function test_it_counts_the_queries_a_page_ran(): void + { + $this->assertMatchesRegularExpression('/^queries=3 \(\d+\.\d ms\); /', $this->line('/queries')); + $this->assertMatchesRegularExpression('/^queries=0 \(0\.0 ms\); /', $this->line('/quiet')); + } + + public function test_the_queries_of_one_page_are_not_counted_twice_or_into_the_next_page(): void + { + $this->line('/queries'); + $this->line('/queries'); + + $this->assertMatchesRegularExpression('/^queries=3 /', $this->line('/queries')); + $this->assertMatchesRegularExpression('/^queries=0 /', $this->line('/quiet')); + } + + public function test_it_adds_up_the_time_of_the_queries(): void + { + $this->assertMatchesRegularExpression('/^queries=2 \(20\.0 ms\); /', $this->line('/timed')); + $this->assertMatchesRegularExpression('/^queries=2 \(20\.0 ms\); /', $this->line('/timed')); + $this->assertMatchesRegularExpression('/^queries=0 \(0\.0 ms\); /', $this->line('/quiet')); + } + + public function test_it_tells_the_hits_and_misses_of_the_record_cache(): void + { + [$book] = $this->books(1); + + $this->assertMatchesRegularExpression('/; cache hits=\d+ misses=[1-9]\d*; /', $this->line('/books/'.$book->id)); + $this->assertMatchesRegularExpression('/; cache hits=[1-9]\d* misses=0; /', $this->line('/books/'.$book->id)); + } + + public function test_it_tells_the_state_of_the_page_cache_in_lower_case(): void + { + $this->assertStringContainsString('; page cache=off; ', $this->line('/quiet')); + + config(['atrium.cache.pages.enabled' => true]); + + $this->assertStringContainsString('; page cache=miss; ', $this->line('/quiet')); + $this->assertStringContainsString('; page cache=hit; ', $this->line('/quiet')); + } + + public function test_it_tells_how_long_the_page_took_in_milliseconds(): void + { + Clock::$instants = [100.0, 100.5]; + + $this->assertStringEndsWith('; 500.0 ms', $this->line('/quiet')); + + Clock::$instants = [10.0, 10.0025]; + + $this->assertStringEndsWith('; 2.5 ms', $this->line('/quiet')); + } + + public function test_the_line_is_put_into_the_page_just_before_its_end(): void + { + $response = $this->get('/quiet'); + $line = e((string) $response->headers->get(CacheDebug::HEADER)); + + $this->assertSame( + 'quiet
Atrium: '.$line.'
', + $response->getContent(), + ); + } + + public function test_the_line_goes_before_the_last_closing_tag_whatever_its_case(): void + { + $this->assertMatchesRegularExpression('#^
$#', (string) $this->get('/two-bodies')->getContent()); + $this->assertMatchesRegularExpression('#^shout
$#', (string) $this->get('/upper')->getContent()); + } + + public function test_a_page_with_no_closing_body_gets_the_header_only(): void + { + $response = $this->get('/fragment')->assertHeader(CacheDebug::HEADER); + + $this->assertSame('

no body here

', $response->getContent()); + } + + public function test_a_page_that_is_not_html_gets_the_header_only(): void + { + $response = $this->get('/data')->assertHeader(CacheDebug::HEADER); + + $this->assertSame('{"html":""}', $response->getContent()); + } + + public function test_a_streamed_page_gets_the_header_only(): void + { + $this->get('/stream')->assertHeader(CacheDebug::HEADER)->assertStreamedContent('streamed'); + } + + public function test_the_page_cache_header_stays_with_the_page(): void + { + config(['atrium.cache.pages.enabled' => true]); + + $this->get('/quiet')->assertHeader(CachePages::HEADER, 'MISS')->assertHeader(CacheDebug::HEADER); + } +} diff --git a/packages/admin/tests/Feature/CacheScreenTest.php b/packages/admin/tests/Feature/CacheScreenTest.php index 6be08056..8bb121d9 100644 --- a/packages/admin/tests/Feature/CacheScreenTest.php +++ b/packages/admin/tests/Feature/CacheScreenTest.php @@ -9,11 +9,19 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Cache\CacheStore; use Atrium\Admin\Cache\RecordCache; +use Atrium\Admin\Http\Controllers\CacheController; use Atrium\Admin\Models\AdminUser; +use Atrium\Admin\Models\Site; +use Atrium\Admin\Support\Sites; use Atrium\Admin\Tests\Fixtures\Cache\Book; +use Atrium\Admin\Tests\Fixtures\CacheScreen\Aardvark; +use Atrium\Admin\Tests\Fixtures\CacheScreen\Zebra; +use Atrium\Admin\Tests\Fixtures\Post; use Illuminate\Support\Facades\DB; use Inertia\Testing\AssertableInertia; +use PHPUnit\Framework\Attributes\DataProvider; /** * The "Cache" section of the panel: it shows how the cache works and @@ -21,6 +29,32 @@ */ class CacheScreenTest extends CacheTestCase { + protected function defineEnvironment($app): void + { + parent::defineEnvironment($app); + + // Added out of the alphabet: the screen sorts the modules by label. + $app['config']->set('atrium.resources', [Post::class, Book::class, Zebra::class, Aardvark::class]); + } + + private function remembered(string $name, int &$builds): string + { + return $this->app->make(RecordCache::class)->remember(Post::class, $name, function () use (&$builds): string { + $builds++; + + return 'value'; + }, perSite: false); + } + + private function totals(int $hits, int $misses): void + { + $repository = $this->app->make(CacheStore::class)->repository(); + $repository->put('atrium:stats:hits', $hits); + $repository->put('atrium:stats:misses', $misses); + // The panel's own request must not add to what is checked here. + config(['atrium.cache.stats' => false]); + } + public function test_a_superadmin_sees_the_hit_rate_and_the_store(): void { [$book] = $this->books(1); @@ -95,4 +129,183 @@ public function test_an_administrator_without_full_rights_cannot_open_it(): void $this->actingAs($editor, 'admin')->get('/admin/cache')->assertForbidden(); $this->actingAs($editor, 'admin')->post('/admin/cache/clear', ['scope' => 'all'])->assertForbidden(); } + + public function test_the_actions_of_the_screen_are_public(): void + { + $this->actingAs($this->admin(), 'admin')->get('/admin/cache')->assertOk(); + $this->post('/admin/cache/clear', ['scope' => 'all'])->assertRedirect(); + + $actions = $this->assertRouteActionsArePublic(); + + $this->assertArrayHasKey(CacheController::class.'::index', $actions); + $this->assertArrayHasKey(CacheController::class.'::clear', $actions); + } + + public function test_the_modules_of_the_screen_are_the_cacheable_ones_sorted_by_label(): void + { + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('modules', [ + ['key' => 'aardvarks', 'label' => 'Aardvarks'], + ['key' => 'books', 'label' => 'Books'], + ['key' => 'zebras', 'label' => 'Zebras'], + ])); + } + + public function test_the_status_tells_how_the_cache_is_set_up(): void + { + $this->totals(0, 0); + config(['atrium.cache.enabled' => 1, 'atrium.cache.pages.enabled' => 1]); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('status.enabled', true) + ->where('status.pages', true) + ->where('status.tags', true) + ->where('status.driver', 'array') + ->where('status.entries', null) + ->where('status.bytes', null)); + + config(['atrium.cache.enabled' => 0, 'atrium.cache.pages.enabled' => 0]); + + $this->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('status.enabled', false) + ->where('status.pages', false)); + } + + public function test_the_page_cache_is_off_on_the_screen_by_default(): void + { + $pages = (array) config('atrium.cache.pages'); + unset($pages['enabled']); + config(['atrium.cache.pages' => $pages]); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page->where('status.pages', false)); + } + + public function test_the_hit_rate_is_a_percentage_of_all_reads_to_one_decimal(): void + { + $this->totals(1, 2); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('status.hits', 1) + ->where('status.misses', 2) + ->where('status.rate', 33.3)); + } + + public function test_the_hit_rate_is_empty_before_the_first_read(): void + { + $this->totals(0, 0); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page->where('status.rate', null)); + } + + public function test_the_sites_of_the_screen_are_the_saved_ones(): void + { + $main = Site::query()->firstOrFail(); + $main->update(['name' => 'Main']); + $shop = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'active' => false]); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page + ->where('sites', [['id' => $main->id, 'name' => 'Main'], ['id' => $shop->id, 'name' => 'Shop']])); + } + + public function test_a_panel_with_no_saved_site_lists_none(): void + { + Site::query()->delete(); + $this->app->make(Sites::class)->flush(); + + $this->actingAs($this->admin(), 'admin')->get('/admin/cache') + ->assertInertia(fn (AssertableInertia $page) => $page->where('sites', [])); + } + + public function test_clearing_a_module_drops_only_its_cards_and_values(): void + { + [$book] = $this->books(1); + Book::cached($book->id); + $builds = 0; + $this->remembered('other', $builds); + DB::table('cache_books')->update(['price' => 7]); + + $this->actingAs($this->admin(), 'admin') + ->post('/admin/cache/clear', ['scope' => 'module', 'module' => 'books']) + ->assertRedirect('/admin/cache') + ->assertSessionHas('success'); + $this->resetRequest(); + + $this->assertSame(7, Book::cached($book->id)->price); + $this->remembered('other', $builds); + $this->assertSame(1, $builds); + } + + public function test_clearing_a_site_drops_only_that_sites_cards(): void + { + $first = Site::query()->firstOrFail(); + $second = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'active' => true]); + $sites = $this->app->make(Sites::class); + [$book] = $this->books(1); + $sites->setCurrent($first); + Book::cached($book->id); + $sites->setCurrent($second); + Book::cached($book->id); + DB::table('cache_books')->update(['price' => 7]); + + $this->actingAs($this->admin(), 'admin') + ->post('/admin/cache/clear', ['scope' => 'site', 'site' => (string) $first->id]) + ->assertRedirect('/admin/cache') + ->assertSessionHas('success'); + $this->resetRequest(); + + $sites->setCurrent($first); + $this->assertSame(7, Book::cached($book->id)->price); + $sites->setCurrent($second); + $this->assertSame(1000, Book::cached($book->id)->price); + } + + /** + * @return array,1:string}> + */ + public static function refusedClearings(): array + { + return [ + 'no scope' => [[], 'scope'], + 'an unknown scope' => [['scope' => 'everything'], 'scope'], + 'a module scope without a module' => [['scope' => 'module'], 'module'], + 'a module that does not exist' => [['scope' => 'module', 'module' => 'ghosts'], 'module'], + 'a module that is not cached' => [['scope' => 'module', 'module' => 'posts'], 'module'], + 'a site scope without a site' => [['scope' => 'site'], 'site'], + 'a site that is not a number' => [['scope' => 'site', 'site' => 'main'], 'site'], + ]; + } + + /** + * @param array $input + */ + #[DataProvider('refusedClearings')] + public function test_a_clearing_that_makes_no_sense_is_refused_and_drops_nothing(array $input, string $field): void + { + $builds = 0; + $this->remembered('kept', $builds); + + $this->actingAs($this->admin(), 'admin')->post('/admin/cache/clear', $input)->assertSessionHasErrors($field); + $this->remembered('kept', $builds); + + $this->assertSame(1, $builds); + } + + public function test_clearing_everything_drops_every_value(): void + { + $builds = 0; + $this->remembered('kept', $builds); + + $this->actingAs($this->admin(), 'admin')->post('/admin/cache/clear', ['scope' => 'all'])->assertRedirect('/admin/cache'); + $this->resetRequest(); + $this->remembered('kept', $builds); + + $this->assertSame(2, $builds); + } } diff --git a/packages/admin/tests/Feature/CacheTestCase.php b/packages/admin/tests/Feature/CacheTestCase.php index 8511797b..7b8de2d4 100644 --- a/packages/admin/tests/Feature/CacheTestCase.php +++ b/packages/admin/tests/Feature/CacheTestCase.php @@ -9,10 +9,13 @@ namespace Atrium\Admin\Tests\Feature; +use Atrium\Admin\Cache\CacheStore; use Atrium\Admin\Cache\RecordCache; +use Atrium\Admin\Cache\Versions; use Atrium\Admin\Models\Language; use Atrium\Admin\Tests\Fixtures\Cache\Book; use Atrium\Admin\Tests\Fixtures\Cache\Shelf; +use Atrium\Admin\Tests\Fixtures\Cache\SpyRepository; use Atrium\Admin\Tests\Fixtures\Cache\Tag; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; @@ -60,6 +63,21 @@ protected function defineDatabaseMigrations(): void $table->timestamps(); }); + Schema::create('cache_codes', function (Blueprint $table): void { + $table->string('code')->primary(); + }); + + Schema::create('cache_nodes', function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + }); + + Schema::create('cache_parts', function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + $table->unsignedBigInteger('parent_id')->nullable(); + }); + Schema::create('cache_book_tag', function (Blueprint $table): void { $table->foreignId('book_id'); $table->foreignId('tag_id'); @@ -106,6 +124,20 @@ protected function resetRequest(): void $this->app->make(RecordCache::class)->reset(); } + /** + * A record cache of its own on a store that writes down every call, to + * read the keys and the times to live it uses. Without tags by default: + * then a key is `atrium:` and what the cache made of it. + * + * @return array{0:RecordCache,1:SpyRepository} + */ + protected function spyCache(bool $tags = false): array + { + $repository = new SpyRepository; + + return [new RecordCache(new CacheStore($repository, $tags), new Versions($repository)), $repository]; + } + /** * @template T * diff --git a/packages/admin/tests/Feature/CacheWarmCommandTest.php b/packages/admin/tests/Feature/CacheWarmCommandTest.php new file mode 100644 index 00000000..f41c7e0f --- /dev/null +++ b/packages/admin/tests/Feature/CacheWarmCommandTest.php @@ -0,0 +1,437 @@ + every address the site was asked for, in order */ + private array $opened = []; + + /** + * @param Router $router + */ + protected function defineRoutes($router): void + { + $router->any('{path?}', function (Request $request) { + $this->opened[] = $request->getUri(); + + if (str_contains($request->path(), 'gone')) { + return response('gone', 404); + } + + if (str_contains($request->path(), 'broken')) { + throw new RuntimeException('the page is broken'); + } + + return response('ok'); + })->where('path', '.*'); + } + + protected function defineEnvironment($app): void + { + parent::defineEnvironment($app); + + $app['config']->set('atrium.resources', [Post::class, Book::class, Zebra::class]); + } + + protected function defineDatabaseMigrations(): void + { + parent::defineDatabaseMigrations(); + + foreach (['cache_screen_zebras', 'cache_screen_aardvarks'] as $name) { + Schema::create($name, function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + }); + } + } + + /** + * @param array $options + * @return array{0:int,1:string} + */ + private function warm(array $options = [], int $verbosity = BufferedOutput::VERBOSITY_NORMAL): array + { + $output = new BufferedOutput($verbosity); + $code = Artisan::call('atrium:cache:warm', $options, $output); + + return [$code, $output->fetch()]; + } + + private function site(string $code, array $attributes = []): Site + { + $site = Site::query()->create($attributes + ['code' => $code, 'name' => ucfirst($code), 'active' => true]); + $this->app->make(Sites::class)->flush(); + + return $site; + } + + public function test_it_opens_the_home_page_and_the_pages_of_the_modules_in_every_language(): void + { + $this->app->make(RecordCache::class)->warmUsing(fn (string $language): array => ['https://elsewhere.test/shop/'.$language.'?page=1', '/news/'.$language]); + + [$code, $output] = $this->warm(); + + $this->assertSame(0, $code); + $this->assertSame([ + 'http://localhost/', + 'http://localhost/shop/en?page=1', + 'http://localhost/news/en', + 'http://localhost/', + 'http://localhost/shop/de?page=1', + 'http://localhost/news/de', + ], $this->opened); + $this->assertStringContainsString('Opened 6 pages.', $output); + $this->assertStringNotContainsString('cards', $output); + } + + public function test_it_lists_the_pages_only_when_asked_to_be_verbose_or_when_one_fails(): void + { + $this->app->make(RecordCache::class)->warmUsing(fn (string $language): array => ['/gone/'.$language]); + + [, $quiet] = $this->warm(); + [, $verbose] = $this->warm([], BufferedOutput::VERBOSITY_VERBOSE); + + $this->assertStringContainsString(' 404 http://localhost/gone/en', $quiet); + $this->assertStringContainsString(' 404 http://localhost/gone/de', $quiet); + $this->assertStringNotContainsString('200', $quiet); + $this->assertStringContainsString(' 200 http://localhost/', $verbose); + $this->assertStringContainsString(' 404 http://localhost/gone/en', $verbose); + } + + public function test_a_page_that_fails_is_reported_and_the_rest_are_opened(): void + { + $this->app->make(RecordCache::class)->warmUsing(fn (string $language): array => ['/broken/'.$language, '/after/'.$language]); + + [$code, $output] = $this->warm(); + + $this->assertSame(0, $code); + $this->assertCount(6, $this->opened); + $this->assertStringContainsString(' 500 http://localhost/broken/en', $output); + $this->assertStringContainsString(' 500 http://localhost/broken/de', $output); + $this->assertStringContainsString('Opened 6 pages.', $output); + } + + public function test_a_kernel_that_throws_is_reported_and_counted_as_a_failed_page(): void + { + Exceptions::fake(); + $kernel = new class($this->app) implements Kernel + { + /** @var list */ + public array $terminated = []; + + public function __construct(private readonly Application $app) {} + + public function bootstrap(): void {} + + public function handle($request): Response + { + if (str_contains($request->getPathInfo(), 'handle')) { + throw new RuntimeException('handle failed'); + } + + return new Response('ok', str_contains($request->getPathInfo(), 'gone') ? 404 : 200); + } + + public function terminate($request, $response): void + { + $this->terminated[] = $request->getPathInfo(); + + if (str_contains($request->getPathInfo(), 'terminate')) { + throw new RuntimeException('terminate failed'); + } + } + + public function getApplication(): Application + { + return $this->app; + } + }; + $this->app->instance(Kernel::class, $kernel); + $this->app->make(RecordCache::class)->warmUsing(fn (string $language): array => ['/handle', '/terminate', '/gone']); + + [$code, $output] = $this->warm(); + + $this->assertSame(0, $code); + $this->assertStringContainsString('Opened 8 pages.', $output); + $this->assertStringContainsString(' 500 http://localhost/handle', $output); + $this->assertStringContainsString(' 500 http://localhost/terminate', $output); + $this->assertStringContainsString(' 404 http://localhost/gone', $output); + $this->assertSame(['/', '/terminate', '/gone', '/', '/terminate', '/gone'], $kernel->terminated); + Exceptions::assertReportedCount(4); + Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'handle failed'); + Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'terminate failed'); + } + + public function test_it_does_nothing_when_the_record_cache_is_off(): void + { + config(['atrium.cache.enabled' => false, 'session.driver' => 'file']); + + [$code, $output] = $this->warm(); + + $this->assertSame(0, $code); + $this->assertStringContainsString('The record cache is off (ATRIUM_CACHE_ENABLED=false): nothing to warm.', $output); + $this->assertSame([], $this->opened); + $this->assertSame('file', config('session.driver')); + } + + public function test_it_works_with_the_record_cache_on_by_default(): void + { + $cache = (array) config('atrium.cache'); + unset($cache['enabled']); + config(['atrium.cache' => $cache]); + + [, $output] = $this->warm(); + + $this->assertStringContainsString('Opened 2 pages.', $output); + } + + public function test_it_keeps_no_session_per_page(): void + { + config(['session.driver' => 'file']); + + $this->warm(); + + $this->assertSame('array', config('session.driver')); + } + + public function test_it_forgets_the_site_it_warmed_last(): void + { + $this->warm(); + + $sites = $this->app->make(Sites::class); + + $this->assertFalse($sites->isResolved()); + } + + public function test_it_opens_every_active_site_in_the_languages_of_that_site(): void + { + Site::query()->delete(); + $this->site('shop', ['domains' => ['shop.test'], 'is_default' => true, 'languages' => ['en']]); + $this->site('blog', ['domains' => ['blog.test'], 'languages' => ['en', 'de']]); + $this->site('old', ['domains' => ['old.test'], 'active' => false]); + + [, $output] = $this->warm(); + + $this->assertSame(['http://shop.test/', 'http://blog.test/', 'http://blog.test/'], $this->opened); + $this->assertStringContainsString('Opened 3 pages.', $output); + } + + public function test_it_opens_only_the_sites_it_is_told_to(): void + { + Site::query()->delete(); + $this->site('shop', ['domains' => ['shop.test'], 'is_default' => true, 'languages' => ['en']]); + $this->site('blog', ['domains' => ['blog.test'], 'languages' => ['en']]); + $this->site('docs', ['domains' => ['docs.test'], 'languages' => ['en']]); + + [, $output] = $this->warm(['--site' => ['blog']]); + + $this->assertSame(['http://blog.test/'], $this->opened); + $this->assertStringContainsString('Opened 1 pages.', $output); + + $this->opened = []; + $this->warm(['--site' => ['docs', 'shop']]); + + $this->assertSame(['http://shop.test/', 'http://docs.test/'], $this->opened); + } + + public function test_a_site_that_is_told_but_inactive_is_not_opened(): void + { + Site::query()->delete(); + $this->site('shop', ['domains' => ['shop.test'], 'is_default' => true]); + $this->site('old', ['domains' => ['old.test'], 'active' => false]); + + [, $output] = $this->warm(['--site' => ['old']]); + + $this->assertSame([], $this->opened); + $this->assertStringContainsString('Opened 0 pages.', $output); + } + + public function test_an_empty_site_option_opens_every_site(): void + { + [, $output] = $this->warm(['--site' => ['']]); + + $this->assertStringContainsString('Opened 2 pages.', $output); + } + + public function test_a_site_that_does_not_exist_opens_nothing(): void + { + [, $output] = $this->warm(['--site' => ['ghost']]); + + $this->assertSame([], $this->opened); + $this->assertStringContainsString('Opened 0 pages.', $output); + } + + /** + * @return array,2:string}> + */ + public static function whereASiteIs(): array + { + return [ + 'the domain it lists' => ['https://app.test', ['domains' => ['shop.test']], 'https://shop.test/'], + 'the first of its domains' => ['https://app.test', ['domains' => ['shop.test', 'other.test']], 'https://shop.test/'], + 'the scheme of the app' => ['http://app.test', ['domains' => ['shop.test']], 'http://shop.test/'], + 'an app address with no scheme means http' => ['app.test', ['domains' => ['shop.test']], 'http://shop.test/'], + 'its folder' => ['https://app.test', ['domains' => ['shop.test'], 'folder' => 'b2b'], 'https://shop.test/b2b/'], + 'a folder and a domain with slashes around' => ['https://app.test', ['domains' => ['shop.test/'], 'folder' => '/b2b/'], 'https://shop.test/b2b/'], + 'the app address when it has no domain' => ['https://app.test/', ['domains' => []], 'https://app.test/'], + 'the app address with a folder when it has no domain' => ['https://app.test/', ['domains' => [], 'folder' => 'b2b'], 'https://app.test/b2b/'], + 'the app address when its domain is empty' => ['https://app.test', ['domains' => ['']], 'https://app.test/'], + ]; + } + + /** + * @param array $attributes + */ + #[DataProvider('whereASiteIs')] + public function test_a_site_is_opened_where_it_lives(string $appUrl, array $attributes, string $expected): void + { + config(['app.url' => $appUrl]); + Site::query()->delete(); + $this->site('main', ['is_default' => true, 'domains' => ['main.test']]); + $this->site('shop', ['languages' => ['en'], 'domains' => ['shop.test']]); + // Written past the model, which would refuse some of these. + DB::table('admin_sites')->where('code', 'shop')->update(['domains' => json_encode($attributes['domains']), 'folder' => $attributes['folder'] ?? null]); + $this->app->make(Sites::class)->flush(); + + $this->warm(['--site' => ['shop']]); + + $this->assertSame([$expected], $this->opened); + } + + public function test_an_app_address_that_is_not_a_string_is_still_read_as_one(): void + { + config(['app.url' => 8080]); + Site::query()->delete(); + $this->site('main', ['is_default' => true, 'domains' => ['main.test']]); + $this->app->make(Sites::class)->flush(); + + $this->warm(); + + $this->assertSame(['http://main.test/', 'http://main.test/'], $this->opened); + } + + public function test_a_default_site_that_is_not_saved_yet_is_opened_at_the_address_of_the_app(): void + { + config(['app.url' => 'https://app.test/']); + Site::query()->delete(); + $this->app->make(Sites::class)->flush(); + + $this->warm(); + + $this->assertSame(['https://app.test/', 'https://app.test/'], $this->opened); + } + + public function test_it_builds_the_cards_of_every_record_when_asked_to(): void + { + $this->books(3); + DB::table('cache_screen_zebras')->insert([['name' => 'One'], ['name' => 'Two']]); + DB::table('cache_screen_aardvarks')->insert([['name' => 'Single']]); + // The modules of the panel (books, zebras, posts) and the models the theme gives addresses to. + config(['atrium.public_urls' => [ + Book::class => [], + 'Not\\A\\Class' => [], + Post::class => [], + stdClass::class => [], + Unwarmable::class => [], + Aardvark::class => [], + 5 => [], + ]]); + $queries = []; + DB::listen(function ($query) use (&$queries): void { + $queries[] = $query->sql; + }); + + [$code, $output] = $this->warm(['--records' => true]); + + $this->assertSame(0, $code); + $this->assertStringContainsString('Opened 2 pages and built 12 cards.', $output); + // Only the key of each record is read, 500 at a time. + $this->assertNotEmpty(preg_grep('/^select\s+\S*cache_books\S*\.\S*id\S*\s+from\s+\S*cache_books\S*\s.*limit 500$/', $queries)); + $this->assertNotEmpty(preg_grep('/^select\s+\S*cache_screen_zebras\S*\.\S*id\S*\s+from\s/', $queries)); + $this->assertNotEmpty(preg_grep('/^select\s+\S*cache_screen_aardvarks\S*\.\S*id\S*\s+from\s/', $queries)); + } + + public function test_the_cards_it_built_are_read_without_a_query(): void + { + [$first, $second] = $this->books(2); + + $this->warm(['--records' => true]); + $this->resetRequest(); + DB::table('cache_books')->delete(); + // A visitor's request is about the site the warmed pages were. + $this->app->make(Sites::class)->setCurrent(Site::query()->firstOrFail()); + + $this->assertSame('Book 1', Book::cached($first->id)?->name); + $this->assertNotNull(Book::cached($second->id, 'de')); + } + + public function test_it_builds_the_cards_of_each_site_in_each_of_its_languages(): void + { + Site::query()->delete(); + $this->site('shop', ['domains' => ['shop.test'], 'is_default' => true, 'languages' => ['en']]); + $this->site('blog', ['domains' => ['blog.test'], 'languages' => ['en', 'de']]); + $this->books(2); + + [, $output] = $this->warm(['--records' => true]); + + $this->assertStringContainsString('Opened 3 pages and built 6 cards.', $output); + } + + public function test_it_builds_no_cards_unless_asked_to(): void + { + $this->books(2); + $queries = []; + DB::listen(function ($query) use (&$queries): void { + $queries[] = $query->sql; + }); + + [, $output] = $this->warm(); + + $this->assertStringNotContainsString('cards', $output); + $this->assertSame([], preg_grep('/limit 500/', $queries)); + } + + public function test_it_lets_go_of_what_a_chunk_of_cards_read(): void + { + $this->books(2); + + $this->warm(['--records' => true]); + + $this->assertSame([], $this->app->make(RecordCache::class)->readNames()); + } +} diff --git a/packages/admin/tests/Feature/PageCacheRulesTest.php b/packages/admin/tests/Feature/PageCacheRulesTest.php new file mode 100644 index 00000000..273e61d8 --- /dev/null +++ b/packages/admin/tests/Feature/PageCacheRulesTest.php @@ -0,0 +1,631 @@ + how many times each route built its page */ + private array $built = []; + + /** + * @param Router $router + */ + protected function defineRoutes($router): void + { + $page = function (string $_, string $body = 'page', int $status = 200, array $headers = []): callable { + return function () use ($body, $status, $headers) { + $this->countBuild(); + + return response(''.$body.'', $status, $headers); + }; + }; + + $router->middleware('web')->get('/', $page('root', 'home')); + $router->middleware('web')->get('/page', $page('page', 'a page')); + $router->middleware('web')->get('/deep/er/page', $page('deep', 'deep')); + $router->middleware('web')->get('/missing', $page('missing', 'gone', 404)); + $router->middleware('web')->get('/moved', fn () => redirect('/page')); + $router->middleware('web')->get('/download', $page('download', 'file', 200, ['Content-Disposition' => 'attachment; filename="a.html"'])); + $router->middleware('web')->get('/nostore', $page('nostore', 'secret', 200, ['Cache-Control' => 'no-store'])); + $router->middleware('web')->get('/nocache', $page('nocache', 'secret', 200, ['X-Atrium-No-Cache' => '1'])); + $router->middleware('web')->get('/charset', $page('charset', 'text', 200, ['Content-Type' => 'text/html; charset=iso-8859-1'])); + $router->middleware('web')->get('/literal', $page('literal', 'the placeholder is '.CachePages::TOKEN)); + $router->middleware('web')->get('/public-token', function () { + return response(''.csrf_token().'', 200, ['Cache-Control' => 'public, max-age=3600']); + }); + $router->middleware('web')->get('/json', function () { + $this->countBuild(); + + return response()->json(['body' => 'text']); + }); + $router->middleware('web')->get('/own', function () { + $this->countBuild(); + app(RecordCache::class)->dontKeepPage(); + + return response('for you alone'); + }); + $router->middleware('web')->get('/queued', function () { + $this->countBuild(); + Cookie::queue('seen', '1'); + + return response('queued'); + }); + $router->middleware('web')->get('/empty', function () { + $this->countBuild(); + + return response('', 200, ['Content-Type' => 'text/html']); + }); + $router->middleware('web')->get('/stream', function () { + $this->countBuild(); + + return response()->stream(function (): void { + echo 'streamed'; + }, 200, ['Content-Type' => 'text/html']); + }); + $router->middleware('web')->get('/token', function () { + $this->countBuild(); + + return response(''); + }); + // Outside the web group: no session. + $router->middleware(CachePages::class)->get('/bare', function () { + $this->countBuild(); + + return response('no session'); + }); + foreach (['/backoffice', '/backoffice/orders', '/backofficer', '/cart', '/cart/items', '/account/orders'] as $path) { + $router->middleware('web')->get($path, function () use ($path) { + $this->countBuild(); + + return response(''.$path.''); + }); + } + } + + protected function setUp(): void + { + parent::setUp(); + + config(['atrium.cache.pages.enabled' => true]); + } + + private function countBuild(): void + { + $path = request()->getPathInfo(); + $this->built[$path] = ($this->built[$path] ?? 0) + 1; + } + + private function kept(string $uri, string $state, int $builds): void + { + $this->get($uri)->assertOk()->assertHeader(CachePages::HEADER, $state); + $this->assertSame($builds, $this->built[strtok($uri, '?')] ?? null, $uri); + } + + private function entry(string $key): mixed + { + return $this->app->make(CacheStore::class)->get('pages', $key); + } + + private function without(string $key): void + { + $parts = explode('.', $key); + $last = array_pop($parts); + $parent = implode('.', $parts); + $values = (array) config($parent); + unset($values[$last]); + config([$parent => $values]); + } + + public function test_the_page_cache_is_off_unless_it_is_turned_on(): void + { + $this->without('atrium.cache.pages.enabled'); + + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built['/page']); + } + + public function test_the_page_cache_is_off_with_the_record_cache(): void + { + config(['atrium.cache.enabled' => false]); + + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built['/page']); + } + + /** + * @return array}> + */ + public static function requestsMadeByAScript(): array + { + return [ + 'an ajax call' => [['X-Requested-With' => 'XMLHttpRequest']], + 'an Inertia visit' => [['X-Inertia' => 'true']], + 'a Livewire call' => [['X-Livewire' => 'true']], + ]; + } + + /** + * @param array $headers + */ + #[DataProvider('requestsMadeByAScript')] + public function test_a_request_made_by_a_script_is_never_kept(array $headers): void + { + $this->get('/page', $headers)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get('/page', $headers)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built['/page']); + } + + /** + * @return array + */ + public static function areasOfThePanel(): array + { + return [ + 'the prefix itself' => ['backoffice', '/backoffice'], + 'below the prefix' => ['backoffice', '/backoffice/orders'], + 'a prefix with slashes around it' => ['/backoffice/', '/backoffice/orders'], + ]; + } + + #[DataProvider('areasOfThePanel')] + public function test_the_panel_is_never_kept(string $prefix, string $uri): void + { + config(['atrium.prefix' => $prefix]); + + $this->get($uri)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get($uri)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built[$uri]); + } + + public function test_an_address_that_only_starts_like_the_panel_is_kept(): void + { + config(['atrium.prefix' => 'backoffice']); + + $this->kept('/backofficer', 'MISS', 1); + $this->kept('/backofficer', 'HIT', 1); + } + + public function test_a_panel_with_no_prefix_does_not_keep_the_site_away(): void + { + config(['atrium.prefix' => '']); + + $this->kept('/page', 'MISS', 1); + $this->kept('/page', 'HIT', 1); + $this->kept('/backoffice', 'MISS', 1); + } + + public function test_pages_matching_the_except_list_are_never_kept(): void + { + config(['atrium.cache.pages.except' => ['/cart*', 'account/*']]); + + foreach (['/cart', '/cart/items', '/account/orders'] as $uri) { + $this->get($uri)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get($uri)->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built[$uri], $uri); + } + + $this->kept('/page', 'MISS', 1); + } + + public function test_one_except_pattern_may_be_given_as_a_string(): void + { + config(['atrium.cache.pages.except' => '/cart*']); + + $this->get('/cart')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->get('/page')->assertOk()->assertHeader(CachePages::HEADER, 'MISS'); + } + + public function test_a_visitor_signed_in_to_the_site_never_gets_a_kept_page(): void + { + $this->kept('/page', 'MISS', 1); + + Auth::guard('web')->setUser(new GenericUser(['id' => 5])); + + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(2, $this->built['/page']); + } + + public function test_an_administrator_signed_in_to_another_guard_never_gets_a_kept_page(): void + { + config(['atrium.auth.guard' => 'staff', 'auth.guards.staff' => ['driver' => 'session', 'provider' => 'users']]); + $this->kept('/page', 'MISS', 1); + + // Not actingAs(): that makes the guard the default one, and the default guard is checked anyway. + Auth::guard('staff')->setUser(new GenericUser(['id' => 5])); + + $this->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + } + + public function test_a_guard_that_is_not_configured_signs_nobody_in(): void + { + config(['atrium.auth.guard' => 'ghost']); + + $this->kept('/page', 'MISS', 1); + $this->kept('/page', 'HIT', 1); + } + + /** + * @return array}> + */ + public static function sessionsWithSomethingForTheNextPage(): array + { + return [ + 'validation errors' => [['errors' => 'something is wrong']], + 'flashed messages' => [['_flash' => ['old' => ['status'], 'new' => []], 'status' => 'saved']], + 'old input' => [['_old_input' => ['name' => 'typed']]], + ]; + } + + /** + * @param array $session + */ + #[DataProvider('sessionsWithSomethingForTheNextPage')] + public function test_a_request_carrying_flashed_messages_or_old_input_is_not_kept(array $session): void + { + $this->withSession($session)->get('/page')->assertOk()->assertHeaderMissing(CachePages::HEADER); + $this->assertSame(1, $this->built['/page']); + + $this->flushSession(); + $this->get('/page')->assertOk()->assertHeader(CachePages::HEADER, 'MISS'); + } + + public function test_a_page_with_no_session_is_kept_too(): void + { + $this->kept('/bare', 'MISS', 1); + $this->kept('/bare', 'HIT', 1); + $this->get('/bare')->assertSee('no session'); + } + + /** + * @return array + */ + public static function pagesNeverKept(): array + { + return [ + 'a missing page' => ['/missing'], + 'a redirect' => ['/moved'], + 'a download' => ['/download'], + 'a page that says no-store' => ['/nostore'], + 'a page that sends X-Atrium-No-Cache' => ['/nocache'], + 'a page made for this visitor alone' => ['/own'], + 'a page that sets a cookie' => ['/queued'], + 'a page that is not HTML' => ['/json'], + 'an empty page' => ['/empty'], + 'a streamed page' => ['/stream'], + ]; + } + + #[DataProvider('pagesNeverKept')] + public function test_a_page_that_must_not_be_kept_is_built_every_time(string $uri): void + { + $first = $this->get($uri); + $second = $this->get($uri); + + $first->assertStatus($uri === '/moved' ? 302 : ($uri === '/missing' ? 404 : 200)); + $first->assertHeaderMissing(CachePages::HEADER); + $second->assertHeaderMissing(CachePages::HEADER); + // A redirect builds no page of its own, but it was not kept either. + $this->assertSame($uri === '/moved' ? null : 2, $this->built[$uri] ?? null); + } + + public function test_a_plain_page_is_kept(): void + { + $this->kept('/deep/er/page', 'MISS', 1); + $this->kept('/deep/er/page', 'HIT', 1); + } + + public function test_a_kept_page_is_named_by_site_address_and_sorted_query(): void + { + $this->get('/page?b=2&a=1')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertIsArray($this->entry('page:1:'.hash('xxh128', 'http://localhost/page?a=1&b=2'))); + $this->kept('/page?a=1&b=2', 'HIT', 1); + $this->get('/page?a=1&b=3')->assertHeader(CachePages::HEADER, 'MISS'); + } + + public function test_the_home_page_is_named_by_its_host_and_no_path(): void + { + $this->get('/')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertIsArray($this->entry('page:1:'.hash('xxh128', 'http://localhost/?'))); + } + + public function test_the_same_path_on_another_host_is_another_page(): void + { + $this->get('http://one.test/page')->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('http://two.test/page')->assertHeader(CachePages::HEADER, 'MISS'); + $this->get('http://one.test/page')->assertHeader(CachePages::HEADER, 'HIT'); + } + + public function test_a_page_is_named_by_the_site_the_request_is_in(): void + { + $site = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'domains' => ['shop.test'], 'active' => true]); + + $this->get('http://shop.test/page')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertIsArray($this->entry('page:'.$site->id.':'.hash('xxh128', 'http://shop.test/page?'))); + } + + public function test_a_request_that_no_site_claimed_names_pages_with_zero(): void + { + $this->get('/bare')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertIsArray($this->entry('page:0:'.hash('xxh128', 'http://localhost/bare?'))); + } + + public function test_a_site_not_saved_yet_names_pages_with_zero(): void + { + Site::query()->delete(); + $this->app->make(Sites::class)->flush(); + + $this->get('/page')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertIsArray($this->entry('page:0:'.hash('xxh128', 'http://localhost/page?'))); + } + + public function test_a_page_that_read_nothing_still_depends_on_the_whole_cache_and_its_site(): void + { + $builds = 0; + $middleware = $this->app->make(CachePages::class); + $handle = function () use ($middleware, &$builds) { + $this->resetRequest(); + + return $middleware->handle(Request::create('http://localhost/direct'), function () use (&$builds) { + $builds++; + + return response('direct', 200, ['Content-Type' => 'text/html']); + }); + }; + + $this->assertSame('MISS', $handle()->headers->get(CachePages::HEADER)); + $this->assertSame(['all', 'site:0'], array_keys((array) $this->entry('page:0:'.hash('xxh128', 'http://localhost/direct?'))['versions'])); + + $this->assertSame('HIT', $handle()->headers->get(CachePages::HEADER)); + + $this->app->make(RecordCache::class)->flushAll(); + + $this->assertSame('MISS', $handle()->headers->get(CachePages::HEADER)); + $this->assertSame(2, $builds); + } + + public function test_a_damaged_entry_is_not_served_and_the_page_is_built_again_quietly(): void + { + Exceptions::fake(); + $key = 'page:0:'.hash('xxh128', 'http://localhost/bare?'); + $this->app->make(CacheStore::class)->put('pages', $key, ['body' => 'damaged', 'versions' => 'damaged', 'etag' => 'x', 'time' => 1, 'type' => 'text/html', 'token' => false], 600); + + $this->get('/bare')->assertOk()->assertSee('no session')->assertDontSee('damaged')->assertHeader(CachePages::HEADER, 'MISS'); + + Exceptions::assertNothingReported(); + $this->assertIsArray($this->entry($key)['versions']); + } + + public function test_a_kept_page_carries_what_it_showed_in_its_versions(): void + { + config(['atrium.cache.pages.depends_on' => ['Zed', 'Alpha']]); + $site = Site::query()->firstOrFail(); + + $this->get('/page'); + + $versions = array_keys((array) $this->entry('page:'.$site->id.':'.hash('xxh128', 'http://localhost/page?'))['versions']); + $this->assertContains('all', $versions); + $this->assertContains('site:'.$site->id, $versions); + $this->assertContains('list:Zed', $versions); + $this->assertContains('list:Alpha', $versions); + $this->assertLessThan(array_search('list:Zed', $versions, true), array_search('list:Alpha', $versions, true)); + $this->assertLessThan(array_search('site:'.$site->id, $versions, true), array_search('list:Zed', $versions, true)); + } + + public function test_one_dependency_may_be_given_as_a_string(): void + { + config(['atrium.cache.pages.depends_on' => 'Zed']); + $site = Site::query()->firstOrFail(); + + $this->get('/page')->assertOk()->assertHeader(CachePages::HEADER, 'MISS'); + + $this->assertContains('list:Zed', array_keys((array) $this->entry('page:'.$site->id.':'.hash('xxh128', 'http://localhost/page?'))['versions'])); + } + + public function test_a_page_with_a_dependency_is_built_again_when_that_model_is_saved(): void + { + config(['atrium.cache.pages.depends_on' => [Site::class]]); + $this->kept('/page', 'MISS', 1); + $this->kept('/page', 'HIT', 1); + + Site::query()->firstOrFail()->update(['name' => 'Renamed']); + + $this->kept('/page', 'MISS', 2); + } + + public function test_a_kept_page_is_stored_for_the_time_the_config_says(): void + { + $this->freezeTime(); + config(['atrium.cache.ttl.pages' => 100]); + $this->kept('/page', 'MISS', 1); + + $this->travel(99)->seconds(); + $this->kept('/page', 'HIT', 1); + + $this->travel(1)->seconds(); + $this->kept('/page', 'MISS', 2); + } + + public function test_a_kept_page_is_stored_for_ten_minutes_by_default(): void + { + $this->without('atrium.cache.ttl.pages'); + $this->freezeTime(); + $this->kept('/page', 'MISS', 1); + + $this->travel(599)->seconds(); + $this->kept('/page', 'HIT', 1); + + $this->travel(1)->seconds(); + $this->kept('/page', 'MISS', 2); + } + + public function test_a_page_is_stored_for_at_least_a_second(): void + { + $this->freezeTime(); + config(['atrium.cache.ttl.pages' => 0]); + $this->kept('/page', 'MISS', 1); + $this->kept('/page', 'HIT', 1); + + $this->travel(1)->seconds(); + $this->kept('/page', 'MISS', 2); + } + + public function test_a_kept_page_carries_its_etag_and_the_type_it_was_built_with(): void + { + $first = $this->get('/charset')->assertHeader(CachePages::HEADER, 'MISS'); + $second = $this->get('/charset')->assertHeader(CachePages::HEADER, 'HIT'); + + $etag = '"'.sha1('text').'"'; + $this->assertSame($etag, $first->headers->get('ETag')); + $this->assertSame($etag, $second->headers->get('ETag')); + $this->assertSame('text/html; charset=iso-8859-1', $first->headers->get('Content-Type')); + $this->assertSame('text/html; charset=iso-8859-1', $second->headers->get('Content-Type')); + $second->assertSee('text'); + } + + /** + * @return array + */ + public static function matchingEtags(): array + { + return [ + 'a strong one' => ['%s'], + 'a weak one' => ['W/%s'], + 'one in a list' => ['"other", %s'], + ]; + } + + #[DataProvider('matchingEtags')] + public function test_a_matching_etag_answers_not_modified(string $template): void + { + $etag = '"'.sha1('a page').'"'; + $this->get('/page'); + + $this->get('/page', ['If-None-Match' => sprintf($template, $etag)])->assertStatus(304); + } + + public function test_another_etag_gets_the_page(): void + { + $this->get('/page'); + + $this->get('/page', ['If-None-Match' => '"something-else"'])->assertOk()->assertSee('a page'); + $this->get('/page', ['If-None-Match' => 'W/"something-else"'])->assertOk()->assertSee('a page'); + } + + public function test_a_page_without_a_token_may_be_shared_for_the_seconds_the_config_says(): void + { + config(['atrium.cache.pages.shared_max_age' => 120]); + + $this->get('/page'); + + $this->assertSame('max-age=0, public, s-maxage=120', $this->get('/page')->headers->get('Cache-Control')); + } + + public function test_a_page_is_shared_for_a_minute_by_default(): void + { + $this->without('atrium.cache.pages.shared_max_age'); + + $this->assertSame('max-age=0, public, s-maxage=60', $this->get('/page')->headers->get('Cache-Control')); + } + + public function test_a_negative_shared_time_means_not_shared(): void + { + config(['atrium.cache.pages.shared_max_age' => -5]); + + $this->assertSame('max-age=0, public, s-maxage=0', $this->get('/page')->headers->get('Cache-Control')); + } + + public function test_a_page_with_a_form_token_is_private_on_the_first_visit_and_after(): void + { + $first = $this->withSession(['_token' => 'visitor-token'])->get('/token'); + $second = $this->get('/token'); + + $this->assertSame('no-cache, private', $first->headers->get('Cache-Control')); + $this->assertSame('no-cache, private', $second->headers->get('Cache-Control')); + } + + public function test_a_page_with_a_form_token_is_private_even_when_it_asked_to_be_public(): void + { + $first = $this->withSession(['_token' => 'visitor-token'])->get('/public-token'); + $second = $this->get('/public-token'); + + $this->assertSame('no-cache, private', $first->headers->get('Cache-Control')); + $this->assertSame('no-cache, private', $second->headers->get('Cache-Control')); + } + + public function test_the_placeholder_of_the_token_is_kept_as_text_in_a_page_with_no_token(): void + { + $this->get('/literal')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->withSession(['_token' => 'someone'])->get('/literal') + ->assertHeader(CachePages::HEADER, 'HIT') + ->assertSee(CachePages::TOKEN); + } + + public function test_a_token_that_is_not_text_is_still_found_in_the_page(): void + { + $this->withSession(['_token' => 4242])->get('/token')->assertHeader(CachePages::HEADER, 'MISS'); + + $this->flushSession(); + $this->withSession(['_token' => 'second'])->get('/token') + ->assertHeader(CachePages::HEADER, 'HIT') + ->assertSee('value="second"', false) + ->assertDontSee('4242'); + } + + public function test_a_store_that_fails_costs_the_page_its_cache_not_the_visitor_his_page(): void + { + Exceptions::fake(); + $broken = new class(new ArrayStore) extends Repository + { + public function many(array $keys): array + { + throw new RuntimeException('the store is down'); + } + + public function putMany(array $values, $ttl = null): bool + { + throw new RuntimeException('the store is down'); + } + }; + $this->app->instance(CacheStore::class, new CacheStore($broken, false)); + + $this->get('/page')->assertOk()->assertSee('a page')->assertHeader(CachePages::HEADER, 'MISS'); + + Exceptions::assertReportedCount(2); + Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'the store is down'); + } +} diff --git a/packages/admin/tests/Fixtures/Cache/Chapter.php b/packages/admin/tests/Fixtures/Cache/Chapter.php new file mode 100644 index 00000000..e73ddde6 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Chapter.php @@ -0,0 +1,116 @@ + + */ + public function shelf(): BelongsTo + { + return $this->belongsTo(Shelf::class, 'shelf_id'); + } + + /** + * @return BelongsTo + */ + public function section(): BelongsTo + { + return $this->belongsTo(Shelf::class, 'section_id'); + } + + /** + * @return BelongsTo + */ + public function owner(): BelongsTo + { + return $this->belongsTo(Shelf::class, 'owner'); + } + + /** + * @return BelongsTo + */ + public function chapter(): BelongsTo + { + return $this->belongsTo(self::class, 'chapter_id'); + } + + /** + * Not a relation, though it answers like one. + */ + public function fake(): object + { + return new class + { + public function getRelated(): Shelf + { + return new Shelf; + } + }; + } + + public function broken(): BelongsTo + { + throw new RuntimeException('No such relation.'); + } + + public static function getAdminLabel(): string + { + return 'Chapters'; + } + + public static function getAdminRoutePrefix(): string + { + return 'chapters'; + } + + public static function getAdministrationFields(): array + { + return [ + TextField::make('name')->label('Name'), + BelongsToField::make('shelf_id')->label('Shelf')->model(Shelf::class), + BelongsToField::make('shelf_id')->label('Shelf again')->model(Shelf::class), + TreeSelectField::make('section_id')->label('Section'), + BelongsToField::make('owner')->label('Owner')->model(Shelf::class), + BelongsToField::make('chapter_id')->label('Chapter')->model(self::class), + BelongsToField::make('fake_id')->label('Fake')->model(Shelf::class), + BelongsToField::make('broken_id')->label('Broken')->model(Shelf::class), + BelongsToField::make('ghost_id')->label('Ghost')->model(Shelf::class), + BelongsToField::make('count_id')->label('Count')->model(Shelf::class), + ]; + } + + public static function getAdministrationListColumns(): array + { + return []; + } +} diff --git a/packages/admin/tests/Fixtures/Cache/Code.php b/packages/admin/tests/Fixtures/Cache/Code.php new file mode 100644 index 00000000..e8f8d12a --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Code.php @@ -0,0 +1,31 @@ += 50 ? [] : $this->tells; + } +} diff --git a/packages/admin/tests/Fixtures/Cache/Part.php b/packages/admin/tests/Fixtures/Cache/Part.php new file mode 100644 index 00000000..e2317bc8 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/Part.php @@ -0,0 +1,56 @@ +label('Name'), + BelongsToField::make('parent_id')->label('Parent')->model(self::class), + ]; + } + + public static function getAdministrationListColumns(): array + { + return []; + } +} diff --git a/packages/admin/tests/Fixtures/Cache/SpyRepository.php b/packages/admin/tests/Fixtures/Cache/SpyRepository.php new file mode 100644 index 00000000..bd201307 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cache/SpyRepository.php @@ -0,0 +1,138 @@ +}> */ + public array $calls = []; + + /** Say false where the array store says null or creates the key, like Memcached. */ + public bool $memcached = false; + + /** The name of a method that throws, to play a cache that is down. */ + public ?string $failing = null; + + /** A value another process writes just before every add(): it wins the race. */ + public ?int $racer = null; + + public function __construct() + { + parent::__construct(new ArrayStore); + } + + /** + * The arguments of every call of a method, in the order they were made. + * + * @return array> + */ + public function callsTo(string $method): array + { + return array_values(array_map(static fn (array $call): array => $call[1], array_filter($this->calls, static fn (array $call): bool => $call[0] === $method))); + } + + public function many(array $keys) + { + $this->note('many', [$keys]); + $values = parent::many($keys); + + if ($this->memcached) { + $values = array_map(static fn (mixed $value): mixed => $value ?? false, $values); + } + + return $values; + } + + public function get($key, $default = null): mixed + { + $this->note('get', [$key]); + + return parent::get($key, $default); + } + + public function put($key, $value, $ttl = null) + { + $this->note('put', [$key, $value, $ttl]); + + return parent::put($key, $value, $ttl); + } + + public function putMany(array $values, $ttl = null) + { + $this->note('putMany', [$values, $ttl]); + + return parent::putMany($values, $ttl); + } + + public function add($key, $value, $ttl = null) + { + $this->note('add', [$key, $value, $ttl]); + + if ($this->racer !== null) { + parent::put($key, $this->racer, 100); + } + + return parent::add($key, $value, $ttl); + } + + public function increment($key, $value = 1) + { + $this->note('increment', [$key, $value]); + + if ($this->memcached && parent::get($key) === null) { + return false; + } + + return parent::increment($key, $value); + } + + public function forever($key, $value) + { + $this->note('forever', [$key, $value]); + + return parent::forever($key, $value); + } + + public function forget($key) + { + $this->note('forget', [$key]); + + return parent::forget($key); + } + + public function tags($names) + { + $this->note('tags', [$names]); + + return parent::tags($names); + } + + /** + * @param array $arguments + */ + private function note(string $method, array $arguments): void + { + $this->calls[] = [$method, $arguments]; + + if ($this->failing === $method) { + throw new RuntimeException('The cache is down.'); + } + } +} diff --git a/packages/admin/tests/Fixtures/CacheScreen/Aardvark.php b/packages/admin/tests/Fixtures/CacheScreen/Aardvark.php new file mode 100644 index 00000000..7d3c4bd0 --- /dev/null +++ b/packages/admin/tests/Fixtures/CacheScreen/Aardvark.php @@ -0,0 +1,49 @@ +label('Name')]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } +} diff --git a/packages/admin/tests/Fixtures/CacheScreen/Zebra.php b/packages/admin/tests/Fixtures/CacheScreen/Zebra.php new file mode 100644 index 00000000..526043ec --- /dev/null +++ b/packages/admin/tests/Fixtures/CacheScreen/Zebra.php @@ -0,0 +1,49 @@ +label('Name')]; + } + + public static function getAdministrationListColumns(): array + { + return [TextColumn::make('name')->label('Name')]; + } +} diff --git a/packages/admin/tests/Fixtures/Cards/CountingImageField.php b/packages/admin/tests/Fixtures/Cards/CountingImageField.php new file mode 100644 index 00000000..924619e0 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cards/CountingImageField.php @@ -0,0 +1,28 @@ + + */ + public function getTranslatableAttributes(): array + { + return ['name']; + } +} diff --git a/packages/admin/tests/Fixtures/Cards/Item.php b/packages/admin/tests/Fixtures/Cards/Item.php new file mode 100644 index 00000000..2401ee61 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cards/Item.php @@ -0,0 +1,167 @@ + Section::class]; + + /** @var array */ + public array $translatable = ['name', 'summary']; + + /** @var array */ + private static array $relationNames = ['owner', 'tags']; + + /** @var array|null */ + private static ?array $fields = null; + + public static int $relationNameCalls = 0; + + public static int $fieldCalls = 0; + + /** + * @param array|null $relations + * @param array|null $fields + */ + public static function declare(?array $relations = null, ?array $fields = null): void + { + self::$relationNames = $relations ?? self::$relationNames; + self::$fields = $fields; + } + + public static function forget(): void + { + self::$relationNames = ['owner', 'tags']; + self::$fields = null; + self::$relationNameCalls = 0; + self::$fieldCalls = 0; + } + + /** + * @return array + */ + public function cacheRelations(): array + { + self::$relationNameCalls++; + + return self::$relationNames; + } + + /** + * @return array + */ + public static function getAdministrationFields(): array + { + self::$fieldCalls++; + + return self::$fields ?? [ + TextField::make('name'), + ImageField::make('picture'), + GalleryField::make('files'), + FileField::make('docs'), + ]; + } + + /** + * @return array + */ + protected function casts(): array + { + return ['docs' => 'array']; + } + + /** + * @return BelongsTo + */ + public function owner(): BelongsTo + { + return $this->belongsTo(Owner::class, 'owner_id'); + } + + /** + * @return BelongsTo + */ + public function halfOwner(): BelongsTo + { + return $this->belongsTo(HalfTranslated::class, 'owner_id'); + } + + /** + * @return BelongsTo + */ + public function link(): BelongsTo + { + return $this->belongsTo(self::class, 'link_id'); + } + + /** + * @return BelongsTo + */ + public function section(): BelongsTo + { + return $this->belongsTo(Section::class, 'section_id'); + } + + /** + * @return BelongsToMany + */ + public function tags(): BelongsToMany + { + return $this->belongsToMany(Label::class, 'card_item_label', 'item_id', 'label_id'); + } + + /** + * @return BelongsToMany + */ + public function related(): BelongsToMany + { + return $this->belongsToMany(self::class, 'card_item_related', 'item_id', 'related_id'); + } + + public function subject(): MorphTo + { + return $this->morphTo(); + } + + public function broken(): never + { + throw new \RuntimeException('no such relation'); + } + + public function notARelation(): string + { + return 'text'; + } +} diff --git a/packages/admin/tests/Fixtures/Cards/Label.php b/packages/admin/tests/Fixtures/Cards/Label.php new file mode 100644 index 00000000..26ebeb36 --- /dev/null +++ b/packages/admin/tests/Fixtures/Cards/Label.php @@ -0,0 +1,24 @@ + */ + public array $translatable = ['name']; +} diff --git a/packages/admin/tests/Fixtures/Cards/Section.php b/packages/admin/tests/Fixtures/Cards/Section.php new file mode 100644 index 00000000..8e3f4a7e --- /dev/null +++ b/packages/admin/tests/Fixtures/Cards/Section.php @@ -0,0 +1,24 @@ + */ + public static array $instants = []; +} + +function microtime(bool $as_float = false): string|float +{ + if ($as_float && Clock::$instants !== []) { + return array_shift(Clock::$instants); + } + + return \microtime($as_float); +} diff --git a/packages/admin/tests/Fixtures/ScopedHandbook.php b/packages/admin/tests/Fixtures/ScopedHandbook.php new file mode 100644 index 00000000..673cf8a0 --- /dev/null +++ b/packages/admin/tests/Fixtures/ScopedHandbook.php @@ -0,0 +1,24 @@ + $query->where('code', '!=', 'secret')); + } +} diff --git a/packages/admin/tests/Fixtures/Unwarmable.php b/packages/admin/tests/Fixtures/Unwarmable.php new file mode 100644 index 00000000..8e36449e --- /dev/null +++ b/packages/admin/tests/Fixtures/Unwarmable.php @@ -0,0 +1,23 @@ +store = new SpyRepository; + $this->versions = new Versions($this->store); + } + + public function test_a_missing_counter_starts_at_a_random_number_that_lives_a_month(): void + { + $read = $this->versions->get(['list:Book']); + + $this->assertSame(['list:Book'], array_keys($read)); + $this->assertMatchesRegularExpression('/^[1-9][0-9]*$/', $read['list:Book']); + $this->assertLessThanOrEqual(PHP_INT_MAX >> 1, (int) $read['list:Book']); + + $added = $this->store->callsTo('add'); + $this->assertCount(1, $added); + $this->assertSame('atrium:v:list:Book', $added[0][0]); + $this->assertSame((int) $read['list:Book'], $added[0][1]); + $this->assertSame(self::MONTH, $added[0][2]); + // What the store holds is what was handed out. + $this->assertSame($read['list:Book'], (string) $this->store->get('atrium:v:list:Book')); + } + + public function test_every_missing_counter_starts_somewhere_of_its_own(): void + { + $read = $this->versions->get(['a', 'b']); + + $this->assertNotSame($read['a'], $read['b']); + } + + public function test_a_counter_the_store_holds_is_read_as_a_string_and_not_started_again(): void + { + $this->seed('a', 17); + + $this->assertSame(['a' => '17'], $this->versions->get(['a'])); + $this->assertSame([], $this->store->callsTo('add')); + } + + public function test_a_counter_the_store_says_false_for_is_started_like_a_missing_one(): void + { + $this->store->memcached = true; + + $read = $this->versions->get(['a']); + + $this->assertMatchesRegularExpression('/^[1-9][0-9]*$/', $read['a']); + $this->assertCount(1, $this->store->callsTo('add')); + } + + public function test_a_counter_another_process_started_first_is_the_one_used(): void + { + $this->store->racer = 777; + + $this->assertSame(['a' => '777'], $this->versions->get(['a'])); + } + + public function test_names_are_read_in_one_multi_get_and_a_name_asked_twice_is_read_once(): void + { + $this->seed('a', 1); + $this->seed('b', 2); + + $this->versions->get(['a', 'b', 'a']); + + $this->assertSame([[['atrium:v:a', 'atrium:v:b']]], $this->store->callsTo('many')); + } + + public function test_what_was_read_is_kept_in_memory_and_only_new_names_go_to_the_store(): void + { + $this->seed('a', 1); + $this->seed('b', 2); + $this->versions->get(['a']); + + $this->versions->get(['a']); + $this->assertCount(1, $this->store->callsTo('many')); + + $this->versions->get(['a', 'b']); + $this->assertSame([['atrium:v:a'], ['atrium:v:b']], array_map(static fn (array $call): array => $call[0], $this->store->callsTo('many'))); + } + + public function test_only_the_names_asked_for_come_back(): void + { + $this->seed('a', 1); + $this->seed('b', 2); + $this->versions->get(['a', 'b']); + + $this->assertSame(['b' => '2'], $this->versions->get(['b'])); + $this->assertSame([], $this->versions->get([])); + } + + public function test_a_stamp_is_one_short_string_that_does_not_depend_on_the_order_of_names(): void + { + $this->seed('a', 11); + $this->seed('b', 22); + $expected = substr(hash('xxh128', 'a=11|b=22'), 0, 16); + + $this->assertSame($expected, $this->versions->stamp(['a', 'b'])); + $this->assertSame($expected, $this->versions->stamp(['b', 'a'])); + $this->assertSame(16, strlen($expected)); + } + + public function test_a_stamp_changes_with_a_version_and_with_a_name(): void + { + $this->seed('a', 11); + $this->seed('b', 11); + $this->seed('ab', 11); + $before = $this->versions->stamp(['a', 'b']); + + $this->assertNotSame($before, $this->versions->stamp(['a'])); + $this->assertNotSame($this->versions->stamp(['a']), $this->versions->stamp(['b'])); + $this->assertNotSame($this->versions->stamp(['ab']), $this->versions->stamp(['a', 'b'])); + + $this->versions->bump('a'); + + $this->assertNotSame($before, $this->versions->stamp(['a', 'b'])); + } + + public function test_bumping_a_counter_adds_one(): void + { + $this->seed('a', 40); + + $this->versions->bump('a'); + + $this->assertSame('41', (string) $this->store->get('atrium:v:a')); + $this->assertSame([['atrium:v:a', 1]], $this->store->callsTo('increment')); + $this->assertSame([], $this->store->callsTo('put')); + + $this->versions->bump('a'); + + $this->assertSame('42', (string) $this->store->get('atrium:v:a')); + } + + public function test_bumping_a_counter_that_is_at_two_leaves_it_at_three(): void + { + $this->seed('a', 2); + + $this->versions->bump('a'); + + $this->assertSame('3', (string) $this->store->get('atrium:v:a')); + } + + public function test_bumping_a_missing_counter_starts_it_at_a_random_number_that_lives_a_month(): void + { + $this->versions->bump('a'); + + $put = $this->store->callsTo('put'); + $this->assertCount(1, $put); + $this->assertSame('atrium:v:a', $put[0][0]); + $this->assertGreaterThan(1, $put[0][1]); + $this->assertLessThanOrEqual(PHP_INT_MAX >> 1, $put[0][1]); + $this->assertSame(self::MONTH, $put[0][2]); + $this->assertSame((string) $put[0][1], $this->versions->get(['a'])['a']); + } + + public function test_bumping_a_counter_the_store_cannot_increment_starts_it_too(): void + { + $this->store->memcached = true; + + $this->versions->bump('a'); + + $this->assertCount(1, $this->store->callsTo('put')); + $this->assertGreaterThan(1, (int) $this->versions->get(['a'])['a']); + } + + public function test_bumping_a_counter_that_would_start_at_one_starts_it_again_at_a_random_number(): void + { + // The array store creates a missing counter at 1: nobody ever read that. + $this->versions->bump('a'); + $this->versions->bump('b'); + + $this->assertNotSame('1', $this->versions->get(['a'])['a']); + $this->assertNotSame($this->versions->get(['a'])['a'], $this->versions->get(['b'])['b']); + } + + public function test_bumping_drops_what_was_read_and_only_that(): void + { + $this->seed('a', 40); + $this->seed('b', 50); + $this->versions->get(['a', 'b']); + $reads = count($this->store->callsTo('many')); + + $this->versions->bump('a'); + + $this->assertEquals(['a' => '41', 'b' => '50'], $this->versions->get(['a', 'b'])); + // b stayed in memory, a was read again. + $this->assertSame([['atrium:v:a']], array_map(static fn (array $call): array => $call[0], array_slice($this->store->callsTo('many'), $reads))); + } + + public function test_bumping_a_name_twice_in_one_call_counts_once(): void + { + $this->seed('a', 40); + $this->seed('b', 50); + + $this->versions->bump('a', 'a', 'b'); + + $this->assertEquals(['a' => '41', 'b' => '51'], $this->versions->get(['a', 'b'])); + $this->assertCount(2, $this->store->callsTo('increment')); + } + + public function test_resetting_makes_the_next_read_see_what_another_process_bumped(): void + { + $this->seed('a', 40); + $this->versions->get(['a']); + $this->seed('a', 99); + + $this->assertSame(['a' => '40'], $this->versions->get(['a'])); + + $this->versions->reset(); + + $this->assertSame(['a' => '99'], $this->versions->get(['a'])); + } + + private function seed(string $name, int $value): void + { + $this->store->put('atrium:v:'.$name, $value, self::MONTH); + $this->store->calls = []; + } +} From 8b2c1162681a4f74b0bcd2619bfea33de933c1be Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:38:09 +0300 Subject: [PATCH 04/10] test(cache): cached pages, questions, reviews and imports tested both ways The theme draws cached cards the same way it draws records, the FAQ list follows its categories, reviews and page trees come from the cache, and every Bitrix import drops the whole cache at the end even when it brought nothing. Linked records in the theme are kept by class, column and value. --- .../ImportsDropTheRecordCacheTest.php | 56 ++++ .../faq/tests/Feature/CachedQuestionsTest.php | 109 +++++++ packages/pages/tests/PageTreeTest.php | 56 ++++ packages/reviews/tests/CachedReviewsTest.php | 123 ++++++++ packages/theme/src/Pages.php | 19 +- packages/theme/src/RecordView.php | 10 +- packages/theme/tests/Fixtures/Parcel.php | 100 ++++++ packages/theme/tests/PagesRecordsTest.php | 140 +++++++++ packages/theme/tests/ParcelLinksTest.php | 287 ++++++++++++++++++ .../theme/tests/RecordViewFromCardTest.php | 281 +++++++++++++++++ .../theme/tests/RecordsWithoutAddressTest.php | 75 +++++ packages/theme/tests/ThemeCardTest.php | 139 +++++++++ ...2026_01_02_000000_create_parcels_table.php | 40 +++ 13 files changed, 1416 insertions(+), 19 deletions(-) create mode 100644 packages/bitrix/tests/Unit/Commands/ImportsDropTheRecordCacheTest.php create mode 100644 packages/faq/tests/Feature/CachedQuestionsTest.php create mode 100644 packages/reviews/tests/CachedReviewsTest.php create mode 100644 packages/theme/tests/Fixtures/Parcel.php create mode 100644 packages/theme/tests/PagesRecordsTest.php create mode 100644 packages/theme/tests/ParcelLinksTest.php create mode 100644 packages/theme/tests/RecordViewFromCardTest.php create mode 100644 packages/theme/tests/RecordsWithoutAddressTest.php create mode 100644 packages/theme/tests/ThemeCardTest.php create mode 100644 packages/theme/tests/database/migrations/2026_01_02_000000_create_parcels_table.php diff --git a/packages/bitrix/tests/Unit/Commands/ImportsDropTheRecordCacheTest.php b/packages/bitrix/tests/Unit/Commands/ImportsDropTheRecordCacheTest.php new file mode 100644 index 00000000..56534141 --- /dev/null +++ b/packages/bitrix/tests/Unit/Commands/ImportsDropTheRecordCacheTest.php @@ -0,0 +1,56 @@ +}> + */ + public static function commands(): array + { + return [ + 'migrate:data' => ['atrium:bitrix:migrate:data', ['--force' => true, '--no-interaction' => true]], + 'migrate:medialibrary' => ['atrium:bitrix:migrate:medialibrary', []], + 'migrate:seo' => ['atrium:bitrix:migrate:seo', ['--force' => true]], + 'migrate:sites' => ['atrium:bitrix:migrate:sites', []], + 'sync' => ['atrium:bitrix:sync', ['--force' => true]], + ]; + } + + /** + * @param array $options + */ + #[DataProvider('commands')] + public function test_a_run_drops_the_whole_record_cache_even_when_it_imports_nothing(string $command, array $options): void + { + $this->generateSchema(); + // Nothing to import: Bitrix has no rows for any of the commands. + foreach (['b_iblock_element', 'b_iblock_section', 'b_iblock_iproperty', 'b_lang', 'b_medialib_item'] as $table) { + $this->bitrix()->table($table)->delete(); + } + + $versions = app(RecordCache::class)->versions(); + $before = $versions->get(['all'])['all']; + + $this->artisan($command, $options); + + $versions->reset(); + $this->assertNotSame($before, $versions->get(['all'])['all']); + } +} diff --git a/packages/faq/tests/Feature/CachedQuestionsTest.php b/packages/faq/tests/Feature/CachedQuestionsTest.php new file mode 100644 index 00000000..5478176f --- /dev/null +++ b/packages/faq/tests/Feature/CachedQuestionsTest.php @@ -0,0 +1,109 @@ + + */ + private function asked(): array + { + app(RecordCache::class)->reset(); + + return app(Faq::class)->questions()->map(fn (Question $q): string => $q->translated('question'))->all(); + } + + /** + * How many times the list of questions was read from the table. + */ + private function listReads(Closure $callback): int + { + $reads = 0; + DB::listen(function ($query) use (&$reads): void { + if (str_contains($query->sql, 'faq_questions') && str_contains($query->sql, 'order by')) { + $reads++; + } + }); + + $callback(); + + return $reads; + } + + public function test_a_warm_list_of_questions_is_not_read_from_the_table_again(): void + { + $category = $this->category('Delivery', 'delivery'); + $this->question($category, 'How long?', '

Days.

'); + $this->asked(); + + $this->assertSame(0, $this->listReads(fn () => $this->asked())); + } + + public function test_a_saved_category_drops_the_cached_list_of_questions(): void + { + $category = $this->category('Delivery', 'delivery'); + $this->question($category, 'How long?', '

Days.

'); + $this->asked(); + + $category->update(['name' => ['en' => 'Shipping']]); + + $this->assertSame(1, $this->listReads(fn () => $this->asked())); + $this->assertSame(['How long?'], $this->asked()); + } + + public function test_a_hidden_category_takes_its_questions_off_a_warm_list(): void + { + $one = $this->category('One', 'one', ['sort' => 100]); + $two = $this->category('Two', 'two', ['sort' => 200]); + $this->question($one, 'In one', '

.

'); + $this->question($two, 'In two', '

.

'); + $this->assertSame(['In one', 'In two'], $this->asked()); + + $one->update(['active' => false]); + + $this->assertSame(['In two'], $this->asked()); + } + + public function test_a_reordered_category_moves_its_questions_on_a_warm_list(): void + { + $one = $this->category('One', 'one', ['sort' => 100]); + $two = $this->category('Two', 'two', ['sort' => 200]); + $this->question($one, 'In one', '

.

'); + $this->question($two, 'In two', '

.

'); + $this->assertSame(['In one', 'In two'], $this->asked()); + + $one->update(['sort' => 300]); + + $this->assertSame(['In two', 'In one'], $this->asked()); + } + + public function test_a_saved_question_shows_on_a_warm_list(): void + { + $category = $this->category('Delivery', 'delivery'); + $question = $this->question($category, 'How long?', '

Days.

'); + $this->assertSame(['How long?'], $this->asked()); + + $question->update(['question' => ['en' => 'How soon?']]); + + $this->assertSame(['How soon?'], $this->asked()); + } +} diff --git a/packages/pages/tests/PageTreeTest.php b/packages/pages/tests/PageTreeTest.php index b8a807fa..19e38bf5 100644 --- a/packages/pages/tests/PageTreeTest.php +++ b/packages/pages/tests/PageTreeTest.php @@ -9,6 +9,7 @@ namespace Atrium\Pages\Tests; +use Atrium\Admin\Cache\RecordCache; use Atrium\Admin\Models\Language; use Atrium\Admin\Models\Site; use Atrium\Admin\Support\Sites; @@ -18,6 +19,8 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\DB; use Illuminate\View\View; +use PHPUnit\Framework\Attributes\DataProvider; +use Spatie\Translatable\Translatable; /** * Which pages are visible and at what path, and how a page is drawn from @@ -151,6 +154,59 @@ public function test_a_page_has_an_address_only_in_the_languages_it_is_written_i $this->assertSame(url('/de/about'), $tree->url($about, 'de')); } + public function test_a_page_has_no_address_in_a_language_the_site_does_not_have_even_if_it_is_written_in_it(): void + { + $about = $this->page('about', 'About us'); + $about->setTranslation('name', 'xx', 'Unknown tongue')->save(); + $tree = app(PageTree::class); + + $this->assertNull($tree->url($about, 'xx')); + $this->assertSame(url('/about'), $tree->url($about, 'en')); + } + + /** + * @return array + */ + public static function emptyNames(): array + { + return [ + 'an empty text' => ['""'], + 'no text at all' => ['null'], + ]; + } + + #[DataProvider('emptyNames')] + public function test_a_page_with_an_empty_name_in_a_language_has_no_address_in_it_even_when_the_site_keeps_empty_translations(string $name): void + { + // A site may let the translations hold empty texts and nulls. + $this->app->instance(Translatable::class, (new Translatable)->allowEmptyStringForTranslation()->allowNullForTranslation()); + Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); + $about = $this->page('about', 'About us'); + DB::table('pages')->where('id', $about->id)->update(['name' => '{"en":"About us","de":'.$name.'}']); + app(RecordCache::class)->flushAll(); + $about = $about->fresh(); + $tree = app(PageTree::class); + + $this->assertNull($tree->url($about, 'de')); + $this->assertSame(['en' => url('/about')], $tree->urls($about)); + } + + public function test_the_tree_is_read_from_the_cache_once_for_the_whole_request(): void + { + $about = $this->page('about', 'About us'); + $team = $this->page('team', 'Our team', $about); + $tree = app(PageTree::class); + $tree->flush(); + $cache = app(RecordCache::class); + $cache->reset(); + + $tree->path($about); + $tree->path($team); + $tree->path($about); + + $this->assertSame(['hits' => 0, 'misses' => 1], $cache->requestStats()); + } + public function test_the_page_is_drawn_with_its_language_switch_breadcrumbs_and_text(): void { Language::query()->create(['code' => 'de', 'name' => 'Deutsch', 'sort' => 200]); diff --git a/packages/reviews/tests/CachedReviewsTest.php b/packages/reviews/tests/CachedReviewsTest.php new file mode 100644 index 00000000..878fbece --- /dev/null +++ b/packages/reviews/tests/CachedReviewsTest.php @@ -0,0 +1,123 @@ + + */ + private function keysWrittenBy(callable $callback): array + { + $keys = []; + Event::listen(KeyWritten::class, function (KeyWritten $event) use (&$keys): void { + $keys[] = $event->key; + }); + + $callback(); + + return $keys; + } + + /** + * @param array $attributes + */ + private function review(array $attributes = [], ?Product $about = null): Review + { + $review = new Review(['author_name' => 'Someone', 'rating' => 5, 'text' => 'Text', 'status' => ReviewStatus::Published, ...$attributes]); + + if ($about !== null) { + $review->reviewable_type = $about->getMorphClass(); + $review->reviewable_id = $about->id; + } + + $review->save(); + + return $review; + } + + public function test_the_summary_of_a_record_is_kept_under_its_type_and_id(): void + { + $phone = Product::query()->create(['name' => 'Phone', 'code' => 'phone']); + $this->review(['rating' => 4], $phone); + app(RecordCache::class)->reset(); + + $keys = $this->keysWrittenBy(fn () => app(Reviews::class)->summary($phone)); + + $expected = ':summary:'.$phone->getMorphClass().':'.$phone->id; + $this->assertCount(1, array_filter($keys, static fn (string $key): bool => str_ends_with($key, $expected)), implode("\n", $keys)); + } + + public function test_the_summary_of_the_whole_site_is_kept_under_an_empty_type_and_id_zero(): void + { + $this->review(['rating' => 4]); + app(RecordCache::class)->reset(); + + $keys = $this->keysWrittenBy(fn () => app(Reviews::class)->summary()); + + $this->assertCount(1, array_filter($keys, static fn (string $key): bool => str_ends_with($key, ':summary::0')), implode("\n", $keys)); + } + + public function test_a_warm_summary_is_read_from_the_cache_and_a_saved_review_drops_it(): void + { + $phone = Product::query()->create(['name' => 'Phone', 'code' => 'phone']); + $this->review(['rating' => 4], $phone); + $reviews = app(Reviews::class); + $cold = $reviews->summary($phone); + $this->assertSame(1, $cold['count']); + + $cache = app(RecordCache::class); + $cache->reset(); + $this->assertSame($cold, $reviews->summary($phone)); + $this->assertSame(['hits' => 1, 'misses' => 0], $cache->requestStats()); + + $this->review(['rating' => 2], $phone); + $cache->reset(); + + $summary = $reviews->summary($phone); + $this->assertSame(['hits' => 0, 'misses' => 1], $cache->requestStats()); + $this->assertSame(['count' => 2, 'average' => 3.0], array_slice($summary, 0, 2)); + } + + public function test_the_latest_reviews_are_models_newest_first(): void + { + $phone = Product::query()->create(['name' => 'Phone', 'code' => 'phone']); + $this->review(['text' => 'Old one', 'posted_at' => now()->subDays(2)], $phone); + $this->review(['text' => 'New one', 'posted_at' => now()->subDay()], $phone); + $this->review(['text' => 'Hidden', 'status' => ReviewStatus::Rejected, 'posted_at' => now()], $phone); + + $latest = app(Reviews::class)->latest($phone); + + $this->assertInstanceOf(Review::class, $latest->first()); + $this->assertSame(['New one', 'Old one'], $latest->pluck('text')->all()); + } + + public function test_a_saved_review_shows_in_the_latest_ones(): void + { + $this->review(['text' => 'First']); + $this->assertSame(['First'], app(Reviews::class)->latest()->pluck('text')->all()); + + $this->review(['text' => 'Second', 'posted_at' => now()->addMinute()]); + + $this->assertSame(['Second', 'First'], app(Reviews::class)->latest()->pluck('text')->all()); + } +} diff --git a/packages/theme/src/Pages.php b/packages/theme/src/Pages.php index 0d8c6e3c..a731aeb6 100644 --- a/packages/theme/src/Pages.php +++ b/packages/theme/src/Pages.php @@ -39,7 +39,7 @@ final class Pages /** How many records one code may match before the lenient lookup gives up. */ private const MAX_CANDIDATES = 50; - /** @var array linked records, for preloadLinks() */ + /** @var array,array>> linked records by model, column and value, for preloadLinks() */ private array $links = []; /** @var array> */ @@ -336,7 +336,7 @@ public function preloadLinks(EloquentCollection $records): void $relations = []; - foreach ((array) $class::getAdministrationFields() as $field) { + foreach ($class::getAdministrationFields() as $field) { if (! $field instanceof BelongsToField || ($class = $field->getModelClass()) === null) { continue; } @@ -352,7 +352,7 @@ public function preloadLinks(EloquentCollection $records): void $values = $records->map(fn (Model $record): mixed => $record->getAttribute($field->getColumn())) ->filter(fn (mixed $value): bool => is_scalar($value) && $value !== '') ->unique() - ->reject(fn (mixed $value): bool => array_key_exists($this->linkKey($class, $field->getValueColumn(), $value), $this->links)) + ->reject(fn (mixed $value): bool => array_key_exists($value, $this->links[$class][$field->getValueColumn()] ?? [])) ->values() ->all(); @@ -361,14 +361,14 @@ public function preloadLinks(EloquentCollection $records): void } foreach ($values as $value) { - $this->links[$this->linkKey($class, $field->getValueColumn(), $value)] = null; + $this->links[$class][$field->getValueColumn()][$value] = null; } /** @var class-string $modelClass */ $modelClass = $class; foreach ($modelClass::query()->whereIn($field->getValueColumn(), $values)->get() as $related) { - $this->links[$this->linkKey($class, $field->getValueColumn(), $related->getAttribute($field->getValueColumn()))] = $related; + $this->links[$class][$field->getValueColumn()][$related->getAttribute($field->getValueColumn())] = $related; } } @@ -385,9 +385,9 @@ public function preloadLinks(EloquentCollection $records): void */ public function linked(string $class, string $column, mixed $value): ?Model { - $key = $this->linkKey($class, $column, $value); + $links = $this->links[$class][$column] ?? []; - return array_key_exists($key, $this->links) ? $this->links[$key] : $class::query()->where($column, $value)->first(); + return array_key_exists($value, $links) ? $links[$value] : $class::query()->where($column, $value)->first(); } /** @@ -398,11 +398,6 @@ public function forgetLinks(): void $this->links = []; } - private function linkKey(string $class, string $column, mixed $value): string - { - return $class.'|'.$column.'|'.(string) $value; - } - /** * The record's page in a language, or null when it has none there: a * translated record needs its name and code in that language. diff --git a/packages/theme/src/RecordView.php b/packages/theme/src/RecordView.php index 605054fc..efa9c3fd 100644 --- a/packages/theme/src/RecordView.php +++ b/packages/theme/src/RecordView.php @@ -423,16 +423,12 @@ private function linkProperty(Field $field, mixed $value): ?array // The relation behind the field, when it is loaded (cards load it // for every record at once); a query otherwise. $relation = Str::camel(Str::beforeLast($field->getColumn(), '_id')); - $loaded = $field->getValueColumn() === 'id' && $relation !== $field->getColumn() && $this->record->relationLoaded($relation) - ? $this->record->getRelation($relation) - : false; - /** @var class-string $class */ - $related = $loaded instanceof Model || $loaded === null - ? $loaded + $related = $field->getValueColumn() === 'id' && $relation !== $field->getColumn() && $this->record->relationLoaded($relation) + ? $this->record->getRelation($relation) : $this->pages->linked($class, $field->getValueColumn(), $value); - if ($related === null) { + if (! $related instanceof Model) { return null; } diff --git a/packages/theme/tests/Fixtures/Parcel.php b/packages/theme/tests/Fixtures/Parcel.php new file mode 100644 index 00000000..6491b514 --- /dev/null +++ b/packages/theme/tests/Fixtures/Parcel.php @@ -0,0 +1,100 @@ + 'boolean']; + } + + protected function name(): Attribute + { + return Attribute::get(fn (?string $name): ?string => self::$explode && $name === 'boom' ? throw new RuntimeException('The name cannot be read.') : $name); + } + + public static function getAdminLabel(): string + { + return 'Parcels'; + } + + /** + * @return BelongsToMany + */ + public function tags(): BelongsToMany + { + return $this->belongsToMany(Brand::class, 'parcel_brand', 'parcel_id', 'brand_id'); + } + + /** + * @return BelongsTo + */ + public function brand(): BelongsTo + { + return $this->belongsTo(Brand::class, 'brand_id'); + } + + /** + * @return BelongsTo + */ + public function maker(): BelongsTo + { + return $this->belongsTo(Brand::class, 'maker_id', 'xml_id'); + } + + /** + * A relation of another kind than the form says. + * + * @return BelongsTo + */ + public function owner(): BelongsTo + { + return $this->belongsTo(Brand::class, 'owner_id'); + } + + public static function getAdministrationFields(): array + { + return [ + TextField::make('name')->label('Name'), + SlugField::make('code')->label('Code'), + BelongsToManyField::make('tags')->label('Tags')->model(Brand::class), + BelongsToField::make('brand_id')->label('Brand')->model(Brand::class), + BelongsToField::make('maker_id')->label('Maker')->model(Brand::class)->valueColumn('xml_id'), + BelongsToField::make('keeper')->label('Keeper')->model(Brand::class)->valueColumn('xml_id'), + BelongsToManyField::make('owner')->label('Owner')->model(Brand::class), + BelongsToManyField::make('parts')->label('Parts')->model(Brand::class), + ]; + } +} diff --git a/packages/theme/tests/PagesRecordsTest.php b/packages/theme/tests/PagesRecordsTest.php new file mode 100644 index 00000000..2db30f32 --- /dev/null +++ b/packages/theme/tests/PagesRecordsTest.php @@ -0,0 +1,140 @@ +app->make(Pages::class); + } + + /** + * @return array + */ + private function titles(callable $records): array + { + return array_map(fn (RecordView $view): string => $view->title(), $records()); + } + + private function queries(callable $callback): int + { + $count = 0; + DB::listen(function () use (&$count): void { + $count++; + }); + $callback(); + + return $count; + } + + public function test_the_records_of_a_cached_module_come_from_the_cache_with_no_query_once_it_is_warm(): void + { + $section = ProductSection::query()->create(['name' => 'Laptops', 'code' => 'laptops']); + Product::query()->create(['name' => 'Alpha', 'code' => 'alpha', 'section_id' => $section->id]); + Product::query()->create(['name' => 'Beta', 'code' => 'beta', 'section_id' => $section->id]); + $this->pages()->records($this->pages()->visible(Product::class)); + $query = $this->pages()->visible(Product::class); + $titles = []; + + $queries = $this->queries(function () use ($query, &$titles): void { + $titles = $this->titles(fn (): array => $this->pages()->records($query)); + }); + + $this->assertSame(['Alpha', 'Beta'], $titles); + $this->assertSame(0, $queries); + } + + public function test_the_records_of_a_cached_module_are_read_from_the_database_when_the_cache_is_off(): void + { + $section = ProductSection::query()->create(['name' => 'Laptops', 'code' => 'laptops']); + Product::query()->create(['name' => 'Alpha', 'code' => 'alpha', 'section_id' => $section->id]); + config(['atrium.cache.enabled' => false]); + $query = $this->pages()->visible(Product::class); + $titles = []; + + $queries = $this->queries(function () use ($query, &$titles): void { + $titles = $this->titles(fn (): array => $this->pages()->records($query)); + }); + + $this->assertSame(['Alpha'], $titles); + $this->assertSame(1, $queries); + } + + public function test_the_records_of_a_module_that_is_not_cached_are_read_from_the_database(): void + { + Post::query()->create(['name' => ['en' => 'Alpha'], 'code' => ['en' => 'alpha']]); + Post::query()->create(['name' => ['en' => 'Beta'], 'code' => ['en' => 'beta']]); + + $records = $this->pages()->records($this->pages()->visible(Post::class)); + + $this->assertSame(['Alpha', 'Beta'], array_map(fn (RecordView $view): string => $view->title(), $records)); + } + + public function test_one_record_of_a_module_that_is_not_cached_is_read_from_the_database(): void + { + $post = Post::query()->create(['name' => ['en' => 'Alpha'], 'code' => ['en' => 'alpha']]); + + $this->assertSame('Alpha', $this->pages()->record(Post::class, $post->id)?->title()); + $this->assertNull($this->pages()->record(Post::class, $post->id + 1)); + } + + public function test_one_record_of_a_cached_module_is_read_from_its_card(): void + { + $product = Product::query()->create(['name' => 'Alpha', 'code' => 'alpha']); + $this->pages()->record(Product::class, $product->id); + + $queries = 0; + DB::listen(function () use (&$queries): void { + $queries++; + }); + $found = $this->pages()->record(Product::class, $product->id); + + $this->assertSame('Alpha', $found?->title()); + $this->assertSame(0, $queries); + $this->assertNull($this->pages()->record(Product::class, $product->id + 1)); + } + + public function test_a_record_found_by_its_code_keeps_the_card_it_came_from_even_when_the_address_is_another(): void + { + $computers = ProductSection::query()->create(['name' => 'Computers', 'code' => 'computers']); + $phones = ProductSection::query()->create(['name' => 'Phones', 'code' => 'phones']); + $first = Product::query()->create(['name' => 'First', 'code' => 'twin', 'section_id' => $computers->id]); + $second = Product::query()->create(['name' => 'Second', 'code' => 'twin', 'section_id' => $phones->id]); + // A card that says what the record could not: whose card it is. + $this->app->make(RecordCache::class)->extend('theme', fn (Collection $models): array => $models->mapWithKeys( + fn (Model $record): array => [$record->getKey() => ['title' => 'Card of '.$record->getAttribute('name')] + (new RecordView($record, $this->pages()))->toArray()], + )->all()); + $this->app->make(RecordCache::class)->flushAll(); + PublicUrl::forgetPaths(); + + $found = $this->pages()->find('catalog', 'nowhere/twin'); + + $this->assertSame($first->id, $found?->getKey()); + $this->assertSame('Card of First', $this->pages()->page($found)->title()); + $this->assertNotSame($second->id, $found->getKey()); + } +} diff --git a/packages/theme/tests/ParcelLinksTest.php b/packages/theme/tests/ParcelLinksTest.php new file mode 100644 index 00000000..db1d783d --- /dev/null +++ b/packages/theme/tests/ParcelLinksTest.php @@ -0,0 +1,287 @@ +set('atrium.public_urls', [...(array) $app['config']->get('atrium.public_urls'), Parcel::class => ['prefix' => 'parcels']]); + } + + private function pages(): Pages + { + return $this->app->make(Pages::class); + } + + private function brand(string $name, string $xml = ''): Brand + { + return Brand::query()->create(['name' => $name, 'xml_id' => $xml ?: strtolower($name)]); + } + + /** + * @param array $attributes + */ + private function parcel(array $attributes = []): Parcel + { + return Parcel::query()->create(['name' => 'Parcel', 'code' => 'parcel-'.(Parcel::query()->count() + 1), ...$attributes]); + } + + /** + * What a callback asks of the table of brands: the values of each query. + * + * @return array> + */ + private function brandQueries(callable $callback): array + { + $queries = []; + DB::listen(function ($query) use (&$queries): void { + if (preg_match('/^select \* from [`"]brands[`"]/', $query->sql) === 1) { + $queries[] = $query->bindings; + } + }); + $callback(); + + return $queries; + } + + /** + * @param array $values + * @return array + */ + private function normal(array $values): array + { + return array_map(fn (mixed $value): int|string => is_numeric($value) ? (int) $value : (string) $value, $values); + } + + /** + * @return Collection + */ + private function batch(Model ...$records): Collection + { + return new Collection(array_values($records)); + } + + private function pageOf(Model $parcel): RecordView + { + return new RecordView($parcel, $this->pages()); + } + + // preloadLinks and linked + + public function test_a_batch_loads_the_records_it_links_to_in_one_query(): void + { + $north = $this->brand('North'); + $south = $this->brand('South'); + $parcels = $this->batch( + $this->parcel(['brand_id' => $north->id]), + $this->parcel(['brand_id' => $north->id]), + $this->parcel(['brand_id' => null]), + $this->parcel(['brand_id' => $south->id]), + $this->parcel(['brand_id' => 999_999]), + ); + + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($parcels)); + + $this->assertCount(1, $queries); + $this->assertSame([$north->id, $south->id, 999_999], $this->normal($queries[0])); + } + + public function test_what_a_batch_loaded_is_read_with_no_query(): void + { + $north = $this->brand('North'); + $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $north->id]), $this->parcel(['brand_id' => 999_999]))); + + $queries = $this->brandQueries(function () use ($north): void { + $this->assertSame($north->id, $this->pages()->linked(Brand::class, 'id', $north->id)?->getKey()); + $this->assertNull($this->pages()->linked(Brand::class, 'id', 999_999)); + }); + + $this->assertSame([], $queries); + } + + public function test_a_record_the_batch_did_not_load_is_asked_for(): void + { + $north = $this->brand('North'); + $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $this->brand('South')->id]))); + + $queries = $this->brandQueries(fn () => $this->assertSame($north->id, $this->pages()->linked(Brand::class, 'id', $north->id)?->getKey())); + + $this->assertCount(1, $queries); + } + + public function test_a_second_batch_loads_only_what_the_first_did_not(): void + { + $north = $this->brand('North'); + $south = $this->brand('South'); + $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $north->id]))); + + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($this->batch( + $this->parcel(['brand_id' => $north->id]), + $this->parcel(['brand_id' => $south->id]), + ))); + + $this->assertCount(1, $queries); + $this->assertSame([$south->id], $this->normal($queries[0])); + } + + public function test_a_batch_that_links_to_nothing_new_asks_for_nothing(): void + { + $north = $this->brand('North'); + $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $north->id]))); + + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $north->id])))); + + $this->assertSame([], $queries); + } + + public function test_a_link_by_another_column_is_loaded_by_that_column_and_only_when_filled_in(): void + { + $north = $this->brand('North', 'n-1'); + $parcels = $this->batch( + $this->parcel(['keeper' => 'n-1']), + $this->parcel(['keeper' => '']), + $this->parcel(['keeper' => null]), + $this->parcel(['keeper' => 'n-1']), + ); + + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($parcels)); + + $this->assertSame([['n-1']], $queries); + $this->assertSame($north->id, $this->pages()->linked(Brand::class, 'xml_id', 'n-1')?->getKey()); + } + + public function test_a_value_that_is_a_list_is_not_a_link(): void + { + $north = $this->brand('North'); + $gadgets = $this->batch( + Gadget::query()->create(['name' => 'Lamp', 'brand' => $north->id, 'owner' => [1, 2]]), + Gadget::query()->create(['name' => 'Fan', 'owner' => [3]]), + ); + + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($gadgets)); + + $this->assertSame([$north->id], $this->normal($queries[0])); + $this->assertCount(1, $queries); + } + + public function test_the_links_to_many_come_with_the_batch_when_the_relation_is_one_of_many(): void + { + $north = $this->brand('North'); + $first = Product::query()->create(['name' => 'First', 'code' => 'first']); + $first->related()->attach(Product::query()->create(['name' => 'Second', 'code' => 'second'])->id); + $this->parcel()->tags()->attach($north->id); + $products = $this->batch(...Product::query()->whereKey($first->id)->get()->all()); + $parcels = $this->batch(...Parcel::query()->get()->all()); + + $this->pages()->preloadLinks($products); + $this->pages()->preloadLinks($parcels); + + $this->assertTrue($products->first()?->relationLoaded('related')); + $this->assertTrue($parcels->first()?->relationLoaded('tags')); + } + + public function test_a_link_to_many_that_is_no_relation_of_that_kind_is_left_alone(): void + { + // "owner" is a belongsTo here, "maker" too, and "parts" is no relation at all. + $parcel = $this->parcel(); + $gadget = Gadget::query()->create(['name' => 'Lamp']); + + $this->pages()->preloadLinks($this->batch($parcel)); + $this->pages()->preloadLinks($this->batch($gadget)); + + $this->assertFalse($parcel->relationLoaded('owner')); + $this->assertFalse($gadget->relationLoaded('maker')); + $this->assertFalse($gadget->relationLoaded('parts')); + } + + public function test_a_batch_of_nothing_loads_nothing(): void + { + $queries = $this->brandQueries(fn () => $this->pages()->preloadLinks($this->batch())); + + $this->assertSame([], $queries); + } + + public function test_what_a_batch_loaded_is_forgotten_on_request(): void + { + $north = $this->brand('North'); + $this->pages()->preloadLinks($this->batch($this->parcel(['brand_id' => $north->id]))); + $this->pages()->forgetLinks(); + + $queries = $this->brandQueries(fn () => $this->pages()->linked(Brand::class, 'id', $north->id)); + + $this->assertCount(1, $queries); + } + + // the relation behind a link + + public function test_a_link_reads_the_relation_the_card_carries_with_no_query(): void + { + $north = $this->brand('North'); + $parcel = $this->parcel(['brand_id' => $north->id]); + $parcel->setRelation('brand', new Brand(['name' => 'Loaded', 'xml_id' => 'loaded'])); + + $queries = $this->brandQueries(fn () => $this->assertSame('Loaded', $this->pageOf($parcel)->blocks()[0]['items'][0]['value'])); + + $this->assertSame([], $queries); + } + + public function test_a_link_without_a_loaded_relation_asks_for_the_record(): void + { + $north = $this->brand('North'); + $parcel = $this->parcel(['brand_id' => $north->id]); + + $this->assertSame('North', $this->pageOf($parcel)->blocks()[0]['items'][0]['value']); + } + + public function test_a_link_by_another_column_ignores_the_relation_that_may_hold_the_wrong_record(): void + { + $this->brand('North', 'n-1'); + $parcel = $this->parcel(['maker_id' => 'n-1']); + $parcel->setRelation('maker', new Brand(['name' => 'Wrong', 'xml_id' => 'wrong'])); + + $this->assertSame('North', $this->pageOf($parcel)->blocks()[0]['items'][0]['value']); + } + + public function test_a_link_by_another_column_and_no_relation_loaded_asks_for_the_record(): void + { + $this->brand('North', 'n-1'); + $parcel = $this->parcel(['keeper' => 'n-1']); + + $this->assertSame('North', $this->pageOf($parcel)->blocks()[0]['items'][0]['value']); + } + + public function test_a_link_with_a_relation_of_the_field_name_asks_for_the_record(): void + { + $north = $this->brand('North'); + $product = Product::query()->create(['name' => 'Lamp', 'code' => 'lamp', 'brand' => $north->id]); + $product->setRelation('brand', new Brand(['name' => 'Wrong', 'xml_id' => 'wrong'])); + + $properties = array_column($this->pageOf($product)->blocks()[0]['items'], 'value', 'label'); + + $this->assertSame('North', $properties['Brand']); + } +} diff --git a/packages/theme/tests/RecordViewFromCardTest.php b/packages/theme/tests/RecordViewFromCardTest.php new file mode 100644 index 00000000..e428da26 --- /dev/null +++ b/packages/theme/tests/RecordViewFromCardTest.php @@ -0,0 +1,281 @@ +create(['name' => 'Laptops', 'code' => 'laptops']); + + return Product::query()->create(['section_id' => $section->id, 'name' => 'Gaming laptop', 'code' => 'gaming', ...$attributes])->fresh(); + } + + /** + * What the page of the record is, the way the card keeps it. + */ + private function pageOf(Product $product): RecordView + { + return new RecordView($product, $this->app->make(Pages::class)); + } + + /** + * A card of the product that carries other page data than its record + * would give: whatever is read from it was not worked out from the model. + * + * @param array|null $theme + */ + private function card(Product $product, ?array $theme): Card + { + $card = $this->app->make(RecordCache::class)->cards(Product::class, [$product->getKey()])[0]; + $extra = $theme === null ? [] : ['theme' => $theme]; + + return new Card([...$card->toArray(), 'extra' => $extra]); + } + + public function test_the_page_of_a_record_as_the_card_keeps_it(): void + { + $brand = Brand::query()->create(['name' => 'Northwind', 'xml_id' => 'nw']); + $mouse = $this->product(['name' => 'Mouse', 'code' => 'mouse']); + $product = $this->product([ + 'article' => 'A-1', 'price' => 10, 'color' => 'silver', 'brand' => $brand->id, 'orderable' => 'Y', + 'preview_picture' => '/upload/iblock/p.jpg', 'preview_text' => '

Teaser

', + 'detail_picture' => 'http://localhost/upload/iblock/d.jpg', 'detail_text' => '

Body

', 'specs' => '

Specs

', + 'photos' => json_encode(['/upload/a.jpg', 'products/b.jpg', 'https://cdn.example.com/c.jpg']), + 'manual' => '/upload/files/manual.pdf', 'active_from' => '2026-03-04 10:00:00', + ]); + $product->related()->attach($mouse->id); + + $this->assertSame([ + 'title' => 'Gaming laptop', + 'seo_title' => 'Gaming laptop', + 'seo_description' => 'Teaser', + 'seo_keywords' => null, + 'og_image' => '/upload/iblock/p.jpg', + 'url' => '/catalog/laptops/gaming', + 'path' => 'laptops/gaming', + 'urls' => ['en' => '/catalog/laptops/gaming'], + 'date' => '2026-03-04T10:00:00+00:00', + 'image' => '/upload/iblock/d.jpg', + 'thumbnail' => '/upload/iblock/p.jpg', + 'teaser' => '

Teaser

', + 'body' => '

Body

', + 'blocks' => [ + ['kind' => 'properties', 'items' => [ + ['label' => 'Article', 'value' => 'A-1', 'url' => null, 'links' => []], + ['label' => 'Price', 'value' => '10', 'url' => null, 'links' => []], + ['label' => 'Color', 'value' => 'Silver', 'url' => null, 'links' => []], + ['label' => 'Brand', 'value' => 'Northwind', 'url' => null, 'links' => []], + ['label' => 'Related', 'value' => 'Mouse', 'url' => null, 'links' => [['value' => 'Mouse', 'url' => '/catalog/laptops/mouse']]], + ]], + ['kind' => 'html', 'label' => 'Specifications', 'html' => '

Specs

'], + ['kind' => 'images', 'label' => 'Photos', 'images' => ['/upload/a.jpg', '/storage/products/b.jpg', 'https://cdn.example.com/c.jpg']], + ['kind' => 'files', 'label' => 'Manual', 'files' => [['name' => 'manual.pdf', 'url' => '/upload/files/manual.pdf']]], + ], + ], $this->pageOf($product)->toArray()); + } + + public function test_a_record_with_nothing_to_show_keeps_nothing_in_its_card(): void + { + $product = $this->product(); + + $this->assertSame([ + 'title' => 'Gaming laptop', + 'seo_title' => 'Gaming laptop', + 'seo_description' => '', + 'seo_keywords' => null, + 'og_image' => null, + 'url' => '/catalog/laptops/gaming', + 'path' => 'laptops/gaming', + 'urls' => ['en' => '/catalog/laptops/gaming'], + 'date' => null, + 'image' => null, + 'thumbnail' => null, + 'teaser' => null, + 'body' => null, + 'blocks' => [], + ], $this->pageOf($product)->toArray()); + } + + /** + * @return array + */ + public static function addresses(): array + { + return [ + 'on this host: kept without it' => ['http://localhost/upload/h.jpg', '/upload/h.jpg'], + 'the host alone: the root' => ['http://localhost', '/'], + 'another host with the same beginning' => ['http://localhost.evil.example/x.jpg', 'http://localhost.evil.example/x.jpg'], + 'another scheme' => ['https://localhost/y.jpg', 'https://localhost/y.jpg'], + 'another host' => ['https://cdn.example.com/c.jpg', 'https://cdn.example.com/c.jpg'], + 'a path' => ['/upload/p.jpg', '/upload/p.jpg'], + ]; + } + + #[DataProvider('addresses')] + public function test_an_address_on_this_host_is_kept_without_it(string $address, string $kept): void + { + $product = $this->product(['photos' => json_encode([$address]), 'detail_picture' => $address]); + + $page = $this->pageOf($product)->toArray(); + + $this->assertSame($kept, $page['image']); + $this->assertSame([$kept], $page['blocks'][0]['images']); + } + + /** + * @return array,mixed}> + */ + public static function readings(): array + { + return [ + 'the path' => ['path', ['path' => 'a/b'], 'a/b'], + 'no path' => ['path', [], null], + 'the addresses, with the host' => ['urls', ['urls' => ['en' => '/en/x', 'de' => '/de/x']], ['en' => '{root}/en/x', 'de' => '{root}/de/x']], + 'an address in no language is left out' => ['urls', ['urls' => ['en' => '/en/x', 'de' => null, 'fr' => '']], ['en' => '{root}/en/x']], + 'no addresses' => ['urls', [], []], + 'the title' => ['title', ['title' => 'From the card'], 'From the card'], + 'the SEO title' => ['seoTitle', ['seo_title' => 'SEO from the card'], 'SEO from the card'], + 'the SEO description' => ['seoDescription', ['seo_description' => 'Description from the card'], 'Description from the card'], + 'the keywords' => ['seoKeywords', ['seo_keywords' => 'a, b'], 'a, b'], + 'no keywords' => ['seoKeywords', [], null], + 'the social image, with the host' => ['ogImage', ['og_image' => '/upload/og.jpg'], '{root}/upload/og.jpg'], + 'a social image on another host' => ['ogImage', ['og_image' => 'https://cdn.example.com/og.jpg'], 'https://cdn.example.com/og.jpg'], + 'no social image' => ['ogImage', [], null], + 'the address, with the host' => ['url', ['url' => '/catalog/x'], '{root}/catalog/x'], + 'no address' => ['url', [], null], + 'the date' => ['date', ['date' => '2026-03-04T10:00:00+00:00'], '2026-03-04T10:00:00+00:00'], + 'no date' => ['date', [], null], + 'the image, with the host' => ['image', ['image' => '/upload/i.jpg'], '{root}/upload/i.jpg'], + 'no image' => ['image', [], null], + 'the thumbnail, with the host' => ['thumbnail', ['thumbnail' => '/upload/t.jpg'], '{root}/upload/t.jpg'], + 'no thumbnail' => ['thumbnail', [], null], + 'the teaser' => ['teaser', ['teaser' => '

Teaser from the card

'], '

Teaser from the card

'], + 'no teaser' => ['teaser', [], null], + 'the body' => ['body', ['body' => '

Body from the card

'], '

Body from the card

'], + 'no body' => ['body', [], null], + 'no blocks' => ['blocks', [], []], + ]; + } + + /** + * @param array $data + */ + #[DataProvider('readings')] + public function test_the_page_is_read_from_the_card_and_not_worked_out_from_the_record(string $method, array $data, mixed $expected): void + { + // A record that would answer every one of them differently. + $product = $this->product([ + 'name' => 'Record name', 'code' => 'record', 'preview_picture' => '/upload/record-preview.jpg', 'detail_picture' => '/upload/record-detail.jpg', + 'preview_text' => '

Record teaser

', 'detail_text' => '

Record body

', 'active_from' => '2020-01-01 00:00:00', 'photos' => json_encode(['/upload/record.jpg']), + ]); + $view = new RecordView($product, $this->app->make(Pages::class), $data); + + $queries = 0; + DB::listen(function () use (&$queries): void { + $queries++; + }); + $value = $view->{$method}(); + + $this->assertSame($this->plain($expected), $this->plain($value)); + $this->assertSame(0, $queries); + } + + /** + * Dates and texts as plain values, the root of the site put in. + */ + private function plain(mixed $value): mixed + { + return match (true) { + $value instanceof Carbon => $value->toIso8601String(), + $value instanceof HtmlString => $value->toHtml(), + is_array($value) => array_map($this->plain(...), $value), + is_string($value) => str_replace('{root}', $this->root(), $value), + default => $value, + }; + } + + public function test_the_date_of_the_card_speaks_the_language_of_the_page(): void + { + app()->setLocale('de'); + $view = new RecordView($this->product(), $this->app->make(Pages::class), ['date' => '2026-03-04T10:00:00+00:00']); + + $this->assertSame('de', $view->date()?->locale); + } + + public function test_the_blocks_come_back_with_their_texts_and_addresses_on_this_host(): void + { + $view = new RecordView($this->product(), $this->app->make(Pages::class), ['blocks' => [ + ['kind' => 'properties', 'items' => [ + ['label' => 'Related', 'value' => 'Mouse', 'url' => null, 'links' => [['value' => 'Mouse', 'url' => '/catalog/mouse'], ['value' => 'Cat', 'url' => null]]], + ['label' => 'Brand', 'value' => 'Northwind', 'url' => '/brands/northwind'], + ['label' => 'Color', 'value' => 'Silver'], + ]], + ['kind' => 'html', 'label' => 'Specifications', 'html' => '

Specs

'], + ['kind' => 'images', 'label' => 'Photos', 'images' => ['/upload/a.jpg', 'https://cdn.example.com/c.jpg']], + ['kind' => 'files', 'label' => 'Manual', 'files' => [['name' => 'manual.pdf', 'url' => '/upload/manual.pdf']]], + ]]); + + $blocks = $view->blocks(); + + $this->assertEquals([ + ['kind' => 'properties', 'items' => [ + ['label' => 'Related', 'value' => 'Mouse', 'url' => null, 'links' => [['value' => 'Mouse', 'url' => $this->root().'/catalog/mouse'], ['value' => 'Cat', 'url' => null]]], + ['label' => 'Brand', 'value' => 'Northwind', 'url' => $this->root().'/brands/northwind', 'links' => []], + ['label' => 'Color', 'value' => 'Silver', 'url' => null, 'links' => []], + ]], + ['kind' => 'html', 'label' => 'Specifications', 'html' => new HtmlString('

Specs

')], + ['kind' => 'images', 'label' => 'Photos', 'images' => [$this->root().'/upload/a.jpg', 'https://cdn.example.com/c.jpg']], + ['kind' => 'files', 'label' => 'Manual', 'files' => [['name' => 'manual.pdf', 'url' => $this->root().'/upload/manual.pdf']]], + ], $blocks); + $this->assertInstanceOf(HtmlString::class, $blocks[1]['html']); + } + + public function test_a_card_with_a_page_gives_that_page_and_a_card_without_one_gives_the_page_of_its_record(): void + { + $product = $this->product(); + $pages = $this->app->make(Pages::class); + + $withPage = RecordView::fromCard($this->card($product, ['title' => 'From the card', 'url' => '/catalog/from-the-card']), $pages); + $without = RecordView::fromCard($this->card($product, null), $pages); + + $this->assertSame('From the card', $withPage->title()); + $this->assertSame($this->root().'/catalog/from-the-card', $withPage->url()); + $this->assertSame('Gaming laptop', $without->title()); + $this->assertSame($this->root().'/catalog/laptops/gaming', $without->url()); + $this->assertSame($product->getKey(), $withPage->record->getKey()); + } + + public function test_a_card_built_by_the_cache_carries_the_page_of_its_record(): void + { + $product = $this->product(['preview_text' => '

Teaser

']); + + $card = $this->app->make(RecordCache::class)->cards(Product::class, [$product->getKey()])[0]; + + $this->assertSame($this->pageOf($product)->toArray(), $card->extra('theme')); + } +} diff --git a/packages/theme/tests/RecordsWithoutAddressTest.php b/packages/theme/tests/RecordsWithoutAddressTest.php new file mode 100644 index 00000000..b7b97e56 --- /dev/null +++ b/packages/theme/tests/RecordsWithoutAddressTest.php @@ -0,0 +1,75 @@ + $views + * @return array + */ + private function titles(array $views): array + { + return array_map(fn (RecordView $view): string => $view->title(), $views); + } + + public function test_the_home_page_leaves_out_a_record_with_no_name_in_the_language(): void + { + Post::query()->create(['name' => ['en' => ''], 'code' => ['en' => 'blank']]); + Post::query()->create(['name' => ['en' => 'Alpha'], 'code' => ['en' => 'alpha']]); + Post::query()->create(['name' => ['en' => 'Beta'], 'code' => ['en' => 'beta']]); + + $modules = $this->get('/')->assertOk()->viewData('modules'); + $posts = collect($modules)->firstWhere('label', 'Posts'); + + $this->assertSame([0 => 'Alpha', 1 => 'Beta'], $this->titles($posts['records'])); + } + + public function test_the_home_page_shows_a_record_that_has_a_page(): void + { + Post::query()->create(['name' => ['en' => 'Alpha'], 'code' => ['en' => 'alpha']]); + + $modules = $this->get('/')->assertOk()->viewData('modules'); + + $this->assertSame([0 => 'Alpha'], $this->titles(collect($modules)->firstWhere('label', 'Posts')['records'])); + } + + public function test_the_list_leaves_out_a_section_with_no_code(): void + { + ProductSection::query()->create(['name' => 'Nameless', 'code' => '']); + ProductSection::query()->create(['name' => 'Computers', 'code' => 'computers']); + ProductSection::query()->create(['name' => 'Phones', 'code' => 'phones']); + + $sections = $this->get('/catalog')->assertOk()->viewData('sections'); + + $this->assertSame([0 => 'Computers', 1 => 'Phones'], $this->titles($sections)); + } + + public function test_a_section_leaves_out_a_child_with_no_code(): void + { + $computers = ProductSection::query()->create(['name' => 'Computers', 'code' => 'computers']); + ProductSection::query()->create(['name' => 'Nameless', 'code' => '', 'parent_id' => $computers->id]); + ProductSection::query()->create(['name' => 'Laptops', 'code' => 'laptops', 'parent_id' => $computers->id]); + ProductSection::query()->create(['name' => 'Desktops', 'code' => 'desktops', 'parent_id' => $computers->id]); + + $sections = $this->get('/catalog/computers')->assertOk()->viewData('sections'); + + $this->assertSame([0 => 'Laptops', 1 => 'Desktops'], $this->titles($sections)); + } +} diff --git a/packages/theme/tests/ThemeCardTest.php b/packages/theme/tests/ThemeCardTest.php new file mode 100644 index 00000000..bbcd526e --- /dev/null +++ b/packages/theme/tests/ThemeCardTest.php @@ -0,0 +1,139 @@ +set('atrium.public_urls', [...(array) $app['config']->get('atrium.public_urls'), Parcel::class => ['prefix' => 'parcels']]); + } + + protected function tearDown(): void + { + Parcel::$explode = false; + + parent::tearDown(); + } + + private function cache(): RecordCache + { + return $this->app->make(RecordCache::class); + } + + /** + * @param array $attributes + */ + private function parcel(string $name, array $attributes = []): Parcel + { + return Parcel::query()->create(['name' => $name, 'code' => strtolower($name), ...$attributes]); + } + + public function test_every_card_of_a_batch_carries_the_page_of_its_record(): void + { + $ids = array_map(fn (string $name): int => $this->parcel($name)->id, ['Alpha', 'Beta', 'Gamma']); + + $titles = array_map(fn ($card): mixed => $card->extra('theme')['title'] ?? null, $this->cache()->cards(Parcel::class, $ids)); + + $this->assertSame(['Alpha', 'Beta', 'Gamma'], $titles); + } + + public function test_a_module_with_no_pages_has_no_page_in_its_cards(): void + { + $brand = Brand::query()->create(['name' => 'North', 'xml_id' => 'north']); + + $card = $this->cache()->cards(Brand::class, [$brand->id])[0]; + + $this->assertNull($card->extra('theme')); + } + + public function test_a_module_whose_pages_have_no_prefix_has_no_page_in_its_cards(): void + { + config(['atrium.public_urls' => [...(array) config('atrium.public_urls'), Brand::class => ['prefix' => '']]]); + PublicUrl::forgetPaths(); + $brand = Brand::query()->create(['name' => 'North', 'xml_id' => 'north']); + + $card = $this->cache()->cards(Brand::class, [$brand->id])[0]; + + $this->assertNull($card->extra('theme')); + } + + public function test_the_links_of_a_batch_are_loaded_for_all_its_cards_and_forgotten_after(): void + { + $north = Brand::query()->create(['name' => 'North', 'xml_id' => 'north']); + $ids = array_map(fn (string $name): int => $this->parcel($name, ['brand_id' => $north->id])->id, ['Alpha', 'Beta', 'Gamma']); + $queries = 0; + DB::listen(function ($query) use (&$queries): void { + $queries += preg_match('/^select \* from [`"]brands[`"]/', $query->sql); + }); + + $cards = $this->cache()->cards(Parcel::class, $ids); + + // One for the links of the batch, one for the relation: not one a record. + $this->assertLessThanOrEqual(2, $queries); + $this->assertSame('North', $cards[2]->extra('theme')['blocks'][0]['items'][0]['value']); + $this->pagesAsk($north); + } + + public function test_the_links_of_a_batch_are_forgotten_even_when_a_record_cannot_be_drawn(): void + { + $north = Brand::query()->create(['name' => 'North', 'xml_id' => 'north']); + $ids = [$this->parcel('Alpha', ['brand_id' => $north->id])->id, $this->parcel('boom', ['brand_id' => $north->id])->id]; + $this->cache()->builder()->relationsOf(Parcel::class); + Parcel::$explode = true; + + $cards = $this->cache()->cards(Parcel::class, $ids); + + $this->assertCount(2, $cards); + $this->assertNull($cards[0]->extra('theme')); + $this->pagesAsk($north); + } + + /** + * The brand is asked for: nothing of the batch is left in the way. + */ + private function pagesAsk(Brand $brand): void + { + $queries = 0; + DB::listen(function ($query) use (&$queries): void { + $queries += preg_match('/^select \* from [`"]brands[`"]/', $query->sql); + }); + + $this->assertSame($brand->id, $this->app->make(Pages::class)->linked(Brand::class, 'id', $brand->id)?->getKey()); + $this->assertSame(1, $queries); + } + + public function test_the_warm_up_opens_the_home_page_and_the_first_page_of_every_list_in_each_language(): void + { + Language::query()->create(['code' => 'de', 'name' => 'Deutsch']); + $this->app->make(ContentLanguages::class)->flush(); + $pages = $this->app->make(Pages::class); + + $this->assertSame(['/', '/catalog', '/parcels', '/posts'], $this->cache()->warmPaths('en')); + $this->assertSame(['/', '/de', '/de/catalog', '/de/parcels', '/de/posts'], $this->cache()->warmPaths('de')); + $this->assertSame(['catalog', 'parcels', 'posts'], $pages->prefixes()); + } +} diff --git a/packages/theme/tests/database/migrations/2026_01_02_000000_create_parcels_table.php b/packages/theme/tests/database/migrations/2026_01_02_000000_create_parcels_table.php new file mode 100644 index 00000000..1b19bdc7 --- /dev/null +++ b/packages/theme/tests/database/migrations/2026_01_02_000000_create_parcels_table.php @@ -0,0 +1,40 @@ +id(); + $table->string('name')->nullable(); + $table->string('code')->nullable(); + $table->boolean('active')->default(true); + $table->integer('sort')->default(500); + $table->unsignedBigInteger('brand_id')->nullable(); + $table->string('maker_id')->nullable(); + $table->string('keeper')->nullable(); + $table->unsignedBigInteger('owner_id')->nullable(); + $table->timestamps(); + }); + + Schema::create('parcel_brand', function (Blueprint $table): void { + $table->id(); + $table->foreignId('parcel_id'); + $table->foreignId('brand_id'); + }); + } +}; From a611be74c54484f0cd87ff115bb05c297beb41b3 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:31:53 +0300 Subject: [PATCH 05/10] fix(cache): boot writes nothing to the cache, tests run on MySQL and PostgreSQL Wiring a module in at boot called PublicUrl::forgetPaths(), which now bumps a version in the cache store: on a fresh install with the database store, artisan and migrate died before the cache table existed, and every request wrote to the cache. Wiring, page saves and the theme's save listener forget only the paths of the request (PublicUrl::forgetMemo()); a saved section drops the kept tree by itself. The debug line lets clicks through to the page under it. The cache fixture tables live in a test migration, so persistent databases do not meet them twice, and two theme tests no longer depend on the quoting and decimals of SQLite. --- .ci/coverage/admin | 2 +- .../admin/src/Http/Middleware/CacheDebug.php | 2 +- packages/admin/src/Modules/Modules.php | 2 +- packages/admin/src/Support/PublicUrl.php | 15 ++- .../tests/Feature/Cache/CacheStoreTest.php | 2 + .../tests/Feature/Cache/CardBuilderTest.php | 49 -------- .../tests/Feature/Cache/PublicUrlMemoTest.php | 81 +++++++++++++ .../admin/tests/Feature/CacheDebugTest.php | 2 +- .../admin/tests/Feature/CacheTestCase.php | 50 -------- .../tests/Feature/CacheWarmCommandTest.php | 14 --- ..._01_000001_create_cache_fixture_tables.php | 114 ++++++++++++++++++ packages/pages/src/Models/Page.php | 2 +- packages/theme/src/ThemeServiceProvider.php | 2 +- .../theme/tests/ControllerInternalsTest.php | 14 ++- .../theme/tests/RecordViewFromCardTest.php | 4 +- 15 files changed, 232 insertions(+), 123 deletions(-) create mode 100644 packages/admin/tests/Feature/Cache/PublicUrlMemoTest.php create mode 100644 packages/admin/tests/database/migrations/2026_01_01_000001_create_cache_fixture_tables.php diff --git a/.ci/coverage/admin b/.ci/coverage/admin index ba526327..620c7091 100644 --- a/.ci/coverage/admin +++ b/.ci/coverage/admin @@ -1 +1 @@ -99.87% of lines, 7 not covered +99.88% of lines, 7 not covered diff --git a/packages/admin/src/Http/Middleware/CacheDebug.php b/packages/admin/src/Http/Middleware/CacheDebug.php index f648bac3..e5690bdd 100644 --- a/packages/admin/src/Http/Middleware/CacheDebug.php +++ b/packages/admin/src/Http/Middleware/CacheDebug.php @@ -64,7 +64,7 @@ public function handle(Request $request, Closure $next): Response $content = $response->getContent(); if (is_string($content) && str_contains((string) $response->headers->get('Content-Type'), 'text/html') && ($at = strripos($content, '')) !== false) { - $bar = '
Atrium: '.e($line).'
'; + $bar = '
Atrium: '.e($line).'
'; $response->setContent(substr($content, 0, $at).$bar.substr($content, $at)); } diff --git a/packages/admin/src/Modules/Modules.php b/packages/admin/src/Modules/Modules.php index cfe104d8..5c41e4e5 100644 --- a/packages/admin/src/Modules/Modules.php +++ b/packages/admin/src/Modules/Modules.php @@ -301,7 +301,7 @@ public function wire(Module $module): void } } - PublicUrl::forgetPaths(); + PublicUrl::forgetMemo(); } /** diff --git a/packages/admin/src/Support/PublicUrl.php b/packages/admin/src/Support/PublicUrl.php index 84f4ada5..05471acc 100644 --- a/packages/admin/src/Support/PublicUrl.php +++ b/packages/admin/src/Support/PublicUrl.php @@ -175,11 +175,22 @@ public static function forRecord(Model $record): ?string } /** - * Forget the cached section paths (for tests and after a data import). + * Forget the cached section paths, the kept ones too: after a data + * import that went past Eloquent, and in tests. */ public static function forgetPaths(): void { - self::$pathCache = []; + self::forgetMemo(); app(RecordCache::class)->flushClass(self::class); } + + /** + * Forget the paths this request worked out. The kept trees stay: a + * saved section drops them by itself, and the rules of the modules do + * not shape them. Runs at boot, so it must not write to the cache. + */ + public static function forgetMemo(): void + { + self::$pathCache = []; + } } diff --git a/packages/admin/tests/Feature/Cache/CacheStoreTest.php b/packages/admin/tests/Feature/Cache/CacheStoreTest.php index 775f89f1..963bfa8a 100644 --- a/packages/admin/tests/Feature/Cache/CacheStoreTest.php +++ b/packages/admin/tests/Feature/Cache/CacheStoreTest.php @@ -96,6 +96,8 @@ private function redis(array $answers): CacheRepository private function databaseRepository(string $table): CacheRepository { + // DDL is not rolled back on MySQL: a table left by an earlier run goes first. + Schema::dropIfExists($table); Schema::create($table, function (Blueprint $blueprint): void { $blueprint->string('key')->primary(); $blueprint->mediumText('value'); diff --git a/packages/admin/tests/Feature/Cache/CardBuilderTest.php b/packages/admin/tests/Feature/Cache/CardBuilderTest.php index 40e97d64..8beed337 100644 --- a/packages/admin/tests/Feature/Cache/CardBuilderTest.php +++ b/packages/admin/tests/Feature/Cache/CardBuilderTest.php @@ -29,10 +29,8 @@ use Atrium\Admin\Tests\Fixtures\Cards\SeoTitleOnly; use Error; use Illuminate\Database\Eloquent\Collection; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Exceptions; -use Illuminate\Support\Facades\Schema; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -43,53 +41,6 @@ */ final class CardBuilderTest extends CacheTestCase { - protected function defineDatabaseMigrations(): void - { - parent::defineDatabaseMigrations(); - - Schema::create('card_owners', function (Blueprint $table): void { - $table->id(); - $table->json('name')->nullable(); - }); - - Schema::create('card_labels', function (Blueprint $table): void { - $table->id(); - $table->string('name'); - }); - - Schema::create('card_sections', function (Blueprint $table): void { - $table->id(); - $table->unsignedBigInteger('parent_id')->nullable(); - $table->string('code')->nullable(); - }); - - Schema::create('card_items', function (Blueprint $table): void { - $table->id(); - $table->json('name')->nullable(); - $table->json('summary')->nullable(); - $table->string('code')->nullable(); - $table->unsignedBigInteger('owner_id')->nullable(); - $table->unsignedBigInteger('link_id')->nullable(); - $table->unsignedBigInteger('section_id')->nullable(); - $table->unsignedBigInteger('site_id')->nullable(); - $table->string('subject_type')->nullable(); - $table->unsignedBigInteger('subject_id')->nullable(); - $table->string('picture')->nullable(); - $table->text('files')->nullable(); - $table->text('docs')->nullable(); - }); - - Schema::create('card_item_label', function (Blueprint $table): void { - $table->unsignedBigInteger('item_id'); - $table->unsignedBigInteger('label_id'); - }); - - Schema::create('card_item_related', function (Blueprint $table): void { - $table->unsignedBigInteger('item_id'); - $table->unsignedBigInteger('related_id'); - }); - } - protected function tearDown(): void { Item::forget(); diff --git a/packages/admin/tests/Feature/Cache/PublicUrlMemoTest.php b/packages/admin/tests/Feature/Cache/PublicUrlMemoTest.php new file mode 100644 index 00000000..8fd284ec --- /dev/null +++ b/packages/admin/tests/Feature/Cache/PublicUrlMemoTest.php @@ -0,0 +1,81 @@ +create(['name' => 'Tours', 'code' => 'tours']); + + return Handbook::query()->create(['name' => 'Italy', 'code' => 'italy', 'parent_id' => $tours->id]); + } + + private function pathsVersion(): string + { + $versions = app(RecordCache::class)->versions(); + $versions->reset(); + + return $versions->get(['list:'.PublicUrl::class])['list:'.PublicUrl::class]; + } + + public function test_forgetting_the_memo_keeps_the_kept_paths_and_forgetting_the_paths_does_not(): void + { + $italy = $this->italy(); + $this->assertSame('tours/italy', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + Handbook::query()->whereKey($italy->id)->update(['code' => 'italia']); + $version = $this->pathsVersion(); + + PublicUrl::forgetMemo(); + + $this->assertSame('tours/italy', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + $this->assertSame($version, $this->pathsVersion()); + + PublicUrl::forgetPaths(); + + $this->assertSame('tours/italia', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + $this->assertNotSame($version, $this->pathsVersion()); + } + + public function test_wiring_a_module_in_forgets_the_paths_of_the_request_and_writes_nothing(): void + { + $italy = $this->italy(); + $this->assertSame('tours/italy', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + // The tree changes behind the request's memo: the kept copy is dropped. + Handbook::query()->whereKey($italy->id)->update(['code' => 'italia']); + app(RecordCache::class)->flushClass(Handbook::class); + $this->assertSame('tours/italy', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + $version = $this->pathsVersion(); + + app(Modules::class)->wire(new Module('acme/plain')); + + $this->assertSame('tours/italia', PublicUrl::sectionPaths(Handbook::class)[$italy->id]); + $this->assertSame($version, $this->pathsVersion()); + } +} diff --git a/packages/admin/tests/Feature/CacheDebugTest.php b/packages/admin/tests/Feature/CacheDebugTest.php index ddb0da53..2eb5a8d0 100644 --- a/packages/admin/tests/Feature/CacheDebugTest.php +++ b/packages/admin/tests/Feature/CacheDebugTest.php @@ -203,7 +203,7 @@ public function test_the_line_is_put_into_the_page_just_before_its_end(): void $line = e((string) $response->headers->get(CacheDebug::HEADER)); $this->assertSame( - 'quiet
Atrium: '.$line.'
', + 'quiet
Atrium: '.$line.'
', $response->getContent(), ); } diff --git a/packages/admin/tests/Feature/CacheTestCase.php b/packages/admin/tests/Feature/CacheTestCase.php index 7b8de2d4..10830c14 100644 --- a/packages/admin/tests/Feature/CacheTestCase.php +++ b/packages/admin/tests/Feature/CacheTestCase.php @@ -19,9 +19,7 @@ use Atrium\Admin\Tests\Fixtures\Cache\Tag; use Atrium\Admin\Tests\Fixtures\Post; use Atrium\Admin\Tests\TestCase; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; /** * Books on shelves with tags, translated, with pictures and SEO: what the @@ -36,54 +34,6 @@ protected function defineEnvironment($app): void $app['config']->set('atrium.resources', [Post::class, Book::class]); } - protected function defineDatabaseMigrations(): void - { - parent::defineDatabaseMigrations(); - - Schema::create('cache_shelves', function (Blueprint $table): void { - $table->id(); - $table->json('name')->nullable(); - $table->timestamps(); - }); - - Schema::create('cache_tags', function (Blueprint $table): void { - $table->id(); - $table->string('name'); - $table->timestamps(); - }); - - Schema::create('cache_books', function (Blueprint $table): void { - $table->id(); - $table->json('name')->nullable(); - $table->boolean('active')->default(true); - $table->integer('price')->nullable(); - $table->foreignId('shelf_id')->nullable(); - $table->string('cover')->nullable(); - $table->json('photos')->nullable(); - $table->timestamps(); - }); - - Schema::create('cache_codes', function (Blueprint $table): void { - $table->string('code')->primary(); - }); - - Schema::create('cache_nodes', function (Blueprint $table): void { - $table->id(); - $table->string('name')->nullable(); - }); - - Schema::create('cache_parts', function (Blueprint $table): void { - $table->id(); - $table->string('name')->nullable(); - $table->unsignedBigInteger('parent_id')->nullable(); - }); - - Schema::create('cache_book_tag', function (Blueprint $table): void { - $table->foreignId('book_id'); - $table->foreignId('tag_id'); - }); - } - protected function setUp(): void { parent::setUp(); diff --git a/packages/admin/tests/Feature/CacheWarmCommandTest.php b/packages/admin/tests/Feature/CacheWarmCommandTest.php index f41c7e0f..04b4fb28 100644 --- a/packages/admin/tests/Feature/CacheWarmCommandTest.php +++ b/packages/admin/tests/Feature/CacheWarmCommandTest.php @@ -19,13 +19,11 @@ use Atrium\Admin\Tests\Fixtures\Unwarmable; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Http\Kernel; -use Illuminate\Database\Schema\Blueprint; use Illuminate\Http\Request; use Illuminate\Routing\Router; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Exceptions; -use Illuminate\Support\Facades\Schema; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use stdClass; @@ -68,18 +66,6 @@ protected function defineEnvironment($app): void $app['config']->set('atrium.resources', [Post::class, Book::class, Zebra::class]); } - protected function defineDatabaseMigrations(): void - { - parent::defineDatabaseMigrations(); - - foreach (['cache_screen_zebras', 'cache_screen_aardvarks'] as $name) { - Schema::create($name, function (Blueprint $table): void { - $table->id(); - $table->string('name')->nullable(); - }); - } - } - /** * @param array $options * @return array{0:int,1:string} diff --git a/packages/admin/tests/database/migrations/2026_01_01_000001_create_cache_fixture_tables.php b/packages/admin/tests/database/migrations/2026_01_01_000001_create_cache_fixture_tables.php new file mode 100644 index 00000000..d143a437 --- /dev/null +++ b/packages/admin/tests/database/migrations/2026_01_01_000001_create_cache_fixture_tables.php @@ -0,0 +1,114 @@ +id(); + $table->json('name')->nullable(); + $table->timestamps(); + }); + + Schema::create('cache_tags', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + $table->timestamps(); + }); + + Schema::create('cache_books', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + $table->boolean('active')->default(true); + $table->integer('price')->nullable(); + $table->foreignId('shelf_id')->nullable(); + $table->string('cover')->nullable(); + $table->json('photos')->nullable(); + $table->timestamps(); + }); + + Schema::create('cache_codes', function (Blueprint $table): void { + $table->string('code')->primary(); + }); + + Schema::create('cache_nodes', function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + }); + + Schema::create('cache_parts', function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + $table->unsignedBigInteger('parent_id')->nullable(); + }); + + Schema::create('cache_book_tag', function (Blueprint $table): void { + $table->foreignId('book_id'); + $table->foreignId('tag_id'); + }); + + foreach (['cache_screen_zebras', 'cache_screen_aardvarks'] as $name) { + Schema::create($name, function (Blueprint $table): void { + $table->id(); + $table->string('name')->nullable(); + }); + } + + Schema::create('card_owners', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + }); + + Schema::create('card_labels', function (Blueprint $table): void { + $table->id(); + $table->string('name'); + }); + + Schema::create('card_sections', function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('parent_id')->nullable(); + $table->string('code')->nullable(); + }); + + Schema::create('card_items', function (Blueprint $table): void { + $table->id(); + $table->json('name')->nullable(); + $table->json('summary')->nullable(); + $table->string('code')->nullable(); + $table->unsignedBigInteger('owner_id')->nullable(); + $table->unsignedBigInteger('link_id')->nullable(); + $table->unsignedBigInteger('section_id')->nullable(); + $table->unsignedBigInteger('site_id')->nullable(); + $table->string('subject_type')->nullable(); + $table->unsignedBigInteger('subject_id')->nullable(); + $table->string('picture')->nullable(); + $table->text('files')->nullable(); + $table->text('docs')->nullable(); + }); + + Schema::create('card_item_label', function (Blueprint $table): void { + $table->unsignedBigInteger('item_id'); + $table->unsignedBigInteger('label_id'); + }); + + Schema::create('card_item_related', function (Blueprint $table): void { + $table->unsignedBigInteger('item_id'); + $table->unsignedBigInteger('related_id'); + }); + } +}; diff --git a/packages/pages/src/Models/Page.php b/packages/pages/src/Models/Page.php index 8e77408f..943207e1 100644 --- a/packages/pages/src/Models/Page.php +++ b/packages/pages/src/Models/Page.php @@ -82,7 +82,7 @@ protected static function booted(): void { $forget = static function (): void { app(PageTree::class)->flush(); - PublicUrl::forgetPaths(); + PublicUrl::forgetMemo(); }; static::saved($forget); diff --git a/packages/theme/src/ThemeServiceProvider.php b/packages/theme/src/ThemeServiceProvider.php index 7bd84218..cf754446 100644 --- a/packages/theme/src/ThemeServiceProvider.php +++ b/packages/theme/src/ThemeServiceProvider.php @@ -133,7 +133,7 @@ public function boot(): void if ($record instanceof Model && ! $record instanceof Sitemapable && PublicUrl::ruleFor($record::class) !== null) { $this->app->make(Sitemap::class)->flush(); - PublicUrl::forgetPaths(); + PublicUrl::forgetMemo(); } }; diff --git a/packages/theme/tests/ControllerInternalsTest.php b/packages/theme/tests/ControllerInternalsTest.php index 885f3d61..14f6d911 100644 --- a/packages/theme/tests/ControllerInternalsTest.php +++ b/packages/theme/tests/ControllerInternalsTest.php @@ -156,6 +156,18 @@ public function test_slashes_around_the_path_do_not_send_the_visitor_elsewhere() $this->assertNotInstanceOf(RedirectResponse::class, $response); } + public function test_of_records_sharing_a_code_the_one_at_the_path_opens_and_the_first_stands_in_for_a_wrong_path(): void + { + // Crates are not cached: the records are read by the query itself. + $wood = Crate::query()->create(['name' => 'Wood', 'code' => 'wood']); + $metal = Crate::query()->create(['name' => 'Metal', 'code' => 'metal']); + Crate::query()->create(['name' => 'Wooden box', 'code' => 'box', 'parent_id' => $wood->id]); + Crate::query()->create(['name' => 'Metal box', 'code' => 'box', 'parent_id' => $metal->id]); + + $this->get('/catalog/metal/box')->assertOk()->assertSee('Metal box')->assertDontSee('Wooden box'); + $this->get('/catalog/stone/box')->assertRedirect($this->root().'/catalog/wood/box'); + } + public function test_a_section_shows_the_records_of_the_first_model_that_stands_in_its_tree(): void { $computers = ProductSection::query()->create(['name' => 'Computers', 'code' => 'computers']); @@ -231,7 +243,7 @@ private function treeQueries(string $uri): array $queries = array_column(DB::getQueryLog(), 'query'); DB::disableQueryLog(); - return array_values(array_filter($queries, fn (string $sql): bool => str_contains($sql, '"product_sections" where'))); + return array_values(array_filter($queries, fn (string $sql): bool => (bool) preg_match('/["`]product_sections["`] where/', $sql))); } public function test_a_record_that_stands_in_no_section_asks_the_tree_nothing(): void diff --git a/packages/theme/tests/RecordViewFromCardTest.php b/packages/theme/tests/RecordViewFromCardTest.php index e428da26..9aa82653 100644 --- a/packages/theme/tests/RecordViewFromCardTest.php +++ b/packages/theme/tests/RecordViewFromCardTest.php @@ -69,6 +69,8 @@ public function test_the_page_of_a_record_as_the_card_keeps_it(): void 'manual' => '/upload/files/manual.pdf', 'active_from' => '2026-03-04 10:00:00', ]); $product->related()->attach($mouse->id); + // A decimal column reads back as "10" on SQLite and "10.00" on MySQL and PostgreSQL. + $price = (string) Product::query()->whereKey($product->id)->value('price'); $this->assertSame([ 'title' => 'Gaming laptop', @@ -87,7 +89,7 @@ public function test_the_page_of_a_record_as_the_card_keeps_it(): void 'blocks' => [ ['kind' => 'properties', 'items' => [ ['label' => 'Article', 'value' => 'A-1', 'url' => null, 'links' => []], - ['label' => 'Price', 'value' => '10', 'url' => null, 'links' => []], + ['label' => 'Price', 'value' => $price, 'url' => null, 'links' => []], ['label' => 'Color', 'value' => 'Silver', 'url' => null, 'links' => []], ['label' => 'Brand', 'value' => 'Northwind', 'url' => null, 'links' => []], ['label' => 'Related', 'value' => 'Mouse', 'url' => null, 'links' => [['value' => 'Mouse', 'url' => '/catalog/laptops/mouse']]], From 237e9857e3cd56613e05ac29532eb887f7260e6b Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:11:25 +0300 Subject: [PATCH 06/10] test(cache): settings, debug line and card language tests hold on MySQL and PostgreSQL --- .../admin/tests/Feature/Cache/SettingsCacheTest.php | 10 +++++++--- packages/admin/tests/Feature/CacheDebugTest.php | 2 ++ packages/admin/tests/Feature/RecordCacheTest.php | 5 ++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/packages/admin/tests/Feature/Cache/SettingsCacheTest.php b/packages/admin/tests/Feature/Cache/SettingsCacheTest.php index 1f7781f3..ea4e361c 100644 --- a/packages/admin/tests/Feature/Cache/SettingsCacheTest.php +++ b/packages/admin/tests/Feature/Cache/SettingsCacheTest.php @@ -10,6 +10,7 @@ namespace Atrium\Admin\Tests\Feature\Cache; use Atrium\Admin\Cache\RecordCache; +use Atrium\Admin\Models\Site; use Atrium\Admin\Modules\Modules; use Atrium\Admin\Modules\Settings; use Atrium\Admin\Tests\Fixtures\Modules\Label; @@ -92,14 +93,17 @@ public function test_every_module_has_a_name_of_its_own_in_the_cache(): void public function test_the_cache_holds_the_values_of_every_site_of_the_module(): void { + // Real sites: MySQL and PostgreSQL hold the settings to them. + $shop = Site::query()->create(['code' => 'shop', 'name' => 'Shop', 'folder' => 'shop']); + $blog = Site::query()->create(['code' => 'blog', 'name' => 'Blog', 'folder' => 'blog']); DB::table(Settings::TABLE)->insert([ ['module' => 'labels', 'site_id' => null, 'values' => '{"color":"red"}', 'created_at' => now(), 'updated_at' => now()], - ['module' => 'labels', 'site_id' => 7, 'values' => '{"color":"blue"}', 'created_at' => now(), 'updated_at' => now()], + ['module' => 'labels', 'site_id' => $shop->id, 'values' => '{"color":"blue"}', 'created_at' => now(), 'updated_at' => now()], ]); - $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels', 7)); + $this->assertSame(['color' => 'blue'], $this->settings()->stored('labels', $shop->id)); $this->assertSame(['color' => 'red'], $this->settings()->stored('labels')); - $this->assertSame([], $this->settings()->stored('labels', 8)); + $this->assertSame([], $this->settings()->stored('labels', $blog->id)); } public function test_a_row_with_something_else_than_a_list_of_values_reads_as_an_array(): void diff --git a/packages/admin/tests/Feature/CacheDebugTest.php b/packages/admin/tests/Feature/CacheDebugTest.php index 2eb5a8d0..e4b10292 100644 --- a/packages/admin/tests/Feature/CacheDebugTest.php +++ b/packages/admin/tests/Feature/CacheDebugTest.php @@ -74,6 +74,8 @@ protected function setUp(): void protected function tearDown(): void { Clock::$instants = []; + // Back to local: the database is refreshed without asking for confirmation. + $this->app['env'] = 'local'; parent::tearDown(); } diff --git a/packages/admin/tests/Feature/RecordCacheTest.php b/packages/admin/tests/Feature/RecordCacheTest.php index ae094c67..a48e0001 100644 --- a/packages/admin/tests/Feature/RecordCacheTest.php +++ b/packages/admin/tests/Feature/RecordCacheTest.php @@ -91,7 +91,10 @@ public function test_a_card_holds_the_record_in_its_language_with_relations_seo_ $this->assertSame(1000, $en['price']); // A card keeps the card's language and the default one, not all of them. - $this->assertSame(['en', 'de'], array_keys(json_decode($de->raw()['name'], true))); + // MySQL keeps the keys of a JSON column in an order of its own. + $languages = array_keys(json_decode($de->raw()['name'], true)); + sort($languages); + $this->assertSame(['de', 'en'], $languages); } public function test_saving_a_record_drops_its_cards_in_every_language(): void From 433fc9a7747140367133537b6711c7ae7f4bbb06 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:11:32 +0300 Subject: [PATCH 07/10] test(cache): build the cache store in parentheses so the tests parse on PHP 8.3 --- .../tests/Feature/Cache/CacheStoreTest.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/packages/admin/tests/Feature/Cache/CacheStoreTest.php b/packages/admin/tests/Feature/Cache/CacheStoreTest.php index 963bfa8a..babda2ec 100644 --- a/packages/admin/tests/Feature/Cache/CacheStoreTest.php +++ b/packages/admin/tests/Feature/Cache/CacheStoreTest.php @@ -157,9 +157,9 @@ public function test_a_repository_that_is_not_laravels_never_has_tags(): void public function test_the_driver_is_named_after_the_store(): void { $this->assertSame('array', $this->tagged()->driver()); - $this->assertSame('file', new CacheStore($this->fileRepository(), false)->driver()); - $this->assertSame('redis', new CacheStore($this->redis([]), true)->driver()); - $this->assertSame('database', new CacheStore($this->databaseRepository('driver_cache'), false)->driver()); + $this->assertSame('file', (new CacheStore($this->fileRepository(), false))->driver()); + $this->assertSame('redis', (new CacheStore($this->redis([]), true))->driver()); + $this->assertSame('database', (new CacheStore($this->databaseRepository('driver_cache'), false))->driver()); } public function test_the_size_of_a_store_that_cannot_tell_is_unknown(): void @@ -187,7 +187,7 @@ public function test_the_size_of_the_file_store_is_its_files(): void $bytes += $file->getSize(); } - $size = new CacheStore($repository, false)->size(); + $size = (new CacheStore($repository, false))->size(); $this->assertSame(['entries' => 3, 'bytes' => $bytes], $size); $this->assertGreaterThan(2100, $bytes); @@ -197,12 +197,12 @@ public function test_the_size_of_an_empty_file_store_is_nothing(): void { mkdir($this->directory); - $this->assertSame(['entries' => 0, 'bytes' => 0], new CacheStore($this->fileRepository(), false)->size()); + $this->assertSame(['entries' => 0, 'bytes' => 0], (new CacheStore($this->fileRepository(), false))->size()); } public function test_a_file_store_without_its_directory_has_no_size_and_no_error(): void { - $this->assertSame(['entries' => null, 'bytes' => null], new CacheStore($this->fileRepository(), false)->size()); + $this->assertSame(['entries' => null, 'bytes' => null], (new CacheStore($this->fileRepository(), false))->size()); } public function test_the_size_of_the_database_store_counts_its_rows_in_the_table_of_the_configured_store(): void @@ -212,7 +212,7 @@ public function test_the_size_of_the_database_store_counts_its_rows_in_the_table $repository->put('b', 2, 60); config(['cache.stores.kept' => ['driver' => 'database', 'table' => 'atrium_kept'], 'atrium.cache.store' => 'kept', 'cache.default' => 'array']); - $this->assertSame(['entries' => 2, 'bytes' => null], new CacheStore($repository, false)->size()); + $this->assertSame(['entries' => 2, 'bytes' => null], (new CacheStore($repository, false))->size()); } public function test_the_size_of_the_database_store_uses_the_default_store_when_none_is_named(): void @@ -221,7 +221,7 @@ public function test_the_size_of_the_database_store_uses_the_default_store_when_ $repository->put('a', 1, 60); config(['cache.stores.kept' => ['driver' => 'database', 'table' => 'atrium_default_kept'], 'atrium.cache.store' => null, 'cache.default' => 'kept']); - $this->assertSame(['entries' => 1, 'bytes' => null], new CacheStore($repository, false)->size()); + $this->assertSame(['entries' => 1, 'bytes' => null], (new CacheStore($repository, false))->size()); } public function test_the_size_of_the_database_store_falls_back_to_the_table_named_cache(): void @@ -232,7 +232,7 @@ public function test_the_size_of_the_database_store_falls_back_to_the_table_name $repository->put('c', 3, 60); config(['cache.stores.kept' => ['driver' => 'database'], 'atrium.cache.store' => 'kept']); - $this->assertSame(['entries' => 3, 'bytes' => null], new CacheStore($repository, false)->size()); + $this->assertSame(['entries' => 3, 'bytes' => null], (new CacheStore($repository, false))->size()); } /** @@ -293,7 +293,7 @@ public function test_nothing_asked_for_is_nothing_read(): void $repository->shouldNotReceive('many'); $repository->shouldNotReceive('tags'); - $this->assertSame([], new CacheStore($repository, true)->many('shelf', [])); + $this->assertSame([], (new CacheStore($repository, true))->many('shelf', [])); } public function test_nothing_to_write_is_nothing_written(): void @@ -303,7 +303,7 @@ public function test_nothing_to_write_is_nothing_written(): void $repository->shouldNotReceive('putMany'); foreach ([true, false] as $tags) { - new CacheStore($repository, $tags)->putMany('shelf', [], 60); + (new CacheStore($repository, $tags))->putMany('shelf', [], 60); } $this->addToAssertionCount(1); From 2857716298270b3d6664191528d1b8594feea6e5 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:50:18 +0300 Subject: [PATCH 08/10] build(admin): rebuild the bundle with the cache screen --- ...ut-I1QMPYpW.js => AdminLayout--RXJFj9t.js} | 2 +- ...{Create-B8v2keK9.js => Create-BxhK0Jvn.js} | 2 +- ...{Create-DWM7DbLl.js => Create-C61-lS2c.js} | 2 +- ...oard-BpfYcZ3c.js => Dashboard-BU7gtvAo.js} | 2 +- .../{Edit-DKlRxfoE.js => Edit-CHndUQJ2.js} | 2 +- .../{Edit-D7McI_eD.js => Edit-D-yhP5A2.js} | 2 +- .../{Edit-BEiwW1oN.js => Edit-DGjzU-uC.js} | 2 +- .../{Edit-ppjiZjeT.js => Edit-pGNJhUsL.js} | 2 +- ...ield-BI8KmQxQ.js => FormField-xD6LELDV.js} | 2 +- .../{Index-CVtF6Jho.js => Index-1mD_GBWn.js} | 2 +- .../{Index-B0DDRHtS.js => Index-9-V30Hlc.js} | 2 +- .../{Index-BzuT6e6D.js => Index-C_p9UH4T.js} | 2 +- .../{Index-By9Fq-LA.js => Index-CjLWl74m.js} | 2 +- .../{Index-waO6UWa5.js => Index-DEbfZBFs.js} | 2 +- .../{Index-CJcjrNaO.js => Index-P5jX14JD.js} | 2 +- packages/admin/dist/assets/Index-bqKVRXw8.js | 1 + ...tings-DiwVH39L.js => Settings-C2VyFPrB.js} | 2 +- .../{app-lI4VKCmX.js => app-BNjy5Z6H.js} | 4 +- packages/admin/dist/assets/app-BncygNAT.css | 2 + packages/admin/dist/assets/app-BvgWOIqU.css | 2 - packages/admin/dist/manifest.json | 92 +++++++++++-------- 21 files changed, 73 insertions(+), 60 deletions(-) rename packages/admin/dist/assets/{AdminLayout-I1QMPYpW.js => AdminLayout--RXJFj9t.js} (99%) rename packages/admin/dist/assets/{Create-B8v2keK9.js => Create-BxhK0Jvn.js} (96%) rename packages/admin/dist/assets/{Create-DWM7DbLl.js => Create-C61-lS2c.js} (96%) rename packages/admin/dist/assets/{Dashboard-BpfYcZ3c.js => Dashboard-BU7gtvAo.js} (98%) rename packages/admin/dist/assets/{Edit-DKlRxfoE.js => Edit-CHndUQJ2.js} (97%) rename packages/admin/dist/assets/{Edit-D7McI_eD.js => Edit-D-yhP5A2.js} (98%) rename packages/admin/dist/assets/{Edit-BEiwW1oN.js => Edit-DGjzU-uC.js} (96%) rename packages/admin/dist/assets/{Edit-ppjiZjeT.js => Edit-pGNJhUsL.js} (95%) rename packages/admin/dist/assets/{FormField-BI8KmQxQ.js => FormField-xD6LELDV.js} (99%) rename packages/admin/dist/assets/{Index-CVtF6Jho.js => Index-1mD_GBWn.js} (98%) rename packages/admin/dist/assets/{Index-B0DDRHtS.js => Index-9-V30Hlc.js} (99%) rename packages/admin/dist/assets/{Index-BzuT6e6D.js => Index-C_p9UH4T.js} (99%) rename packages/admin/dist/assets/{Index-By9Fq-LA.js => Index-CjLWl74m.js} (96%) rename packages/admin/dist/assets/{Index-waO6UWa5.js => Index-DEbfZBFs.js} (97%) rename packages/admin/dist/assets/{Index-CJcjrNaO.js => Index-P5jX14JD.js} (97%) create mode 100644 packages/admin/dist/assets/Index-bqKVRXw8.js rename packages/admin/dist/assets/{Settings-DiwVH39L.js => Settings-C2VyFPrB.js} (88%) rename packages/admin/dist/assets/{app-lI4VKCmX.js => app-BNjy5Z6H.js} (88%) create mode 100644 packages/admin/dist/assets/app-BncygNAT.css delete mode 100644 packages/admin/dist/assets/app-BvgWOIqU.css diff --git a/packages/admin/dist/assets/AdminLayout-I1QMPYpW.js b/packages/admin/dist/assets/AdminLayout--RXJFj9t.js similarity index 99% rename from packages/admin/dist/assets/AdminLayout-I1QMPYpW.js rename to packages/admin/dist/assets/AdminLayout--RXJFj9t.js index 28492410..72f26aa9 100644 --- a/packages/admin/dist/assets/AdminLayout-I1QMPYpW.js +++ b/packages/admin/dist/assets/AdminLayout--RXJFj9t.js @@ -1 +1 @@ -import{C as e,E as t,F as n,G as r,H as i,I as a,M as o,P as s,Q as c,R as l,S as u,T as d,W as f,Y as p,Z as m,_ as h,b as g,c as _,et as v,h as y,i as b,m as x,o as S,r as C,s as w,v as T,w as E,x as D,z as O}from"./dist-MY__znoP.js";import{n as k,r as A,t as j}from"./LocaleSwitcher-DdLJ9WTE.js";import{n as M,t as N}from"./app-lI4VKCmX.js";var P=[`aria-expanded`,`title`],F={class:`flex items-center`},I=[`innerHTML`],L={key:0},R=[`innerHTML`],z={key:0,class:`mt-1 ml-4 space-y-1 border-l border-sidebar-line pl-3`},B=[`innerHTML`],V={key:0},H=`flex items-center px-3 py-2 text-sm rounded-lg transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`,U=`bg-sidebar-active text-sidebar-active-fg font-semibold shadow-[inset_3px_0_0_var(--atrium-sidebar-accent)]`,W=`text-sidebar-fg font-medium hover:bg-sidebar-hover`,G={__name:`AdminMenuItem`,props:{item:{type:Object,required:!0},collapsed:Boolean},setup(n){let i=n,o=S(),s=p(!1),h=g(()=>i.item.children&&i.item.children.length>0),_=e=>{let t=route(e,void 0,!1),n=o.url.split(`?`)[0];return n===t||t!==route(`admin.dashboard`,void 0,!1)&&n.startsWith(t+`/`)},x=g(()=>!!i.item.route&&_(i.item.route)),C=g(()=>h.value?i.item.children.some(e=>e.route&&_(e.route)):!1),w=()=>{h.value&&(s.value=!s.value)};C.value&&(s.value=!0);let O={home:``,users:``,settings:``,folder:``,document:``,chart:``,"file-text":``,package:``,"help-circle":``,briefcase:``,star:``,tool:``,info:``,image:``,inbox:``,"shopping-cart":``,globe:``,shield:``,chevronDown:``,default:``},k=e=>_(e.route),A=g(()=>O[i.item.icon]||O.default);return(i,o)=>(a(),E(`li`,null,[h.value?(a(),E(T,{key:0},[D(`button`,{onClick:w,class:c([`w-full flex items-center px-3 py-2 text-sm rounded-lg transition-colors duration-200 hover:bg-sidebar-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`,[C.value?`text-sidebar-fg font-semibold`:`text-sidebar-fg font-medium`,n.collapsed?`justify-center`:`justify-between`]]),"aria-expanded":s.value?`true`:`false`,title:n.collapsed?n.item.label:``},[D(`span`,F,[(a(),E(`svg`,{class:c([`w-5 h-5 flex-shrink-0 text-sidebar-muted`,n.collapsed?``:`mr-3`]),fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,innerHTML:A.value},null,10,I)),n.collapsed?e(``,!0):(a(),E(`span`,L,v(n.item.label),1))]),n.collapsed?e(``,!0):(a(),E(`svg`,{key:0,class:c([`w-4 h-4 text-sidebar-muted transition-transform duration-200`,{"rotate-180":s.value}]),"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,innerHTML:O.chevronDown},null,10,R))],10,P),n.collapsed?e(``,!0):r((a(),E(`ul`,z,[(a(!0),E(T,null,l(n.item.children,e=>(a(),E(`li`,{key:e.route},[t(m(b),{"data-menu-route":e.route,href:i.route(e.route),class:c([H,k(e)?U:W]),"aria-current":k(e)?`page`:void 0},{default:f(()=>[d(v(e.label),1)]),_:2},1032,[`data-menu-route`,`href`,`class`,`aria-current`])]))),128))],512)),[[y,s.value]])],64)):(a(),u(m(b),{key:1,"data-menu-route":n.item.route,href:i.route(n.item.route),class:c([H,x.value?U:W,n.collapsed?`justify-center`:``]),"aria-current":x.value?`page`:void 0,title:n.collapsed?n.item.label:``},{default:f(()=>[(a(),E(`svg`,{class:c([`w-5 h-5 flex-shrink-0`,[n.collapsed?``:`mr-3`,x.value?``:`text-sidebar-muted`]]),fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,innerHTML:A.value},null,10,B)),n.collapsed?e(``,!0):(a(),E(`span`,V,v(n.item.label),1))]),_:1},8,[`data-menu-route`,`href`,`class`,`aria-current`,`title`]))]))}},K={class:`h-16 flex items-center justify-between px-4 border-b border-sidebar-line`},q=[`src`,`alt`],J={key:1,class:`text-xl font-bold truncate`},Y={class:`flex-1 overflow-y-auto py-4 px-3`},ee={class:`space-y-1`},te={class:`lg:hidden border-t border-sidebar-line p-4`},ne={class:`flex items-center space-x-3`},re={class:`w-10 h-10 rounded-full bg-sidebar-active text-sidebar-active-fg flex items-center justify-center`},ie={class:`text-lg font-medium`},ae={key:0},oe={class:`text-sm font-medium`},se={class:`text-xs text-sidebar-muted`},ce={__name:`AdminSidebar`,props:{open:Boolean,collapsed:Boolean,menu:{type:Array,default:()=>[]},branding:{type:Object,default:()=>({})}},emits:[`close`],setup(n,{emit:r}){let i=S();return g(()=>i.url),(r,i)=>(a(),E(`aside`,{class:c([`fixed inset-y-0 left-0 z-50 flex flex-col bg-sidebar text-sidebar-fg border-r border-sidebar-line transform transition-transform duration-300 lg:translate-x-0`,[n.open?`translate-x-0`:`-translate-x-full`,n.collapsed?`lg:w-20`:`lg:w-64`,`w-64`]])},[D(`div`,K,[t(m(b),{href:r.route(`admin.dashboard`),"data-sidebar-brand":``,class:`flex min-w-0 items-center space-x-3 rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`},{default:f(()=>[n.branding.logo?(a(),E(`img`,{key:0,src:n.branding.logo,alt:n.branding.name,class:`h-8 w-auto`},null,8,q)):e(``,!0),n.branding.logo&&!n.collapsed?(a(),E(`span`,J,v(n.branding.name||r.$t(`layout.brand_short`)),1)):e(``,!0),n.branding.logo?e(``,!0):(a(),u(A,{key:2,name:n.branding.name||`Atrium`,wordmark:!n.collapsed,size:28},null,8,[`name`,`wordmark`]))]),_:1},8,[`href`]),D(`button`,{onClick:i[0]||=e=>r.$emit(`close`),class:`lg:hidden p-2 rounded-md text-sidebar-muted hover:text-sidebar-fg hover:bg-sidebar-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`},[...i[1]||=[D(`svg`,{class:`w-6 h-6`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M6 18L18 6M6 6l12 12`})],-1)]])]),D(`nav`,Y,[D(`ul`,ee,[(a(!0),E(T,null,l(n.menu,e=>(a(),u(G,{key:e.route,item:e,collapsed:n.collapsed},null,8,[`item`,`collapsed`]))),128))])]),D(`div`,te,[D(`div`,ne,[D(`div`,re,[D(`span`,ie,v(r.$page.props.auth?.user?.name?.charAt(0)||`A`),1)]),n.collapsed?e(``,!0):(a(),E(`div`,ae,[D(`p`,oe,v(r.$page.props.auth?.user?.name),1),D(`p`,se,v(r.$page.props.auth?.user?.email),1)]))])]),t(k,{on:`sidebar`,compact:n.collapsed,class:c([`border-t border-sidebar-line px-4 py-3`,n.collapsed?`lg:px-2 lg:text-center`:``])},null,8,[`compact`,`class`])],2))}},le=[`aria-expanded`],ue={class:`w-8 h-8 rounded-full bg-accent-soft flex items-center justify-center text-accent-soft-fg font-semibold`},de={class:`hidden md:block text-left`},fe={class:`text-sm font-medium text-fg`},pe={class:`text-xs text-muted`},me={key:0,class:`absolute right-0 mt-2 w-56 bg-surface rounded-lg shadow-lg border border-line py-1 z-50`},he={class:`px-4 py-3 border-b border-line`},ge={class:`text-sm font-medium text-fg`},_e={class:`text-xs text-muted truncate`},ve={class:`py-1`},ye=[`aria-label`],be={class:`px-4 pt-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted`},xe=[`aria-checked`,`data-theme-option`,`onClick`],Se=[`data-theme`],Ce={key:1,class:`flex h-4 w-6 flex-none overflow-hidden rounded-sm ring-1 ring-field`,"aria-hidden":`true`},we={class:`flex-1 text-left`},Te={key:2,class:`h-4 w-4 flex-none text-accent`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},Ee={class:`border-t border-line py-1`},De={__name:`AdminUserDropdown`,props:{user:{type:Object,default:()=>({})}},setup(r){let i=p(!1),o=p(null),u=()=>{i.value=!i.value},h=()=>{i.value=!1},y=S(),x=g(()=>y.props.themes||[]),C=g(()=>y.props.theme),O=e=>{N(e),w.put(route(`admin.profile.theme`),{theme:e},{preserveScroll:!0,preserveState:!0})},k=()=>{w.post(route(`admin.logout`))},A=e=>{o.value&&!o.value.contains(e.target)&&h()};return s(()=>{document.addEventListener(`click`,A)}),n(()=>{document.removeEventListener(`click`,A)}),(n,s)=>(a(),E(`div`,{ref_key:`dropdownRef`,ref:o,class:`relative`},[D(`button`,{"data-action":`user-menu`,onClick:u,"aria-expanded":i.value?`true`:`false`,class:`flex items-center gap-3 p-2 rounded-lg hover:bg-hover transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`},[D(`div`,ue,v(r.user.name?.charAt(0)?.toUpperCase()||`A`),1),D(`div`,de,[D(`p`,fe,v(r.user.name),1),D(`p`,pe,v(r.user.email),1)]),s[0]||=D(`svg`,{class:`hidden sm:block w-4 h-4 text-muted`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M19 9l-7 7-7-7`})],-1)],8,le),t(_,{"enter-active-class":`transition ease-out duration-100`,"enter-from-class":`transform opacity-0 scale-95`,"enter-to-class":`transform opacity-100 scale-100`,"leave-active-class":`transition ease-in duration-75`,"leave-from-class":`transform opacity-100 scale-100`,"leave-to-class":`transform opacity-0 scale-95`},{default:f(()=>[i.value?(a(),E(`div`,me,[D(`div`,he,[D(`p`,ge,v(r.user.name),1),D(`p`,_e,v(r.user.email),1)]),D(`div`,ve,[t(m(b),{href:n.route(`admin.profile.edit`),class:`flex items-center px-4 py-2 text-sm text-fg hover:bg-hover`,onClick:h},{default:f(()=>[s[1]||=D(`svg`,{class:`w-4 h-4 mr-3 text-muted`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z`})],-1),d(` `+v(n.$t(`layout.user_menu.profile`)),1)]),_:1},8,[`href`])]),D(`div`,{class:`border-t border-line py-1`,role:`radiogroup`,"aria-label":n.$t(`layout.theme.label`)},[D(`p`,be,v(n.$t(`layout.theme.label`)),1),(a(!0),E(T,null,l(x.value,t=>(a(),E(`button`,{key:t,type:`button`,role:`radio`,"aria-checked":t===C.value?`true`:`false`,"data-theme-option":t,class:c([`flex items-center w-full gap-3 px-4 py-2 text-sm text-fg hover:bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus`,t===C.value?`font-semibold`:``]),onClick:e=>O(t)},[t===`system`?(a(),E(`span`,Ce,[...s[3]||=[D(`span`,{"data-theme":`graphite`,class:`flex-1 bg-page`},null,-1),D(`span`,{"data-theme":`night`,class:`flex-1 bg-page`},null,-1)]])):(a(),E(`span`,{key:0,"data-theme":t,class:`flex h-4 w-6 flex-none overflow-hidden rounded-sm ring-1 ring-field`,"aria-hidden":`true`},[...s[2]||=[D(`span`,{class:`w-2 bg-sidebar`},null,-1),D(`span`,{class:`flex flex-1 items-center justify-center bg-page`},[D(`span`,{class:`h-1.5 w-1.5 rounded-full bg-accent`})],-1)]],8,Se)),D(`span`,we,v(n.$t(`layout.theme.${t}`)),1),t===C.value?(a(),E(`svg`,Te,[...s[4]||=[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2.5`,d:`M5 13l4 4L19 7`},null,-1)]])):e(``,!0)],10,xe))),128))],8,ye),D(`div`,Ee,[D(`button`,{"data-action":`logout`,onClick:k,class:`flex items-center w-full px-4 py-2 text-sm text-danger hover:bg-danger-soft`},[s[5]||=D(`svg`,{class:`w-4 h-4 mr-3`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1`})],-1),d(` `+v(n.$t(`layout.user_menu.logout`)),1)])])])):e(``,!0)]),_:1})],512))}},Oe={key:0,class:`relative flex min-w-0 items-center gap-1 rounded-lg px-1 py-1 text-muted hover:bg-hover hover:text-fg sm:gap-2 sm:px-2`},ke={class:`flex min-w-0 flex-col text-left leading-tight`,"aria-hidden":`true`},Ae={"data-switcher-caption":``,class:`truncate text-[11px] sm:text-xs`},je={class:`max-w-14 truncate text-sm font-medium text-fg sm:max-w-32 xl:max-w-48`},Me=[`aria-label`,`aria-description`,`title`,`value`],Ne=[`value`],Pe={__name:`SiteSwitcher`,setup(t){let n=S(),r=g(()=>n.props.sites||[]),i=g(()=>n.props.currentSite?.id),o=g(()=>n.props.currentSite?.name??``),s=e=>{w.post(route(`admin.site`),{site_id:e.target.value},{preserveScroll:!0,preserveState:!1})};return(t,n)=>r.value.length>1?(a(),E(`div`,Oe,[n[0]||=D(`svg`,{class:`h-5 w-5 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M3 8.25V18a2.25 2.25 0 002.25 2.25h13.5A2.25 2.25 0 0021 18V8.25m-18 0V6a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 6v2.25m-18 0h18M5.25 6h.008v.008H5.25V6zm2.25 0h.008v.008H7.5V6zm2.25 0h.008v.008H9.75V6z`})],-1),D(`span`,ke,[D(`span`,Ae,v(t.$t(`layout.site`)),1),D(`span`,je,v(o.value),1)]),n[1]||=D(`svg`,{class:`hidden h-4 w-4 shrink-0 sm:block`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M19 9l-7 7-7-7`})],-1),D(`select`,{"data-site-switcher":``,name:`site_id`,"aria-label":t.$t(`layout.site`),"aria-description":t.$t(`layout.site_hint`),title:t.$t(`layout.site_hint`),value:i.value,class:`absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-lg bg-transparent text-transparent focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,onChange:s},[(a(!0),E(T,null,l(r.value,e=>(a(),E(`option`,{key:e.id,value:e.id,class:`bg-surface text-fg`},v(e.name),9,Ne))),128))],40,Me)])):e(``,!0)}},Fe={class:`sticky top-0 z-30 transform-gpu h-16 bg-surface border-b border-line flex items-center justify-between gap-1 px-3 sm:gap-2 sm:px-4 lg:px-6`},Ie={class:`flex shrink-0 items-center gap-1 sm:gap-4`},Le=[`href`,`title`],Re={class:`hidden sm:inline`},ze={class:`flex min-w-0 items-center gap-1 sm:gap-2 lg:gap-3`},Be={__name:`AdminHeader`,props:{user:{type:Object,default:()=>({})},branding:{type:Object,default:()=>({})}},emits:[`toggle-sidebar`,`toggle-collapse`],setup(e,{emit:n}){return(n,r)=>(a(),E(`header`,Fe,[D(`div`,Ie,[D(`button`,{onClick:r[0]||=e=>n.$emit(`toggle-sidebar`),class:`lg:hidden p-2 rounded-md text-muted hover:text-fg hover:bg-hover`},[...r[2]||=[D(`svg`,{class:`w-6 h-6`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M4 6h16M4 12h16M4 18h16`})],-1)]]),D(`button`,{"data-action":`collapse-sidebar`,onClick:r[1]||=e=>n.$emit(`toggle-collapse`),class:`hidden lg:block p-2 rounded-md text-muted hover:text-fg hover:bg-hover`},[...r[3]||=[D(`svg`,{class:`w-5 h-5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M4 6h16M4 12h8m-8 6h16`})],-1)]]),D(`a`,{"data-action":`visit-site`,href:n.$page.props.currentSite?.url||`/`,target:`_blank`,rel:`noopener`,class:`flex items-center gap-2 rounded-md px-2 py-2 text-sm text-muted hover:bg-hover hover:text-fg`,title:n.$t(`layout.visit_site_hint`)},[r[4]||=D(`svg`,{class:`w-5 h-5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M21 12a9 9 0 11-18 0 9 9 0 0118 0zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 010 18M12 3a15 15 0 000 18`})],-1),D(`span`,Re,v(n.$t(`layout.visit_site`)),1)],8,Le)]),D(`div`,ze,[t(Pe),t(j),t(De,{user:e.user},null,8,[`user`])])]))}};function X(){return M(`fields.upload.session_expired`)}function Ve(e){let t=document.cookie.match(RegExp(`(?:^|;\\s*)`+e+`=([^;]*)`));if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function He(){let e=Ve(`XSRF-TOKEN`);if(e)return{"X-XSRF-TOKEN":e};let t=document.querySelector(`meta[name="csrf-token"]`)?.getAttribute(`content`);return t?{"X-CSRF-TOKEN":t}:{}}function Z(e={}){return{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,...He(),...e}}async function Q(e,t=M(`fields.upload.request_failed`)){return e.status===419?X():e.status===413?M(`fields.upload.too_large`):(await e.json().catch(()=>({}))).message||t}var Ue=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},We=[`aria-label`],Ge={class:`flex items-center justify-between gap-2 border-b border-line px-4 py-2.5`},Ke={class:`text-sm font-semibold`},qe={class:`flex items-center gap-3 text-xs`},Je=[`aria-label`],Ye={class:`rounded-lg bg-surface-alt px-3 py-2`},Xe={key:0,class:`max-w-[85%] whitespace-pre-wrap rounded-lg bg-accent-soft px-3 py-2 text-accent-soft-fg`,dusk:`ai-question`},Ze=[`dusk`,`innerHTML`],Qe={key:0,class:`text-muted`,dusk:`ai-thinking`},$e={class:`flex items-end gap-2`},et=[`placeholder`,`aria-label`],tt=[`disabled`],$={class:`mt-2 text-xs text-muted`},nt=[`aria-label`,`aria-expanded`,`title`],rt={viewBox:`0 0 48 52`,class:`h-full w-full overflow-visible`,"aria-hidden":`true`},it={class:`ai-mascot-body`},at={class:`ai-mascot-eyes`},ot=[`cx`,`cy`],st=[`cx`,`cy`],ct=Ue({__name:`AiHelper`,setup(t){let u=S(),d=g(()=>u.props.ai?.help||null),f=g(()=>d.value?.labels||{}),m=g(()=>u.props.ai?.url||``),_=g(()=>`atrium-ai-help:${u.props.auth?.user?.id??``}`),y=p(!1),b=p(!1),C=p(``),O=p([]),k=p(null),A=p(null),j=p({x:0,y:0}),M=p(null),N=null,P=0;s(()=>{try{O.value=JSON.parse(sessionStorage.getItem(_.value)||`[]`)}catch{O.value=[]}window.addEventListener(`pointermove`,F)}),n(()=>{I(),window.removeEventListener(`pointermove`,F)}),i(O,e=>{try{sessionStorage.setItem(_.value,JSON.stringify(e.slice(-20)))}catch{}},{deep:!0});function F(e){let t=M.value?.getBoundingClientRect();if(!t)return;let n=e.clientX-(t.left+t.width/2),r=e.clientY-(t.top+t.height/3),i=Math.hypot(n,r)||1;j.value={x:n/i*.9,y:r/i*.9}}function I(){clearTimeout(N),N=null,P++}async function L(){y.value=!y.value,y.value&&(await o(),z(),A.value?.focus())}function R(){I(),b.value=!1,O.value=[],A.value?.focus()}async function z(){await o(),k.value&&(k.value.scrollTop=k.value.scrollHeight)}async function B(){let e=C.value.trim();if(e===``||b.value)return;let t=O.value.filter(e=>!e.error).slice(-10).map(({role:e,text:t})=>({role:e,text:t}));O.value.push({role:`user`,text:e}),C.value=``,b.value=!0,z(),I();let n=P;try{let r=await fetch(d.value.url,{method:`POST`,credentials:`same-origin`,headers:Z({"Content-Type":`application/json`}),body:JSON.stringify({question:e,history:t})});if(!r.ok)throw Error(await Q(r,f.value.error));V(await r.json(),n)}catch(e){n===P&&U(e.message)}}function V(e,t){t===P&&(e.status===`done`?(b.value=!1,O.value.push({role:`assistant`,text:e.value||``}),z()):e.status===`failed`?U(e.message):N=setTimeout(()=>H(e.id,t),1500))}async function H(e,t){try{let n=await fetch(`${m.value}/${e}`,{credentials:`same-origin`,headers:Z()});if(!n.ok)throw Error(await Q(n,f.value.error));V(await n.json(),t)}catch(e){t===P&&U(e.message)}}function U(e){b.value=!1,O.value.push({role:`assistant`,text:e||f.value.error,error:!0}),z()}function W(e){e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),B())}let G={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},K=e=>String(e).replace(/[&<>"']/g,e=>G[e]);function q(e){let t=e=>K(e).replace(/\*\*(.+?)\*\*/g,`$1`).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(e,t,n)=>n.startsWith(`/`)&&!n.startsWith(`//`)?`${t}`:t),n=[],r=[],i=()=>{r.length&&(n.push(`
    ${r.map(e=>`
  • ${e}
  • `).join(``)}
`),r=[])};for(let a of String(e).split(/\r?\n/)){let e=a.match(/^\s*[-*]\s+(.*)$/);e?r.push(t(e[1])):(i(),a.trim()!==``&&n.push(`

${t(a)}

`))}return i(),n.join(``)}function J(e){let t=e.target.closest?.(`a[data-ai-link]`);t&&(e.preventDefault(),w.visit(t.getAttribute(`href`)))}function Y(e){e.key===`Escape`&&y.value&&(y.value=!1)}return(t,n)=>d.value?(a(),E(`div`,{key:0,class:`fixed bottom-4 right-4 z-40 flex flex-col items-end gap-3`,dusk:`ai-helper`,onKeydown:Y},[y.value?(a(),E(`section`,{key:0,class:`flex w-[22rem] max-w-[calc(100vw-2rem)] max-h-[min(36rem,calc(100vh-8rem))] flex-col rounded-lg border border-line bg-surface text-fg shadow-xl`,role:`dialog`,"aria-label":f.value.title,dusk:`ai-chat`},[D(`header`,Ge,[D(`h2`,Ke,v(f.value.title),1),D(`div`,qe,[O.value.length?(a(),E(`button`,{key:0,type:`button`,class:`text-muted hover:text-fg`,dusk:`ai-clear`,onClick:R},v(f.value.clear),1)):e(``,!0),D(`button`,{type:`button`,class:`text-muted hover:text-fg`,"aria-label":f.value.close,dusk:`ai-close`,onClick:n[0]||=e=>y.value=!1},[...n[2]||=[D(`svg`,{class:`h-4 w-4`,viewBox:`0 0 20 20`,fill:`currentColor`,"aria-hidden":`true`},[D(`path`,{d:`M5.3 4.3 10 9l4.7-4.7 1 1L11 10l4.7 4.7-1 1L10 11l-4.7 4.7-1-1L9 10 4.3 5.3z`})],-1)]],8,Je)])]),D(`div`,{ref_key:`list`,ref:k,class:`flex-1 space-y-3 overflow-y-auto px-4 py-3 text-sm`,"aria-live":`polite`,onClick:J},[D(`p`,Ye,v(f.value.hello),1),(a(!0),E(T,null,l(O.value,(e,t)=>(a(),E(`div`,{key:t,class:c([`flex`,e.role===`user`?`justify-end`:`justify-start`])},[e.role===`user`?(a(),E(`p`,Xe,v(e.text),1)):(a(),E(`div`,{key:1,class:c([`max-w-[90%] space-y-2 rounded-lg px-3 py-2`,e.error?`border border-danger bg-danger-soft text-danger-soft-fg`:`bg-surface-alt`]),dusk:e.error?`ai-error`:`ai-answer`,innerHTML:q(e.text)},null,10,Ze))],2))),128)),b.value?(a(),E(`p`,Qe,v(f.value.thinking),1)):e(``,!0)],512),D(`form`,{class:`border-t border-line p-3`,onSubmit:h(B,[`prevent`])},[D(`div`,$e,[r(D(`textarea`,{ref_key:`input`,ref:A,"onUpdate:modelValue":n[1]||=e=>C.value=e,rows:`2`,maxlength:`2000`,class:`flex-1 resize-none rounded-md border border-field bg-surface px-3 py-2 text-sm text-fg focus:border-focus focus:outline-none focus:ring-1 focus:ring-focus`,placeholder:f.value.placeholder,"aria-label":f.value.placeholder,dusk:`ai-input`,onKeydown:W},null,40,et),[[x,C.value]]),D(`button`,{type:`submit`,class:`rounded-md bg-accent px-3 py-2 text-sm font-medium text-on-accent hover:bg-accent-hover disabled:opacity-50`,disabled:b.value||C.value.trim()===``,dusk:`ai-send`},v(f.value.send),9,tt)]),D(`p`,$,v(f.value.note),1)],32)],8,We)):e(``,!0),D(`button`,{ref_key:`mascot`,ref:M,type:`button`,class:c([`ai-mascot group relative h-16 w-16 rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,{"is-thinking":b.value,"is-open":y.value}]),"aria-label":f.value.open,"aria-expanded":y.value,title:f.value.open,dusk:`ai-mascot`,onClick:L},[(a(),E(`svg`,rt,[n[9]||=D(`ellipse`,{class:`ai-mascot-shadow fill-fg`,cx:`24`,cy:`49`,rx:`15`,ry:`2.2`,opacity:`0.15`},null,-1),D(`g`,it,[n[5]||=D(`path`,{class:`fill-fg`,d:`M6 42V22a18 18 0 0 1 36 0v20H32V22a8 8 0 0 0-16 0v20z`},null,-1),n[6]||=D(`rect`,{class:`ai-mascot-belt fill-accent`,x:`16`,y:`28`,width:`16`,height:`5`},null,-1),n[7]||=D(`rect`,{class:`fill-fg`,x:`4`,y:`41`,width:`13`,height:`3.5`,rx:`1.75`},null,-1),n[8]||=D(`rect`,{class:`fill-fg`,x:`31`,y:`41`,width:`13`,height:`3.5`,rx:`1.75`},null,-1),D(`g`,at,[n[3]||=D(`circle`,{class:`fill-surface`,cx:`19`,cy:`10.5`,r:`3`},null,-1),n[4]||=D(`circle`,{class:`fill-surface`,cx:`29`,cy:`10.5`,r:`3`},null,-1),D(`circle`,{class:`fill-fg`,cx:19+j.value.x,cy:10.5+j.value.y,r:`1.4`},null,8,ot),D(`circle`,{class:`fill-fg`,cx:29+j.value.x,cy:10.5+j.value.y,r:`1.4`},null,8,st)])])]))],10,nt)],32)):e(``,!0)}},[[`__scopeId`,`data-v-6928fa25`]]),lt={class:`min-h-screen bg-page`},ut={"data-page-content":`true`,class:`p-4 lg:p-6`},dt={key:0,"data-flash":`success`,class:`mb-4 p-4 bg-success-soft border border-success text-success-soft-fg rounded`},ft={key:1,"data-flash":`error`,class:`mb-4 p-4 bg-danger-soft border border-danger text-danger-soft-fg rounded`},pt={__name:`AdminLayout`,props:{title:{type:String,default:``}},setup(n){let r=S(),i=p(!1),o=p(!1),s=g(()=>r.props.branding||{}),l=g(()=>r.props.menu||[]),u=g(()=>r.props.auth?.user||{}),d=()=>{i.value=!i.value},f=()=>{o.value=!o.value},h=()=>{i.value=!1};return(r,p)=>(a(),E(T,null,[t(m(C),{title:n.title||``},null,8,[`title`]),D(`div`,lt,[i.value?(a(),E(`div`,{key:0,class:`fixed inset-0 z-40 bg-black/50 lg:hidden`,onClick:h})):e(``,!0),t(ce,{open:i.value,collapsed:o.value,menu:l.value,branding:s.value,onClose:h},null,8,[`open`,`collapsed`,`menu`,`branding`]),D(`div`,{class:c([`transition-all duration-300`,o.value?`lg:pl-20`:`lg:pl-64`])},[t(Be,{user:u.value,branding:s.value,onToggleSidebar:d,onToggleCollapse:f},null,8,[`user`,`branding`]),D(`main`,ut,[r.$page.props.flash?.success?(a(),E(`div`,dt,v(r.$page.props.flash.success),1)):e(``,!0),r.$page.props.flash?.error?(a(),E(`div`,ft,v(r.$page.props.flash.error),1)):e(``,!0),O(r.$slots,`default`)])],2),t(ct)])],64))}};export{X as i,Z as n,Q as r,pt as t}; \ No newline at end of file +import{C as e,E as t,F as n,G as r,H as i,I as a,M as o,P as s,Q as c,R as l,S as u,T as d,W as f,Y as p,Z as m,_ as h,b as g,c as _,et as v,h as y,i as b,m as x,o as S,r as C,s as w,v as T,w as E,x as D,z as O}from"./dist-MY__znoP.js";import{n as k,r as A,t as j}from"./LocaleSwitcher-DdLJ9WTE.js";import{n as M,t as N}from"./app-BNjy5Z6H.js";var P=[`aria-expanded`,`title`],F={class:`flex items-center`},I=[`innerHTML`],L={key:0},R=[`innerHTML`],z={key:0,class:`mt-1 ml-4 space-y-1 border-l border-sidebar-line pl-3`},B=[`innerHTML`],V={key:0},H=`flex items-center px-3 py-2 text-sm rounded-lg transition-colors duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`,U=`bg-sidebar-active text-sidebar-active-fg font-semibold shadow-[inset_3px_0_0_var(--atrium-sidebar-accent)]`,W=`text-sidebar-fg font-medium hover:bg-sidebar-hover`,G={__name:`AdminMenuItem`,props:{item:{type:Object,required:!0},collapsed:Boolean},setup(n){let i=n,o=S(),s=p(!1),h=g(()=>i.item.children&&i.item.children.length>0),_=e=>{let t=route(e,void 0,!1),n=o.url.split(`?`)[0];return n===t||t!==route(`admin.dashboard`,void 0,!1)&&n.startsWith(t+`/`)},x=g(()=>!!i.item.route&&_(i.item.route)),C=g(()=>h.value?i.item.children.some(e=>e.route&&_(e.route)):!1),w=()=>{h.value&&(s.value=!s.value)};C.value&&(s.value=!0);let O={home:``,users:``,settings:``,folder:``,document:``,chart:``,"file-text":``,package:``,"help-circle":``,briefcase:``,star:``,tool:``,info:``,image:``,inbox:``,"shopping-cart":``,globe:``,shield:``,chevronDown:``,default:``},k=e=>_(e.route),A=g(()=>O[i.item.icon]||O.default);return(i,o)=>(a(),E(`li`,null,[h.value?(a(),E(T,{key:0},[D(`button`,{onClick:w,class:c([`w-full flex items-center px-3 py-2 text-sm rounded-lg transition-colors duration-200 hover:bg-sidebar-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`,[C.value?`text-sidebar-fg font-semibold`:`text-sidebar-fg font-medium`,n.collapsed?`justify-center`:`justify-between`]]),"aria-expanded":s.value?`true`:`false`,title:n.collapsed?n.item.label:``},[D(`span`,F,[(a(),E(`svg`,{class:c([`w-5 h-5 flex-shrink-0 text-sidebar-muted`,n.collapsed?``:`mr-3`]),fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,innerHTML:A.value},null,10,I)),n.collapsed?e(``,!0):(a(),E(`span`,L,v(n.item.label),1))]),n.collapsed?e(``,!0):(a(),E(`svg`,{key:0,class:c([`w-4 h-4 text-sidebar-muted transition-transform duration-200`,{"rotate-180":s.value}]),"aria-hidden":`true`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,innerHTML:O.chevronDown},null,10,R))],10,P),n.collapsed?e(``,!0):r((a(),E(`ul`,z,[(a(!0),E(T,null,l(n.item.children,e=>(a(),E(`li`,{key:e.route},[t(m(b),{"data-menu-route":e.route,href:i.route(e.route),class:c([H,k(e)?U:W]),"aria-current":k(e)?`page`:void 0},{default:f(()=>[d(v(e.label),1)]),_:2},1032,[`data-menu-route`,`href`,`class`,`aria-current`])]))),128))],512)),[[y,s.value]])],64)):(a(),u(m(b),{key:1,"data-menu-route":n.item.route,href:i.route(n.item.route),class:c([H,x.value?U:W,n.collapsed?`justify-center`:``]),"aria-current":x.value?`page`:void 0,title:n.collapsed?n.item.label:``},{default:f(()=>[(a(),E(`svg`,{class:c([`w-5 h-5 flex-shrink-0`,[n.collapsed?``:`mr-3`,x.value?``:`text-sidebar-muted`]]),fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`,innerHTML:A.value},null,10,B)),n.collapsed?e(``,!0):(a(),E(`span`,V,v(n.item.label),1))]),_:1},8,[`data-menu-route`,`href`,`class`,`aria-current`,`title`]))]))}},K={class:`h-16 flex items-center justify-between px-4 border-b border-sidebar-line`},q=[`src`,`alt`],J={key:1,class:`text-xl font-bold truncate`},Y={class:`flex-1 overflow-y-auto py-4 px-3`},ee={class:`space-y-1`},te={class:`lg:hidden border-t border-sidebar-line p-4`},ne={class:`flex items-center space-x-3`},re={class:`w-10 h-10 rounded-full bg-sidebar-active text-sidebar-active-fg flex items-center justify-center`},ie={class:`text-lg font-medium`},ae={key:0},oe={class:`text-sm font-medium`},se={class:`text-xs text-sidebar-muted`},ce={__name:`AdminSidebar`,props:{open:Boolean,collapsed:Boolean,menu:{type:Array,default:()=>[]},branding:{type:Object,default:()=>({})}},emits:[`close`],setup(n,{emit:r}){let i=S();return g(()=>i.url),(r,i)=>(a(),E(`aside`,{class:c([`fixed inset-y-0 left-0 z-50 flex flex-col bg-sidebar text-sidebar-fg border-r border-sidebar-line transform transition-transform duration-300 lg:translate-x-0`,[n.open?`translate-x-0`:`-translate-x-full`,n.collapsed?`lg:w-20`:`lg:w-64`,`w-64`]])},[D(`div`,K,[t(m(b),{href:r.route(`admin.dashboard`),"data-sidebar-brand":``,class:`flex min-w-0 items-center space-x-3 rounded-md focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`},{default:f(()=>[n.branding.logo?(a(),E(`img`,{key:0,src:n.branding.logo,alt:n.branding.name,class:`h-8 w-auto`},null,8,q)):e(``,!0),n.branding.logo&&!n.collapsed?(a(),E(`span`,J,v(n.branding.name||r.$t(`layout.brand_short`)),1)):e(``,!0),n.branding.logo?e(``,!0):(a(),u(A,{key:2,name:n.branding.name||`Atrium`,wordmark:!n.collapsed,size:28},null,8,[`name`,`wordmark`]))]),_:1},8,[`href`]),D(`button`,{onClick:i[0]||=e=>r.$emit(`close`),class:`lg:hidden p-2 rounded-md text-sidebar-muted hover:text-sidebar-fg hover:bg-sidebar-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-sidebar-accent`},[...i[1]||=[D(`svg`,{class:`w-6 h-6`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M6 18L18 6M6 6l12 12`})],-1)]])]),D(`nav`,Y,[D(`ul`,ee,[(a(!0),E(T,null,l(n.menu,e=>(a(),u(G,{key:e.route,item:e,collapsed:n.collapsed},null,8,[`item`,`collapsed`]))),128))])]),D(`div`,te,[D(`div`,ne,[D(`div`,re,[D(`span`,ie,v(r.$page.props.auth?.user?.name?.charAt(0)||`A`),1)]),n.collapsed?e(``,!0):(a(),E(`div`,ae,[D(`p`,oe,v(r.$page.props.auth?.user?.name),1),D(`p`,se,v(r.$page.props.auth?.user?.email),1)]))])]),t(k,{on:`sidebar`,compact:n.collapsed,class:c([`border-t border-sidebar-line px-4 py-3`,n.collapsed?`lg:px-2 lg:text-center`:``])},null,8,[`compact`,`class`])],2))}},le=[`aria-expanded`],ue={class:`w-8 h-8 rounded-full bg-accent-soft flex items-center justify-center text-accent-soft-fg font-semibold`},de={class:`hidden md:block text-left`},fe={class:`text-sm font-medium text-fg`},pe={class:`text-xs text-muted`},me={key:0,class:`absolute right-0 mt-2 w-56 bg-surface rounded-lg shadow-lg border border-line py-1 z-50`},he={class:`px-4 py-3 border-b border-line`},ge={class:`text-sm font-medium text-fg`},_e={class:`text-xs text-muted truncate`},ve={class:`py-1`},ye=[`aria-label`],be={class:`px-4 pt-2 pb-1 text-xs font-semibold uppercase tracking-wide text-muted`},xe=[`aria-checked`,`data-theme-option`,`onClick`],Se=[`data-theme`],Ce={key:1,class:`flex h-4 w-6 flex-none overflow-hidden rounded-sm ring-1 ring-field`,"aria-hidden":`true`},we={class:`flex-1 text-left`},Te={key:2,class:`h-4 w-4 flex-none text-accent`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},Ee={class:`border-t border-line py-1`},De={__name:`AdminUserDropdown`,props:{user:{type:Object,default:()=>({})}},setup(r){let i=p(!1),o=p(null),u=()=>{i.value=!i.value},h=()=>{i.value=!1},y=S(),x=g(()=>y.props.themes||[]),C=g(()=>y.props.theme),O=e=>{N(e),w.put(route(`admin.profile.theme`),{theme:e},{preserveScroll:!0,preserveState:!0})},k=()=>{w.post(route(`admin.logout`))},A=e=>{o.value&&!o.value.contains(e.target)&&h()};return s(()=>{document.addEventListener(`click`,A)}),n(()=>{document.removeEventListener(`click`,A)}),(n,s)=>(a(),E(`div`,{ref_key:`dropdownRef`,ref:o,class:`relative`},[D(`button`,{"data-action":`user-menu`,onClick:u,"aria-expanded":i.value?`true`:`false`,class:`flex items-center gap-3 p-2 rounded-lg hover:bg-hover transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`},[D(`div`,ue,v(r.user.name?.charAt(0)?.toUpperCase()||`A`),1),D(`div`,de,[D(`p`,fe,v(r.user.name),1),D(`p`,pe,v(r.user.email),1)]),s[0]||=D(`svg`,{class:`hidden sm:block w-4 h-4 text-muted`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M19 9l-7 7-7-7`})],-1)],8,le),t(_,{"enter-active-class":`transition ease-out duration-100`,"enter-from-class":`transform opacity-0 scale-95`,"enter-to-class":`transform opacity-100 scale-100`,"leave-active-class":`transition ease-in duration-75`,"leave-from-class":`transform opacity-100 scale-100`,"leave-to-class":`transform opacity-0 scale-95`},{default:f(()=>[i.value?(a(),E(`div`,me,[D(`div`,he,[D(`p`,ge,v(r.user.name),1),D(`p`,_e,v(r.user.email),1)]),D(`div`,ve,[t(m(b),{href:n.route(`admin.profile.edit`),class:`flex items-center px-4 py-2 text-sm text-fg hover:bg-hover`,onClick:h},{default:f(()=>[s[1]||=D(`svg`,{class:`w-4 h-4 mr-3 text-muted`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z`})],-1),d(` `+v(n.$t(`layout.user_menu.profile`)),1)]),_:1},8,[`href`])]),D(`div`,{class:`border-t border-line py-1`,role:`radiogroup`,"aria-label":n.$t(`layout.theme.label`)},[D(`p`,be,v(n.$t(`layout.theme.label`)),1),(a(!0),E(T,null,l(x.value,t=>(a(),E(`button`,{key:t,type:`button`,role:`radio`,"aria-checked":t===C.value?`true`:`false`,"data-theme-option":t,class:c([`flex items-center w-full gap-3 px-4 py-2 text-sm text-fg hover:bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus`,t===C.value?`font-semibold`:``]),onClick:e=>O(t)},[t===`system`?(a(),E(`span`,Ce,[...s[3]||=[D(`span`,{"data-theme":`graphite`,class:`flex-1 bg-page`},null,-1),D(`span`,{"data-theme":`night`,class:`flex-1 bg-page`},null,-1)]])):(a(),E(`span`,{key:0,"data-theme":t,class:`flex h-4 w-6 flex-none overflow-hidden rounded-sm ring-1 ring-field`,"aria-hidden":`true`},[...s[2]||=[D(`span`,{class:`w-2 bg-sidebar`},null,-1),D(`span`,{class:`flex flex-1 items-center justify-center bg-page`},[D(`span`,{class:`h-1.5 w-1.5 rounded-full bg-accent`})],-1)]],8,Se)),D(`span`,we,v(n.$t(`layout.theme.${t}`)),1),t===C.value?(a(),E(`svg`,Te,[...s[4]||=[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2.5`,d:`M5 13l4 4L19 7`},null,-1)]])):e(``,!0)],10,xe))),128))],8,ye),D(`div`,Ee,[D(`button`,{"data-action":`logout`,onClick:k,class:`flex items-center w-full px-4 py-2 text-sm text-danger hover:bg-danger-soft`},[s[5]||=D(`svg`,{class:`w-4 h-4 mr-3`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1`})],-1),d(` `+v(n.$t(`layout.user_menu.logout`)),1)])])])):e(``,!0)]),_:1})],512))}},Oe={key:0,class:`relative flex min-w-0 items-center gap-1 rounded-lg px-1 py-1 text-muted hover:bg-hover hover:text-fg sm:gap-2 sm:px-2`},ke={class:`flex min-w-0 flex-col text-left leading-tight`,"aria-hidden":`true`},Ae={"data-switcher-caption":``,class:`truncate text-[11px] sm:text-xs`},je={class:`max-w-14 truncate text-sm font-medium text-fg sm:max-w-32 xl:max-w-48`},Me=[`aria-label`,`aria-description`,`title`,`value`],Ne=[`value`],Pe={__name:`SiteSwitcher`,setup(t){let n=S(),r=g(()=>n.props.sites||[]),i=g(()=>n.props.currentSite?.id),o=g(()=>n.props.currentSite?.name??``),s=e=>{w.post(route(`admin.site`),{site_id:e.target.value},{preserveScroll:!0,preserveState:!1})};return(t,n)=>r.value.length>1?(a(),E(`div`,Oe,[n[0]||=D(`svg`,{class:`h-5 w-5 shrink-0`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M3 8.25V18a2.25 2.25 0 002.25 2.25h13.5A2.25 2.25 0 0021 18V8.25m-18 0V6a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 6v2.25m-18 0h18M5.25 6h.008v.008H5.25V6zm2.25 0h.008v.008H7.5V6zm2.25 0h.008v.008H9.75V6z`})],-1),D(`span`,ke,[D(`span`,Ae,v(t.$t(`layout.site`)),1),D(`span`,je,v(o.value),1)]),n[1]||=D(`svg`,{class:`hidden h-4 w-4 shrink-0 sm:block`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`,"aria-hidden":`true`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M19 9l-7 7-7-7`})],-1),D(`select`,{"data-site-switcher":``,name:`site_id`,"aria-label":t.$t(`layout.site`),"aria-description":t.$t(`layout.site_hint`),title:t.$t(`layout.site_hint`),value:i.value,class:`absolute inset-0 h-full w-full cursor-pointer appearance-none rounded-lg bg-transparent text-transparent focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,onChange:s},[(a(!0),E(T,null,l(r.value,e=>(a(),E(`option`,{key:e.id,value:e.id,class:`bg-surface text-fg`},v(e.name),9,Ne))),128))],40,Me)])):e(``,!0)}},Fe={class:`sticky top-0 z-30 transform-gpu h-16 bg-surface border-b border-line flex items-center justify-between gap-1 px-3 sm:gap-2 sm:px-4 lg:px-6`},Ie={class:`flex shrink-0 items-center gap-1 sm:gap-4`},Le=[`href`,`title`],Re={class:`hidden sm:inline`},ze={class:`flex min-w-0 items-center gap-1 sm:gap-2 lg:gap-3`},Be={__name:`AdminHeader`,props:{user:{type:Object,default:()=>({})},branding:{type:Object,default:()=>({})}},emits:[`toggle-sidebar`,`toggle-collapse`],setup(e,{emit:n}){return(n,r)=>(a(),E(`header`,Fe,[D(`div`,Ie,[D(`button`,{onClick:r[0]||=e=>n.$emit(`toggle-sidebar`),class:`lg:hidden p-2 rounded-md text-muted hover:text-fg hover:bg-hover`},[...r[2]||=[D(`svg`,{class:`w-6 h-6`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M4 6h16M4 12h16M4 18h16`})],-1)]]),D(`button`,{"data-action":`collapse-sidebar`,onClick:r[1]||=e=>n.$emit(`toggle-collapse`),class:`hidden lg:block p-2 rounded-md text-muted hover:text-fg hover:bg-hover`},[...r[3]||=[D(`svg`,{class:`w-5 h-5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M4 6h16M4 12h8m-8 6h16`})],-1)]]),D(`a`,{"data-action":`visit-site`,href:n.$page.props.currentSite?.url||`/`,target:`_blank`,rel:`noopener`,class:`flex items-center gap-2 rounded-md px-2 py-2 text-sm text-muted hover:bg-hover hover:text-fg`,title:n.$t(`layout.visit_site_hint`)},[r[4]||=D(`svg`,{class:`w-5 h-5`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[D(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M21 12a9 9 0 11-18 0 9 9 0 0118 0zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 010 18M12 3a15 15 0 000 18`})],-1),D(`span`,Re,v(n.$t(`layout.visit_site`)),1)],8,Le)]),D(`div`,ze,[t(Pe),t(j),t(De,{user:e.user},null,8,[`user`])])]))}};function X(){return M(`fields.upload.session_expired`)}function Ve(e){let t=document.cookie.match(RegExp(`(?:^|;\\s*)`+e+`=([^;]*)`));if(!t)return null;try{return decodeURIComponent(t[1])}catch{return t[1]}}function He(){let e=Ve(`XSRF-TOKEN`);if(e)return{"X-XSRF-TOKEN":e};let t=document.querySelector(`meta[name="csrf-token"]`)?.getAttribute(`content`);return t?{"X-CSRF-TOKEN":t}:{}}function Z(e={}){return{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,...He(),...e}}async function Q(e,t=M(`fields.upload.request_failed`)){return e.status===419?X():e.status===413?M(`fields.upload.too_large`):(await e.json().catch(()=>({}))).message||t}var Ue=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},We=[`aria-label`],Ge={class:`flex items-center justify-between gap-2 border-b border-line px-4 py-2.5`},Ke={class:`text-sm font-semibold`},qe={class:`flex items-center gap-3 text-xs`},Je=[`aria-label`],Ye={class:`rounded-lg bg-surface-alt px-3 py-2`},Xe={key:0,class:`max-w-[85%] whitespace-pre-wrap rounded-lg bg-accent-soft px-3 py-2 text-accent-soft-fg`,dusk:`ai-question`},Ze=[`dusk`,`innerHTML`],Qe={key:0,class:`text-muted`,dusk:`ai-thinking`},$e={class:`flex items-end gap-2`},et=[`placeholder`,`aria-label`],tt=[`disabled`],$={class:`mt-2 text-xs text-muted`},nt=[`aria-label`,`aria-expanded`,`title`],rt={viewBox:`0 0 48 52`,class:`h-full w-full overflow-visible`,"aria-hidden":`true`},it={class:`ai-mascot-body`},at={class:`ai-mascot-eyes`},ot=[`cx`,`cy`],st=[`cx`,`cy`],ct=Ue({__name:`AiHelper`,setup(t){let u=S(),d=g(()=>u.props.ai?.help||null),f=g(()=>d.value?.labels||{}),m=g(()=>u.props.ai?.url||``),_=g(()=>`atrium-ai-help:${u.props.auth?.user?.id??``}`),y=p(!1),b=p(!1),C=p(``),O=p([]),k=p(null),A=p(null),j=p({x:0,y:0}),M=p(null),N=null,P=0;s(()=>{try{O.value=JSON.parse(sessionStorage.getItem(_.value)||`[]`)}catch{O.value=[]}window.addEventListener(`pointermove`,F)}),n(()=>{I(),window.removeEventListener(`pointermove`,F)}),i(O,e=>{try{sessionStorage.setItem(_.value,JSON.stringify(e.slice(-20)))}catch{}},{deep:!0});function F(e){let t=M.value?.getBoundingClientRect();if(!t)return;let n=e.clientX-(t.left+t.width/2),r=e.clientY-(t.top+t.height/3),i=Math.hypot(n,r)||1;j.value={x:n/i*.9,y:r/i*.9}}function I(){clearTimeout(N),N=null,P++}async function L(){y.value=!y.value,y.value&&(await o(),z(),A.value?.focus())}function R(){I(),b.value=!1,O.value=[],A.value?.focus()}async function z(){await o(),k.value&&(k.value.scrollTop=k.value.scrollHeight)}async function B(){let e=C.value.trim();if(e===``||b.value)return;let t=O.value.filter(e=>!e.error).slice(-10).map(({role:e,text:t})=>({role:e,text:t}));O.value.push({role:`user`,text:e}),C.value=``,b.value=!0,z(),I();let n=P;try{let r=await fetch(d.value.url,{method:`POST`,credentials:`same-origin`,headers:Z({"Content-Type":`application/json`}),body:JSON.stringify({question:e,history:t})});if(!r.ok)throw Error(await Q(r,f.value.error));V(await r.json(),n)}catch(e){n===P&&U(e.message)}}function V(e,t){t===P&&(e.status===`done`?(b.value=!1,O.value.push({role:`assistant`,text:e.value||``}),z()):e.status===`failed`?U(e.message):N=setTimeout(()=>H(e.id,t),1500))}async function H(e,t){try{let n=await fetch(`${m.value}/${e}`,{credentials:`same-origin`,headers:Z()});if(!n.ok)throw Error(await Q(n,f.value.error));V(await n.json(),t)}catch(e){t===P&&U(e.message)}}function U(e){b.value=!1,O.value.push({role:`assistant`,text:e||f.value.error,error:!0}),z()}function W(e){e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),B())}let G={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},K=e=>String(e).replace(/[&<>"']/g,e=>G[e]);function q(e){let t=e=>K(e).replace(/\*\*(.+?)\*\*/g,`$1`).replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(e,t,n)=>n.startsWith(`/`)&&!n.startsWith(`//`)?`${t}`:t),n=[],r=[],i=()=>{r.length&&(n.push(`
    ${r.map(e=>`
  • ${e}
  • `).join(``)}
`),r=[])};for(let a of String(e).split(/\r?\n/)){let e=a.match(/^\s*[-*]\s+(.*)$/);e?r.push(t(e[1])):(i(),a.trim()!==``&&n.push(`

${t(a)}

`))}return i(),n.join(``)}function J(e){let t=e.target.closest?.(`a[data-ai-link]`);t&&(e.preventDefault(),w.visit(t.getAttribute(`href`)))}function Y(e){e.key===`Escape`&&y.value&&(y.value=!1)}return(t,n)=>d.value?(a(),E(`div`,{key:0,class:`fixed bottom-4 right-4 z-40 flex flex-col items-end gap-3`,dusk:`ai-helper`,onKeydown:Y},[y.value?(a(),E(`section`,{key:0,class:`flex w-[22rem] max-w-[calc(100vw-2rem)] max-h-[min(36rem,calc(100vh-8rem))] flex-col rounded-lg border border-line bg-surface text-fg shadow-xl`,role:`dialog`,"aria-label":f.value.title,dusk:`ai-chat`},[D(`header`,Ge,[D(`h2`,Ke,v(f.value.title),1),D(`div`,qe,[O.value.length?(a(),E(`button`,{key:0,type:`button`,class:`text-muted hover:text-fg`,dusk:`ai-clear`,onClick:R},v(f.value.clear),1)):e(``,!0),D(`button`,{type:`button`,class:`text-muted hover:text-fg`,"aria-label":f.value.close,dusk:`ai-close`,onClick:n[0]||=e=>y.value=!1},[...n[2]||=[D(`svg`,{class:`h-4 w-4`,viewBox:`0 0 20 20`,fill:`currentColor`,"aria-hidden":`true`},[D(`path`,{d:`M5.3 4.3 10 9l4.7-4.7 1 1L11 10l4.7 4.7-1 1L10 11l-4.7 4.7-1-1L9 10 4.3 5.3z`})],-1)]],8,Je)])]),D(`div`,{ref_key:`list`,ref:k,class:`flex-1 space-y-3 overflow-y-auto px-4 py-3 text-sm`,"aria-live":`polite`,onClick:J},[D(`p`,Ye,v(f.value.hello),1),(a(!0),E(T,null,l(O.value,(e,t)=>(a(),E(`div`,{key:t,class:c([`flex`,e.role===`user`?`justify-end`:`justify-start`])},[e.role===`user`?(a(),E(`p`,Xe,v(e.text),1)):(a(),E(`div`,{key:1,class:c([`max-w-[90%] space-y-2 rounded-lg px-3 py-2`,e.error?`border border-danger bg-danger-soft text-danger-soft-fg`:`bg-surface-alt`]),dusk:e.error?`ai-error`:`ai-answer`,innerHTML:q(e.text)},null,10,Ze))],2))),128)),b.value?(a(),E(`p`,Qe,v(f.value.thinking),1)):e(``,!0)],512),D(`form`,{class:`border-t border-line p-3`,onSubmit:h(B,[`prevent`])},[D(`div`,$e,[r(D(`textarea`,{ref_key:`input`,ref:A,"onUpdate:modelValue":n[1]||=e=>C.value=e,rows:`2`,maxlength:`2000`,class:`flex-1 resize-none rounded-md border border-field bg-surface px-3 py-2 text-sm text-fg focus:border-focus focus:outline-none focus:ring-1 focus:ring-focus`,placeholder:f.value.placeholder,"aria-label":f.value.placeholder,dusk:`ai-input`,onKeydown:W},null,40,et),[[x,C.value]]),D(`button`,{type:`submit`,class:`rounded-md bg-accent px-3 py-2 text-sm font-medium text-on-accent hover:bg-accent-hover disabled:opacity-50`,disabled:b.value||C.value.trim()===``,dusk:`ai-send`},v(f.value.send),9,tt)]),D(`p`,$,v(f.value.note),1)],32)],8,We)):e(``,!0),D(`button`,{ref_key:`mascot`,ref:M,type:`button`,class:c([`ai-mascot group relative h-16 w-16 rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,{"is-thinking":b.value,"is-open":y.value}]),"aria-label":f.value.open,"aria-expanded":y.value,title:f.value.open,dusk:`ai-mascot`,onClick:L},[(a(),E(`svg`,rt,[n[9]||=D(`ellipse`,{class:`ai-mascot-shadow fill-fg`,cx:`24`,cy:`49`,rx:`15`,ry:`2.2`,opacity:`0.15`},null,-1),D(`g`,it,[n[5]||=D(`path`,{class:`fill-fg`,d:`M6 42V22a18 18 0 0 1 36 0v20H32V22a8 8 0 0 0-16 0v20z`},null,-1),n[6]||=D(`rect`,{class:`ai-mascot-belt fill-accent`,x:`16`,y:`28`,width:`16`,height:`5`},null,-1),n[7]||=D(`rect`,{class:`fill-fg`,x:`4`,y:`41`,width:`13`,height:`3.5`,rx:`1.75`},null,-1),n[8]||=D(`rect`,{class:`fill-fg`,x:`31`,y:`41`,width:`13`,height:`3.5`,rx:`1.75`},null,-1),D(`g`,at,[n[3]||=D(`circle`,{class:`fill-surface`,cx:`19`,cy:`10.5`,r:`3`},null,-1),n[4]||=D(`circle`,{class:`fill-surface`,cx:`29`,cy:`10.5`,r:`3`},null,-1),D(`circle`,{class:`fill-fg`,cx:19+j.value.x,cy:10.5+j.value.y,r:`1.4`},null,8,ot),D(`circle`,{class:`fill-fg`,cx:29+j.value.x,cy:10.5+j.value.y,r:`1.4`},null,8,st)])])]))],10,nt)],32)):e(``,!0)}},[[`__scopeId`,`data-v-6928fa25`]]),lt={class:`min-h-screen bg-page`},ut={"data-page-content":`true`,class:`p-4 lg:p-6`},dt={key:0,"data-flash":`success`,class:`mb-4 p-4 bg-success-soft border border-success text-success-soft-fg rounded`},ft={key:1,"data-flash":`error`,class:`mb-4 p-4 bg-danger-soft border border-danger text-danger-soft-fg rounded`},pt={__name:`AdminLayout`,props:{title:{type:String,default:``}},setup(n){let r=S(),i=p(!1),o=p(!1),s=g(()=>r.props.branding||{}),l=g(()=>r.props.menu||[]),u=g(()=>r.props.auth?.user||{}),d=()=>{i.value=!i.value},f=()=>{o.value=!o.value},h=()=>{i.value=!1};return(r,p)=>(a(),E(T,null,[t(m(C),{title:n.title||``},null,8,[`title`]),D(`div`,lt,[i.value?(a(),E(`div`,{key:0,class:`fixed inset-0 z-40 bg-black/50 lg:hidden`,onClick:h})):e(``,!0),t(ce,{open:i.value,collapsed:o.value,menu:l.value,branding:s.value,onClose:h},null,8,[`open`,`collapsed`,`menu`,`branding`]),D(`div`,{class:c([`transition-all duration-300`,o.value?`lg:pl-20`:`lg:pl-64`])},[t(Be,{user:u.value,branding:s.value,onToggleSidebar:d,onToggleCollapse:f},null,8,[`user`,`branding`]),D(`main`,ut,[r.$page.props.flash?.success?(a(),E(`div`,dt,v(r.$page.props.flash.success),1)):e(``,!0),r.$page.props.flash?.error?(a(),E(`div`,ft,v(r.$page.props.flash.error),1)):e(``,!0),O(r.$slots,`default`)])],2),t(ct)])],64))}};export{X as i,Z as n,Q as r,pt as t}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Create-B8v2keK9.js b/packages/admin/dist/assets/Create-BxhK0Jvn.js similarity index 96% rename from packages/admin/dist/assets/Create-B8v2keK9.js rename to packages/admin/dist/assets/Create-BxhK0Jvn.js index e665b8d4..8b4414b8 100644 --- a/packages/admin/dist/assets/Create-B8v2keK9.js +++ b/packages/admin/dist/assets/Create-BxhK0Jvn.js @@ -1 +1 @@ -import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as u,a as d,b as f,et as p,i as m,q as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout-I1QMPYpW.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{n as S,r as C,t as w}from"./ContentLocaleSwitcher-BJIieXK-.js";import{t as T}from"./FormField-BI8KmQxQ.js";import{n as E,r as D,t as O}from"./contentLocale-BtGD-iBF.js";var k={class:`mb-6`},A={class:`flex`,"aria-label":`Breadcrumb`},j={class:`inline-flex items-center space-x-1 md:space-x-3`},M={class:`inline-flex items-center`},N={class:`flex items-center`},P={class:`ml-1 text-muted`},F={class:`max-w-4xl`},I={class:`text-2xl font-bold text-fg mb-6`},L=[`data-resource`],R={class:`space-y-6`},z={key:0,class:`text-center py-12 text-muted`},B={key:2,class:`space-y-6`},V={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},H={__name:`Create`,props:{routeName:String,createLabel:String,fields:Array,fieldsByTab:Object,tabs:Array,useTabs:Boolean,title:String,adminLabel:String},setup(H){let U=H,W=c(U.tabs?.[0]?.name||`main`),G={};U.useTabs&&U.fieldsByTab?Object.values(U.fieldsByTab).flat().forEach(e=>{G[e.name]=E(e,void 0)}):U.fields.forEach(e=>{G[e.name]=E(e,void 0)});let K=d(G),q=()=>(U.useTabs&&U.fieldsByTab?Object.values(U.fieldsByTab).flat():U.fields)||[],{locale:J,locales:Y,showSwitcher:X}=D(q),Z=f(()=>({...K.data()}));r(`formData`,Z),r(`aiModule`,U.routeName?.replace(/^admin\./,``)||null);let Q=()=>{K.submit(`post`,route(`${U.routeName}.store`))},$=e=>U.fieldsByTab?.[e]?U.fieldsByTab[e].filter(e=>O(K.errors,e)).length:0,ee=f(()=>U.tabs?U.tabs.map(e=>({...e,badge:$(e.name)>0?String($(e.name)):null})):[]);return(r,c)=>(n(),a(y,{title:H.title},{default:s(()=>[v(`div`,k,[v(`nav`,A,[v(`ol`,j,[v(`li`,M,[t(l(m),{href:r.route(`${U.routeName}.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(p(H.adminLabel),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,N,[c[2]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,P,p(r.$t(`resource.form.breadcrumb_create`)),1)])])])])]),v(`div`,F,[v(`h1`,I,p(H.title),1),t(x,null,{default:s(()=>[v(`form`,{onSubmit:u(Q,[`prevent`]),"data-admin-form":`true`,"data-resource":H.routeName,"data-context":`create`},[l(X)?(n(),a(w,{key:0,modelValue:l(J),"onUpdate:modelValue":c[0]||=e=>h(J)?J.value=e:null,locales:l(Y),fields:q(),errors:l(K).errors},null,8,[`modelValue`,`locales`,`fields`,`errors`])):e(``,!0),H.useTabs&&H.tabs&&H.fieldsByTab?(n(),a(C,{key:1,tabs:ee.value,modelValue:W.value,"onUpdate:modelValue":c[1]||=e=>W.value=e},{default:s(({activeTab:t})=>[(n(!0),_(g,null,i(H.tabs,o=>(n(),a(S,{key:o.name,name:o.name,activeTab:t},{default:s(()=>[v(`div`,R,[(n(!0),_(g,null,i(H.fieldsByTab[o.name],e=>(n(),a(T,{key:e.name,field:e,modelValue:l(K)[e.name],"onUpdate:modelValue":t=>l(K)[e.name]=t,errors:l(K).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128)),H.fieldsByTab[o.name]?.length?e(``,!0):(n(),_(`div`,z,[v(`p`,null,p(r.$t(`resource.form.empty_tab`)),1)]))])]),_:2},1032,[`name`,`activeTab`]))),128))]),_:1},8,[`tabs`,`modelValue`])):(n(),_(`div`,B,[(n(!0),_(g,null,i(H.fields,e=>(n(),a(T,{key:e.name,field:e,modelValue:l(K)[e.name],"onUpdate:modelValue":t=>l(K)[e.name]=t,errors:l(K).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))])),v(`div`,V,[t(b,{"data-action":`cancel`,href:r.route(`${U.routeName}.index`),variant:`secondary`},{default:s(()=>[o(p(r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(b,{"data-action":`save`,type:`submit`,loading:l(K).processing},{default:s(()=>[o(p(r.$t(`common.create`)),1)]),_:1},8,[`loading`])])],40,L)]),_:1})])]),_:1},8,[`title`]))}};export{H as default}; \ No newline at end of file +import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as u,a as d,b as f,et as p,i as m,q as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout--RXJFj9t.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{n as S,r as C,t as w}from"./ContentLocaleSwitcher-BJIieXK-.js";import{t as T}from"./FormField-xD6LELDV.js";import{n as E,r as D,t as O}from"./contentLocale-BtGD-iBF.js";var k={class:`mb-6`},A={class:`flex`,"aria-label":`Breadcrumb`},j={class:`inline-flex items-center space-x-1 md:space-x-3`},M={class:`inline-flex items-center`},N={class:`flex items-center`},P={class:`ml-1 text-muted`},F={class:`max-w-4xl`},I={class:`text-2xl font-bold text-fg mb-6`},L=[`data-resource`],R={class:`space-y-6`},z={key:0,class:`text-center py-12 text-muted`},B={key:2,class:`space-y-6`},V={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},H={__name:`Create`,props:{routeName:String,createLabel:String,fields:Array,fieldsByTab:Object,tabs:Array,useTabs:Boolean,title:String,adminLabel:String},setup(H){let U=H,W=c(U.tabs?.[0]?.name||`main`),G={};U.useTabs&&U.fieldsByTab?Object.values(U.fieldsByTab).flat().forEach(e=>{G[e.name]=E(e,void 0)}):U.fields.forEach(e=>{G[e.name]=E(e,void 0)});let K=d(G),q=()=>(U.useTabs&&U.fieldsByTab?Object.values(U.fieldsByTab).flat():U.fields)||[],{locale:J,locales:Y,showSwitcher:X}=D(q),Z=f(()=>({...K.data()}));r(`formData`,Z),r(`aiModule`,U.routeName?.replace(/^admin\./,``)||null);let Q=()=>{K.submit(`post`,route(`${U.routeName}.store`))},$=e=>U.fieldsByTab?.[e]?U.fieldsByTab[e].filter(e=>O(K.errors,e)).length:0,ee=f(()=>U.tabs?U.tabs.map(e=>({...e,badge:$(e.name)>0?String($(e.name)):null})):[]);return(r,c)=>(n(),a(y,{title:H.title},{default:s(()=>[v(`div`,k,[v(`nav`,A,[v(`ol`,j,[v(`li`,M,[t(l(m),{href:r.route(`${U.routeName}.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(p(H.adminLabel),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,N,[c[2]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,P,p(r.$t(`resource.form.breadcrumb_create`)),1)])])])])]),v(`div`,F,[v(`h1`,I,p(H.title),1),t(x,null,{default:s(()=>[v(`form`,{onSubmit:u(Q,[`prevent`]),"data-admin-form":`true`,"data-resource":H.routeName,"data-context":`create`},[l(X)?(n(),a(w,{key:0,modelValue:l(J),"onUpdate:modelValue":c[0]||=e=>h(J)?J.value=e:null,locales:l(Y),fields:q(),errors:l(K).errors},null,8,[`modelValue`,`locales`,`fields`,`errors`])):e(``,!0),H.useTabs&&H.tabs&&H.fieldsByTab?(n(),a(C,{key:1,tabs:ee.value,modelValue:W.value,"onUpdate:modelValue":c[1]||=e=>W.value=e},{default:s(({activeTab:t})=>[(n(!0),_(g,null,i(H.tabs,o=>(n(),a(S,{key:o.name,name:o.name,activeTab:t},{default:s(()=>[v(`div`,R,[(n(!0),_(g,null,i(H.fieldsByTab[o.name],e=>(n(),a(T,{key:e.name,field:e,modelValue:l(K)[e.name],"onUpdate:modelValue":t=>l(K)[e.name]=t,errors:l(K).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128)),H.fieldsByTab[o.name]?.length?e(``,!0):(n(),_(`div`,z,[v(`p`,null,p(r.$t(`resource.form.empty_tab`)),1)]))])]),_:2},1032,[`name`,`activeTab`]))),128))]),_:1},8,[`tabs`,`modelValue`])):(n(),_(`div`,B,[(n(!0),_(g,null,i(H.fields,e=>(n(),a(T,{key:e.name,field:e,modelValue:l(K)[e.name],"onUpdate:modelValue":t=>l(K)[e.name]=t,errors:l(K).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))])),v(`div`,V,[t(b,{"data-action":`cancel`,href:r.route(`${U.routeName}.index`),variant:`secondary`},{default:s(()=>[o(p(r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(b,{"data-action":`save`,type:`submit`,loading:l(K).processing},{default:s(()=>[o(p(r.$t(`common.create`)),1)]),_:1},8,[`loading`])])],40,L)]),_:1})])]),_:1},8,[`title`]))}};export{H as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Create-DWM7DbLl.js b/packages/admin/dist/assets/Create-C61-lS2c.js similarity index 96% rename from packages/admin/dist/assets/Create-DWM7DbLl.js rename to packages/admin/dist/assets/Create-C61-lS2c.js index e1089530..276f1ff8 100644 --- a/packages/admin/dist/assets/Create-DWM7DbLl.js +++ b/packages/admin/dist/assets/Create-C61-lS2c.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,Q as i,R as a,S as o,T as s,W as c,Z as l,_ as u,a as d,d as f,et as p,i as m,u as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout-I1QMPYpW.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{t as S}from"./FormField-BI8KmQxQ.js";var C={class:`mb-6`},w={class:`flex`,"aria-label":`Breadcrumb`},T={class:`inline-flex items-center space-x-1 md:space-x-3`},E={class:`inline-flex items-center`},D={class:`flex items-center`},O={class:`ml-1 text-muted`},k={class:`max-w-2xl`},A={class:`text-2xl font-bold text-fg mb-6`},j={key:1},M={key:0,class:`flex items-center`},N=[`id`,`onUpdate:modelValue`],P=[`for`],F=[`for`],I={key:0,class:`text-danger`},L=[`id`,`onUpdate:modelValue`,`type`,`placeholder`,`required`],R={key:2,class:`mt-1 text-sm text-muted`},z={key:3,class:`mt-1 text-sm text-danger`},B={class:`flex items-center justify-end space-x-3 pt-4 border-t`},V={__name:`Create`,props:{fields:Array,title:String},setup(V){let H=V,U={};H.fields.forEach(e=>{U[e.name]=e.default??``});let W=d(U),G=()=>{W.post(route(`admin.users.store`))},K=e=>[`text`,`email`,`password`,`checkbox`].includes(e.type);return(d,H)=>(r(),o(y,{title:V.title},{default:c(()=>[v(`div`,C,[v(`nav`,w,[v(`ol`,T,[v(`li`,E,[t(l(m),{href:d.route(`admin.users.index`),class:`text-muted hover:text-accent`},{default:c(()=>[s(p(d.$t(`menu.administrators`)),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,D,[H[0]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,O,p(d.$t(`account.users.creating`)),1)])])])])]),v(`div`,k,[v(`h1`,A,p(V.title),1),t(x,null,{default:c(()=>[v(`form`,{onSubmit:u(G,[`prevent`]),class:`space-y-6`},[(r(!0),_(g,null,a(V.fields,t=>(r(),_(g,{key:t.name},[K(t)?(r(),_(`div`,j,[t.type===`checkbox`?(r(),_(`div`,M,[n(v(`input`,{id:t.name,"onUpdate:modelValue":e=>l(W)[t.name]=e,type:`checkbox`,class:`h-4 w-4 text-accent focus:ring-focus border-field rounded`},null,8,N),[[h,l(W)[t.name]]]),v(`label`,{for:t.name,class:`ml-2 text-sm text-fg`},p(t.label),9,P)])):(r(),_(g,{key:1},[v(`label`,{for:t.name,class:`block text-sm font-medium text-fg mb-1`},[s(p(t.label)+` `,1),t.required?(r(),_(`span`,I,`*`)):e(``,!0)],8,F),n(v(`input`,{id:t.name,"onUpdate:modelValue":e=>l(W)[t.name]=e,type:t.type===`password`?`password`:t.type===`email`?`email`:`text`,placeholder:t.placeholder,required:t.required,class:i([`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`,{"border-danger":l(W).errors[t.name]}])},null,10,L),[[f,l(W)[t.name]]])],64)),t.hint?(r(),_(`p`,R,p(t.hint),1)):e(``,!0),l(W).errors[t.name]?(r(),_(`p`,z,p(l(W).errors[t.name]),1)):e(``,!0)])):(r(),o(S,{key:0,field:t,modelValue:l(W)[t.name],"onUpdate:modelValue":e=>l(W)[t.name]=e,errors:l(W).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))],64))),128)),v(`div`,B,[t(b,{href:d.route(`admin.users.index`),variant:`secondary`},{default:c(()=>[s(p(d.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(b,{"data-action":`save`,type:`submit`,loading:l(W).processing},{default:c(()=>[s(p(d.$t(`common.create`)),1)]),_:1},8,[`loading`])])],32)]),_:1})])]),_:1},8,[`title`]))}};export{V as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,Q as i,R as a,S as o,T as s,W as c,Z as l,_ as u,a as d,d as f,et as p,i as m,u as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout--RXJFj9t.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{t as S}from"./FormField-xD6LELDV.js";var C={class:`mb-6`},w={class:`flex`,"aria-label":`Breadcrumb`},T={class:`inline-flex items-center space-x-1 md:space-x-3`},E={class:`inline-flex items-center`},D={class:`flex items-center`},O={class:`ml-1 text-muted`},k={class:`max-w-2xl`},A={class:`text-2xl font-bold text-fg mb-6`},j={key:1},M={key:0,class:`flex items-center`},N=[`id`,`onUpdate:modelValue`],P=[`for`],F=[`for`],I={key:0,class:`text-danger`},L=[`id`,`onUpdate:modelValue`,`type`,`placeholder`,`required`],R={key:2,class:`mt-1 text-sm text-muted`},z={key:3,class:`mt-1 text-sm text-danger`},B={class:`flex items-center justify-end space-x-3 pt-4 border-t`},V={__name:`Create`,props:{fields:Array,title:String},setup(V){let H=V,U={};H.fields.forEach(e=>{U[e.name]=e.default??``});let W=d(U),G=()=>{W.post(route(`admin.users.store`))},K=e=>[`text`,`email`,`password`,`checkbox`].includes(e.type);return(d,H)=>(r(),o(y,{title:V.title},{default:c(()=>[v(`div`,C,[v(`nav`,w,[v(`ol`,T,[v(`li`,E,[t(l(m),{href:d.route(`admin.users.index`),class:`text-muted hover:text-accent`},{default:c(()=>[s(p(d.$t(`menu.administrators`)),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,D,[H[0]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,O,p(d.$t(`account.users.creating`)),1)])])])])]),v(`div`,k,[v(`h1`,A,p(V.title),1),t(x,null,{default:c(()=>[v(`form`,{onSubmit:u(G,[`prevent`]),class:`space-y-6`},[(r(!0),_(g,null,a(V.fields,t=>(r(),_(g,{key:t.name},[K(t)?(r(),_(`div`,j,[t.type===`checkbox`?(r(),_(`div`,M,[n(v(`input`,{id:t.name,"onUpdate:modelValue":e=>l(W)[t.name]=e,type:`checkbox`,class:`h-4 w-4 text-accent focus:ring-focus border-field rounded`},null,8,N),[[h,l(W)[t.name]]]),v(`label`,{for:t.name,class:`ml-2 text-sm text-fg`},p(t.label),9,P)])):(r(),_(g,{key:1},[v(`label`,{for:t.name,class:`block text-sm font-medium text-fg mb-1`},[s(p(t.label)+` `,1),t.required?(r(),_(`span`,I,`*`)):e(``,!0)],8,F),n(v(`input`,{id:t.name,"onUpdate:modelValue":e=>l(W)[t.name]=e,type:t.type===`password`?`password`:t.type===`email`?`email`:`text`,placeholder:t.placeholder,required:t.required,class:i([`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`,{"border-danger":l(W).errors[t.name]}])},null,10,L),[[f,l(W)[t.name]]])],64)),t.hint?(r(),_(`p`,R,p(t.hint),1)):e(``,!0),l(W).errors[t.name]?(r(),_(`p`,z,p(l(W).errors[t.name]),1)):e(``,!0)])):(r(),o(S,{key:0,field:t,modelValue:l(W)[t.name],"onUpdate:modelValue":e=>l(W)[t.name]=e,errors:l(W).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))],64))),128)),v(`div`,B,[t(b,{href:d.route(`admin.users.index`),variant:`secondary`},{default:c(()=>[s(p(d.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(b,{"data-action":`save`,type:`submit`,loading:l(W).processing},{default:c(()=>[s(p(d.$t(`common.create`)),1)]),_:1},8,[`loading`])])],32)]),_:1})])]),_:1},8,[`title`]))}};export{V as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Dashboard-BpfYcZ3c.js b/packages/admin/dist/assets/Dashboard-BU7gtvAo.js similarity index 98% rename from packages/admin/dist/assets/Dashboard-BpfYcZ3c.js rename to packages/admin/dist/assets/Dashboard-BU7gtvAo.js index 5c9f7882..21369017 100644 --- a/packages/admin/dist/assets/Dashboard-BpfYcZ3c.js +++ b/packages/admin/dist/assets/Dashboard-BU7gtvAo.js @@ -1 +1 @@ -import{$ as e,C as t,I as n,Q as r,R as i,S as a,T as o,V as s,W as c,Y as l,b as u,et as d,v as f,w as p,x as m}from"./dist-MY__znoP.js";import{t as h}from"./AdminLayout-I1QMPYpW.js";var g={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`site-speed`},_={class:`text-sm font-semibold text-fg`},v={class:`mt-3 flex items-baseline gap-2`},y={class:`text-3xl font-semibold text-fg tabular-nums`},b={class:`text-sm text-muted`},x={class:`mt-4`},S={class:`relative h-2 rounded-full bg-off overflow-hidden`},C={class:`mt-1.5 grid grid-cols-5 gap-1 text-xs text-muted`},w={class:`mt-1 flex justify-between text-xs text-muted tabular-nums`},T={class:`mt-3 text-xs text-muted`},E={__name:`SiteSpeedGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(a){let s=a,c=u(()=>s.data.bands.indexOf(s.data.label));return(s,l)=>(n(),p(`div`,g,[m(`h2`,_,d(a.title||s.$t(`dashboard.site_speed.title`)),1),m(`div`,v,[a.data.seconds?(n(),p(f,{key:0},[m(`span`,y,d(a.data.seconds),1),m(`span`,b,d(a.data.unit),1)],64)):t(``,!0),m(`span`,{class:r([`text-sm font-medium text-fg`,{"ml-2":a.data.seconds}]),"data-speed-band":``},d(a.data.label),3)]),m(`div`,x,[m(`div`,S,[a.data.percent===null?t(``,!0):(n(),p(`div`,{key:0,class:`absolute inset-y-0 left-0 bg-accent`,style:e({width:a.data.percent+`%`})},null,4)),(n(),p(f,null,i([20,40,60,80],t=>m(`span`,{key:t,class:`absolute inset-y-0 w-0.5 bg-surface`,style:e({left:t+`%`})},null,4)),64))]),m(`div`,C,[(n(!0),p(f,null,i(a.data.bands,(e,t)=>(n(),p(`span`,{key:e,class:r([`text-center leading-tight`,{"font-semibold text-fg":t===c.value}])},d(e),3))),128))]),m(`div`,w,[l[0]||=m(`span`,null,`0`,-1),m(`span`,null,d(a.data.scaleSeconds)+` `+d(a.data.unit),1)])]),m(`p`,T,[a.data.samples?(n(),p(f,{key:0},[o(d(s.$t(`dashboard.site_speed.samples_note`,{samples:a.data.samples,days:a.data.windowDays})),1)],64)):(n(),p(f,{key:1},[o(d(s.$t(`dashboard.site_speed.no_samples`)),1)],64))])]))}},D={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`performance`},O={class:`flex items-start justify-between gap-4`},k={class:`text-sm font-semibold text-fg`},A=[`aria-expanded`],j={key:0,class:`mt-3`},M={class:`flex items-baseline gap-2`},N={class:`text-3xl font-semibold text-fg tabular-nums`},P={class:`text-sm text-muted`},F={class:`text-xs text-muted`},ee={key:1,class:`mt-3 text-sm text-muted`},I={key:2,class:`mt-3 text-xs text-muted`},L={key:3,class:`mt-3 border-t border-line pt-3`,"data-performance-details":``},R={class:`text-xs font-semibold text-fg`},z={class:`mt-1 divide-y divide-line text-sm`},B=[`title`],V={class:`whitespace-nowrap text-muted tabular-nums`},H={__name:`PerformanceGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(e){let r=l(!1);return(a,o)=>(n(),p(`div`,D,[m(`div`,O,[m(`h2`,k,d(e.title||a.$t(`dashboard.performance.title`)),1),e.data.slowest.length?(n(),p(`button`,{key:0,type:`button`,class:`rounded-md border border-field bg-surface px-3 py-1 text-sm text-fg hover:bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,"aria-expanded":r.value?`true`:`false`,"data-action":`performance-details`,onClick:o[0]||=e=>r.value=!r.value},d(r.value?a.$t(`dashboard.performance.collapse`):a.$t(`dashboard.performance.details`)),9,A)):t(``,!0)]),e.data.rate?(n(),p(`div`,j,[m(`div`,M,[m(`span`,N,d(e.data.rate),1),m(`span`,P,d(e.data.unit),1)]),m(`div`,F,d(e.data.caption),1)])):(n(),p(`p`,ee,d(a.$t(`dashboard.performance.pending`)),1)),e.data.rate?(n(),p(`p`,I,d(a.$t(`dashboard.performance.note`,{seconds:e.data.averageSeconds,pages:e.data.samples,days:e.data.windowDays})),1)):t(``,!0),r.value?(n(),p(`div`,L,[m(`h3`,R,d(a.$t(`dashboard.performance.slowest_title`)),1),m(`ul`,z,[(n(!0),p(f,null,i(e.data.slowest,e=>(n(),p(`li`,{key:e.path,class:`flex justify-between gap-3 py-1.5`},[m(`span`,{class:`truncate text-fg`,title:e.path},d(e.path),9,B),m(`span`,V,d(a.$t(`dashboard.performance.slowest_row`,{ms:e.ms,hits:e.hits})),1)]))),128))])])):t(``,!0)]))}},U={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`recent`},W={class:`text-sm font-semibold text-fg`},G={key:0,class:`mt-3 divide-y divide-line`},K=[`src`],q={key:1,class:`h-12 w-12 flex-none rounded bg-off`},J={class:`min-w-0`},Y={key:0,class:`text-xs text-muted`},X=[`href`],Z={key:2,class:`text-sm text-fg line-clamp-2`},Q={key:1,class:`mt-3 text-sm text-muted`},$=[`href`],te={__name:`RecentElementsGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(e){return(r,a)=>(n(),p(`div`,U,[m(`h2`,W,d(e.title||r.$t(`dashboard.recent.title`)),1),e.data.items.length?(n(),p(`ul`,G,[(n(!0),p(f,null,i(e.data.items,e=>(n(),p(`li`,{key:e.id,class:`flex gap-3 py-2`},[e.image?(n(),p(`img`,{key:0,src:e.image,alt:``,class:`h-12 w-12 flex-none rounded object-cover bg-off`},null,8,K)):(n(),p(`div`,q)),m(`div`,J,[e.date?(n(),p(`div`,Y,d(e.date),1)):t(``,!0),e.url?(n(),p(`a`,{key:1,href:e.url,class:`text-sm text-accent hover:underline line-clamp-2`},d(e.name),9,X)):(n(),p(`span`,Z,d(e.name),1))])]))),128))])):(n(),p(`p`,Q,d(r.$t(`dashboard.recent.empty`)),1)),e.data.allUrl?(n(),p(`a`,{key:2,href:e.data.allUrl,class:`mt-3 inline-block text-sm text-accent hover:underline`},d(e.data.allLabel),9,$)):t(``,!0)]))}},ne={class:`mb-6`},re={class:`text-2xl font-bold text-fg`},ie={class:`grid grid-cols-1 gap-6 lg:grid-cols-2`},ae={__name:`Dashboard`,props:{gadgets:{type:Array,default:()=>[]}},setup(e){let t={SiteSpeedGadget:E,PerformanceGadget:H,RecentElementsGadget:te},o=e,l=u(()=>o.gadgets.filter(e=>t[e.component]));return(e,o)=>(n(),a(h,{title:e.$t(`dashboard.title`)},{default:c(()=>[m(`div`,ne,[m(`h1`,re,d(e.$t(`dashboard.title`)),1)]),m(`div`,ie,[(n(!0),p(f,null,i(l.value,e=>(n(),a(s(t[e.component]),{key:e.key,title:e.title,data:e.data,class:r(e.width===`full`?`lg:col-span-2`:``)},null,8,[`title`,`data`,`class`]))),128))])]),_:1},8,[`title`]))}};export{ae as default}; \ No newline at end of file +import{$ as e,C as t,I as n,Q as r,R as i,S as a,T as o,V as s,W as c,Y as l,b as u,et as d,v as f,w as p,x as m}from"./dist-MY__znoP.js";import{t as h}from"./AdminLayout--RXJFj9t.js";var g={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`site-speed`},_={class:`text-sm font-semibold text-fg`},v={class:`mt-3 flex items-baseline gap-2`},y={class:`text-3xl font-semibold text-fg tabular-nums`},b={class:`text-sm text-muted`},x={class:`mt-4`},S={class:`relative h-2 rounded-full bg-off overflow-hidden`},C={class:`mt-1.5 grid grid-cols-5 gap-1 text-xs text-muted`},w={class:`mt-1 flex justify-between text-xs text-muted tabular-nums`},T={class:`mt-3 text-xs text-muted`},E={__name:`SiteSpeedGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(a){let s=a,c=u(()=>s.data.bands.indexOf(s.data.label));return(s,l)=>(n(),p(`div`,g,[m(`h2`,_,d(a.title||s.$t(`dashboard.site_speed.title`)),1),m(`div`,v,[a.data.seconds?(n(),p(f,{key:0},[m(`span`,y,d(a.data.seconds),1),m(`span`,b,d(a.data.unit),1)],64)):t(``,!0),m(`span`,{class:r([`text-sm font-medium text-fg`,{"ml-2":a.data.seconds}]),"data-speed-band":``},d(a.data.label),3)]),m(`div`,x,[m(`div`,S,[a.data.percent===null?t(``,!0):(n(),p(`div`,{key:0,class:`absolute inset-y-0 left-0 bg-accent`,style:e({width:a.data.percent+`%`})},null,4)),(n(),p(f,null,i([20,40,60,80],t=>m(`span`,{key:t,class:`absolute inset-y-0 w-0.5 bg-surface`,style:e({left:t+`%`})},null,4)),64))]),m(`div`,C,[(n(!0),p(f,null,i(a.data.bands,(e,t)=>(n(),p(`span`,{key:e,class:r([`text-center leading-tight`,{"font-semibold text-fg":t===c.value}])},d(e),3))),128))]),m(`div`,w,[l[0]||=m(`span`,null,`0`,-1),m(`span`,null,d(a.data.scaleSeconds)+` `+d(a.data.unit),1)])]),m(`p`,T,[a.data.samples?(n(),p(f,{key:0},[o(d(s.$t(`dashboard.site_speed.samples_note`,{samples:a.data.samples,days:a.data.windowDays})),1)],64)):(n(),p(f,{key:1},[o(d(s.$t(`dashboard.site_speed.no_samples`)),1)],64))])]))}},D={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`performance`},O={class:`flex items-start justify-between gap-4`},k={class:`text-sm font-semibold text-fg`},A=[`aria-expanded`],j={key:0,class:`mt-3`},M={class:`flex items-baseline gap-2`},N={class:`text-3xl font-semibold text-fg tabular-nums`},P={class:`text-sm text-muted`},F={class:`text-xs text-muted`},ee={key:1,class:`mt-3 text-sm text-muted`},I={key:2,class:`mt-3 text-xs text-muted`},L={key:3,class:`mt-3 border-t border-line pt-3`,"data-performance-details":``},R={class:`text-xs font-semibold text-fg`},z={class:`mt-1 divide-y divide-line text-sm`},B=[`title`],V={class:`whitespace-nowrap text-muted tabular-nums`},H={__name:`PerformanceGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(e){let r=l(!1);return(a,o)=>(n(),p(`div`,D,[m(`div`,O,[m(`h2`,k,d(e.title||a.$t(`dashboard.performance.title`)),1),e.data.slowest.length?(n(),p(`button`,{key:0,type:`button`,class:`rounded-md border border-field bg-surface px-3 py-1 text-sm text-fg hover:bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-focus`,"aria-expanded":r.value?`true`:`false`,"data-action":`performance-details`,onClick:o[0]||=e=>r.value=!r.value},d(r.value?a.$t(`dashboard.performance.collapse`):a.$t(`dashboard.performance.details`)),9,A)):t(``,!0)]),e.data.rate?(n(),p(`div`,j,[m(`div`,M,[m(`span`,N,d(e.data.rate),1),m(`span`,P,d(e.data.unit),1)]),m(`div`,F,d(e.data.caption),1)])):(n(),p(`p`,ee,d(a.$t(`dashboard.performance.pending`)),1)),e.data.rate?(n(),p(`p`,I,d(a.$t(`dashboard.performance.note`,{seconds:e.data.averageSeconds,pages:e.data.samples,days:e.data.windowDays})),1)):t(``,!0),r.value?(n(),p(`div`,L,[m(`h3`,R,d(a.$t(`dashboard.performance.slowest_title`)),1),m(`ul`,z,[(n(!0),p(f,null,i(e.data.slowest,e=>(n(),p(`li`,{key:e.path,class:`flex justify-between gap-3 py-1.5`},[m(`span`,{class:`truncate text-fg`,title:e.path},d(e.path),9,B),m(`span`,V,d(a.$t(`dashboard.performance.slowest_row`,{ms:e.ms,hits:e.hits})),1)]))),128))])])):t(``,!0)]))}},U={class:`bg-surface rounded-lg shadow px-5 py-4`,"data-gadget":`recent`},W={class:`text-sm font-semibold text-fg`},G={key:0,class:`mt-3 divide-y divide-line`},K=[`src`],q={key:1,class:`h-12 w-12 flex-none rounded bg-off`},J={class:`min-w-0`},Y={key:0,class:`text-xs text-muted`},X=[`href`],Z={key:2,class:`text-sm text-fg line-clamp-2`},Q={key:1,class:`mt-3 text-sm text-muted`},$=[`href`],te={__name:`RecentElementsGadget`,props:{title:{type:String,default:``},data:{type:Object,required:!0}},setup(e){return(r,a)=>(n(),p(`div`,U,[m(`h2`,W,d(e.title||r.$t(`dashboard.recent.title`)),1),e.data.items.length?(n(),p(`ul`,G,[(n(!0),p(f,null,i(e.data.items,e=>(n(),p(`li`,{key:e.id,class:`flex gap-3 py-2`},[e.image?(n(),p(`img`,{key:0,src:e.image,alt:``,class:`h-12 w-12 flex-none rounded object-cover bg-off`},null,8,K)):(n(),p(`div`,q)),m(`div`,J,[e.date?(n(),p(`div`,Y,d(e.date),1)):t(``,!0),e.url?(n(),p(`a`,{key:1,href:e.url,class:`text-sm text-accent hover:underline line-clamp-2`},d(e.name),9,X)):(n(),p(`span`,Z,d(e.name),1))])]))),128))])):(n(),p(`p`,Q,d(r.$t(`dashboard.recent.empty`)),1)),e.data.allUrl?(n(),p(`a`,{key:2,href:e.data.allUrl,class:`mt-3 inline-block text-sm text-accent hover:underline`},d(e.data.allLabel),9,$)):t(``,!0)]))}},ne={class:`mb-6`},re={class:`text-2xl font-bold text-fg`},ie={class:`grid grid-cols-1 gap-6 lg:grid-cols-2`},ae={__name:`Dashboard`,props:{gadgets:{type:Array,default:()=>[]}},setup(e){let t={SiteSpeedGadget:E,PerformanceGadget:H,RecentElementsGadget:te},o=e,l=u(()=>o.gadgets.filter(e=>t[e.component]));return(e,o)=>(n(),a(h,{title:e.$t(`dashboard.title`)},{default:c(()=>[m(`div`,ne,[m(`h1`,re,d(e.$t(`dashboard.title`)),1)]),m(`div`,ie,[(n(!0),p(f,null,i(l.value,e=>(n(),a(s(t[e.component]),{key:e.key,title:e.title,data:e.data,class:r(e.width===`full`?`lg:col-span-2`:``)},null,8,[`title`,`data`,`class`]))),128))])]),_:1},8,[`title`]))}};export{ae as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Edit-DKlRxfoE.js b/packages/admin/dist/assets/Edit-CHndUQJ2.js similarity index 97% rename from packages/admin/dist/assets/Edit-DKlRxfoE.js rename to packages/admin/dist/assets/Edit-CHndUQJ2.js index 5ff29b4e..42835efe 100644 --- a/packages/admin/dist/assets/Edit-DKlRxfoE.js +++ b/packages/admin/dist/assets/Edit-CHndUQJ2.js @@ -1 +1 @@ -import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as u,a as d,b as f,et as p,i as m,q as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout-I1QMPYpW.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{n as S,r as C,t as w}from"./ContentLocaleSwitcher-BJIieXK-.js";import{t as T}from"./FormField-BI8KmQxQ.js";import{n as E,r as ee,t as D}from"./contentLocale-BtGD-iBF.js";import{t as O}from"./recordActions-CtRs42tG.js";var k={class:`mb-6`},A={class:`flex`,"aria-label":`Breadcrumb`},j={class:`inline-flex items-center space-x-1 md:space-x-3`},M={class:`inline-flex items-center`},N={class:`flex items-center`},P={class:`ml-1 text-muted`},F={class:`max-w-4xl`},I={class:`mb-6 flex flex-wrap items-center justify-between gap-4`},L={class:`text-2xl font-bold text-fg`},R={key:0,class:`flex gap-2`},z={key:0,"data-read-only":``,class:`mb-6 rounded-md border border-field bg-surface-alt px-4 py-3 text-sm text-fg`},B=[`data-resource`,`data-item-id`],V=[`disabled`],H={class:`space-y-6`},te={key:0,class:`text-center py-12 text-muted`},U={key:2,class:`space-y-6`},W={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},G={__name:`Edit`,props:{routeName:String,createLabel:String,item:Object,itemTitle:String,fields:Array,fieldsByTab:Object,tabs:Array,useTabs:Boolean,title:String,adminLabel:String,can:{type:Object,default:()=>({})},actions:{type:Array,default:()=>[]}},setup(G){let K=G,q=f(()=>K.can.update===!1),J=c(K.tabs?.[0]?.name||`main`),Y={};K.useTabs&&K.fieldsByTab?Object.values(K.fieldsByTab).flat().forEach(e=>{Y[e.name]=E(e,K.item[e.name])}):K.fields.forEach(e=>{Y[e.name]=E(e,K.item[e.name])});let X=d(Y),Z=()=>(K.useTabs&&K.fieldsByTab?Object.values(K.fieldsByTab).flat():K.fields)||[],{locale:Q,locales:ne,showSwitcher:re}=ee(Z),ie=f(()=>({...K.item,...X.data()}));r(`formData`,ie),r(`aiModule`,K.routeName?.replace(/^admin\./,``)||null);let ae=()=>{X.submit(`put`,route(`${K.routeName}.update`,K.item.id))},$=e=>K.fieldsByTab?.[e]?K.fieldsByTab[e].filter(e=>D(X.errors,e)).length:0,oe=f(()=>K.tabs?K.tabs.map(e=>({...e,badge:$(e.name)>0?String($(e.name)):null})):[]);return(r,c)=>(n(),a(y,{title:G.title},{default:s(()=>[v(`div`,k,[v(`nav`,A,[v(`ol`,j,[v(`li`,M,[t(l(m),{href:r.route(`${K.routeName}.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(p(G.adminLabel),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,N,[c[2]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,P,p(G.itemTitle||`#`+G.item.id),1)])])])])]),v(`div`,F,[v(`div`,I,[v(`h1`,L,p(G.title),1),G.actions.length?(n(),_(`div`,R,[(n(!0),_(g,null,i(G.actions,e=>(n(),a(b,{key:e.name,"data-action":e.name,variant:`secondary`,href:l(O)(G.routeName,e,G.item)},{default:s(()=>[o(p(e.label),1)]),_:2},1032,[`data-action`,`href`]))),128))])):e(``,!0)]),t(x,null,{default:s(()=>[q.value?(n(),_(`p`,z,p(r.$t(`resource.form.read_only`)),1)):e(``,!0),v(`form`,{onSubmit:u(ae,[`prevent`]),"data-admin-form":`true`,"data-resource":G.routeName,"data-context":`edit`,"data-item-id":G.item.id},[v(`fieldset`,{disabled:q.value,class:`contents`},[l(re)?(n(),a(w,{key:0,modelValue:l(Q),"onUpdate:modelValue":c[0]||=e=>h(Q)?Q.value=e:null,locales:l(ne),fields:Z(),errors:l(X).errors},null,8,[`modelValue`,`locales`,`fields`,`errors`])):e(``,!0),G.useTabs&&G.tabs&&G.fieldsByTab?(n(),a(C,{key:1,tabs:oe.value,modelValue:J.value,"onUpdate:modelValue":c[1]||=e=>J.value=e},{default:s(({activeTab:t})=>[(n(!0),_(g,null,i(G.tabs,o=>(n(),a(S,{key:o.name,name:o.name,activeTab:t},{default:s(()=>[v(`div`,H,[(n(!0),_(g,null,i(G.fieldsByTab[o.name],e=>(n(),a(T,{key:e.name,field:e,modelValue:l(X)[e.name],"onUpdate:modelValue":t=>l(X)[e.name]=t,errors:l(X).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128)),G.fieldsByTab[o.name]?.length?e(``,!0):(n(),_(`div`,te,[v(`p`,null,p(r.$t(`resource.form.empty_tab`)),1)]))])]),_:2},1032,[`name`,`activeTab`]))),128))]),_:1},8,[`tabs`,`modelValue`])):(n(),_(`div`,U,[(n(!0),_(g,null,i(G.fields,e=>(n(),a(T,{key:e.name,field:e,modelValue:l(X)[e.name],"onUpdate:modelValue":t=>l(X)[e.name]=t,errors:l(X).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))]))],8,V),v(`div`,W,[t(b,{"data-action":`cancel`,href:r.route(`${K.routeName}.index`),variant:`secondary`},{default:s(()=>[o(p(q.value?r.$t(`common.back`):r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),q.value?e(``,!0):(n(),a(b,{key:0,"data-action":`save`,type:`submit`,loading:l(X).processing},{default:s(()=>[o(p(r.$t(`common.save`)),1)]),_:1},8,[`loading`]))])],40,B)]),_:1})])]),_:1},8,[`title`]))}};export{G as default}; \ No newline at end of file +import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as u,a as d,b as f,et as p,i as m,q as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{t as y}from"./AdminLayout--RXJFj9t.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{n as S,r as C,t as w}from"./ContentLocaleSwitcher-BJIieXK-.js";import{t as T}from"./FormField-xD6LELDV.js";import{n as E,r as ee,t as D}from"./contentLocale-BtGD-iBF.js";import{t as O}from"./recordActions-CtRs42tG.js";var k={class:`mb-6`},A={class:`flex`,"aria-label":`Breadcrumb`},j={class:`inline-flex items-center space-x-1 md:space-x-3`},M={class:`inline-flex items-center`},N={class:`flex items-center`},P={class:`ml-1 text-muted`},F={class:`max-w-4xl`},I={class:`mb-6 flex flex-wrap items-center justify-between gap-4`},L={class:`text-2xl font-bold text-fg`},R={key:0,class:`flex gap-2`},z={key:0,"data-read-only":``,class:`mb-6 rounded-md border border-field bg-surface-alt px-4 py-3 text-sm text-fg`},B=[`data-resource`,`data-item-id`],V=[`disabled`],H={class:`space-y-6`},te={key:0,class:`text-center py-12 text-muted`},U={key:2,class:`space-y-6`},W={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},G={__name:`Edit`,props:{routeName:String,createLabel:String,item:Object,itemTitle:String,fields:Array,fieldsByTab:Object,tabs:Array,useTabs:Boolean,title:String,adminLabel:String,can:{type:Object,default:()=>({})},actions:{type:Array,default:()=>[]}},setup(G){let K=G,q=f(()=>K.can.update===!1),J=c(K.tabs?.[0]?.name||`main`),Y={};K.useTabs&&K.fieldsByTab?Object.values(K.fieldsByTab).flat().forEach(e=>{Y[e.name]=E(e,K.item[e.name])}):K.fields.forEach(e=>{Y[e.name]=E(e,K.item[e.name])});let X=d(Y),Z=()=>(K.useTabs&&K.fieldsByTab?Object.values(K.fieldsByTab).flat():K.fields)||[],{locale:Q,locales:ne,showSwitcher:re}=ee(Z),ie=f(()=>({...K.item,...X.data()}));r(`formData`,ie),r(`aiModule`,K.routeName?.replace(/^admin\./,``)||null);let ae=()=>{X.submit(`put`,route(`${K.routeName}.update`,K.item.id))},$=e=>K.fieldsByTab?.[e]?K.fieldsByTab[e].filter(e=>D(X.errors,e)).length:0,oe=f(()=>K.tabs?K.tabs.map(e=>({...e,badge:$(e.name)>0?String($(e.name)):null})):[]);return(r,c)=>(n(),a(y,{title:G.title},{default:s(()=>[v(`div`,k,[v(`nav`,A,[v(`ol`,j,[v(`li`,M,[t(l(m),{href:r.route(`${K.routeName}.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(p(G.adminLabel),1)]),_:1},8,[`href`])]),v(`li`,null,[v(`div`,N,[c[2]||=v(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[v(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),v(`span`,P,p(G.itemTitle||`#`+G.item.id),1)])])])])]),v(`div`,F,[v(`div`,I,[v(`h1`,L,p(G.title),1),G.actions.length?(n(),_(`div`,R,[(n(!0),_(g,null,i(G.actions,e=>(n(),a(b,{key:e.name,"data-action":e.name,variant:`secondary`,href:l(O)(G.routeName,e,G.item)},{default:s(()=>[o(p(e.label),1)]),_:2},1032,[`data-action`,`href`]))),128))])):e(``,!0)]),t(x,null,{default:s(()=>[q.value?(n(),_(`p`,z,p(r.$t(`resource.form.read_only`)),1)):e(``,!0),v(`form`,{onSubmit:u(ae,[`prevent`]),"data-admin-form":`true`,"data-resource":G.routeName,"data-context":`edit`,"data-item-id":G.item.id},[v(`fieldset`,{disabled:q.value,class:`contents`},[l(re)?(n(),a(w,{key:0,modelValue:l(Q),"onUpdate:modelValue":c[0]||=e=>h(Q)?Q.value=e:null,locales:l(ne),fields:Z(),errors:l(X).errors},null,8,[`modelValue`,`locales`,`fields`,`errors`])):e(``,!0),G.useTabs&&G.tabs&&G.fieldsByTab?(n(),a(C,{key:1,tabs:oe.value,modelValue:J.value,"onUpdate:modelValue":c[1]||=e=>J.value=e},{default:s(({activeTab:t})=>[(n(!0),_(g,null,i(G.tabs,o=>(n(),a(S,{key:o.name,name:o.name,activeTab:t},{default:s(()=>[v(`div`,H,[(n(!0),_(g,null,i(G.fieldsByTab[o.name],e=>(n(),a(T,{key:e.name,field:e,modelValue:l(X)[e.name],"onUpdate:modelValue":t=>l(X)[e.name]=t,errors:l(X).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128)),G.fieldsByTab[o.name]?.length?e(``,!0):(n(),_(`div`,te,[v(`p`,null,p(r.$t(`resource.form.empty_tab`)),1)]))])]),_:2},1032,[`name`,`activeTab`]))),128))]),_:1},8,[`tabs`,`modelValue`])):(n(),_(`div`,U,[(n(!0),_(g,null,i(G.fields,e=>(n(),a(T,{key:e.name,field:e,modelValue:l(X)[e.name],"onUpdate:modelValue":t=>l(X)[e.name]=t,errors:l(X).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))]))],8,V),v(`div`,W,[t(b,{"data-action":`cancel`,href:r.route(`${K.routeName}.index`),variant:`secondary`},{default:s(()=>[o(p(q.value?r.$t(`common.back`):r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),q.value?e(``,!0):(n(),a(b,{key:0,"data-action":`save`,type:`submit`,loading:l(X).processing},{default:s(()=>[o(p(r.$t(`common.save`)),1)]),_:1},8,[`loading`]))])],40,B)]),_:1})])]),_:1},8,[`title`]))}};export{G as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Edit-D7McI_eD.js b/packages/admin/dist/assets/Edit-D-yhP5A2.js similarity index 98% rename from packages/admin/dist/assets/Edit-D7McI_eD.js rename to packages/admin/dist/assets/Edit-D-yhP5A2.js index 88bba40f..1a7d4f85 100644 --- a/packages/admin/dist/assets/Edit-D7McI_eD.js +++ b/packages/admin/dist/assets/Edit-D-yhP5A2.js @@ -1 +1 @@ -import{C as e,G as t,I as n,Q as r,S as i,W as a,Z as o,_ as s,a as c,et as l,m as u,w as d,x as f}from"./dist-MY__znoP.js";import{t as p}from"./AdminLayout-I1QMPYpW.js";var m={class:`mb-8`},h={class:`text-2xl font-bold text-fg`},g={class:`mt-1 text-sm text-muted`},_={class:`max-w-2xl space-y-6`},v={class:`bg-surface rounded-lg shadow`},y={class:`p-6 border-b border-line`},b={class:`text-lg font-medium text-fg`},x={class:`mt-1 text-sm text-muted`},S={for:`name`,class:`block text-sm font-medium text-fg`},C={key:0,class:`mt-1 text-sm text-danger`},w={for:`email`,class:`block text-sm font-medium text-fg`},T={key:0,class:`mt-1 text-sm text-danger`},E={class:`flex justify-end`},D=[`disabled`],O={class:`bg-surface rounded-lg shadow`},k={class:`p-6 border-b border-line`},A={class:`text-lg font-medium text-fg`},j={class:`mt-1 text-sm text-muted`},M={for:`current_password`,class:`block text-sm font-medium text-fg`},N={key:0,class:`mt-1 text-sm text-danger`},P={for:`password`,class:`block text-sm font-medium text-fg`},F={key:0,class:`mt-1 text-sm text-danger`},I={for:`password_confirmation`,class:`block text-sm font-medium text-fg`},L={class:`flex justify-end`},R=[`disabled`],z={__name:`Edit`,props:{user:{type:Object,required:!0}},setup(z){let B=z,V=c({name:B.user.name,email:B.user.email}),H=c({current_password:``,password:``,password_confirmation:``}),U=()=>{V.put(route(`admin.profile.update`),{preserveScroll:!0})},W=()=>{H.put(route(`admin.profile.password`),{preserveScroll:!0,onSuccess:()=>H.reset()})};return(c,z)=>(n(),i(p,{title:c.$t(`account.profile.title`)},{default:a(()=>[f(`div`,m,[f(`h1`,h,l(c.$t(`account.profile.title`)),1),f(`p`,g,l(c.$t(`account.profile.subtitle`)),1)]),f(`div`,_,[f(`div`,v,[f(`div`,y,[f(`h2`,b,l(c.$t(`account.profile.info_title`)),1),f(`p`,x,l(c.$t(`account.profile.info_subtitle`)),1)]),f(`form`,{onSubmit:s(U,[`prevent`]),class:`p-6 space-y-4`},[f(`div`,null,[f(`label`,S,l(c.$t(`account.profile.name`)),1),t(f(`input`,{id:`name`,"onUpdate:modelValue":z[0]||=e=>o(V).name=e,type:`text`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(V).errors.name}])},null,2),[[u,o(V).name]]),o(V).errors.name?(n(),d(`p`,C,l(o(V).errors.name),1)):e(``,!0)]),f(`div`,null,[f(`label`,w,l(c.$t(`account.profile.email`)),1),t(f(`input`,{id:`email`,"onUpdate:modelValue":z[1]||=e=>o(V).email=e,type:`email`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(V).errors.email}])},null,2),[[u,o(V).email]]),o(V).errors.email?(n(),d(`p`,T,l(o(V).errors.email),1)):e(``,!0)]),f(`div`,E,[f(`button`,{type:`submit`,disabled:o(V).processing,class:`px-4 py-2 bg-accent text-on-accent text-sm font-medium rounded-md hover:bg-accent-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-focus disabled:opacity-50`},l(o(V).processing?c.$t(`common.saving`):c.$t(`common.save`)),9,D)])],32)]),f(`div`,O,[f(`div`,k,[f(`h2`,A,l(c.$t(`account.profile.password_title`)),1),f(`p`,j,l(c.$t(`account.profile.password_subtitle`)),1)]),f(`form`,{onSubmit:s(W,[`prevent`]),class:`p-6 space-y-4`},[f(`div`,null,[f(`label`,M,l(c.$t(`account.profile.current_password`)),1),t(f(`input`,{id:`current_password`,"onUpdate:modelValue":z[2]||=e=>o(H).current_password=e,type:`password`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(H).errors.current_password}])},null,2),[[u,o(H).current_password]]),o(H).errors.current_password?(n(),d(`p`,N,l(o(H).errors.current_password),1)):e(``,!0)]),f(`div`,null,[f(`label`,P,l(c.$t(`account.profile.new_password`)),1),t(f(`input`,{id:`password`,"onUpdate:modelValue":z[3]||=e=>o(H).password=e,type:`password`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(H).errors.password}])},null,2),[[u,o(H).password]]),o(H).errors.password?(n(),d(`p`,F,l(o(H).errors.password),1)):e(``,!0)]),f(`div`,null,[f(`label`,I,l(c.$t(`account.profile.password_confirmation`)),1),t(f(`input`,{id:`password_confirmation`,"onUpdate:modelValue":z[4]||=e=>o(H).password_confirmation=e,type:`password`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,512),[[u,o(H).password_confirmation]])]),f(`div`,L,[f(`button`,{type:`submit`,disabled:o(H).processing,class:`px-4 py-2 bg-accent text-on-accent text-sm font-medium rounded-md hover:bg-accent-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-focus disabled:opacity-50`},l(o(H).processing?c.$t(`common.saving`):c.$t(`account.profile.change_password`)),9,R)])],32)])])]),_:1},8,[`title`]))}};export{z as default}; \ No newline at end of file +import{C as e,G as t,I as n,Q as r,S as i,W as a,Z as o,_ as s,a as c,et as l,m as u,w as d,x as f}from"./dist-MY__znoP.js";import{t as p}from"./AdminLayout--RXJFj9t.js";var m={class:`mb-8`},h={class:`text-2xl font-bold text-fg`},g={class:`mt-1 text-sm text-muted`},_={class:`max-w-2xl space-y-6`},v={class:`bg-surface rounded-lg shadow`},y={class:`p-6 border-b border-line`},b={class:`text-lg font-medium text-fg`},x={class:`mt-1 text-sm text-muted`},S={for:`name`,class:`block text-sm font-medium text-fg`},C={key:0,class:`mt-1 text-sm text-danger`},w={for:`email`,class:`block text-sm font-medium text-fg`},T={key:0,class:`mt-1 text-sm text-danger`},E={class:`flex justify-end`},D=[`disabled`],O={class:`bg-surface rounded-lg shadow`},k={class:`p-6 border-b border-line`},A={class:`text-lg font-medium text-fg`},j={class:`mt-1 text-sm text-muted`},M={for:`current_password`,class:`block text-sm font-medium text-fg`},N={key:0,class:`mt-1 text-sm text-danger`},P={for:`password`,class:`block text-sm font-medium text-fg`},F={key:0,class:`mt-1 text-sm text-danger`},I={for:`password_confirmation`,class:`block text-sm font-medium text-fg`},L={class:`flex justify-end`},R=[`disabled`],z={__name:`Edit`,props:{user:{type:Object,required:!0}},setup(z){let B=z,V=c({name:B.user.name,email:B.user.email}),H=c({current_password:``,password:``,password_confirmation:``}),U=()=>{V.put(route(`admin.profile.update`),{preserveScroll:!0})},W=()=>{H.put(route(`admin.profile.password`),{preserveScroll:!0,onSuccess:()=>H.reset()})};return(c,z)=>(n(),i(p,{title:c.$t(`account.profile.title`)},{default:a(()=>[f(`div`,m,[f(`h1`,h,l(c.$t(`account.profile.title`)),1),f(`p`,g,l(c.$t(`account.profile.subtitle`)),1)]),f(`div`,_,[f(`div`,v,[f(`div`,y,[f(`h2`,b,l(c.$t(`account.profile.info_title`)),1),f(`p`,x,l(c.$t(`account.profile.info_subtitle`)),1)]),f(`form`,{onSubmit:s(U,[`prevent`]),class:`p-6 space-y-4`},[f(`div`,null,[f(`label`,S,l(c.$t(`account.profile.name`)),1),t(f(`input`,{id:`name`,"onUpdate:modelValue":z[0]||=e=>o(V).name=e,type:`text`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(V).errors.name}])},null,2),[[u,o(V).name]]),o(V).errors.name?(n(),d(`p`,C,l(o(V).errors.name),1)):e(``,!0)]),f(`div`,null,[f(`label`,w,l(c.$t(`account.profile.email`)),1),t(f(`input`,{id:`email`,"onUpdate:modelValue":z[1]||=e=>o(V).email=e,type:`email`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(V).errors.email}])},null,2),[[u,o(V).email]]),o(V).errors.email?(n(),d(`p`,T,l(o(V).errors.email),1)):e(``,!0)]),f(`div`,E,[f(`button`,{type:`submit`,disabled:o(V).processing,class:`px-4 py-2 bg-accent text-on-accent text-sm font-medium rounded-md hover:bg-accent-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-focus disabled:opacity-50`},l(o(V).processing?c.$t(`common.saving`):c.$t(`common.save`)),9,D)])],32)]),f(`div`,O,[f(`div`,k,[f(`h2`,A,l(c.$t(`account.profile.password_title`)),1),f(`p`,j,l(c.$t(`account.profile.password_subtitle`)),1)]),f(`form`,{onSubmit:s(W,[`prevent`]),class:`p-6 space-y-4`},[f(`div`,null,[f(`label`,M,l(c.$t(`account.profile.current_password`)),1),t(f(`input`,{id:`current_password`,"onUpdate:modelValue":z[2]||=e=>o(H).current_password=e,type:`password`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(H).errors.current_password}])},null,2),[[u,o(H).current_password]]),o(H).errors.current_password?(n(),d(`p`,N,l(o(H).errors.current_password),1)):e(``,!0)]),f(`div`,null,[f(`label`,P,l(c.$t(`account.profile.new_password`)),1),t(f(`input`,{id:`password`,"onUpdate:modelValue":z[3]||=e=>o(H).password=e,type:`password`,class:r([`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`,{"border-danger":o(H).errors.password}])},null,2),[[u,o(H).password]]),o(H).errors.password?(n(),d(`p`,F,l(o(H).errors.password),1)):e(``,!0)]),f(`div`,null,[f(`label`,I,l(c.$t(`account.profile.password_confirmation`)),1),t(f(`input`,{id:`password_confirmation`,"onUpdate:modelValue":z[4]||=e=>o(H).password_confirmation=e,type:`password`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,512),[[u,o(H).password_confirmation]])]),f(`div`,L,[f(`button`,{type:`submit`,disabled:o(H).processing,class:`px-4 py-2 bg-accent text-on-accent text-sm font-medium rounded-md hover:bg-accent-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-focus disabled:opacity-50`},l(o(H).processing?c.$t(`common.saving`):c.$t(`account.profile.change_password`)),9,R)])],32)])])]),_:1},8,[`title`]))}};export{z as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Edit-BEiwW1oN.js b/packages/admin/dist/assets/Edit-DGjzU-uC.js similarity index 96% rename from packages/admin/dist/assets/Edit-BEiwW1oN.js rename to packages/admin/dist/assets/Edit-DGjzU-uC.js index dc750c8d..6ca4030c 100644 --- a/packages/admin/dist/assets/Edit-BEiwW1oN.js +++ b/packages/admin/dist/assets/Edit-DGjzU-uC.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,L as i,Q as a,R as o,S as s,T as c,W as l,Z as u,_ as d,a as f,b as p,d as m,et as h,i as g,u as _,v,w as y,x as b}from"./dist-MY__znoP.js";import{t as x}from"./AdminLayout-I1QMPYpW.js";import{t as S}from"./AdminButton-Bx141Bs3.js";import{t as C}from"./AdminCard--HubMtUj.js";import{t as w}from"./FormField-BI8KmQxQ.js";var T={class:`mb-6`},E={class:`flex`,"aria-label":`Breadcrumb`},D={class:`inline-flex items-center space-x-1 md:space-x-3`},O={class:`inline-flex items-center`},k={class:`flex items-center`},A={class:`ml-1 text-muted`},j={class:`max-w-2xl`},M={class:`text-2xl font-bold text-fg mb-6`},N={key:0,"data-read-only":``,class:`mb-6 rounded-md border border-field bg-surface-alt px-4 py-3 text-sm text-fg`},P=[`disabled`],F={key:1},I=[`for`],L={key:0,class:`text-danger`},R={key:0,class:`flex items-center`},z=[`id`,`onUpdate:modelValue`],B=[`for`],V=[`id`,`onUpdate:modelValue`,`type`,`placeholder`,`required`],H={key:2,class:`mt-1 text-sm text-muted`},U={key:3,class:`mt-1 text-sm text-muted`},W={key:4,class:`mt-1 text-sm text-danger`},G={class:`flex items-center justify-end space-x-3 pt-4 border-t`},K={__name:`Edit`,props:{item:Object,fields:Array,title:String,can:{type:Object,default:()=>({})}},setup(K){let q=K,J=e=>[`text`,`email`,`password`,`checkbox`].includes(e.type),Y=p(()=>q.can.update===!1),X={};q.fields.forEach(e=>{X[e.name]=q.item[e.name]??e.default??``}),X.password=``,X.password_confirmation=``;let Z=f(X),Q=p(()=>({...q.item,...Z.data()}));i(`formData`,Q);let $=()=>{Z.put(route(`admin.users.update`,q.item.id))};return(i,f)=>(r(),s(x,{title:K.title},{default:l(()=>[b(`div`,T,[b(`nav`,E,[b(`ol`,D,[b(`li`,O,[t(u(g),{href:i.route(`admin.users.index`),class:`text-muted hover:text-accent`},{default:l(()=>[c(h(i.$t(`menu.administrators`)),1)]),_:1},8,[`href`])]),b(`li`,null,[b(`div`,k,[f[0]||=b(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[b(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),b(`span`,A,h(K.item.name),1)])])])])]),b(`div`,j,[b(`h1`,M,h(K.title),1),t(C,null,{default:l(()=>[Y.value?(r(),y(`p`,N,h(i.$t(`resource.form.read_only`)),1)):e(``,!0),b(`form`,{onSubmit:d($,[`prevent`]),class:`space-y-6`},[b(`fieldset`,{disabled:Y.value,class:`space-y-6`},[(r(!0),y(v,null,o(K.fields,t=>(r(),y(v,{key:t.name},[J(t)?(r(),y(`div`,F,[b(`label`,{for:t.name,class:`block text-sm font-medium text-fg mb-1`},[c(h(t.label)+` `,1),t.required&&t.type!==`password`?(r(),y(`span`,L,`*`)):e(``,!0)],8,I),t.type===`checkbox`?(r(),y(`div`,R,[n(b(`input`,{id:t.name,"onUpdate:modelValue":e=>u(Z)[t.name]=e,type:`checkbox`,class:`h-4 w-4 text-accent focus:ring-focus border-field rounded`},null,8,z),[[_,u(Z)[t.name]]]),b(`label`,{for:t.name,class:`ml-2 text-sm text-fg`},h(t.label),9,B)])):n((r(),y(`input`,{key:1,id:t.name,"onUpdate:modelValue":e=>u(Z)[t.name]=e,type:t.type===`password`?`password`:t.type===`email`?`email`:`text`,placeholder:t.type===`password`?i.$t(`account.users.password_keep_placeholder`):t.placeholder,required:t.required&&t.type!==`password`,class:a([`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`,{"border-danger":u(Z).errors[t.name]}])},null,10,V)),[[m,u(Z)[t.name]]]),t.hint?(r(),y(`p`,H,h(t.hint),1)):e(``,!0),t.type===`password`&&t.name===`password`?(r(),y(`p`,U,h(i.$t(`account.users.password_keep_hint`)),1)):e(``,!0),u(Z).errors[t.name]?(r(),y(`p`,W,h(u(Z).errors[t.name]),1)):e(``,!0)])):(r(),s(w,{key:0,field:t,modelValue:u(Z)[t.name],"onUpdate:modelValue":e=>u(Z)[t.name]=e,errors:u(Z).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))],64))),128))],8,P),b(`div`,G,[t(S,{href:i.route(`admin.users.index`),variant:`secondary`},{default:l(()=>[c(h(Y.value?i.$t(`common.back`):i.$t(`common.cancel`)),1)]),_:1},8,[`href`]),Y.value?e(``,!0):(r(),s(S,{key:0,"data-action":`save`,type:`submit`,loading:u(Z).processing},{default:l(()=>[c(h(i.$t(`common.save`)),1)]),_:1},8,[`loading`]))])],32)]),_:1})])]),_:1},8,[`title`]))}};export{K as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,L as i,Q as a,R as o,S as s,T as c,W as l,Z as u,_ as d,a as f,b as p,d as m,et as h,i as g,u as _,v,w as y,x as b}from"./dist-MY__znoP.js";import{t as x}from"./AdminLayout--RXJFj9t.js";import{t as S}from"./AdminButton-Bx141Bs3.js";import{t as C}from"./AdminCard--HubMtUj.js";import{t as w}from"./FormField-xD6LELDV.js";var T={class:`mb-6`},E={class:`flex`,"aria-label":`Breadcrumb`},D={class:`inline-flex items-center space-x-1 md:space-x-3`},O={class:`inline-flex items-center`},k={class:`flex items-center`},A={class:`ml-1 text-muted`},j={class:`max-w-2xl`},M={class:`text-2xl font-bold text-fg mb-6`},N={key:0,"data-read-only":``,class:`mb-6 rounded-md border border-field bg-surface-alt px-4 py-3 text-sm text-fg`},P=[`disabled`],F={key:1},I=[`for`],L={key:0,class:`text-danger`},R={key:0,class:`flex items-center`},z=[`id`,`onUpdate:modelValue`],B=[`for`],V=[`id`,`onUpdate:modelValue`,`type`,`placeholder`,`required`],H={key:2,class:`mt-1 text-sm text-muted`},U={key:3,class:`mt-1 text-sm text-muted`},W={key:4,class:`mt-1 text-sm text-danger`},G={class:`flex items-center justify-end space-x-3 pt-4 border-t`},K={__name:`Edit`,props:{item:Object,fields:Array,title:String,can:{type:Object,default:()=>({})}},setup(K){let q=K,J=e=>[`text`,`email`,`password`,`checkbox`].includes(e.type),Y=p(()=>q.can.update===!1),X={};q.fields.forEach(e=>{X[e.name]=q.item[e.name]??e.default??``}),X.password=``,X.password_confirmation=``;let Z=f(X),Q=p(()=>({...q.item,...Z.data()}));i(`formData`,Q);let $=()=>{Z.put(route(`admin.users.update`,q.item.id))};return(i,f)=>(r(),s(x,{title:K.title},{default:l(()=>[b(`div`,T,[b(`nav`,E,[b(`ol`,D,[b(`li`,O,[t(u(g),{href:i.route(`admin.users.index`),class:`text-muted hover:text-accent`},{default:l(()=>[c(h(i.$t(`menu.administrators`)),1)]),_:1},8,[`href`])]),b(`li`,null,[b(`div`,k,[f[0]||=b(`svg`,{class:`w-4 h-4 text-muted`,fill:`currentColor`,viewBox:`0 0 20 20`},[b(`path`,{"fill-rule":`evenodd`,d:`M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z`,"clip-rule":`evenodd`})],-1),b(`span`,A,h(K.item.name),1)])])])])]),b(`div`,j,[b(`h1`,M,h(K.title),1),t(C,null,{default:l(()=>[Y.value?(r(),y(`p`,N,h(i.$t(`resource.form.read_only`)),1)):e(``,!0),b(`form`,{onSubmit:d($,[`prevent`]),class:`space-y-6`},[b(`fieldset`,{disabled:Y.value,class:`space-y-6`},[(r(!0),y(v,null,o(K.fields,t=>(r(),y(v,{key:t.name},[J(t)?(r(),y(`div`,F,[b(`label`,{for:t.name,class:`block text-sm font-medium text-fg mb-1`},[c(h(t.label)+` `,1),t.required&&t.type!==`password`?(r(),y(`span`,L,`*`)):e(``,!0)],8,I),t.type===`checkbox`?(r(),y(`div`,R,[n(b(`input`,{id:t.name,"onUpdate:modelValue":e=>u(Z)[t.name]=e,type:`checkbox`,class:`h-4 w-4 text-accent focus:ring-focus border-field rounded`},null,8,z),[[_,u(Z)[t.name]]]),b(`label`,{for:t.name,class:`ml-2 text-sm text-fg`},h(t.label),9,B)])):n((r(),y(`input`,{key:1,id:t.name,"onUpdate:modelValue":e=>u(Z)[t.name]=e,type:t.type===`password`?`password`:t.type===`email`?`email`:`text`,placeholder:t.type===`password`?i.$t(`account.users.password_keep_placeholder`):t.placeholder,required:t.required&&t.type!==`password`,class:a([`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`,{"border-danger":u(Z).errors[t.name]}])},null,10,V)),[[m,u(Z)[t.name]]]),t.hint?(r(),y(`p`,H,h(t.hint),1)):e(``,!0),t.type===`password`&&t.name===`password`?(r(),y(`p`,U,h(i.$t(`account.users.password_keep_hint`)),1)):e(``,!0),u(Z).errors[t.name]?(r(),y(`p`,W,h(u(Z).errors[t.name]),1)):e(``,!0)])):(r(),s(w,{key:0,field:t,modelValue:u(Z)[t.name],"onUpdate:modelValue":e=>u(Z)[t.name]=e,errors:u(Z).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))],64))),128))],8,P),b(`div`,G,[t(S,{href:i.route(`admin.users.index`),variant:`secondary`},{default:l(()=>[c(h(Y.value?i.$t(`common.back`):i.$t(`common.cancel`)),1)]),_:1},8,[`href`]),Y.value?e(``,!0):(r(),s(S,{key:0,"data-action":`save`,type:`submit`,loading:u(Z).processing},{default:l(()=>[c(h(i.$t(`common.save`)),1)]),_:1},8,[`loading`]))])],32)]),_:1})])]),_:1},8,[`title`]))}};export{K as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Edit-ppjiZjeT.js b/packages/admin/dist/assets/Edit-pGNJhUsL.js similarity index 95% rename from packages/admin/dist/assets/Edit-ppjiZjeT.js rename to packages/admin/dist/assets/Edit-pGNJhUsL.js index 4dcde530..3dce9a7b 100644 --- a/packages/admin/dist/assets/Edit-ppjiZjeT.js +++ b/packages/admin/dist/assets/Edit-pGNJhUsL.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Z as c,_ as l,a as u,et as d,i as f,m as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout-I1QMPYpW.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminCard--HubMtUj.js";import{n as b}from"./app-lI4VKCmX.js";var x={class:`mb-6`},S={class:`max-w-4xl`},ee={class:`text-2xl font-bold text-fg mb-6`},te={for:`role-name`,class:`block text-sm font-medium text-fg mb-1`},ne={key:0,class:`mt-1 text-sm text-danger`},re={class:`flex flex-wrap items-center justify-between gap-2`},ie={class:`text-sm font-medium text-fg`},C={class:`flex gap-2`},w={class:`mt-1 text-sm text-muted`},T={key:0,class:`mt-1 text-sm text-danger`},E={class:`mt-2 overflow-x-auto border border-line rounded-md`},D={class:`min-w-full text-sm`},O={class:`bg-surface-alt`},k={class:`px-3 py-2 text-left font-medium text-fg`},A={key:0,class:`px-3 py-2 text-left font-medium text-fg`},j={class:`px-3 py-2 w-20 text-center font-medium text-fg`},M={class:`divide-y divide-line`},N=[`data-section`],P={class:`px-3 py-1.5`},F={class:`ml-1 text-xs text-muted font-mono`},I=[`data-permission`,`aria-label`,`checked`,`onChange`],L={key:0,class:`px-3 py-1.5`},ae=[`data-permission`,`checked`,`onChange`],R=[`colspan`],z=[`data-permission`,`checked`,`onChange`],B={class:`px-3 py-1.5 text-center`},V=[`aria-label`,`checked`,`onChange`],H={class:`flex items-center justify-end space-x-3 pt-4 border-t`},U={__name:`Edit`,props:{role:{type:Object,default:null},sections:{type:Array,required:!0},title:String},setup(U){let W=U,G=[`view`,`create`,`update`,`delete`],K=u({name:W.role?.name??``,permissions:[...W.role?.permissions??[]]}),q=(e,t)=>K.permissions.includes(`${e.key}.${t}`),J=e=>G.every(t=>e.actions.includes(t)),Y=e=>J(e)?e.actions.filter(e=>!G.includes(e)):[],X=W.sections.some(e=>Y(e).length>0),Z=(e,t)=>e.labels?.[t]??b(`permissions.actions.${t}`),Q=(e,t)=>{let n=new Set(K.permissions),r=`${e.key}.${t}`;n.has(r)?(n.delete(r),t===`view`&&G.forEach(t=>n.delete(`${e.key}.${t}`))):(n.add(r),J(e)&&G.includes(t)&&t!==`view`&&n.add(`${e.key}.view`)),K.permissions=[...n]},$=e=>e.actions.every(t=>q(e,t)),oe=e=>{let t=new Set(K.permissions),n=$(e);e.actions.forEach(r=>n?t.delete(`${e.key}.${r}`):t.add(`${e.key}.${r}`)),K.permissions=[...t]},se=()=>{K.permissions=W.sections.flatMap(e=>e.actions.map(t=>`${e.key}.${t}`))},ce=()=>{W.role?K.put(route(`admin.roles.update`,W.role.id)):K.post(route(`admin.roles.store`))};return(u,b)=>(r(),a(_,{title:U.title},{default:s(()=>[g(`div`,x,[t(c(f),{href:u.route(`admin.roles.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(d(u.$t(`menu.roles`)),1)]),_:1},8,[`href`])]),g(`div`,S,[g(`h1`,ee,d(U.title),1),t(y,null,{default:s(()=>[g(`form`,{class:`space-y-6`,"data-role-form":``,onSubmit:l(ce,[`prevent`])},[g(`div`,null,[g(`label`,te,[o(d(u.$t(`permissions.name`))+` `,1),b[2]||=g(`span`,{class:`text-danger`},`*`,-1)]),n(g(`input`,{id:`role-name`,"onUpdate:modelValue":b[0]||=e=>c(K).name=e,type:`text`,required:``,class:`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`},null,512),[[p,c(K).name]]),c(K).errors.name?(r(),h(`p`,ne,d(c(K).errors.name),1)):e(``,!0)]),g(`div`,null,[g(`div`,re,[g(`span`,ie,d(u.$t(`permissions.permissions`)),1),g(`div`,C,[t(v,{type:`button`,size:`sm`,variant:`outline`,onClick:se},{default:s(()=>[o(d(u.$t(`permissions.select_all`)),1)]),_:1}),t(v,{type:`button`,size:`sm`,variant:`outline`,onClick:b[1]||=e=>c(K).permissions=[]},{default:s(()=>[o(d(u.$t(`permissions.clear`)),1)]),_:1})])]),g(`p`,w,d(u.$t(`permissions.matrix_hint`)),1),c(K).errors.permissions?(r(),h(`p`,T,d(c(K).errors.permissions),1)):e(``,!0),g(`div`,E,[g(`table`,D,[g(`thead`,O,[g(`tr`,null,[g(`th`,k,d(u.$t(`permissions.section`)),1),(r(),h(m,null,i(G,e=>g(`th`,{key:e,class:`px-3 py-2 w-24 text-center font-medium text-fg`},d(u.$t(`permissions.actions.${e}`)),1)),64)),c(X)?(r(),h(`th`,A,d(u.$t(`permissions.other`)),1)):e(``,!0),g(`th`,j,d(u.$t(`permissions.all`)),1)])]),g(`tbody`,M,[(r(!0),h(m,null,i(U.sections,t=>(r(),h(`tr`,{key:t.key,"data-section":t.key},[g(`td`,P,[o(d(t.label)+` `,1),g(`span`,F,d(t.key),1)]),J(t)?(r(),h(m,{key:0},[(r(),h(m,null,i(G,e=>g(`td`,{key:e,class:`px-3 py-1.5 text-center`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,"aria-label":`${t.label}: ${u.$t(`permissions.actions.${e}`)}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,I)])),64)),c(X)?(r(),h(`td`,L,[(r(!0),h(m,null,i(Y(t),e=>(r(),h(`label`,{key:e,class:`inline-flex items-center gap-2 mr-3`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,ae),o(` `+d(Z(t,e)),1)]))),128))])):e(``,!0)],64)):(r(),h(`td`,{key:1,colspan:c(X)?5:4,class:`px-3 py-1.5`},[(r(!0),h(m,null,i(t.actions,e=>(r(),h(`label`,{key:e,class:`inline-flex items-center gap-2 mr-3`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,z),o(` `+d(Z(t,e)),1)]))),128))],8,R)),g(`td`,B,[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"aria-label":`${t.label}: ${u.$t(`permissions.all`)}`,checked:$(t),onChange:e=>oe(t)},null,40,V)])],8,N))),128))])])])]),g(`div`,H,[t(v,{href:u.route(`admin.roles.index`),variant:`secondary`},{default:s(()=>[o(d(u.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(v,{"data-action":`save`,type:`submit`,loading:c(K).processing},{default:s(()=>[o(d(u.$t(`common.save`)),1)]),_:1},8,[`loading`])])],32)]),_:1})])]),_:1},8,[`title`]))}};export{U as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Z as c,_ as l,a as u,et as d,i as f,m as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout--RXJFj9t.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminCard--HubMtUj.js";import{n as b}from"./app-BNjy5Z6H.js";var x={class:`mb-6`},S={class:`max-w-4xl`},ee={class:`text-2xl font-bold text-fg mb-6`},te={for:`role-name`,class:`block text-sm font-medium text-fg mb-1`},ne={key:0,class:`mt-1 text-sm text-danger`},re={class:`flex flex-wrap items-center justify-between gap-2`},ie={class:`text-sm font-medium text-fg`},C={class:`flex gap-2`},w={class:`mt-1 text-sm text-muted`},T={key:0,class:`mt-1 text-sm text-danger`},E={class:`mt-2 overflow-x-auto border border-line rounded-md`},D={class:`min-w-full text-sm`},O={class:`bg-surface-alt`},k={class:`px-3 py-2 text-left font-medium text-fg`},A={key:0,class:`px-3 py-2 text-left font-medium text-fg`},j={class:`px-3 py-2 w-20 text-center font-medium text-fg`},M={class:`divide-y divide-line`},N=[`data-section`],P={class:`px-3 py-1.5`},F={class:`ml-1 text-xs text-muted font-mono`},I=[`data-permission`,`aria-label`,`checked`,`onChange`],L={key:0,class:`px-3 py-1.5`},ae=[`data-permission`,`checked`,`onChange`],R=[`colspan`],z=[`data-permission`,`checked`,`onChange`],B={class:`px-3 py-1.5 text-center`},V=[`aria-label`,`checked`,`onChange`],H={class:`flex items-center justify-end space-x-3 pt-4 border-t`},U={__name:`Edit`,props:{role:{type:Object,default:null},sections:{type:Array,required:!0},title:String},setup(U){let W=U,G=[`view`,`create`,`update`,`delete`],K=u({name:W.role?.name??``,permissions:[...W.role?.permissions??[]]}),q=(e,t)=>K.permissions.includes(`${e.key}.${t}`),J=e=>G.every(t=>e.actions.includes(t)),Y=e=>J(e)?e.actions.filter(e=>!G.includes(e)):[],X=W.sections.some(e=>Y(e).length>0),Z=(e,t)=>e.labels?.[t]??b(`permissions.actions.${t}`),Q=(e,t)=>{let n=new Set(K.permissions),r=`${e.key}.${t}`;n.has(r)?(n.delete(r),t===`view`&&G.forEach(t=>n.delete(`${e.key}.${t}`))):(n.add(r),J(e)&&G.includes(t)&&t!==`view`&&n.add(`${e.key}.view`)),K.permissions=[...n]},$=e=>e.actions.every(t=>q(e,t)),oe=e=>{let t=new Set(K.permissions),n=$(e);e.actions.forEach(r=>n?t.delete(`${e.key}.${r}`):t.add(`${e.key}.${r}`)),K.permissions=[...t]},se=()=>{K.permissions=W.sections.flatMap(e=>e.actions.map(t=>`${e.key}.${t}`))},ce=()=>{W.role?K.put(route(`admin.roles.update`,W.role.id)):K.post(route(`admin.roles.store`))};return(u,b)=>(r(),a(_,{title:U.title},{default:s(()=>[g(`div`,x,[t(c(f),{href:u.route(`admin.roles.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(d(u.$t(`menu.roles`)),1)]),_:1},8,[`href`])]),g(`div`,S,[g(`h1`,ee,d(U.title),1),t(y,null,{default:s(()=>[g(`form`,{class:`space-y-6`,"data-role-form":``,onSubmit:l(ce,[`prevent`])},[g(`div`,null,[g(`label`,te,[o(d(u.$t(`permissions.name`))+` `,1),b[2]||=g(`span`,{class:`text-danger`},`*`,-1)]),n(g(`input`,{id:`role-name`,"onUpdate:modelValue":b[0]||=e=>c(K).name=e,type:`text`,required:``,class:`w-full px-3 py-2 border border-field rounded-md shadow-sm focus:ring-focus focus:border-focus`},null,512),[[p,c(K).name]]),c(K).errors.name?(r(),h(`p`,ne,d(c(K).errors.name),1)):e(``,!0)]),g(`div`,null,[g(`div`,re,[g(`span`,ie,d(u.$t(`permissions.permissions`)),1),g(`div`,C,[t(v,{type:`button`,size:`sm`,variant:`outline`,onClick:se},{default:s(()=>[o(d(u.$t(`permissions.select_all`)),1)]),_:1}),t(v,{type:`button`,size:`sm`,variant:`outline`,onClick:b[1]||=e=>c(K).permissions=[]},{default:s(()=>[o(d(u.$t(`permissions.clear`)),1)]),_:1})])]),g(`p`,w,d(u.$t(`permissions.matrix_hint`)),1),c(K).errors.permissions?(r(),h(`p`,T,d(c(K).errors.permissions),1)):e(``,!0),g(`div`,E,[g(`table`,D,[g(`thead`,O,[g(`tr`,null,[g(`th`,k,d(u.$t(`permissions.section`)),1),(r(),h(m,null,i(G,e=>g(`th`,{key:e,class:`px-3 py-2 w-24 text-center font-medium text-fg`},d(u.$t(`permissions.actions.${e}`)),1)),64)),c(X)?(r(),h(`th`,A,d(u.$t(`permissions.other`)),1)):e(``,!0),g(`th`,j,d(u.$t(`permissions.all`)),1)])]),g(`tbody`,M,[(r(!0),h(m,null,i(U.sections,t=>(r(),h(`tr`,{key:t.key,"data-section":t.key},[g(`td`,P,[o(d(t.label)+` `,1),g(`span`,F,d(t.key),1)]),J(t)?(r(),h(m,{key:0},[(r(),h(m,null,i(G,e=>g(`td`,{key:e,class:`px-3 py-1.5 text-center`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,"aria-label":`${t.label}: ${u.$t(`permissions.actions.${e}`)}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,I)])),64)),c(X)?(r(),h(`td`,L,[(r(!0),h(m,null,i(Y(t),e=>(r(),h(`label`,{key:e,class:`inline-flex items-center gap-2 mr-3`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,ae),o(` `+d(Z(t,e)),1)]))),128))])):e(``,!0)],64)):(r(),h(`td`,{key:1,colspan:c(X)?5:4,class:`px-3 py-1.5`},[(r(!0),h(m,null,i(t.actions,e=>(r(),h(`label`,{key:e,class:`inline-flex items-center gap-2 mr-3`},[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"data-permission":`${t.key}.${e}`,checked:q(t,e),onChange:n=>Q(t,e)},null,40,z),o(` `+d(Z(t,e)),1)]))),128))],8,R)),g(`td`,B,[g(`input`,{type:`checkbox`,class:`h-4 w-4`,"aria-label":`${t.label}: ${u.$t(`permissions.all`)}`,checked:$(t),onChange:e=>oe(t)},null,40,V)])],8,N))),128))])])])]),g(`div`,H,[t(v,{href:u.route(`admin.roles.index`),variant:`secondary`},{default:s(()=>[o(d(u.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(v,{"data-action":`save`,type:`submit`,loading:c(K).processing},{default:s(()=>[o(d(u.$t(`common.save`)),1)]),_:1},8,[`loading`])])],32)]),_:1})])]),_:1},8,[`title`]))}};export{U as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/FormField-BI8KmQxQ.js b/packages/admin/dist/assets/FormField-xD6LELDV.js similarity index 99% rename from packages/admin/dist/assets/FormField-BI8KmQxQ.js rename to packages/admin/dist/assets/FormField-xD6LELDV.js index f2b52e53..9e944d07 100644 --- a/packages/admin/dist/assets/FormField-BI8KmQxQ.js +++ b/packages/admin/dist/assets/FormField-xD6LELDV.js @@ -1,4 +1,4 @@ -import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,M as f,N as p,O as m,P as h,Q as g,R as _,S as v,T as y,U as b,V as x,W as S,X as C,Y as w,Z as T,_ as E,b as D,c as ee,d as te,et as O,f as ne,g as k,h as re,j as ie,k as ae,m as oe,o as se,p as ce,u as le,v as A,w as j,x as M,y as ue,z as N}from"./dist-MY__znoP.js";import{n as P}from"./app-lI4VKCmX.js";import{i as de,n as fe,r as pe}from"./AdminLayout-I1QMPYpW.js";import{t as me}from"./AdminModal-DNJ_V4iq.js";import{t as he}from"./AdminButton-Bx141Bs3.js";var ge=Object.defineProperty,_e=(e,t)=>{let n={};for(var r in e)ge(n,r,{get:e[r],enumerable:!0});return t||ge(n,Symbol.toStringTag,{value:`Module`}),n};function ve(e){this.content=e}ve.prototype={constructor:ve,find:function(e){for(var t=0;t>1}},ve.from=function(e){if(e instanceof ve)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new ve(t)};function ye(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(r),a=t.child(r);if(i==a)n+=i.nodeSize;else{if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){let e=i.text,t=a.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r0&&a>0&&e[i-1]==t[a-1];)i--,a--,n--,r--;return i&&a&&i=56320&&e<57344}function Se(e){return e>=55296&&e<56320}var F=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;te&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);at)for(let e=0,a=0;at&&((an)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),i=n+r.nodeSize;if(i>=e)return i==e?we(t+1,i):we(t,n);n=i}}toString(){return`<`+this.toStringInner()+`>`}toStringInner(){return this.content.join(`, `)}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(t,n){if(!n)return e.empty;if(!Array.isArray(n))throw RangeError(`Invalid input for Fragment.fromJSON`);return e.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return e.empty;let n,r=0;for(let e=0;ethis.type.rank&&(t||=e.slice(0,r),t.push(this),n=!0),t&&t.push(i)}return t||=e.slice(),n||t.push(this),t}removeFromSet(e){for(let t=0;te.type.rank-t.type.rank),n}};I.none=[];var Ee=class extends Error{},L=class e{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=Oe(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new e(r,this.openStart,this.openEnd)}removeBetween(t,n){return new e(De(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+`(`+this.openStart+`,`+this.openEnd+`)`}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(t,n){if(!n)return e.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!=`number`||typeof i!=`number`)throw RangeError(`Invalid input for Slice.fromJSON`);return new e(F.fromJSON(t,n.content),r,i)}static maxOpen(t,n=!0){let r=0,i=0;for(let e=t.firstChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.firstChild)r++;for(let e=t.lastChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.lastChild)i++;return new e(t,r,i)}};L.empty=new L(F.empty,0,0);function De(e,t,n){let{index:r,offset:i}=e.findIndex(t),a=e.maybeChild(r),{index:o,offset:s}=e.findIndex(n);if(i==t||a.isText){if(s!=n&&!e.child(o).isText)throw RangeError(`Removing non-flat range`);return e.cut(0,t).append(e.cut(n))}if(r!=o)throw RangeError(`Removing non-flat range`);return e.replaceChild(r,a.copy(De(a.content,t-i-1,n-i-1)))}function Oe(e,t,n,r,i,a){let{index:o,offset:s}=e.findIndex(t),c=e.maybeChild(o);if(s==t||c.isText)return a&&r<=0&&i<=0&&!a.canReplace(o,o,n)?null:e.cut(0,t).append(n).append(e.cut(t));let l=Oe(c.content,t-s-1,n,o==0?r-1:0,o==e.childCount-1?i-1:0,c);return l&&e.replaceChild(o,c.copy(l))}function ke(e,t,n){if(n.openStart>e.depth)throw new Ee(`Inserted content deeper than insertion position`);if(e.depth-n.openStart!=t.depth-n.openEnd)throw new Ee(`Inconsistent open depths`);return Ae(e,t,n,0)}function Ae(e,t,n,r){let i=e.index(r),a=e.node(r);if(i==t.index(r)&&r=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function Pe(e,t,n,r){let i=(t||e).node(n),a=0,o=t?t.index(n):i.childCount;e&&(a=e.index(n),e.depth>n?a++:e.textOffset&&(Ne(e.nodeAfter,r),a++));for(let e=a;ei&&Me(e,t,i+1),o=r.depth>i&&Me(n,r,i+1),s=[];return Pe(null,e,i,s),a&&o&&t.index(i)==n.index(i)?(je(a,o),Ne(Fe(a,Ie(e,t,n,r,i+1)),s)):(a&&Ne(Fe(a,Le(e,t,i+1)),s),Pe(t,n,i,s),o&&Ne(Fe(o,Le(n,r,i+1)),s)),Pe(r,null,i,s),new F(s)}function Le(e,t,n){let r=[];return Pe(null,e,n,r),e.depth>n&&Ne(Fe(Me(e,t,n+1),Le(e,t,n+1)),r),Pe(t,null,n,r),new F(r)}function Re(e,t){let n=t.depth-e.openStart,r=t.node(n).copy(e.content);for(let e=n-1;e>=0;e--)r=t.node(e).copy(F.from(r));return{start:r.resolveNoCache(e.openStart+n),end:r.resolveNoCache(r.content.size-e.openEnd-n)}}var ze=class e{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position before the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position after the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let t=0;t0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new Ue(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=t.content.size))throw RangeError(`Position `+n+` out of range`);let r=[],i=0,a=n;for(let e=t;;){let{index:t,offset:n}=e.content.findIndex(a),o=a-n;if(r.push(e,t,i+n),!o||(e=e.child(t),e.isText))break;a=o-1,i+=n+1}return new e(n,r,a)}static resolveCached(t,n){let r=He.get(t);if(r)for(let e=0;ee&&this.nodesBetween(e,t,e=>(n.isInSet(e.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+=`(`+this.content.toStringInner()+`)`),Je(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw Error(`Called contentMatchAt on a node with invalid content`);return t}canReplace(e,t,n=F.empty,r=0,i=n.childCount){let a=this.contentMatchAt(e).matchFragment(n,r,i),o=a&&a.matchFragment(this.content,t);if(!o||!o.validEnd)return!1;for(let e=r;ee.type.name)}`);this.content.forEach(e=>e.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(e=>e.toJSON())),e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Node.fromJSON`);let n;if(t.marks){if(!Array.isArray(t.marks))throw RangeError(`Invalid mark data for Node.fromJSON`);n=t.marks.map(e.markFromJSON)}if(t.type==`text`){if(typeof t.text!=`string`)throw RangeError(`Invalid text node in JSON`);return e.text(t.text,n)}let r=F.fromJSON(e,t.content);return e.nodeType(t.type).create(t.attrs,r,n)}};Ge.prototype.text=void 0;var Ke=(()=>{let{stack:e}=Error(`/`);if(!e||!/\n\s*at\s/.test(e))return e=>e;let t=Object.create(null);return e=>(t[e],e)})(),qe=class e extends Ge{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw RangeError(`Empty text nodes are not allowed`);this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Je(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return Ke(this.text.slice(e,t))}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new e(this.type,this.attrs,t,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(Ke(this.text.slice(e,t)))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Je(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+`(`+t+`)`;return t}function Ye(e,t,n,r){for(let i in t)if(!(i in e))throw RangeError(`Unsupported attribute ${i} for ${n} of type ${r}`);for(let n in e)e[n].validate&&e[n].validate(t[n])}var Xe=class e{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Ze(t,n);if(r.next==null)return e.empty;let i=Qe(r);r.next&&r.err(`Unexpected trailing text`);let a=ct(at(i));return lt(a,r),a}matchType(e){for(let t=0;te.createAndFill()));for(let e=0;e=this.next.length)throw RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r{let r=n+(t.validEnd?`*`:` `)+` `;for(let n=0;n`+e.indexOf(t.next[n].next);return r}).join(` +import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,M as f,N as p,O as m,P as h,Q as g,R as _,S as v,T as y,U as b,V as x,W as S,X as C,Y as w,Z as T,_ as E,b as D,c as ee,d as te,et as O,f as ne,g as k,h as re,j as ie,k as ae,m as oe,o as se,p as ce,u as le,v as A,w as j,x as M,y as ue,z as N}from"./dist-MY__znoP.js";import{n as P}from"./app-BNjy5Z6H.js";import{i as de,n as fe,r as pe}from"./AdminLayout--RXJFj9t.js";import{t as me}from"./AdminModal-DNJ_V4iq.js";import{t as he}from"./AdminButton-Bx141Bs3.js";var ge=Object.defineProperty,_e=(e,t)=>{let n={};for(var r in e)ge(n,r,{get:e[r],enumerable:!0});return t||ge(n,Symbol.toStringTag,{value:`Module`}),n};function ve(e){this.content=e}ve.prototype={constructor:ve,find:function(e){for(var t=0;t>1}},ve.from=function(e){if(e instanceof ve)return e;var t=[];if(e)for(var n in e)t.push(n,e[n]);return new ve(t)};function ye(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(r),a=t.child(r);if(i==a)n+=i.nodeSize;else{if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){let e=i.text,t=a.text,r=0;for(;e[r]==t[r];r++)n++;return r&&r0&&a>0&&e[i-1]==t[a-1];)i--,a--,n--,r--;return i&&a&&i=56320&&e<57344}function Se(e){return e>=55296&&e<56320}var F=class e{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let t=0;te&&n(s,r+o,i||null,a)!==!1&&s.content.size){let i=o+1;s.nodesBetween(Math.max(0,e-i),Math.min(s.content.size,t-i),n,r+i)}o=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,n,r){let i=``,a=!0;return this.nodesBetween(e,t,(o,s)=>{let c=o.isText?o.text.slice(Math.max(e,s)-s,t-s):o.isLeaf?r?typeof r==`function`?r(o):r:o.type.spec.leafText?o.type.spec.leafText(o):``:``;o.isBlock&&(o.isLeaf&&c||o.isTextblock)&&n&&(a?a=!1:i+=n),i+=c},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(r)&&(i[i.length-1]=n.withText(n.text+r.text),a=1);at)for(let e=0,a=0;at&&((an)&&(o=o.isText?o.cut(Math.max(0,t-a),Math.min(o.text.length,n-a)):o.cut(Math.max(0,t-a-1),Math.min(o.content.size,n-a-1))),r.push(o),i+=o.nodeSize),a=s}return new e(r,i)}cutByIndex(t,n){return t==n?e.empty:t==0&&n==this.content.length?this:new e(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-r.nodeSize;return i[t]=n,new e(i,a)}addToStart(t){return new e([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new e(this.content.concat(t),this.size+t.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,n=0;;t++){let r=this.child(t),i=n+r.nodeSize;if(i>=e)return i==e?we(t+1,i):we(t,n);n=i}}toString(){return`<`+this.toStringInner()+`>`}toStringInner(){return this.content.join(`, `)}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(t,n){if(!n)return e.empty;if(!Array.isArray(n))throw RangeError(`Invalid input for Fragment.fromJSON`);return e.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return e.empty;let n,r=0;for(let e=0;ethis.type.rank&&(t||=e.slice(0,r),t.push(this),n=!0),t&&t.push(i)}return t||=e.slice(),n||t.push(this),t}removeFromSet(e){for(let t=0;te.type.rank-t.type.rank),n}};I.none=[];var Ee=class extends Error{},L=class e{constructor(e,t,n){this.content=e,this.openStart=t,this.openEnd=n}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=Oe(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new e(r,this.openStart,this.openEnd)}removeBetween(t,n){return new e(De(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+`(`+this.openStart+`,`+this.openEnd+`)`}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(t,n){if(!n)return e.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!=`number`||typeof i!=`number`)throw RangeError(`Invalid input for Slice.fromJSON`);return new e(F.fromJSON(t,n.content),r,i)}static maxOpen(t,n=!0){let r=0,i=0;for(let e=t.firstChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.firstChild)r++;for(let e=t.lastChild;e&&!e.isLeaf&&(n||!e.type.spec.isolating);e=e.lastChild)i++;return new e(t,r,i)}};L.empty=new L(F.empty,0,0);function De(e,t,n){let{index:r,offset:i}=e.findIndex(t),a=e.maybeChild(r),{index:o,offset:s}=e.findIndex(n);if(i==t||a.isText){if(s!=n&&!e.child(o).isText)throw RangeError(`Removing non-flat range`);return e.cut(0,t).append(e.cut(n))}if(r!=o)throw RangeError(`Removing non-flat range`);return e.replaceChild(r,a.copy(De(a.content,t-i-1,n-i-1)))}function Oe(e,t,n,r,i,a){let{index:o,offset:s}=e.findIndex(t),c=e.maybeChild(o);if(s==t||c.isText)return a&&r<=0&&i<=0&&!a.canReplace(o,o,n)?null:e.cut(0,t).append(n).append(e.cut(t));let l=Oe(c.content,t-s-1,n,o==0?r-1:0,o==e.childCount-1?i-1:0,c);return l&&e.replaceChild(o,c.copy(l))}function ke(e,t,n){if(n.openStart>e.depth)throw new Ee(`Inserted content deeper than insertion position`);if(e.depth-n.openStart!=t.depth-n.openEnd)throw new Ee(`Inconsistent open depths`);return Ae(e,t,n,0)}function Ae(e,t,n,r){let i=e.index(r),a=e.node(r);if(i==t.index(r)&&r=0&&e.isText&&e.sameMarkup(t[n])?t[n]=e.withText(t[n].text+e.text):t.push(e)}function Pe(e,t,n,r){let i=(t||e).node(n),a=0,o=t?t.index(n):i.childCount;e&&(a=e.index(n),e.depth>n?a++:e.textOffset&&(Ne(e.nodeAfter,r),a++));for(let e=a;ei&&Me(e,t,i+1),o=r.depth>i&&Me(n,r,i+1),s=[];return Pe(null,e,i,s),a&&o&&t.index(i)==n.index(i)?(je(a,o),Ne(Fe(a,Ie(e,t,n,r,i+1)),s)):(a&&Ne(Fe(a,Le(e,t,i+1)),s),Pe(t,n,i,s),o&&Ne(Fe(o,Le(n,r,i+1)),s)),Pe(r,null,i,s),new F(s)}function Le(e,t,n){let r=[];return Pe(null,e,n,r),e.depth>n&&Ne(Fe(Me(e,t,n+1),Le(e,t,n+1)),r),Pe(t,null,n,r),new F(r)}function Re(e,t){let n=t.depth-e.openStart,r=t.node(n).copy(e.content);for(let e=n-1;e>=0;e--)r=t.node(e).copy(F.from(r));return{start:r.resolveNoCache(e.openStart+n),end:r.resolveNoCache(r.content.size-e.openEnd-n)}}var ze=class e{constructor(e,t,n){this.pos=e,this.path=t,this.parentOffset=n,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position before the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw RangeError(`There is no position after the top-level node`);return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let n=this.pos-this.path[this.path.length-1],r=e.child(t);return n?e.child(t).cut(n):r}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let n=this.path[t*3],r=t==0?0:this.path[t*3-1]+1;for(let t=0;t0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;n--)if(e.pos<=this.end(n)&&(!t||t(this.node(n))))return new Ue(this,e,n);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=t.content.size))throw RangeError(`Position `+n+` out of range`);let r=[],i=0,a=n;for(let e=t;;){let{index:t,offset:n}=e.content.findIndex(a),o=a-n;if(r.push(e,t,i+n),!o||(e=e.child(t),e.isText))break;a=o-1,i+=n+1}return new e(n,r,a)}static resolveCached(t,n){let r=He.get(t);if(r)for(let e=0;ee&&this.nodesBetween(e,t,e=>(n.isInSet(e.marks)&&(r=!0),!r)),r}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+=`(`+this.content.toStringInner()+`)`),Je(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw Error(`Called contentMatchAt on a node with invalid content`);return t}canReplace(e,t,n=F.empty,r=0,i=n.childCount){let a=this.contentMatchAt(e).matchFragment(n,r,i),o=a&&a.matchFragment(this.content,t);if(!o||!o.validEnd)return!1;for(let e=r;ee.type.name)}`);this.content.forEach(e=>e.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(e=>e.toJSON())),e}static fromJSON(e,t){if(!t)throw RangeError(`Invalid input for Node.fromJSON`);let n;if(t.marks){if(!Array.isArray(t.marks))throw RangeError(`Invalid mark data for Node.fromJSON`);n=t.marks.map(e.markFromJSON)}if(t.type==`text`){if(typeof t.text!=`string`)throw RangeError(`Invalid text node in JSON`);return e.text(t.text,n)}let r=F.fromJSON(e,t.content);return e.nodeType(t.type).create(t.attrs,r,n)}};Ge.prototype.text=void 0;var Ke=(()=>{let{stack:e}=Error(`/`);if(!e||!/\n\s*at\s/.test(e))return e=>e;let t=Object.create(null);return e=>(t[e],e)})(),qe=class e extends Ge{constructor(e,t,n,r){if(super(e,t,null,r),!n)throw RangeError(`Empty text nodes are not allowed`);this.text=n}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Je(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return Ke(this.text.slice(e,t))}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new e(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new e(this.type,this.attrs,t,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(Ke(this.text.slice(e,t)))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}};function Je(e,t){for(let n=e.length-1;n>=0;n--)t=e[n].type.name+`(`+t+`)`;return t}function Ye(e,t,n,r){for(let i in t)if(!(i in e))throw RangeError(`Unsupported attribute ${i} for ${n} of type ${r}`);for(let n in e)e[n].validate&&e[n].validate(t[n])}var Xe=class e{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Ze(t,n);if(r.next==null)return e.empty;let i=Qe(r);r.next&&r.err(`Unexpected trailing text`);let a=ct(at(i));return lt(a,r),a}matchType(e){for(let t=0;te.createAndFill()));for(let e=0;e=this.next.length)throw RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(n){e.push(n);for(let r=0;r{let r=n+(t.validEnd?`*`:` `)+` `;for(let n=0;n`+e.indexOf(t.next[n].next);return r}).join(` `)}};Xe.empty=new Xe(!0);var Ze=class{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==``&&this.tokens.pop(),this.tokens[0]==``&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw SyntaxError(e+` (in content expression '`+this.string+`')`)}};function Qe(e){let t=[];do t.push($e(e));while(e.eat(`|`));return t.length==1?t[0]:{type:`choice`,exprs:t}}function $e(e){let t=[];do t.push(et(e));while(e.next&&e.next!=`)`&&e.next!=`|`);return t.length==1?t[0]:{type:`seq`,exprs:t}}function et(e){let t=it(e);for(;;)if(e.eat(`+`))t={type:`plus`,expr:t};else if(e.eat(`*`))t={type:`star`,expr:t};else if(e.eat(`?`))t={type:`opt`,expr:t};else if(e.eat(`{`))t=nt(e,t);else break;return t}function tt(e){/\D/.test(e.next)&&e.err(`Expected number, got '`+e.next+`'`);let t=Number(e.next);return e.pos++,t}function nt(e,t){let n=tt(e),r=n;return e.eat(`,`)&&(r=e.next==`}`?-1:tt(e)),e.eat(`}`)||e.err(`Unclosed braced range`),{type:`range`,min:n,max:r,expr:t}}function rt(e,t){let n=e.nodeTypes,r=n[t];if(r)return[r];let i=[];for(let e in n){let r=n[e];r.isInGroup(t)&&i.push(r)}return i.length==0&&e.err(`No node type or group '`+t+`' found`),i}function it(e){if(e.eat(`(`)){let t=Qe(e);return e.eat(`)`)||e.err(`Missing closing paren`),t}if(/\W/.test(e.next))e.err(`Unexpected token '`+e.next+`'`);else{let t=rt(e,e.next).map(t=>(e.inline==null?e.inline=t.isInline:e.inline!=t.isInline&&e.err(`Mixing inline and block content`),{type:`name`,value:t}));return e.pos++,t.length==1?t[0]:{type:`choice`,exprs:t}}}function at(e){let t=[[]];return i(a(e,0),n()),t;function n(){return t.push([])-1}function r(e,n,r){let i={term:r,to:n};return t[e].push(i),i}function i(e,t){e.forEach(e=>e.to=t)}function a(e,t){if(e.type==`choice`)return e.exprs.reduce((e,n)=>e.concat(a(n,t)),[]);if(e.type==`seq`)for(let r=0;;r++){let o=a(e.exprs[r],t);if(r==e.exprs.length-1)return o;i(o,t=n())}else if(e.type==`star`){let o=n();return r(t,o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`plus`){let o=n();return i(a(e.expr,t),o),i(a(e.expr,o),o),[r(o)]}else if(e.type==`opt`)return[r(t)].concat(a(e.expr,t));else if(e.type==`range`){let o=t;for(let t=0;t{e[t].forEach(({term:t,to:n})=>{if(!t)return;let r;for(let e=0;e{r||i.push([t,r=[]]),r.indexOf(e)==-1&&r.push(e)})})});let a=t[r.join(`,`)]=new Xe(r.indexOf(e.length-1)>-1);for(let e=0;e-1}get whitespace(){return this.spec.whitespace||(this.spec.code?`pre`:`normal`)}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:dt(this.attrs,e)}create(e=null,t,n){if(this.isText)throw Error(`NodeType.create can't construct text nodes`);return new Ge(this,this.computeAttrs(e),F.from(t),I.setFrom(n))}createChecked(e=null,t,n){return t=F.from(t),this.checkContent(t),new Ge(this,this.computeAttrs(e),t,I.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=F.from(t),t.size){let e=this.contentMatch.fillBefore(t);if(!e)return null;t=e.append(t)}let r=this.contentMatch.matchFragment(t),i=r&&r.fillBefore(F.empty,!0);return i?new Ge(this,e,t.append(i),I.setFrom(n)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let t=0;t-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[t]=new e(t,n,i));let i=n.spec.topNode||`doc`;if(!r[i])throw RangeError(`Schema is missing its top node type ('`+i+`')`);if(!r.text)throw RangeError(`Every schema needs a 'text' type`);for(let e in r.text.attrs)throw RangeError(`The text node type should not have attributes`);return r}};function mt(e,t,n){let r=n.split(`|`);return n=>{let i=n===null?`null`:typeof n;if(r.indexOf(i)<0)throw RangeError(`Expected value of type ${r} for attribute ${t} on type ${e}, got ${i}`)}}var ht=class{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,`default`),this.default=n.default,this.validate=typeof n.validate==`string`?mt(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}},gt=class e{constructor(e,t,n,r){this.name=e,this.rank=t,this.schema=n,this.spec=r,this.attrs=ft(e,r.attrs),this.excluded=null;let i=ut(this.attrs);this.instance=i?new I(this,i):null}create(e=null){return!e&&this.instance?this.instance:new I(this,dt(this.attrs,e))}static compile(t,n){let r=Object.create(null),i=0;return t.forEach((t,a)=>r[t]=new e(t,i++,n,a)),r}removeFromSet(e){for(var t=0;t-1}},_t=class{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let n in e)t[n]=e[n];t.nodes=ve.from(e.nodes),t.marks=ve.from(e.marks||{}),this.nodes=pt.compile(this.spec.nodes,this),this.marks=gt.compile(this.spec.marks,this);let n=Object.create(null);for(let e in this.nodes){if(e in this.marks)throw RangeError(e+` can not be both a node and a mark`);let t=this.nodes[e],r=t.spec.content||``,i=t.spec.marks;if(t.contentMatch=n[r]||(n[r]=Xe.parse(r,this.nodes)),t.inlineContent=t.contentMatch.inlineContent,t.spec.linebreakReplacement){if(this.linebreakReplacement)throw RangeError(`Multiple linebreak nodes defined`);if(!t.isInline||!t.isLeaf)throw RangeError(`Linebreak replacement nodes must be inline leaf nodes`);this.linebreakReplacement=t}t.markSet=i==`_`?null:i?vt(this,i.split(` `)):i==``||!t.inlineContent?[]:null}for(let e in this.marks){let t=this.marks[e],n=t.spec.excludes;t.excluded=n==null?[t]:n==``?[]:vt(this,n.split(` `))}this.nodeFromJSON=e=>Ge.fromJSON(this,e),this.markFromJSON=e=>I.fromJSON(this,e),this.topNodeType=this.nodes[this.spec.topNode||`doc`],this.cached.wrappings=Object.create(null)}node(e,t=null,n,r){if(typeof e==`string`)e=this.nodeType(e);else if(!(e instanceof pt))throw RangeError(`Invalid node type: `+e);else if(e.schema!=this)throw RangeError(`Node type from different schema used (`+e.name+`)`);return e.createChecked(t,n,r)}text(e,t){let n=this.nodes.text;return new qe(n,n.defaultAttrs,e,I.setFrom(t))}mark(e,t){return typeof e==`string`&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw RangeError(`Unknown node type: `+e);return t}};function vt(e,t){let n=[];for(let r=0;r-1)&&n.push(o=r)}if(!o)throw SyntaxError(`Unknown mark type: '`+t[r]+`'`)}return n}function yt(e){return e.tag!=null}function bt(e){return e.style!=null}var xt=class e{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(e=>{if(yt(e))this.tags.push(e);else if(bt(e)){let t=/[^=]*/.exec(e.style)[0];n.indexOf(t)<0&&n.push(t),this.styles.push(e)}}),this.normalizeLists=!this.tags.some(t=>{if(!/^(ul|ol)\b/.test(t.tag)||!t.node)return!1;let n=e.nodes[t.node];return n.contentMatch.matchType(n)})}parse(e,t={}){let n=new At(this,t,!1);return n.addAll(e,I.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new At(this,t,!0);return n.addAll(e,I.none,t.from,t.to),L.maxOpen(n.finish())}matchTag(e,t,n){for(let r=n?this.tags.indexOf(n)+1:0;re.length&&(a.charCodeAt(e.length)!=61||a.slice(e.length+1)!=t))){if(r.getAttrs){let e=r.getAttrs(t);if(e===!1)continue;r.attrs=e||void 0}return r}}}static schemaRules(e){let t=[];function n(e){let n=e.priority==null?50:e.priority,r=0;for(;r{n(e=Nt(e)),e.mark||e.ignore||e.clearMark||(e.mark=t)})}for(let t in e.nodes){let r=e.nodes[t].spec.parseDOM;r&&r.forEach(e=>{n(e=Nt(e)),e.node||e.ignore||e.mark||(e.node=t)})}return t}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new e(t,e.schemaRules(t)))}},St={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Ct={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},wt={ol:!0,ul:!0},Tt=1,Et=2,Dt=4;function Ot(e,t,n){return t==null?e&&e.whitespace==`pre`?3:n&-5:(t?Tt:0)|(t===`full`?Et:0)}var kt=class{constructor(e,t,n,r,i,a){this.type=e,this.attrs=t,this.marks=n,this.solid=r,this.options=a,this.content=[],this.activeMarks=I.none,this.match=i||(a&Dt?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(F.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let t=this.type.contentMatch,n;return(n=t.findWrapping(e.type))?(this.match=t,n):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Tt)){let e=this.content[this.content.length-1],t;if(e&&e.isText&&(t=/[ \t\r\n\u000c]+$/.exec(e.text))){let n=e;e.text.length==t[0].length?this.content.pop():this.content[this.content.length-1]=n.withText(n.text.slice(0,n.text.length-t[0].length))}}let t=F.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(F.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!St.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}},At=class{constructor(e,t,n){this.parser=e,this.options=t,this.isOpen=n,this.open=0,this.localPreserveWS=!1;let r=t.topNode,i,a=Ot(null,t.preserveWhitespace,0)|(n?Dt:0);i=r?new kt(r.type,r.attrs,I.none,!0,t.topMatch||r.type.contentMatch,a):n?new kt(null,null,I.none,!0,null,a):new kt(e.schema.topNodeType,null,I.none,!0,null,a),this.nodes=[i],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let n=e.nodeValue,r=this.top,i=r.options&Et?`full`:this.localPreserveWS||(r.options&Tt)>0,{schema:a}=this.parser;if(i===`full`||r.inlineContext(e)||/[^ \t\r\n\u000c]/.test(n)){if(!i){if(n=n.replace(/[ \t\r\n\u000c]+/g,` `),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let t=r.content[r.content.length-1],i=e.previousSibling;(!t||i&&i.nodeName==`BR`||t.isText&&/[ \t\r\n\u000c]$/.test(t.text))&&(n=n.slice(1))}}else if(i===`full`)n=n.replace(/\r\n?/g,` `);else if(a.linebreakReplacement&&/[\r\n]/.test(n)&&this.top.findWrapping(a.linebreakReplacement.create())){let e=n.split(/\r?\n|\r/);for(let n=0;n!n.clearMark(e)):t.concat(this.parser.schema.marks[n.mark].create(n.attrs)),n.consuming===!1)e=n;else break}}return t}addElementByRule(e,t,n,r){let i,a;if(t.node){if(a=this.parser.schema.nodes[t.node],a.isLeaf)this.insertNode(a.create(t.attrs),n,e.nodeName==`BR`)||this.leafFallback(e,n);else{let e=this.enter(a,t.attrs||null,n,t.preserveWhitespace);e&&(i=!0,n=e)}}else{let e=this.parser.schema.marks[t.mark];n=n.concat(e.create(t.attrs))}let o=this.top;if(a&&a.isLeaf)this.findInside(e);else if(r)this.addElement(e,n,r);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(e=>this.insertNode(e,n,!1));else{let r=e;typeof t.contentElement==`string`?r=e.querySelector(t.contentElement):typeof t.contentElement==`function`?r=t.contentElement(e):t.contentElement&&(r=t.contentElement),this.findAround(e,r,!0),this.addAll(r,n),this.findAround(e,r,!1)}i&&this.sync(o)&&this.open--}addAll(e,t,n,r){let i=n||0;for(let a=n?e.childNodes[n]:e.firstChild,o=r==null?null:e.childNodes[r];a!=o;a=a.nextSibling,++i)this.findAtPoint(e,i),this.addDOM(a,t);this.findAtPoint(e,i)}findPlace(e,t,n){let r,i;for(let t=this.open,a=0;t>=0;t--){let o=this.nodes[t],s=o.findWrapping(e);if(s&&(!r||r.length>s.length+a)&&(r=s,i=o,!s.length))break;if(o.solid){if(n)break;a+=2}}if(!r)return null;this.sync(i);for(let e=0;e!(a.type?a.type.allowsMarkType(t.type):Pt(t.type,e))||(s=t.addToSet(s),!1)),this.nodes.push(new kt(e,t,s,r,null,o)),this.open++,n}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--)if(this.nodes[t]==e)return this.open=t,!0;else this.localPreserveWS&&(this.nodes[t].options|=Tt);return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let n=this.nodes[t].content;for(let t=n.length-1;t>=0;t--)e+=n[t].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let n=0;n-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split(`/`),n=this.options.context,r=!this.isOpen&&(!n||n.parent.type==this.nodes[0].type),i=-(n?n.depth+1:0)+ +!r,a=(e,o)=>{for(;e>=0;e--){let s=t[e];if(s==``){if(e==t.length-1||e==0)continue;for(;o>=i;o--)if(a(e-1,o))return!0;return!1}{let e=o>0||o==0&&r?this.nodes[o].type:n&&o>=i?n.node(o-i).type:null;if(!e||e.name!=s&&!e.isInGroup(s))return!1;o--}}return!0};return a(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let n=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(n&&n.isTextblock&&n.defaultAttrs)return n}for(let e in this.parser.schema.nodes){let t=this.parser.schema.nodes[e];if(t.isTextblock&&t.defaultAttrs)return t}}};function jt(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let e=t.nodeType==1?t.nodeName.toLowerCase():null;e&&wt.hasOwnProperty(e)&&n?(n.appendChild(t),t=n):e==`li`?n=t:e&&(n=null)}}function Mt(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function Nt(e){let t={};for(let n in e)t[n]=e[n];return t}function Pt(e,t){let n=t.schema.nodes;for(let r in n){let i=n[r];if(!i.allowsMarkType(e))continue;let a=[],o=e=>{a.push(e);for(let n=0;n{if(i.length||e.marks.length){let n=0,a=0;for(;n=0;r--){let i=this.serializeMark(e.marks[r],e.isInline,t);i&&((i.contentDOM||i.dom).appendChild(n),n=i.dom)}return n}serializeMark(e,t,n={}){let r=this.marks[e.type.name];return r&&Vt(Lt(n),r(e,t),null,e.attrs)}static renderSpec(e,t,n=null,r){return typeof t==`string`?{dom:e.createTextNode(t)}:Vt(e,t,n,r)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new e(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(e){let t=It(e.nodes);return t.text||=e=>e.text,t}static marksFromSchema(e){return It(e.marks)}};function It(e){let t={};for(let n in e){let r=e[n].spec.toDOM;r&&(t[n]=r)}return t}function Lt(e){return e.document||window.document}var Rt=new WeakMap;function zt(e){let t=Rt.get(e);return t===void 0&&Rt.set(e,t=Bt(e)),t}function Bt(e){let t=null;function n(e){if(e&&typeof e==`object`){if(Array.isArray(e)){if(typeof e[0]==`string`)t||=[],t.push(e);else for(let t=0;t-1)throw RangeError(`Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.`);let o=i.indexOf(` `);o>0&&(n=i.slice(0,o),i=i.slice(o+1));let s,c=n?e.createElementNS(n,i):e.createElement(i),l=t[1],u=1;if(l&&typeof l==`object`&&l.nodeType==null&&!Array.isArray(l)){u=2;for(let e in l)if(l[e]!=null){let t=e.indexOf(` `);t>0?c.setAttributeNS(e.slice(0,t),e.slice(t+1),l[e]):e==`style`&&c.style?c.style.cssText=l[e]:c.setAttribute(e,l[e])}}for(let i=u;iu)throw RangeError(`Content hole must be the only child of its parent node`);return{dom:c,contentDOM:c}}if(typeof a==`string`)c.appendChild(e.createTextNode(a));else{let{dom:t,contentDOM:i}=Vt(e,a,n,r);if(c.appendChild(t),i){if(s)throw RangeError(`Multiple content holes`);s=i}}}return{dom:c,contentDOM:s}}var Ht=65535,Ut=2**16;function Wt(e,t){return e+t*Ut}function Gt(e){return e&Ht}function Kt(e){return(e-(e&Ht))/Ut}var qt=1,Jt=2,Yt=4,Xt=8,Zt=class{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&Xt)>0}get deletedBefore(){return(this.delInfo&5)>0}get deletedAfter(){return(this.delInfo&6)>0}get deletedAcross(){return(this.delInfo&Yt)>0}},Qt=class e{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&e.empty)return e.empty}recover(e){let t=0,n=Gt(e);if(!this.inverted)for(let e=0;ee)break;let c=this.ranges[o+i],l=this.ranges[o+a],u=s+c;if(e<=u){let i=c?e==s?-1:e==u?1:t:t,a=s+r+(i<0?0:l);if(n)return a;let d=e==(t<0?s:u)?null:Wt(o/3,e-s),f=0;return c&&(f|=e==s?Jt:e==u?qt:Yt,(t<0?e!=s:e!=u)&&(f|=Xt)),new Zt(a,f,d)}r+=l-c}return n?e+r:new Zt(e+r,0,null)}touches(e,t){let n=0,r=Gt(t),i=this.inverted?2:1,a=this.inverted?1:2;for(let t=0;te)break;let s=this.ranges[t+i];if(e<=o+s&&t==r*3)return!0;n+=this.ranges[t+a]-s}return!1}forEach(e){let t=this.inverted?2:1,n=this.inverted?1:2;for(let r=0,i=0;r=0;t--){let r=e.getMirror(t);this.appendMap(e._maps[t].invert(),r!=null&&r>t?n-r-1:void 0)}}invert(){let t=new e;return t.appendMappingInverted(this),t}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let n=this.from;nn&&t!e.isAtom||!t.type.allowsMarkType(this.mark.type)?e:e.mark(this.mark.addToSet(e.marks)),r),t.openStart,t.openEnd);return nn.fromReplace(e,this.from,this.to,i)}invert(t){let n=[];return t.nodesBetween(this.from,this.to,(t,r)=>{if(t.isInline&&t.isAtom){let i=this.mark.addToSet(t.marks);if(!I.sameSet(i,t.marks)){let a=Math.max(this.from,r),o=Math.min(this.to,r+t.nodeSize);sn(on,a,o,this.mark,n);for(let r of t.marks)r.isInSet(i)||sn(e,a,o,r,n)}}}),n.length==1?n[0]:new cn(n)}map(t){let n=t.map(this.from,1),r=t.map(this.to,-1);return n>=r?null:new e(n,r,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`addMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`)throw RangeError(`Invalid input for AddMarkStep.fromJSON`);return new e(n.from,n.to,t.markFromJSON(n.mark))}};tn.jsonID(`addMark`,an);var on=class e extends tn{constructor(e,t,n){super(),this.from=e,this.to=t,this.mark=n}apply(e){let t=e.slice(this.from,this.to),n=new L(rn(t.content,e=>e.mark(this.mark.removeFromSet(e.marks)),e),t.openStart,t.openEnd);return nn.fromReplace(e,this.from,this.to,n)}invert(e){let t=[];return e.nodesBetween(this.from,this.to,(e,n)=>{e.isInline&&e.isAtom&&this.mark.isInSet(e.marks)&&sn(an,Math.max(this.from,n),Math.min(this.to,n+e.nodeSize),this.mark,t)}),t.length==1?t[0]:new cn(t)}map(t){let n=t.map(this.from,1),r=t.map(this.to,-1);return n>=r?null:new e(n,r,this.mark)}merge(t){return t instanceof e&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new e(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:`removeMark`,mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`)throw RangeError(`Invalid input for RemoveMarkStep.fromJSON`);return new e(n.from,n.to,t.markFromJSON(n.mark))}};tn.jsonID(`removeMark`,on);function sn(e,t,n,r,i){let a=i.length?i[i.length-1]:null;a&&a instanceof e&&a.to==t&&a.mark.eq(r)?i[i.length-1]=new e(a.from,n,r):i.push(new e(t,n,r))}var cn=class e extends tn{constructor(e){super(),this.steps=e}apply(e){for(let t of this.steps){let n=t.apply(e);if(!n.doc)return n;e=n.doc}return new nn(e,null)}invert(t){return new e(this.steps.map(e=>e.invert(t)))}map(t){let n=[];for(let e of this.steps){let r=e.map(t);r&&n.push(r)}return n.length?new e(n):null}toJSON(){return{stepType:`markSet`,steps:this.steps.map(e=>e.toJSON())}}static fromJSON(t,n){if(!Array.isArray(n.steps)||!n.steps.every(e=>e.stepType==`addMark`||e.stepType==`removeMark`))throw RangeError(`Invalid JSON for MarkSetStep`);return new e(n.steps.map(e=>tn.fromJSON(t,e)))}};tn.jsonID(`markSet`,cn);var ln=class e extends tn{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return nn.fail(`No node at mark step's position`);let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return nn.fromReplace(e,this.pos,this.pos+1,new L(F.from(n),0,+!t.isLeaf))}invert(t){let n=t.nodeAt(this.pos);if(n){let t=this.mark.addToSet(n.marks);if(t.length==n.marks.length){for(let r=0;rr.pos||i>a?null:new e(n.pos,r.pos,i,a,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:`replaceAround`,from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(t,n){if(typeof n.from!=`number`||typeof n.to!=`number`||typeof n.gapFrom!=`number`||typeof n.gapTo!=`number`||typeof n.insert!=`number`)throw RangeError(`Invalid input for ReplaceAroundStep.fromJSON`);return new e(n.from,n.to,n.gapFrom,n.gapTo,L.fromJSON(t,n.slice),n.insert,!!n.structure)}};tn.jsonID(`replaceAround`,fn);function pn(e,t,n){let r=e.resolve(t),i=n-t,a=r.depth;for(;i>0&&a>0&&r.indexAfter(a)==r.node(a).childCount;)a--,i--;if(i>0){let e=r.node(a).maybeChild(r.indexAfter(a));for(;i>0;){if(!e||e.isLeaf)return!0;e=e.firstChild,i--}}return!1}function mn(e,t,n,r){let i=[];e.doc.nodesBetween(t,n,(e,a,o)=>{if(!e.isInline)return;let s=e.marks;!r.isInSet(s)&&o.type.allowsMarkType(r.type)&&sn(an,Math.max(a,t),Math.min(a+e.nodeSize,n),r,i)}),i.forEach(t=>e.step(t))}function hn(e,t,n,r){let i=[],a=0;e.doc.nodesBetween(t,n,(e,o)=>{if(!e.isInline||!e.isAtom)return;a++;let s=null;if(r instanceof gt){let t=e.marks,n;for(;n=r.isInSet(t);)(s||=[]).push(n),t=n.removeFromSet(t)}else r?r.isInSet(e.marks)&&(s=[r]):s=e.marks;if(s&&s.length){let r=Math.min(o+e.nodeSize,n);for(let e=0;ee.step(new on(t.from,t.to,t.style)))}function gn(e,t,n,r=n.contentMatch,i=!0){let a=e.doc.nodeAt(t),o=[],s=t+1;for(let t=0;t=0;t--)e.step(o[t])}function _n(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function vn(e){let t=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let n=e.depth,r=0,i=0;;--n){let a=e.$from.node(n),o=e.$from.index(n)+r,s=e.$to.indexAfter(n)-i;if(nn;e--)t||r.index(e)>0?(t=!0,u=F.from(r.node(e).copy(u)),d++):c--;let f=F.empty,p=0;for(let e=a,t=!1;e>n;e--)t||i.after(e+1)=0;e--){if(r.size){let t=n[e].type.contentMatch.matchFragment(r);if(!t||!t.validEnd)throw RangeError(`Wrapper type given to Transform.wrap does not form valid content of its parent wrapper`)}r=F.from(n[e].type.create(n[e].attrs,r))}let i=t.start,a=t.end;e.step(new fn(i,a,i,a,new L(r,0,0),n.length,!0))}function Tn(e,t,n,r,i){if(!r.isTextblock)throw RangeError(`Type given to setBlockType should be a textblock`);let a=e.steps.length;e.doc.nodesBetween(t,n,(t,n)=>{let o=typeof i==`function`?i(t):i;if(t.isTextblock&&!t.hasMarkup(r,o)&&On(e.doc,e.mapping.slice(a).map(n),r)){let i=null;if(r.schema.linebreakReplacement){let e=r.whitespace==`pre`,t=!!r.contentMatch.matchType(r.schema.linebreakReplacement);e&&!t?i=!1:!e&&t&&(i=!0)}i===!1&&Dn(e,t,n,a),gn(e,e.mapping.slice(a).map(n,1),r,void 0,i===null);let s=e.mapping.slice(a),c=s.map(n,1),l=s.map(n+t.nodeSize,1);return e.step(new fn(c,l,c+1,l-1,new L(F.from(r.create(o,null,t.marks)),0,0),1,!0)),i===!0&&En(e,t,n,a),!1}})}function En(e,t,n,r){t.forEach((i,a)=>{if(i.isText){let o,s=/\r?\n|\r/g;for(;o=s.exec(i.text);){let i=e.mapping.slice(r).map(n+1+a+o.index);e.replaceWith(i,i+1,t.type.schema.linebreakReplacement.create())}}})}function Dn(e,t,n,r){t.forEach((i,a)=>{if(i.type==i.type.schema.linebreakReplacement){let i=e.mapping.slice(r).map(n+1+a);e.replaceWith(i,i+1,t.type.schema.text(` diff --git a/packages/admin/dist/assets/Index-CVtF6Jho.js b/packages/admin/dist/assets/Index-1mD_GBWn.js similarity index 98% rename from packages/admin/dist/assets/Index-CVtF6Jho.js rename to packages/admin/dist/assets/Index-1mD_GBWn.js index 8bc14ee8..6539e871 100644 --- a/packages/admin/dist/assets/Index-CVtF6Jho.js +++ b/packages/admin/dist/assets/Index-1mD_GBWn.js @@ -1 +1 @@ -import{C as e,E as t,I as n,Q as r,R as i,S as a,T as o,W as s,Z as ee,et as c,n as l,s as u,v as d,w as f,x as p}from"./dist-MY__znoP.js";import{t as te}from"./AdminLayout-I1QMPYpW.js";import{t as m}from"./AdminButton-Bx141Bs3.js";var h={class:`mb-6`},g={"data-page-title":`admin.modules`,class:`text-2xl font-bold text-fg`},_={class:`mt-1 text-sm text-muted`},v={class:`bg-surface rounded-lg shadow overflow-hidden`},y={key:0,class:`p-6 text-sm text-muted`},b={key:1,class:`min-w-full text-sm`},x={class:`bg-surface-alt`},S={class:`px-4 py-2 text-left font-medium text-fg`},C={class:`px-4 py-2 text-left font-medium text-fg`},w={class:`divide-y divide-line`},T=[`data-module`,`data-parent`,`data-enabled`],E={key:0,"aria-hidden":`true`,class:`mr-1 text-muted`},D={key:1,class:`ml-2 rounded bg-surface-alt px-1.5 py-0.5 text-xs font-normal text-muted`},O={key:0,class:`text-muted`},k={class:`px-4 py-2 font-mono text-xs text-muted`},A={class:`px-4 py-2 text-right whitespace-nowrap space-x-2`},j={key:0,"data-section":`required`,class:`mt-8`},M={class:`text-lg font-semibold text-fg`},N={class:`mt-1 text-sm text-muted`},P={class:`mt-3 bg-surface rounded-lg shadow divide-y divide-line text-sm`},ne=[`data-required`],F={class:`font-medium text-fg`},I={key:0,class:`text-muted`},L={class:`mt-1 block font-mono text-xs text-fg select-all`},R={key:1,"data-section":`catalogue`,class:`mt-8`},z={class:`text-lg font-semibold text-fg`},B={class:`mt-1 text-sm text-muted`},V={class:`mt-3 text-sm text-muted`},H={key:0,"data-catalogue":`unavailable`,class:`mt-3 text-sm text-muted`},U={key:1,class:`mt-3 text-sm text-muted`},W={key:2,class:`mt-3 bg-surface rounded-lg shadow divide-y divide-line text-sm`},G=[`data-package`,`data-status`],K={class:`flex flex-wrap items-baseline gap-x-3`},q=[`href`],J={key:0,class:`rounded bg-surface-alt px-1.5 py-0.5 text-xs text-muted`},Y={class:`text-xs text-muted`},X={key:0,class:`text-muted`},Z={key:0,class:`mt-1 block font-mono text-xs text-fg select-all`},re={class:`mt-1 block font-mono text-xs text-fg select-all`},Q={__name:`Index`,props:{modules:Array,required:Array,canManage:Boolean,catalogue:Object,title:String},setup(Q){let ie=e=>{u.post(route(e.enabled?`admin.modules.disable`:`admin.modules.enable`,e.key),{},{preserveScroll:!0})},$=e=>`php artisan atrium:module:install ${e}`;return(u,ae)=>(n(),a(te,{title:Q.title},{default:s(()=>[p(`div`,h,[p(`h1`,g,c(Q.title),1),p(`p`,_,c(u.$t(`modules.index_hint`)),1)]),p(`div`,v,[Q.modules.length===0?(n(),f(`p`,y,c(u.$t(`modules.empty`)),1)):(n(),f(`table`,b,[p(`thead`,x,[p(`tr`,null,[p(`th`,S,c(u.$t(`modules.module`)),1),p(`th`,C,c(u.$t(`modules.package`)),1),ae[0]||=p(`th`,{class:`px-4 py-2`},null,-1)])]),p(`tbody`,w,[(n(!0),f(d,null,i(Q.modules,t=>(n(),f(`tr`,{key:t.name,"data-module":t.name,"data-parent":t.parent,"data-enabled":t.enabled?`true`:`false`},[p(`td`,{class:r([`py-2 pr-4`,t.parent?`pl-10`:`pl-4`])},[p(`div`,{class:r([`font-medium`,t.enabled?`text-fg`:`text-muted`])},[t.parent?(n(),f(`span`,E,`↳`)):e(``,!0),o(c(t.label)+` `,1),t.enabled?e(``,!0):(n(),f(`span`,D,c(u.$t(`modules.status_disabled`)),1))],2),t.description?(n(),f(`div`,O,c(t.description),1)):e(``,!0)],2),p(`td`,k,c(t.name),1),p(`td`,A,[t.settings?(n(),a(m,{key:0,size:`sm`,variant:`outline`,"data-action":`settings`,href:u.route(`admin.modules.settings`,t.key)},{default:s(()=>[o(c(u.$t(`modules.settings`)),1)]),_:1},8,[`href`])):e(``,!0),Q.canManage?(n(),a(m,{key:1,size:`sm`,variant:t.enabled?`secondary`:`success`,"data-action":t.enabled?`disable`:`enable`,onClick:e=>ie(t)},{default:s(()=>[o(c(t.enabled?u.$t(`modules.disable`):u.$t(`modules.enable`)),1)]),_:2},1032,[`variant`,`data-action`,`onClick`])):e(``,!0)])],8,T))),128))])]))]),Q.canManage&&Q.required.length?(n(),f(`section`,j,[p(`h2`,M,c(u.$t(`modules.required_title`)),1),p(`p`,N,c(u.$t(`modules.required_hint`)),1),p(`ul`,P,[(n(!0),f(d,null,i(Q.required,t=>(n(),f(`li`,{key:t.name,"data-required":t.name,class:`px-4 py-3`},[p(`div`,F,c(t.label),1),t.description?(n(),f(`div`,I,c(t.description),1)):e(``,!0),p(`code`,L,c($(t.name)),1)],8,ne))),128))])])):e(``,!0),Q.canManage?(n(),f(`section`,R,[p(`h2`,z,c(u.$t(`modules.catalogue_title`)),1),p(`p`,B,c(u.$t(`modules.catalogue_hint`)),1),t(ee(l),{data:`catalogue`},{fallback:s(()=>[p(`p`,V,c(u.$t(`modules.catalogue_loading`)),1)]),default:s(()=>[Q.catalogue.packages===null?(n(),f(`p`,H,c(u.$t(`modules.catalogue_unavailable`)),1)):Q.catalogue.packages.length===0?(n(),f(`p`,U,c(u.$t(`modules.catalogue_empty`)),1)):(n(),f(`ul`,W,[(n(!0),f(d,null,i(Q.catalogue.packages,t=>(n(),f(`li`,{key:t.name,"data-package":t.name,"data-status":t.status,class:`px-4 py-3`},[p(`div`,K,[p(`a`,{href:t.url,target:`_blank`,rel:`noopener`,class:`font-mono text-sm font-medium text-fg hover:underline`},c(t.name),9,q),t.status===`available`?e(``,!0):(n(),f(`span`,J,c(u.$t(`modules.status_${t.status}`)),1)),p(`span`,Y,c(u.$t(`modules.downloads`,{count:t.downloads})),1)]),t.description?(n(),f(`div`,X,c(t.description),1)):e(``,!0),t.status===`available`||t.status===`required`?(n(),f(d,{key:1},[t.status===`available`?(n(),f(`code`,Z,`composer require `+c(t.name),1)):e(``,!0),p(`code`,re,c($(t.name)),1)],64)):e(``,!0)],8,G))),128))]))]),_:1})])):e(``,!0)]),_:1},8,[`title`]))}};export{Q as default}; \ No newline at end of file +import{C as e,E as t,I as n,Q as r,R as i,S as a,T as o,W as s,Z as ee,et as c,n as l,s as u,v as d,w as f,x as p}from"./dist-MY__znoP.js";import{t as te}from"./AdminLayout--RXJFj9t.js";import{t as m}from"./AdminButton-Bx141Bs3.js";var h={class:`mb-6`},g={"data-page-title":`admin.modules`,class:`text-2xl font-bold text-fg`},_={class:`mt-1 text-sm text-muted`},v={class:`bg-surface rounded-lg shadow overflow-hidden`},y={key:0,class:`p-6 text-sm text-muted`},b={key:1,class:`min-w-full text-sm`},x={class:`bg-surface-alt`},S={class:`px-4 py-2 text-left font-medium text-fg`},C={class:`px-4 py-2 text-left font-medium text-fg`},w={class:`divide-y divide-line`},T=[`data-module`,`data-parent`,`data-enabled`],E={key:0,"aria-hidden":`true`,class:`mr-1 text-muted`},D={key:1,class:`ml-2 rounded bg-surface-alt px-1.5 py-0.5 text-xs font-normal text-muted`},O={key:0,class:`text-muted`},k={class:`px-4 py-2 font-mono text-xs text-muted`},A={class:`px-4 py-2 text-right whitespace-nowrap space-x-2`},j={key:0,"data-section":`required`,class:`mt-8`},M={class:`text-lg font-semibold text-fg`},N={class:`mt-1 text-sm text-muted`},P={class:`mt-3 bg-surface rounded-lg shadow divide-y divide-line text-sm`},ne=[`data-required`],F={class:`font-medium text-fg`},I={key:0,class:`text-muted`},L={class:`mt-1 block font-mono text-xs text-fg select-all`},R={key:1,"data-section":`catalogue`,class:`mt-8`},z={class:`text-lg font-semibold text-fg`},B={class:`mt-1 text-sm text-muted`},V={class:`mt-3 text-sm text-muted`},H={key:0,"data-catalogue":`unavailable`,class:`mt-3 text-sm text-muted`},U={key:1,class:`mt-3 text-sm text-muted`},W={key:2,class:`mt-3 bg-surface rounded-lg shadow divide-y divide-line text-sm`},G=[`data-package`,`data-status`],K={class:`flex flex-wrap items-baseline gap-x-3`},q=[`href`],J={key:0,class:`rounded bg-surface-alt px-1.5 py-0.5 text-xs text-muted`},Y={class:`text-xs text-muted`},X={key:0,class:`text-muted`},Z={key:0,class:`mt-1 block font-mono text-xs text-fg select-all`},re={class:`mt-1 block font-mono text-xs text-fg select-all`},Q={__name:`Index`,props:{modules:Array,required:Array,canManage:Boolean,catalogue:Object,title:String},setup(Q){let ie=e=>{u.post(route(e.enabled?`admin.modules.disable`:`admin.modules.enable`,e.key),{},{preserveScroll:!0})},$=e=>`php artisan atrium:module:install ${e}`;return(u,ae)=>(n(),a(te,{title:Q.title},{default:s(()=>[p(`div`,h,[p(`h1`,g,c(Q.title),1),p(`p`,_,c(u.$t(`modules.index_hint`)),1)]),p(`div`,v,[Q.modules.length===0?(n(),f(`p`,y,c(u.$t(`modules.empty`)),1)):(n(),f(`table`,b,[p(`thead`,x,[p(`tr`,null,[p(`th`,S,c(u.$t(`modules.module`)),1),p(`th`,C,c(u.$t(`modules.package`)),1),ae[0]||=p(`th`,{class:`px-4 py-2`},null,-1)])]),p(`tbody`,w,[(n(!0),f(d,null,i(Q.modules,t=>(n(),f(`tr`,{key:t.name,"data-module":t.name,"data-parent":t.parent,"data-enabled":t.enabled?`true`:`false`},[p(`td`,{class:r([`py-2 pr-4`,t.parent?`pl-10`:`pl-4`])},[p(`div`,{class:r([`font-medium`,t.enabled?`text-fg`:`text-muted`])},[t.parent?(n(),f(`span`,E,`↳`)):e(``,!0),o(c(t.label)+` `,1),t.enabled?e(``,!0):(n(),f(`span`,D,c(u.$t(`modules.status_disabled`)),1))],2),t.description?(n(),f(`div`,O,c(t.description),1)):e(``,!0)],2),p(`td`,k,c(t.name),1),p(`td`,A,[t.settings?(n(),a(m,{key:0,size:`sm`,variant:`outline`,"data-action":`settings`,href:u.route(`admin.modules.settings`,t.key)},{default:s(()=>[o(c(u.$t(`modules.settings`)),1)]),_:1},8,[`href`])):e(``,!0),Q.canManage?(n(),a(m,{key:1,size:`sm`,variant:t.enabled?`secondary`:`success`,"data-action":t.enabled?`disable`:`enable`,onClick:e=>ie(t)},{default:s(()=>[o(c(t.enabled?u.$t(`modules.disable`):u.$t(`modules.enable`)),1)]),_:2},1032,[`variant`,`data-action`,`onClick`])):e(``,!0)])],8,T))),128))])]))]),Q.canManage&&Q.required.length?(n(),f(`section`,j,[p(`h2`,M,c(u.$t(`modules.required_title`)),1),p(`p`,N,c(u.$t(`modules.required_hint`)),1),p(`ul`,P,[(n(!0),f(d,null,i(Q.required,t=>(n(),f(`li`,{key:t.name,"data-required":t.name,class:`px-4 py-3`},[p(`div`,F,c(t.label),1),t.description?(n(),f(`div`,I,c(t.description),1)):e(``,!0),p(`code`,L,c($(t.name)),1)],8,ne))),128))])])):e(``,!0),Q.canManage?(n(),f(`section`,R,[p(`h2`,z,c(u.$t(`modules.catalogue_title`)),1),p(`p`,B,c(u.$t(`modules.catalogue_hint`)),1),t(ee(l),{data:`catalogue`},{fallback:s(()=>[p(`p`,V,c(u.$t(`modules.catalogue_loading`)),1)]),default:s(()=>[Q.catalogue.packages===null?(n(),f(`p`,H,c(u.$t(`modules.catalogue_unavailable`)),1)):Q.catalogue.packages.length===0?(n(),f(`p`,U,c(u.$t(`modules.catalogue_empty`)),1)):(n(),f(`ul`,W,[(n(!0),f(d,null,i(Q.catalogue.packages,t=>(n(),f(`li`,{key:t.name,"data-package":t.name,"data-status":t.status,class:`px-4 py-3`},[p(`div`,K,[p(`a`,{href:t.url,target:`_blank`,rel:`noopener`,class:`font-mono text-sm font-medium text-fg hover:underline`},c(t.name),9,q),t.status===`available`?e(``,!0):(n(),f(`span`,J,c(u.$t(`modules.status_${t.status}`)),1)),p(`span`,Y,c(u.$t(`modules.downloads`,{count:t.downloads})),1)]),t.description?(n(),f(`div`,X,c(t.description),1)):e(``,!0),t.status===`available`||t.status===`required`?(n(),f(d,{key:1},[t.status===`available`?(n(),f(`code`,Z,`composer require `+c(t.name),1)):e(``,!0),p(`code`,re,c($(t.name)),1)],64)):e(``,!0)],8,G))),128))]))]),_:1})])):e(``,!0)]),_:1},8,[`title`]))}};export{Q as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-B0DDRHtS.js b/packages/admin/dist/assets/Index-9-V30Hlc.js similarity index 99% rename from packages/admin/dist/assets/Index-B0DDRHtS.js rename to packages/admin/dist/assets/Index-9-V30Hlc.js index 223ab5a3..65fcb8cf 100644 --- a/packages/admin/dist/assets/Index-B0DDRHtS.js +++ b/packages/admin/dist/assets/Index-9-V30Hlc.js @@ -1 +1 @@ -import{C as e,E as t,G as n,H as r,I as i,N as a,Q as o,R as s,S as ee,T as c,W as l,Y as u,b as d,et as f,m as p,o as te,s as m,u as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{n as y,r as ne,t as re}from"./AdminLayout-I1QMPYpW.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{t as S}from"./AdminModal-DNJ_V4iq.js";var ie={class:`mb-6 flex flex-wrap items-start justify-between gap-4`},ae={class:`text-2xl font-bold text-fg`},oe={class:`mt-1 text-sm text-muted`},se={class:`flex flex-wrap gap-2`},ce={key:0,dusk:`backup-running`,role:`status`,class:`mb-6 flex items-center gap-3 p-4 bg-accent-soft text-accent-soft-fg border border-line rounded-lg text-sm`},le={class:`space-y-6`},ue={key:0,class:`p-6 text-sm text-muted`},de={key:1,class:`overflow-x-auto`},fe={dusk:`backups`,class:`min-w-full text-sm`},pe={class:`bg-surface-alt`},me={class:`px-4 py-2 text-left font-medium text-fg`},he={class:`px-4 py-2 text-left font-medium text-fg`},ge={class:`px-4 py-2 text-left font-medium text-fg`},_e={class:`px-4 py-2 text-right font-medium text-fg`},ve={class:`divide-y divide-line`},ye=[`data-backup`],be={class:`px-4 py-2 font-mono text-fg`},xe={class:`px-4 py-2 text-fg`},C={class:`px-4 py-2 text-fg`},w={class:`px-4 py-2 text-right text-fg whitespace-nowrap`},T={class:`px-4 py-2 text-right whitespace-nowrap space-x-2`},E=[`href`],D=[`disabled`,`onClick`],O=[`onClick`],k={class:`grid gap-6 lg:grid-cols-2`},A={class:`space-y-4`},j=[`data-destination`,`dusk`],M={class:`flex flex-wrap items-center gap-2`},Se={class:`font-medium text-fg`},Ce={key:0,class:`mt-1 text-sm text-fg`},we={key:1,class:`mt-1 list-disc pl-5 text-sm text-danger`},Te={class:`grid grid-cols-1 sm:grid-cols-3 gap-x-4 gap-y-3 text-sm`},Ee={class:`font-medium text-fg`},De={class:`sm:col-span-2 text-fg`},Oe={class:`font-medium text-fg`},ke={class:`sm:col-span-2 text-fg break-all`},Ae={class:`font-medium text-fg`},je={class:`sm:col-span-2 text-fg`},Me={class:`font-medium text-fg`},Ne={class:`sm:col-span-2 text-fg`},Pe={key:0},Fe={class:`font-medium text-fg`},Ie={class:`sm:col-span-2 text-fg`},Le={class:`font-medium text-fg`},Re={class:`sm:col-span-2 text-fg`},ze={key:0,class:`p-6 text-sm text-muted`},Be={key:1,class:`overflow-x-auto`},Ve={dusk:`backup-log`,class:`min-w-full text-sm`},He={class:`bg-surface-alt`},Ue={class:`px-4 py-2 text-left font-medium text-fg`},We={class:`px-4 py-2 text-left font-medium text-fg`},Ge={class:`px-4 py-2 text-left font-medium text-fg`},Ke={class:`px-4 py-2 text-left font-medium text-fg`},qe={class:`divide-y divide-line`},Je={class:`px-4 py-2 text-fg whitespace-nowrap`},Ye={class:`px-4 py-2 text-fg`},Xe={class:`px-4 py-2`},Ze={class:`px-4 py-2 text-fg break-words`},Qe={class:`p-6`},$e={class:`text-fg`},et={class:`mt-6 flex justify-end gap-2`},tt={key:0,dusk:`restore-dialog`,class:`p-6 space-y-5 text-sm`},nt={class:`text-fg`},rt={class:`flex flex-wrap items-end gap-3`},it={class:`flex-1 min-w-48`},at={for:`backup-password`,class:`block font-medium text-fg`},ot={class:`mt-1 text-xs text-muted`},st={key:0,"data-error":``,class:`text-danger`,role:`alert`},ct={key:0,class:`text-fg`},lt={key:1,class:`overflow-x-auto border border-line rounded-md`},ut={dusk:`plan-databases`,class:`min-w-full`},dt={class:`bg-surface-alt`},ft={class:`px-3 py-2 text-left font-medium text-fg`},pt={class:`px-3 py-2 text-left font-medium text-fg`},mt={class:`px-3 py-2 text-right font-medium text-fg`},ht={class:`px-3 py-2 text-left font-medium text-fg`},gt={class:`divide-y divide-line`},_t={class:`px-3 py-1.5 text-fg`},vt={class:`px-3 py-1.5 text-fg`},yt={class:`px-3 py-1.5 text-right text-fg`},bt={class:`px-3 py-1.5 text-fg break-all`},xt={key:2,class:`overflow-x-auto border border-line rounded-md`},St={dusk:`plan-folders`,class:`min-w-full`},Ct={class:`bg-surface-alt`},N={class:`px-3 py-2 text-left font-medium text-fg`},wt={class:`px-3 py-2 text-right font-medium text-fg`},Tt={class:`px-3 py-2 text-right font-medium text-fg`},Et={class:`px-3 py-2 text-right font-medium text-fg`},Dt={class:`px-3 py-2 text-right font-medium text-fg`},Ot={class:`px-3 py-2 text-right font-medium text-fg`},kt={class:`divide-y divide-line`},At={class:`px-3 py-1.5 text-fg break-all`},jt={class:`px-3 py-1.5 text-right text-fg`},Mt={class:`px-3 py-1.5 text-right text-fg`},Nt={class:`px-3 py-1.5 text-right text-fg`},Pt={class:`px-3 py-1.5 text-right text-fg`},Ft={class:`px-3 py-1.5 text-right text-fg`},It={key:3,class:`list-disc pl-5 bg-warning-soft text-warning-soft-fg border border-line rounded-md p-3 space-y-1`},Lt={class:`space-y-2`},Rt={class:`flex items-center gap-2 text-fg`},zt={class:`flex items-center gap-2 text-fg`},Bt={class:`flex items-center gap-2 text-fg ml-6`},Vt=[`disabled`],Ht={class:`flex items-center gap-2 text-fg`},Ut={class:`p-4 bg-surface text-fg border-2 border-danger rounded-lg`},Wt={class:`font-medium`},Gt={class:`mt-2 list-disc pl-5 space-y-1`},Kt={key:0},qt={key:1},Jt={key:2},Yt={for:`backup-confirm`,class:`block font-medium text-fg`},Xt={key:0,"data-error":``,class:`mt-1 text-danger`},Zt={class:`flex justify-end gap-2`},P={__name:`Index`,props:{backups:Array,running:Object,log:Array,health:Array,settings:Object,labels:Object},setup(P){let F=P,Qt=te(),I=d(()=>String(Qt.props.locale||`en`).replace(`_`,`-`));function L(e,t={}){let n=F.labels?.[e]??e;for(let[e,r]of Object.entries(t))n=n.replaceAll(`:${e}`,String(r??``));return n}function R(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Number(e)||0,r=0;for(;n>=1024&&r1)})} ${t[r]}`}function z(e){return e?new Date(e).toLocaleString(I.value,{dateStyle:`medium`,timeStyle:`short`}):``}let B=u({backups:F.backups,running:F.running,log:F.log}),V=null;r(()=>[F.backups,F.running,F.log],()=>{B.value={backups:F.backups,running:F.running,log:F.log}});async function H(){let e=await fetch(route(`admin.backups.status`),{headers:y()}).catch(()=>null);if(e?.ok){let t=await e.json(),n=B.value.running&&!t.running;B.value=t,n&&m.reload({only:[`health`,`backups`,`running`,`log`]})}}r(()=>B.value.running,e=>{clearInterval(V),V=e?setInterval(H,3e3):null},{immediate:!0}),a(()=>clearInterval(V));let U=u(!1);function W(e=null){U.value=!0,m.post(route(`admin.backups.store`),{only:e},{preserveScroll:!0,onSuccess:()=>H(),onFinish:()=>{U.value=!1}})}let G=u(null);function $t(){m.delete(route(`admin.backups.destroy`,G.value.id),{preserveScroll:!0,onFinish:()=>{G.value=null}})}let K=u(null),q=u(null),J=u(``),Y=u(!1),X=u({}),Z=u({}),Q=u(!1);function en(e){K.value=e,q.value=null,J.value=``,Z.value={},X.value={password:``,database:!0,files:!0,delete_extra:!1,safety_backup:!0,confirm:``}}async function tn(){Y.value=!0,J.value=``;try{let e=await fetch(route(`admin.backups.plan`,K.value.id),{method:`POST`,headers:y({"Content-Type":`application/json`}),body:JSON.stringify({password:X.value.password||null})});if(!e.ok){J.value=await ne(e,L(`preview_failed`)),q.value=null;return}q.value=(await e.json()).plan}catch{J.value=L(`preview_failed`)}finally{Y.value=!1}}let nn=d(()=>q.value&&(X.value.database||X.value.files)&&X.value.confirm.trim()===K.value?.file);function rn(){Q.value=!0,m.post(route(`admin.backups.restore`,K.value.id),{...X.value,confirm:X.value.confirm.trim(),password:X.value.password||null},{preserveScroll:!0,onSuccess:()=>{K.value=null,H()},onError:e=>{Z.value=e},onFinish:()=>{Q.value=!1}})}let an=d(()=>{let e=F.settings?.schedule||{};return e.frequency===`daily`?L(`schedule_daily`,{time:e.time}):e.frequency===`weekly`?L(`schedule_weekly`,{weekday:F.settings.weekday,time:e.time}):L(`schedule_off`)}),on=d(()=>{let e=F.settings?.retention||{};return L(`retention_text`,{all:e.keep_all_days,daily:e.daily,weekly:e.weekly,monthly:e.monthly,yearly:e.yearly})}),$={ok:`bg-success-soft text-success-soft-fg`,partial:`bg-warning-soft text-warning-soft-fg`,failed:`bg-danger-soft text-danger-soft-fg`};function sn(e){let t=[];return e.trigger&&t.push(L(`trigger_${e.trigger}`)),e.by&&t.push(e.by),e.file&&t.push(e.disk?`${e.file} (${e.disk})`:e.file),e.disks?.length&&t.push(L(`copied_to`,{disks:e.disks.join(`, `)})),e.failed?.length&&t.push(L(`not_copied_to`,{disks:e.failed.map(e=>e.disk??e).join(`, `)})),e.action===`restore`&&e.status===`ok`&&t.push(L(`restored`,{databases:(e.databases||[]).join(`, `)||`—`,files:e.files??0,deleted:e.deleted??0})),e.seconds!==void 0&&t.push(L(`seconds`,{seconds:e.seconds})),e.message&&t.push(e.message),t.join(` · `)}return(r,a)=>(i(),ee(re,{title:L(`menu`)},{default:l(()=>[v(`div`,ie,[v(`div`,null,[v(`h1`,ae,f(P.labels.menu),1),v(`p`,oe,f(L(`subtitle`)),1)]),v(`div`,se,[t(b,{dusk:`backup-now`,loading:U.value,disabled:!!B.value.running,onClick:a[0]||=e=>W()},{default:l(()=>[c(f(L(`back_up_now`)),1)]),_:1},8,[`loading`,`disabled`]),t(b,{variant:`secondary`,disabled:U.value||!!B.value.running,onClick:a[1]||=e=>W(`database`)},{default:l(()=>[c(f(L(`only_database`)),1)]),_:1},8,[`disabled`]),t(b,{variant:`secondary`,disabled:U.value||!!B.value.running,onClick:a[2]||=e=>W(`files`)},{default:l(()=>[c(f(L(`only_files`)),1)]),_:1},8,[`disabled`])])]),B.value.running?(i(),_(`div`,ce,[a[13]||=v(`svg`,{class:`animate-spin h-5 w-5`,fill:`none`,viewBox:`0 0 24 24`,"aria-hidden":`true`},[v(`circle`,{class:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,"stroke-width":`4`}),v(`path`,{class:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})],-1),c(` `+f(L(B.value.running.action===`restore`?`running_restore`:`running_backup`,{time:z(B.value.running.started_at)})),1)])):e(``,!0),v(`div`,le,[t(x,{title:L(`archives`),"no-padding":``},{default:l(()=>[B.value.backups.length?(i(),_(`div`,de,[v(`table`,fe,[v(`thead`,pe,[v(`tr`,null,[v(`th`,me,f(L(`file`)),1),v(`th`,he,f(L(`destination`)),1),v(`th`,ge,f(L(`date`)),1),v(`th`,_e,f(L(`size`)),1),a[14]||=v(`th`,{class:`px-4 py-2`},null,-1)])]),v(`tbody`,ve,[(i(!0),_(g,null,s(B.value.backups,e=>(i(),_(`tr`,{key:e.id,"data-backup":e.file,dusk:`backup`},[v(`td`,be,f(e.file),1),v(`td`,xe,f(e.disk),1),v(`td`,C,f(z(e.date)),1),v(`td`,w,f(R(e.size)),1),v(`td`,T,[v(`a`,{href:e.download_url,class:`text-accent underline`},f(L(`download`)),9,E),v(`button`,{type:`button`,dusk:`restore`,class:`text-accent underline`,disabled:!!B.value.running,onClick:t=>en(e)},f(L(`restore`)),9,D),v(`button`,{type:`button`,dusk:`delete`,class:`text-danger underline`,onClick:t=>G.value=e},f(L(`delete`)),9,O)])],8,ye))),128))])])])):(i(),_(`p`,ue,f(L(`empty`)),1))]),_:1},8,[`title`]),v(`div`,k,[t(x,{title:L(`destinations`)},{default:l(()=>[v(`ul`,A,[(i(!0),_(g,null,s(P.health,t=>(i(),_(`li`,{key:t.disk,"data-destination":t.disk,dusk:`destination-${t.disk}`},[v(`div`,M,[v(`span`,Se,f(t.disk),1),v(`span`,{class:o([`px-2 py-0.5 rounded text-xs font-medium`,!t.reachable||!t.healthy?$.failed:$.ok])},f(t.reachable?t.healthy?L(`healthy`):L(`unhealthy`):L(`unreachable`)),3)]),t.reachable?(i(),_(`p`,Ce,f(L(`stored`,{count:t.count,size:R(t.used)}))+` · `+f(t.newest?L(`newest`,{date:z(t.newest)}):L(`no_archive`)),1)):e(``,!0),t.problems.length?(i(),_(`ul`,we,[(i(!0),_(g,null,s(t.problems,e=>(i(),_(`li`,{key:e},f(e),1))),128))])):e(``,!0)],8,j))),128))])]),_:1},8,[`title`]),t(x,{title:L(`settings`),subtitle:L(`settings_note`)},{default:l(()=>[v(`dl`,Te,[v(`dt`,Ee,f(L(`databases`)),1),v(`dd`,De,f(P.settings.databases.map(e=>`${e.connection} (${e.driver})`).join(`, `)||L(`nothing`)),1),v(`dt`,Oe,f(L(`folders`)),1),v(`dd`,ke,f(P.settings.folders.join(`, `)||L(`nothing`)),1),v(`dt`,Ae,f(L(`destinations`)),1),v(`dd`,je,f(P.settings.destinations.join(`, `)),1),v(`dt`,Me,f(L(`schedule`)),1),v(`dd`,Ne,[c(f(an.value),1),P.settings.queue?(i(),_(`span`,Pe,`. `+f(L(`queue`,{queue:P.settings.queue})),1)):e(``,!0)]),v(`dt`,Fe,f(L(`retention`)),1),v(`dd`,Ie,f(on.value),1),v(`dt`,Le,f(L(`encryption`)),1),v(`dd`,Re,f(P.settings.encrypted?L(`encrypted`):L(`not_encrypted`)),1)])]),_:1},8,[`title`,`subtitle`])]),t(x,{title:L(`log`),"no-padding":``},{default:l(()=>[B.value.log.length?(i(),_(`div`,Be,[v(`table`,Ve,[v(`thead`,He,[v(`tr`,null,[v(`th`,Ue,f(L(`when`)),1),v(`th`,We,f(L(`what`)),1),v(`th`,Ge,f(L(`result`)),1),v(`th`,Ke,f(L(`details`)),1)])]),v(`tbody`,qe,[(i(!0),_(g,null,s(B.value.log,(e,t)=>(i(),_(`tr`,{key:t},[v(`td`,Je,f(z(e.at)),1),v(`td`,Ye,f(L(`action_${e.action}`)),1),v(`td`,Xe,[v(`span`,{class:o([`px-2 py-0.5 rounded text-xs font-medium`,$[e.status]||$.failed])},f(L(`status_${e.status}`)),3)]),v(`td`,Ze,f(sn(e)),1)]))),128))])])])):(i(),_(`p`,ze,f(L(`log_empty`)),1))]),_:1},8,[`title`])]),t(S,{show:!!G.value,title:L(`delete`),onClose:a[4]||=e=>G.value=null},{default:l(()=>[v(`div`,Qe,[v(`p`,$e,f(G.value?L(`delete_confirm`,{file:G.value.file,disk:G.value.disk}):``),1),v(`div`,et,[t(b,{variant:`secondary`,onClick:a[3]||=e=>G.value=null},{default:l(()=>[c(f(L(`cancel`)),1)]),_:1}),t(b,{dusk:`confirm-delete`,variant:`danger`,onClick:$t},{default:l(()=>[c(f(L(`delete`)),1)]),_:1})])])]),_:1},8,[`show`,`title`]),t(S,{show:!!K.value,"max-width":`2xl`,title:K.value?L(`restore_title`,{file:K.value.file}):``,onClose:a[12]||=e=>K.value=null},{default:l(()=>[K.value?(i(),_(`div`,tt,[v(`p`,nt,f(L(`restore_intro`)),1),v(`div`,rt,[v(`div`,it,[v(`label`,at,f(L(`password`)),1),n(v(`input`,{id:`backup-password`,"onUpdate:modelValue":a[5]||=e=>X.value.password=e,type:`password`,autocomplete:`off`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus`},null,512),[[p,X.value.password]]),v(`p`,ot,f(L(`password_hint`)),1)]),t(b,{dusk:`preview`,variant:`secondary`,loading:Y.value,onClick:tn},{default:l(()=>[c(f(L(`preview`)),1)]),_:1},8,[`loading`])]),J.value?(i(),_(`p`,st,f(J.value),1)):e(``,!0),q.value?(i(),_(g,{key:1},[q.value.created_at?(i(),_(`p`,ct,f(L(`made`,{date:z(q.value.created_at)})),1)):e(``,!0),q.value.databases.length?(i(),_(`div`,lt,[v(`table`,ut,[v(`thead`,dt,[v(`tr`,null,[v(`th`,ft,f(L(`connection`)),1),v(`th`,pt,f(L(`driver`)),1),v(`th`,mt,f(L(`dump`)),1),v(`th`,ht,f(L(`replaces`)),1)])]),v(`tbody`,gt,[(i(!0),_(g,null,s(q.value.databases,e=>(i(),_(`tr`,{key:e.connection},[v(`td`,_t,f(e.connection),1),v(`td`,vt,f(e.driver),1),v(`td`,yt,f(R(e.size)),1),v(`td`,bt,f(e.restorable?e.target:L(`skipped`)),1)]))),128))])])])):e(``,!0),q.value.folders.length?(i(),_(`div`,xt,[v(`table`,St,[v(`thead`,Ct,[v(`tr`,null,[v(`th`,N,f(L(`into`)),1),v(`th`,wt,f(L(`files`)),1),v(`th`,Tt,f(L(`new`)),1),v(`th`,Et,f(L(`changed`)),1),v(`th`,Dt,f(L(`unchanged`)),1),v(`th`,Ot,f(L(`extra`)),1)])]),v(`tbody`,kt,[(i(!0),_(g,null,s(q.value.folders,e=>(i(),_(`tr`,{key:e.prefix},[v(`td`,At,f(e.target),1),v(`td`,jt,f(e.files),1),v(`td`,Mt,f(e.new),1),v(`td`,Nt,f(e.changed),1),v(`td`,Pt,f(e.unchanged),1),v(`td`,Ft,f(e.extra),1)]))),128))])])])):e(``,!0),q.value.warnings.length?(i(),_(`ul`,It,[(i(!0),_(g,null,s(q.value.warnings,e=>(i(),_(`li`,{key:e,class:`ml-3`},f(e),1))),128))])):e(``,!0),v(`fieldset`,Lt,[v(`label`,Rt,[n(v(`input`,{"onUpdate:modelValue":a[6]||=e=>X.value.database=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.database]]),c(` `+f(L(`restore_database`)),1)]),v(`label`,zt,[n(v(`input`,{"onUpdate:modelValue":a[7]||=e=>X.value.files=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.files]]),c(` `+f(L(`restore_files`)),1)]),v(`label`,Bt,[n(v(`input`,{"onUpdate:modelValue":a[8]||=e=>X.value.delete_extra=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`,disabled:!X.value.files},null,8,Vt),[[h,X.value.delete_extra]]),c(` `+f(L(`delete_extra`)),1)]),v(`label`,Ht,[n(v(`input`,{"onUpdate:modelValue":a[9]||=e=>X.value.safety_backup=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.safety_backup]]),c(` `+f(L(`safety_backup`)),1)])]),v(`div`,Ut,[v(`p`,Wt,f(L(`risks`)),1),v(`ul`,Gt,[X.value.database?(i(),_(`li`,Kt,f(L(`risk_database`,{date:z(q.value.created_at||K.value.date)})),1)):e(``,!0),X.value.database?(i(),_(`li`,qt,f(L(`risk_sessions`)),1)):e(``,!0),X.value.files?(i(),_(`li`,Jt,f(L(`risk_files`)),1)):e(``,!0),v(`li`,null,f(L(`risk_site`)),1)])]),v(`div`,null,[v(`label`,Yt,f(L(`confirm`,{file:K.value.file})),1),n(v(`input`,{id:`backup-confirm`,dusk:`restore-confirm`,"onUpdate:modelValue":a[10]||=e=>X.value.confirm=e,type:`text`,autocomplete:`off`,spellcheck:`false`,class:`mt-1 block w-full px-3 py-2 font-mono border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus`},null,512),[[p,X.value.confirm]]),Z.value.confirm?(i(),_(`p`,Xt,f(Z.value.confirm),1)):e(``,!0)])],64)):e(``,!0),v(`div`,Zt,[t(b,{dusk:`cancel-restore`,variant:`secondary`,onClick:a[11]||=e=>K.value=null},{default:l(()=>[c(f(L(`cancel`)),1)]),_:1}),t(b,{dusk:`start-restore`,variant:`danger`,loading:Q.value,disabled:!nn.value,onClick:rn},{default:l(()=>[c(f(L(`start_restore`)),1)]),_:1},8,[`loading`,`disabled`])])])):e(``,!0)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{P as default}; \ No newline at end of file +import{C as e,E as t,G as n,H as r,I as i,N as a,Q as o,R as s,S as ee,T as c,W as l,Y as u,b as d,et as f,m as p,o as te,s as m,u as h,v as g,w as _,x as v}from"./dist-MY__znoP.js";import{n as y,r as ne,t as re}from"./AdminLayout--RXJFj9t.js";import{t as b}from"./AdminButton-Bx141Bs3.js";import{t as x}from"./AdminCard--HubMtUj.js";import{t as S}from"./AdminModal-DNJ_V4iq.js";var ie={class:`mb-6 flex flex-wrap items-start justify-between gap-4`},ae={class:`text-2xl font-bold text-fg`},oe={class:`mt-1 text-sm text-muted`},se={class:`flex flex-wrap gap-2`},ce={key:0,dusk:`backup-running`,role:`status`,class:`mb-6 flex items-center gap-3 p-4 bg-accent-soft text-accent-soft-fg border border-line rounded-lg text-sm`},le={class:`space-y-6`},ue={key:0,class:`p-6 text-sm text-muted`},de={key:1,class:`overflow-x-auto`},fe={dusk:`backups`,class:`min-w-full text-sm`},pe={class:`bg-surface-alt`},me={class:`px-4 py-2 text-left font-medium text-fg`},he={class:`px-4 py-2 text-left font-medium text-fg`},ge={class:`px-4 py-2 text-left font-medium text-fg`},_e={class:`px-4 py-2 text-right font-medium text-fg`},ve={class:`divide-y divide-line`},ye=[`data-backup`],be={class:`px-4 py-2 font-mono text-fg`},xe={class:`px-4 py-2 text-fg`},C={class:`px-4 py-2 text-fg`},w={class:`px-4 py-2 text-right text-fg whitespace-nowrap`},T={class:`px-4 py-2 text-right whitespace-nowrap space-x-2`},E=[`href`],D=[`disabled`,`onClick`],O=[`onClick`],k={class:`grid gap-6 lg:grid-cols-2`},A={class:`space-y-4`},j=[`data-destination`,`dusk`],M={class:`flex flex-wrap items-center gap-2`},Se={class:`font-medium text-fg`},Ce={key:0,class:`mt-1 text-sm text-fg`},we={key:1,class:`mt-1 list-disc pl-5 text-sm text-danger`},Te={class:`grid grid-cols-1 sm:grid-cols-3 gap-x-4 gap-y-3 text-sm`},Ee={class:`font-medium text-fg`},De={class:`sm:col-span-2 text-fg`},Oe={class:`font-medium text-fg`},ke={class:`sm:col-span-2 text-fg break-all`},Ae={class:`font-medium text-fg`},je={class:`sm:col-span-2 text-fg`},Me={class:`font-medium text-fg`},Ne={class:`sm:col-span-2 text-fg`},Pe={key:0},Fe={class:`font-medium text-fg`},Ie={class:`sm:col-span-2 text-fg`},Le={class:`font-medium text-fg`},Re={class:`sm:col-span-2 text-fg`},ze={key:0,class:`p-6 text-sm text-muted`},Be={key:1,class:`overflow-x-auto`},Ve={dusk:`backup-log`,class:`min-w-full text-sm`},He={class:`bg-surface-alt`},Ue={class:`px-4 py-2 text-left font-medium text-fg`},We={class:`px-4 py-2 text-left font-medium text-fg`},Ge={class:`px-4 py-2 text-left font-medium text-fg`},Ke={class:`px-4 py-2 text-left font-medium text-fg`},qe={class:`divide-y divide-line`},Je={class:`px-4 py-2 text-fg whitespace-nowrap`},Ye={class:`px-4 py-2 text-fg`},Xe={class:`px-4 py-2`},Ze={class:`px-4 py-2 text-fg break-words`},Qe={class:`p-6`},$e={class:`text-fg`},et={class:`mt-6 flex justify-end gap-2`},tt={key:0,dusk:`restore-dialog`,class:`p-6 space-y-5 text-sm`},nt={class:`text-fg`},rt={class:`flex flex-wrap items-end gap-3`},it={class:`flex-1 min-w-48`},at={for:`backup-password`,class:`block font-medium text-fg`},ot={class:`mt-1 text-xs text-muted`},st={key:0,"data-error":``,class:`text-danger`,role:`alert`},ct={key:0,class:`text-fg`},lt={key:1,class:`overflow-x-auto border border-line rounded-md`},ut={dusk:`plan-databases`,class:`min-w-full`},dt={class:`bg-surface-alt`},ft={class:`px-3 py-2 text-left font-medium text-fg`},pt={class:`px-3 py-2 text-left font-medium text-fg`},mt={class:`px-3 py-2 text-right font-medium text-fg`},ht={class:`px-3 py-2 text-left font-medium text-fg`},gt={class:`divide-y divide-line`},_t={class:`px-3 py-1.5 text-fg`},vt={class:`px-3 py-1.5 text-fg`},yt={class:`px-3 py-1.5 text-right text-fg`},bt={class:`px-3 py-1.5 text-fg break-all`},xt={key:2,class:`overflow-x-auto border border-line rounded-md`},St={dusk:`plan-folders`,class:`min-w-full`},Ct={class:`bg-surface-alt`},N={class:`px-3 py-2 text-left font-medium text-fg`},wt={class:`px-3 py-2 text-right font-medium text-fg`},Tt={class:`px-3 py-2 text-right font-medium text-fg`},Et={class:`px-3 py-2 text-right font-medium text-fg`},Dt={class:`px-3 py-2 text-right font-medium text-fg`},Ot={class:`px-3 py-2 text-right font-medium text-fg`},kt={class:`divide-y divide-line`},At={class:`px-3 py-1.5 text-fg break-all`},jt={class:`px-3 py-1.5 text-right text-fg`},Mt={class:`px-3 py-1.5 text-right text-fg`},Nt={class:`px-3 py-1.5 text-right text-fg`},Pt={class:`px-3 py-1.5 text-right text-fg`},Ft={class:`px-3 py-1.5 text-right text-fg`},It={key:3,class:`list-disc pl-5 bg-warning-soft text-warning-soft-fg border border-line rounded-md p-3 space-y-1`},Lt={class:`space-y-2`},Rt={class:`flex items-center gap-2 text-fg`},zt={class:`flex items-center gap-2 text-fg`},Bt={class:`flex items-center gap-2 text-fg ml-6`},Vt=[`disabled`],Ht={class:`flex items-center gap-2 text-fg`},Ut={class:`p-4 bg-surface text-fg border-2 border-danger rounded-lg`},Wt={class:`font-medium`},Gt={class:`mt-2 list-disc pl-5 space-y-1`},Kt={key:0},qt={key:1},Jt={key:2},Yt={for:`backup-confirm`,class:`block font-medium text-fg`},Xt={key:0,"data-error":``,class:`mt-1 text-danger`},Zt={class:`flex justify-end gap-2`},P={__name:`Index`,props:{backups:Array,running:Object,log:Array,health:Array,settings:Object,labels:Object},setup(P){let F=P,Qt=te(),I=d(()=>String(Qt.props.locale||`en`).replace(`_`,`-`));function L(e,t={}){let n=F.labels?.[e]??e;for(let[e,r]of Object.entries(t))n=n.replaceAll(`:${e}`,String(r??``));return n}function R(e){let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=Number(e)||0,r=0;for(;n>=1024&&r1)})} ${t[r]}`}function z(e){return e?new Date(e).toLocaleString(I.value,{dateStyle:`medium`,timeStyle:`short`}):``}let B=u({backups:F.backups,running:F.running,log:F.log}),V=null;r(()=>[F.backups,F.running,F.log],()=>{B.value={backups:F.backups,running:F.running,log:F.log}});async function H(){let e=await fetch(route(`admin.backups.status`),{headers:y()}).catch(()=>null);if(e?.ok){let t=await e.json(),n=B.value.running&&!t.running;B.value=t,n&&m.reload({only:[`health`,`backups`,`running`,`log`]})}}r(()=>B.value.running,e=>{clearInterval(V),V=e?setInterval(H,3e3):null},{immediate:!0}),a(()=>clearInterval(V));let U=u(!1);function W(e=null){U.value=!0,m.post(route(`admin.backups.store`),{only:e},{preserveScroll:!0,onSuccess:()=>H(),onFinish:()=>{U.value=!1}})}let G=u(null);function $t(){m.delete(route(`admin.backups.destroy`,G.value.id),{preserveScroll:!0,onFinish:()=>{G.value=null}})}let K=u(null),q=u(null),J=u(``),Y=u(!1),X=u({}),Z=u({}),Q=u(!1);function en(e){K.value=e,q.value=null,J.value=``,Z.value={},X.value={password:``,database:!0,files:!0,delete_extra:!1,safety_backup:!0,confirm:``}}async function tn(){Y.value=!0,J.value=``;try{let e=await fetch(route(`admin.backups.plan`,K.value.id),{method:`POST`,headers:y({"Content-Type":`application/json`}),body:JSON.stringify({password:X.value.password||null})});if(!e.ok){J.value=await ne(e,L(`preview_failed`)),q.value=null;return}q.value=(await e.json()).plan}catch{J.value=L(`preview_failed`)}finally{Y.value=!1}}let nn=d(()=>q.value&&(X.value.database||X.value.files)&&X.value.confirm.trim()===K.value?.file);function rn(){Q.value=!0,m.post(route(`admin.backups.restore`,K.value.id),{...X.value,confirm:X.value.confirm.trim(),password:X.value.password||null},{preserveScroll:!0,onSuccess:()=>{K.value=null,H()},onError:e=>{Z.value=e},onFinish:()=>{Q.value=!1}})}let an=d(()=>{let e=F.settings?.schedule||{};return e.frequency===`daily`?L(`schedule_daily`,{time:e.time}):e.frequency===`weekly`?L(`schedule_weekly`,{weekday:F.settings.weekday,time:e.time}):L(`schedule_off`)}),on=d(()=>{let e=F.settings?.retention||{};return L(`retention_text`,{all:e.keep_all_days,daily:e.daily,weekly:e.weekly,monthly:e.monthly,yearly:e.yearly})}),$={ok:`bg-success-soft text-success-soft-fg`,partial:`bg-warning-soft text-warning-soft-fg`,failed:`bg-danger-soft text-danger-soft-fg`};function sn(e){let t=[];return e.trigger&&t.push(L(`trigger_${e.trigger}`)),e.by&&t.push(e.by),e.file&&t.push(e.disk?`${e.file} (${e.disk})`:e.file),e.disks?.length&&t.push(L(`copied_to`,{disks:e.disks.join(`, `)})),e.failed?.length&&t.push(L(`not_copied_to`,{disks:e.failed.map(e=>e.disk??e).join(`, `)})),e.action===`restore`&&e.status===`ok`&&t.push(L(`restored`,{databases:(e.databases||[]).join(`, `)||`—`,files:e.files??0,deleted:e.deleted??0})),e.seconds!==void 0&&t.push(L(`seconds`,{seconds:e.seconds})),e.message&&t.push(e.message),t.join(` · `)}return(r,a)=>(i(),ee(re,{title:L(`menu`)},{default:l(()=>[v(`div`,ie,[v(`div`,null,[v(`h1`,ae,f(P.labels.menu),1),v(`p`,oe,f(L(`subtitle`)),1)]),v(`div`,se,[t(b,{dusk:`backup-now`,loading:U.value,disabled:!!B.value.running,onClick:a[0]||=e=>W()},{default:l(()=>[c(f(L(`back_up_now`)),1)]),_:1},8,[`loading`,`disabled`]),t(b,{variant:`secondary`,disabled:U.value||!!B.value.running,onClick:a[1]||=e=>W(`database`)},{default:l(()=>[c(f(L(`only_database`)),1)]),_:1},8,[`disabled`]),t(b,{variant:`secondary`,disabled:U.value||!!B.value.running,onClick:a[2]||=e=>W(`files`)},{default:l(()=>[c(f(L(`only_files`)),1)]),_:1},8,[`disabled`])])]),B.value.running?(i(),_(`div`,ce,[a[13]||=v(`svg`,{class:`animate-spin h-5 w-5`,fill:`none`,viewBox:`0 0 24 24`,"aria-hidden":`true`},[v(`circle`,{class:`opacity-25`,cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,"stroke-width":`4`}),v(`path`,{class:`opacity-75`,fill:`currentColor`,d:`M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z`})],-1),c(` `+f(L(B.value.running.action===`restore`?`running_restore`:`running_backup`,{time:z(B.value.running.started_at)})),1)])):e(``,!0),v(`div`,le,[t(x,{title:L(`archives`),"no-padding":``},{default:l(()=>[B.value.backups.length?(i(),_(`div`,de,[v(`table`,fe,[v(`thead`,pe,[v(`tr`,null,[v(`th`,me,f(L(`file`)),1),v(`th`,he,f(L(`destination`)),1),v(`th`,ge,f(L(`date`)),1),v(`th`,_e,f(L(`size`)),1),a[14]||=v(`th`,{class:`px-4 py-2`},null,-1)])]),v(`tbody`,ve,[(i(!0),_(g,null,s(B.value.backups,e=>(i(),_(`tr`,{key:e.id,"data-backup":e.file,dusk:`backup`},[v(`td`,be,f(e.file),1),v(`td`,xe,f(e.disk),1),v(`td`,C,f(z(e.date)),1),v(`td`,w,f(R(e.size)),1),v(`td`,T,[v(`a`,{href:e.download_url,class:`text-accent underline`},f(L(`download`)),9,E),v(`button`,{type:`button`,dusk:`restore`,class:`text-accent underline`,disabled:!!B.value.running,onClick:t=>en(e)},f(L(`restore`)),9,D),v(`button`,{type:`button`,dusk:`delete`,class:`text-danger underline`,onClick:t=>G.value=e},f(L(`delete`)),9,O)])],8,ye))),128))])])])):(i(),_(`p`,ue,f(L(`empty`)),1))]),_:1},8,[`title`]),v(`div`,k,[t(x,{title:L(`destinations`)},{default:l(()=>[v(`ul`,A,[(i(!0),_(g,null,s(P.health,t=>(i(),_(`li`,{key:t.disk,"data-destination":t.disk,dusk:`destination-${t.disk}`},[v(`div`,M,[v(`span`,Se,f(t.disk),1),v(`span`,{class:o([`px-2 py-0.5 rounded text-xs font-medium`,!t.reachable||!t.healthy?$.failed:$.ok])},f(t.reachable?t.healthy?L(`healthy`):L(`unhealthy`):L(`unreachable`)),3)]),t.reachable?(i(),_(`p`,Ce,f(L(`stored`,{count:t.count,size:R(t.used)}))+` · `+f(t.newest?L(`newest`,{date:z(t.newest)}):L(`no_archive`)),1)):e(``,!0),t.problems.length?(i(),_(`ul`,we,[(i(!0),_(g,null,s(t.problems,e=>(i(),_(`li`,{key:e},f(e),1))),128))])):e(``,!0)],8,j))),128))])]),_:1},8,[`title`]),t(x,{title:L(`settings`),subtitle:L(`settings_note`)},{default:l(()=>[v(`dl`,Te,[v(`dt`,Ee,f(L(`databases`)),1),v(`dd`,De,f(P.settings.databases.map(e=>`${e.connection} (${e.driver})`).join(`, `)||L(`nothing`)),1),v(`dt`,Oe,f(L(`folders`)),1),v(`dd`,ke,f(P.settings.folders.join(`, `)||L(`nothing`)),1),v(`dt`,Ae,f(L(`destinations`)),1),v(`dd`,je,f(P.settings.destinations.join(`, `)),1),v(`dt`,Me,f(L(`schedule`)),1),v(`dd`,Ne,[c(f(an.value),1),P.settings.queue?(i(),_(`span`,Pe,`. `+f(L(`queue`,{queue:P.settings.queue})),1)):e(``,!0)]),v(`dt`,Fe,f(L(`retention`)),1),v(`dd`,Ie,f(on.value),1),v(`dt`,Le,f(L(`encryption`)),1),v(`dd`,Re,f(P.settings.encrypted?L(`encrypted`):L(`not_encrypted`)),1)])]),_:1},8,[`title`,`subtitle`])]),t(x,{title:L(`log`),"no-padding":``},{default:l(()=>[B.value.log.length?(i(),_(`div`,Be,[v(`table`,Ve,[v(`thead`,He,[v(`tr`,null,[v(`th`,Ue,f(L(`when`)),1),v(`th`,We,f(L(`what`)),1),v(`th`,Ge,f(L(`result`)),1),v(`th`,Ke,f(L(`details`)),1)])]),v(`tbody`,qe,[(i(!0),_(g,null,s(B.value.log,(e,t)=>(i(),_(`tr`,{key:t},[v(`td`,Je,f(z(e.at)),1),v(`td`,Ye,f(L(`action_${e.action}`)),1),v(`td`,Xe,[v(`span`,{class:o([`px-2 py-0.5 rounded text-xs font-medium`,$[e.status]||$.failed])},f(L(`status_${e.status}`)),3)]),v(`td`,Ze,f(sn(e)),1)]))),128))])])])):(i(),_(`p`,ze,f(L(`log_empty`)),1))]),_:1},8,[`title`])]),t(S,{show:!!G.value,title:L(`delete`),onClose:a[4]||=e=>G.value=null},{default:l(()=>[v(`div`,Qe,[v(`p`,$e,f(G.value?L(`delete_confirm`,{file:G.value.file,disk:G.value.disk}):``),1),v(`div`,et,[t(b,{variant:`secondary`,onClick:a[3]||=e=>G.value=null},{default:l(()=>[c(f(L(`cancel`)),1)]),_:1}),t(b,{dusk:`confirm-delete`,variant:`danger`,onClick:$t},{default:l(()=>[c(f(L(`delete`)),1)]),_:1})])])]),_:1},8,[`show`,`title`]),t(S,{show:!!K.value,"max-width":`2xl`,title:K.value?L(`restore_title`,{file:K.value.file}):``,onClose:a[12]||=e=>K.value=null},{default:l(()=>[K.value?(i(),_(`div`,tt,[v(`p`,nt,f(L(`restore_intro`)),1),v(`div`,rt,[v(`div`,it,[v(`label`,at,f(L(`password`)),1),n(v(`input`,{id:`backup-password`,"onUpdate:modelValue":a[5]||=e=>X.value.password=e,type:`password`,autocomplete:`off`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus`},null,512),[[p,X.value.password]]),v(`p`,ot,f(L(`password_hint`)),1)]),t(b,{dusk:`preview`,variant:`secondary`,loading:Y.value,onClick:tn},{default:l(()=>[c(f(L(`preview`)),1)]),_:1},8,[`loading`])]),J.value?(i(),_(`p`,st,f(J.value),1)):e(``,!0),q.value?(i(),_(g,{key:1},[q.value.created_at?(i(),_(`p`,ct,f(L(`made`,{date:z(q.value.created_at)})),1)):e(``,!0),q.value.databases.length?(i(),_(`div`,lt,[v(`table`,ut,[v(`thead`,dt,[v(`tr`,null,[v(`th`,ft,f(L(`connection`)),1),v(`th`,pt,f(L(`driver`)),1),v(`th`,mt,f(L(`dump`)),1),v(`th`,ht,f(L(`replaces`)),1)])]),v(`tbody`,gt,[(i(!0),_(g,null,s(q.value.databases,e=>(i(),_(`tr`,{key:e.connection},[v(`td`,_t,f(e.connection),1),v(`td`,vt,f(e.driver),1),v(`td`,yt,f(R(e.size)),1),v(`td`,bt,f(e.restorable?e.target:L(`skipped`)),1)]))),128))])])])):e(``,!0),q.value.folders.length?(i(),_(`div`,xt,[v(`table`,St,[v(`thead`,Ct,[v(`tr`,null,[v(`th`,N,f(L(`into`)),1),v(`th`,wt,f(L(`files`)),1),v(`th`,Tt,f(L(`new`)),1),v(`th`,Et,f(L(`changed`)),1),v(`th`,Dt,f(L(`unchanged`)),1),v(`th`,Ot,f(L(`extra`)),1)])]),v(`tbody`,kt,[(i(!0),_(g,null,s(q.value.folders,e=>(i(),_(`tr`,{key:e.prefix},[v(`td`,At,f(e.target),1),v(`td`,jt,f(e.files),1),v(`td`,Mt,f(e.new),1),v(`td`,Nt,f(e.changed),1),v(`td`,Pt,f(e.unchanged),1),v(`td`,Ft,f(e.extra),1)]))),128))])])])):e(``,!0),q.value.warnings.length?(i(),_(`ul`,It,[(i(!0),_(g,null,s(q.value.warnings,e=>(i(),_(`li`,{key:e,class:`ml-3`},f(e),1))),128))])):e(``,!0),v(`fieldset`,Lt,[v(`label`,Rt,[n(v(`input`,{"onUpdate:modelValue":a[6]||=e=>X.value.database=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.database]]),c(` `+f(L(`restore_database`)),1)]),v(`label`,zt,[n(v(`input`,{"onUpdate:modelValue":a[7]||=e=>X.value.files=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.files]]),c(` `+f(L(`restore_files`)),1)]),v(`label`,Bt,[n(v(`input`,{"onUpdate:modelValue":a[8]||=e=>X.value.delete_extra=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`,disabled:!X.value.files},null,8,Vt),[[h,X.value.delete_extra]]),c(` `+f(L(`delete_extra`)),1)]),v(`label`,Ht,[n(v(`input`,{"onUpdate:modelValue":a[9]||=e=>X.value.safety_backup=e,type:`checkbox`,class:`h-4 w-4 text-accent border-field rounded focus:ring-focus`},null,512),[[h,X.value.safety_backup]]),c(` `+f(L(`safety_backup`)),1)])]),v(`div`,Ut,[v(`p`,Wt,f(L(`risks`)),1),v(`ul`,Gt,[X.value.database?(i(),_(`li`,Kt,f(L(`risk_database`,{date:z(q.value.created_at||K.value.date)})),1)):e(``,!0),X.value.database?(i(),_(`li`,qt,f(L(`risk_sessions`)),1)):e(``,!0),X.value.files?(i(),_(`li`,Jt,f(L(`risk_files`)),1)):e(``,!0),v(`li`,null,f(L(`risk_site`)),1)])]),v(`div`,null,[v(`label`,Yt,f(L(`confirm`,{file:K.value.file})),1),n(v(`input`,{id:`backup-confirm`,dusk:`restore-confirm`,"onUpdate:modelValue":a[10]||=e=>X.value.confirm=e,type:`text`,autocomplete:`off`,spellcheck:`false`,class:`mt-1 block w-full px-3 py-2 font-mono border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus`},null,512),[[p,X.value.confirm]]),Z.value.confirm?(i(),_(`p`,Xt,f(Z.value.confirm),1)):e(``,!0)])],64)):e(``,!0),v(`div`,Zt,[t(b,{dusk:`cancel-restore`,variant:`secondary`,onClick:a[11]||=e=>K.value=null},{default:l(()=>[c(f(L(`cancel`)),1)]),_:1}),t(b,{dusk:`start-restore`,variant:`danger`,loading:Q.value,disabled:!nn.value,onClick:rn},{default:l(()=>[c(f(L(`start_restore`)),1)]),_:1},8,[`loading`,`disabled`])])])):e(``,!0)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{P as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-BzuT6e6D.js b/packages/admin/dist/assets/Index-C_p9UH4T.js similarity index 99% rename from packages/admin/dist/assets/Index-BzuT6e6D.js rename to packages/admin/dist/assets/Index-C_p9UH4T.js index d5bac2c2..82fcf859 100644 --- a/packages/admin/dist/assets/Index-BzuT6e6D.js +++ b/packages/admin/dist/assets/Index-C_p9UH4T.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as ee,a as u,et as d,m as f,s as te,v as p,w as m,x as h}from"./dist-MY__znoP.js";import{t as g}from"./AdminLayout-I1QMPYpW.js";import{n as ne}from"./app-lI4VKCmX.js";import{t as _}from"./AdminButton-Bx141Bs3.js";import{t as v}from"./AdminCard--HubMtUj.js";import{t as re}from"./AdminModal-DNJ_V4iq.js";var ie={class:`space-y-6`},ae={key:0,"data-api-token-plain":``,class:`p-4 bg-warning-soft border-2 border-warning-soft-fg rounded-lg`},oe={class:`font-medium text-fg`},y={class:`mt-3 flex flex-col sm:flex-row gap-2`},b={class:`flex-1 px-3 py-2 bg-surface border border-field rounded font-mono text-sm break-all`},x={class:`space-y-1 text-sm`},S=[`href`],C=[`href`],w={class:`grid gap-4 sm:grid-cols-2`},T={for:`token-name`,class:`block text-sm font-medium text-fg`},E=[`placeholder`],D={key:0,class:`mt-1 text-sm text-danger`},O={for:`token-expires`,class:`block text-sm font-medium text-fg`},k={key:0,class:`mt-1 text-sm text-danger`},A={class:`flex flex-wrap items-center justify-between gap-2`},j={class:`text-sm font-medium text-fg`},M={class:`flex gap-2`},N={key:0,class:`mt-1 text-sm text-danger`},P={class:`mt-2 max-h-96 overflow-y-auto border border-line rounded-md`},F={class:`min-w-full text-sm`},I={class:`bg-surface-alt sticky top-0`},L={class:`px-3 py-2 text-left font-medium text-fg`},R={class:`px-3 py-2 w-24 text-center font-medium text-fg`},z={class:`px-3 py-2 w-24 text-center font-medium text-fg`},B={class:`divide-y divide-line`},V={class:`px-3 py-1.5`},H={class:`ml-1 text-xs text-muted font-mono`},U={class:`px-3 py-1.5 text-center`},W=[`aria-label`,`checked`,`onChange`],G={class:`px-3 py-1.5 text-center`},K=[`aria-label`,`checked`,`onChange`],se={class:`flex justify-end`},ce={key:0,class:`p-6 text-sm text-muted`},le={key:1,class:`overflow-x-auto`},ue={class:`min-w-full text-sm`},de={class:`bg-surface-alt`},fe={class:`px-4 py-2 text-left font-medium text-fg`},pe={class:`px-4 py-2 text-left font-medium text-fg`},me={class:`px-4 py-2 text-left font-medium text-fg`},he={class:`px-4 py-2 text-left font-medium text-fg`},ge={class:`px-4 py-2 text-left font-medium text-fg`},_e={class:`divide-y divide-line`},ve={class:`px-4 py-2 font-medium text-fg`},ye={class:`px-4 py-2 text-fg`},be={class:`cursor-pointer`},xe={class:`mt-1 space-y-0.5`},Se={class:`px-4 py-2 text-fg`},Ce={class:`text-xs text-muted`},we={class:`px-4 py-2 text-fg`},Te={class:`px-4 py-2 text-fg`},Ee={key:0,class:`font-medium`},q={class:`px-4 py-2 text-right`},De={class:`text-muted`},J={__name:`ApiTokensManager`,props:{tokens:{type:Array,required:!0},modules:{type:Array,required:!0},plainToken:{type:String,default:null},docsUrl:{type:String,required:!0},openApiUrl:{type:String,required:!0}},setup(a){let g=a,J=u({name:``,abilities:[],expires_at:``}),Y=c(!1),X=c(null),Z=e=>J.abilities.includes(e),Q=(e,t)=>{let n=`${e}:${t}`,r=new Set(J.abilities);r.has(n)?(r.delete(n),t===`read`&&r.delete(`${e}:write`)):(r.add(n),t===`write`&&r.add(`${e}:read`)),J.abilities=[...r]},$=e=>{let t=new Set(J.abilities);for(let n of g.modules)t.add(`${n.key}:read`),e===`write`&&n.writable&&t.add(`${n.key}:write`);J.abilities=[...t]},Oe=()=>{J.post(route(`admin.api-tokens.store`),{onSuccess:()=>J.reset()})},ke=async()=>{await navigator.clipboard.writeText(g.plainToken),Y.value=!0},Ae=()=>{te.delete(route(`admin.api-tokens.destroy`,X.value.id),{preserveScroll:!0,onFinish:()=>{X.value=null}})},je=e=>{let[t,n]=e.split(`:`),r=g.modules.find(e=>e.key===t);return ne(n===`write`?`account.api_tokens.ability_write`:`account.api_tokens.ability_read`,{module:r?r.label:t})};return(c,u)=>(r(),m(`div`,ie,[a.plainToken?(r(),m(`div`,ae,[h(`p`,oe,d(c.$t(`account.api_tokens.plain_notice`)),1),h(`div`,y,[h(`code`,b,d(a.plainToken),1),t(_,{variant:`outline`,onClick:ke},{default:s(()=>[o(d(Y.value?c.$t(`common.copied`):c.$t(`common.copy`)),1)]),_:1})])])):e(``,!0),t(v,{title:c.$t(`account.api_tokens.docs_title`),subtitle:c.$t(`account.api_tokens.docs_subtitle`)},{default:s(()=>[h(`ul`,x,[h(`li`,null,[o(d(c.$t(`account.api_tokens.docs_page`))+` `,1),h(`a`,{href:a.docsUrl,target:`_blank`,class:`text-accent-hover underline break-all`},d(a.docsUrl),9,S)]),h(`li`,null,[o(d(c.$t(`account.api_tokens.openapi_schema`))+` `,1),h(`a`,{href:a.openApiUrl,target:`_blank`,class:`text-accent-hover underline break-all`},d(a.openApiUrl),9,C)])])]),_:1},8,[`title`,`subtitle`]),t(v,{title:c.$t(`account.api_tokens.create_title`)},{default:s(()=>[h(`form`,{class:`space-y-5`,onSubmit:ee(Oe,[`prevent`])},[h(`div`,w,[h(`div`,null,[h(`label`,T,d(c.$t(`account.api_tokens.name`)),1),n(h(`input`,{id:`token-name`,"onUpdate:modelValue":u[0]||=e=>l(J).name=e,type:`text`,placeholder:c.$t(`account.api_tokens.name_placeholder`),class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,8,E),[[f,l(J).name]]),l(J).errors.name?(r(),m(`p`,D,d(l(J).errors.name),1)):e(``,!0)]),h(`div`,null,[h(`label`,O,d(c.$t(`account.api_tokens.expires_at`)),1),n(h(`input`,{id:`token-expires`,"onUpdate:modelValue":u[1]||=e=>l(J).expires_at=e,type:`date`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,512),[[f,l(J).expires_at]]),l(J).errors.expires_at?(r(),m(`p`,k,d(l(J).errors.expires_at),1)):e(``,!0)])]),h(`div`,null,[h(`div`,A,[h(`span`,j,d(c.$t(`account.api_tokens.abilities`)),1),h(`div`,M,[t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[2]||=e=>$(`read`)},{default:s(()=>[o(d(c.$t(`account.api_tokens.select_read_all`)),1)]),_:1}),t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[3]||=e=>$(`write`)},{default:s(()=>[o(d(c.$t(`account.api_tokens.select_all`)),1)]),_:1}),t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[4]||=e=>l(J).abilities=[]},{default:s(()=>[o(d(c.$t(`account.api_tokens.clear`)),1)]),_:1})])]),l(J).errors.abilities?(r(),m(`p`,N,d(l(J).errors.abilities),1)):e(``,!0),h(`div`,P,[h(`table`,F,[h(`thead`,I,[h(`tr`,null,[h(`th`,L,d(c.$t(`account.api_tokens.module`)),1),h(`th`,R,d(c.$t(`account.api_tokens.read`)),1),h(`th`,z,d(c.$t(`account.api_tokens.write`)),1)])]),h(`tbody`,B,[(r(!0),m(p,null,i(a.modules,t=>(r(),m(`tr`,{key:t.key},[h(`td`,V,[o(d(t.label)+` `,1),h(`span`,H,d(t.key),1)]),h(`td`,U,[h(`input`,{type:`checkbox`,class:`h-4 w-4`,"aria-label":c.$t(`account.api_tokens.ability_read`,{module:t.label}),checked:Z(`${t.key}:read`),onChange:e=>Q(t.key,`read`)},null,40,W)]),h(`td`,G,[t.writable?(r(),m(`input`,{key:0,type:`checkbox`,class:`h-4 w-4`,"aria-label":c.$t(`account.api_tokens.ability_write`,{module:t.label}),checked:Z(`${t.key}:write`),onChange:e=>Q(t.key,`write`)},null,40,K)):e(``,!0)])]))),128))])])])]),h(`div`,se,[t(_,{type:`submit`,loading:l(J).processing,disabled:l(J).processing},{default:s(()=>[o(d(c.$t(`account.api_tokens.submit`)),1)]),_:1},8,[`loading`,`disabled`])])],32)]),_:1},8,[`title`]),t(v,{title:c.$t(`account.api_tokens.list_title`),"no-padding":``},{default:s(()=>[a.tokens.length===0?(r(),m(`p`,ce,d(c.$t(`account.api_tokens.empty`)),1)):(r(),m(`div`,le,[h(`table`,ue,[h(`thead`,de,[h(`tr`,null,[h(`th`,fe,d(c.$t(`account.api_tokens.name`)),1),h(`th`,pe,d(c.$t(`account.api_tokens.abilities`)),1),h(`th`,me,d(c.$t(`account.api_tokens.owner`)),1),h(`th`,he,d(c.$t(`account.api_tokens.last_used`)),1),h(`th`,ge,d(c.$t(`account.api_tokens.expiry`)),1),u[7]||=h(`th`,{class:`px-4 py-2`},null,-1)])]),h(`tbody`,_e,[(r(!0),m(p,null,i(a.tokens,n=>(r(),m(`tr`,{key:n.id,"data-api-token-row":``},[h(`td`,ve,d(n.name),1),h(`td`,ye,[h(`details`,null,[h(`summary`,be,d(c.$tc(`account.api_tokens.abilities_count`,n.abilities.length)),1),h(`ul`,xe,[(r(!0),m(p,null,i(n.abilities,e=>(r(),m(`li`,{key:e},d(je(e)),1))),128))])])]),h(`td`,Se,[o(d(n.owner),1),h(`div`,Ce,d(n.created_at),1)]),h(`td`,we,d(n.last_used_at||c.$t(`account.api_tokens.never_used`)),1),h(`td`,Te,[n.expires_at?(r(),m(p,{key:0},[o(d(c.$t(`account.api_tokens.until`,{date:n.expires_at})),1),n.expired?(r(),m(`span`,Ee,d(c.$t(`account.api_tokens.expired`)),1)):e(``,!0)],64)):(r(),m(p,{key:1},[o(d(c.$t(`account.api_tokens.no_expiry`)),1)],64))]),h(`td`,q,[t(_,{size:`sm`,variant:`danger`,onClick:e=>X.value=n},{default:s(()=>[o(d(c.$t(`account.api_tokens.revoke`)),1)]),_:1},8,[`onClick`])])]))),128))])])]))]),_:1},8,[`title`]),t(re,{show:X.value!==null,title:c.$t(`account.api_tokens.revoke_title`),onClose:u[6]||=e=>X.value=null},{footer:s(()=>[t(_,{variant:`secondary`,onClick:u[5]||=e=>X.value=null},{default:s(()=>[o(d(c.$t(`common.cancel`)),1)]),_:1}),t(_,{variant:`danger`,onClick:Ae},{default:s(()=>[o(d(c.$t(`account.api_tokens.revoke`)),1)]),_:1})]),default:s(()=>[h(`p`,De,[o(d(c.$t(`account.api_tokens.revoke_confirm_before`))+` `,1),h(`strong`,null,d(X.value?.name),1),o(` `+d(c.$t(`account.api_tokens.revoke_confirm_after`)),1)])]),_:1},8,[`show`,`title`])]))}},Y={class:`mb-6`},X={class:`text-2xl font-bold text-fg`},Z={class:`mt-1 text-sm text-muted`},Q={__name:`Index`,props:{tokens:Array,modules:Array,plainToken:String,docsUrl:String,openApiUrl:String},setup(e){return(n,i)=>(r(),a(g,{title:n.$t(`menu.api_tokens`)},{default:s(()=>[h(`div`,Y,[h(`h1`,X,d(n.$t(`menu.api_tokens`)),1),h(`p`,Z,d(n.$t(`account.api_tokens.subtitle`)),1)]),t(J,{tokens:e.tokens,modules:e.modules,"plain-token":e.plainToken,"docs-url":e.docsUrl,"open-api-url":e.openApiUrl},null,8,[`tokens`,`modules`,`plain-token`,`docs-url`,`open-api-url`])]),_:1},8,[`title`]))}};export{Q as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Y as c,Z as l,_ as ee,a as u,et as d,m as f,s as te,v as p,w as m,x as h}from"./dist-MY__znoP.js";import{t as g}from"./AdminLayout--RXJFj9t.js";import{n as ne}from"./app-BNjy5Z6H.js";import{t as _}from"./AdminButton-Bx141Bs3.js";import{t as v}from"./AdminCard--HubMtUj.js";import{t as re}from"./AdminModal-DNJ_V4iq.js";var ie={class:`space-y-6`},ae={key:0,"data-api-token-plain":``,class:`p-4 bg-warning-soft border-2 border-warning-soft-fg rounded-lg`},oe={class:`font-medium text-fg`},y={class:`mt-3 flex flex-col sm:flex-row gap-2`},b={class:`flex-1 px-3 py-2 bg-surface border border-field rounded font-mono text-sm break-all`},x={class:`space-y-1 text-sm`},S=[`href`],C=[`href`],w={class:`grid gap-4 sm:grid-cols-2`},T={for:`token-name`,class:`block text-sm font-medium text-fg`},E=[`placeholder`],D={key:0,class:`mt-1 text-sm text-danger`},O={for:`token-expires`,class:`block text-sm font-medium text-fg`},k={key:0,class:`mt-1 text-sm text-danger`},A={class:`flex flex-wrap items-center justify-between gap-2`},j={class:`text-sm font-medium text-fg`},M={class:`flex gap-2`},N={key:0,class:`mt-1 text-sm text-danger`},P={class:`mt-2 max-h-96 overflow-y-auto border border-line rounded-md`},F={class:`min-w-full text-sm`},I={class:`bg-surface-alt sticky top-0`},L={class:`px-3 py-2 text-left font-medium text-fg`},R={class:`px-3 py-2 w-24 text-center font-medium text-fg`},z={class:`px-3 py-2 w-24 text-center font-medium text-fg`},B={class:`divide-y divide-line`},V={class:`px-3 py-1.5`},H={class:`ml-1 text-xs text-muted font-mono`},U={class:`px-3 py-1.5 text-center`},W=[`aria-label`,`checked`,`onChange`],G={class:`px-3 py-1.5 text-center`},K=[`aria-label`,`checked`,`onChange`],se={class:`flex justify-end`},ce={key:0,class:`p-6 text-sm text-muted`},le={key:1,class:`overflow-x-auto`},ue={class:`min-w-full text-sm`},de={class:`bg-surface-alt`},fe={class:`px-4 py-2 text-left font-medium text-fg`},pe={class:`px-4 py-2 text-left font-medium text-fg`},me={class:`px-4 py-2 text-left font-medium text-fg`},he={class:`px-4 py-2 text-left font-medium text-fg`},ge={class:`px-4 py-2 text-left font-medium text-fg`},_e={class:`divide-y divide-line`},ve={class:`px-4 py-2 font-medium text-fg`},ye={class:`px-4 py-2 text-fg`},be={class:`cursor-pointer`},xe={class:`mt-1 space-y-0.5`},Se={class:`px-4 py-2 text-fg`},Ce={class:`text-xs text-muted`},we={class:`px-4 py-2 text-fg`},Te={class:`px-4 py-2 text-fg`},Ee={key:0,class:`font-medium`},q={class:`px-4 py-2 text-right`},De={class:`text-muted`},J={__name:`ApiTokensManager`,props:{tokens:{type:Array,required:!0},modules:{type:Array,required:!0},plainToken:{type:String,default:null},docsUrl:{type:String,required:!0},openApiUrl:{type:String,required:!0}},setup(a){let g=a,J=u({name:``,abilities:[],expires_at:``}),Y=c(!1),X=c(null),Z=e=>J.abilities.includes(e),Q=(e,t)=>{let n=`${e}:${t}`,r=new Set(J.abilities);r.has(n)?(r.delete(n),t===`read`&&r.delete(`${e}:write`)):(r.add(n),t===`write`&&r.add(`${e}:read`)),J.abilities=[...r]},$=e=>{let t=new Set(J.abilities);for(let n of g.modules)t.add(`${n.key}:read`),e===`write`&&n.writable&&t.add(`${n.key}:write`);J.abilities=[...t]},Oe=()=>{J.post(route(`admin.api-tokens.store`),{onSuccess:()=>J.reset()})},ke=async()=>{await navigator.clipboard.writeText(g.plainToken),Y.value=!0},Ae=()=>{te.delete(route(`admin.api-tokens.destroy`,X.value.id),{preserveScroll:!0,onFinish:()=>{X.value=null}})},je=e=>{let[t,n]=e.split(`:`),r=g.modules.find(e=>e.key===t);return ne(n===`write`?`account.api_tokens.ability_write`:`account.api_tokens.ability_read`,{module:r?r.label:t})};return(c,u)=>(r(),m(`div`,ie,[a.plainToken?(r(),m(`div`,ae,[h(`p`,oe,d(c.$t(`account.api_tokens.plain_notice`)),1),h(`div`,y,[h(`code`,b,d(a.plainToken),1),t(_,{variant:`outline`,onClick:ke},{default:s(()=>[o(d(Y.value?c.$t(`common.copied`):c.$t(`common.copy`)),1)]),_:1})])])):e(``,!0),t(v,{title:c.$t(`account.api_tokens.docs_title`),subtitle:c.$t(`account.api_tokens.docs_subtitle`)},{default:s(()=>[h(`ul`,x,[h(`li`,null,[o(d(c.$t(`account.api_tokens.docs_page`))+` `,1),h(`a`,{href:a.docsUrl,target:`_blank`,class:`text-accent-hover underline break-all`},d(a.docsUrl),9,S)]),h(`li`,null,[o(d(c.$t(`account.api_tokens.openapi_schema`))+` `,1),h(`a`,{href:a.openApiUrl,target:`_blank`,class:`text-accent-hover underline break-all`},d(a.openApiUrl),9,C)])])]),_:1},8,[`title`,`subtitle`]),t(v,{title:c.$t(`account.api_tokens.create_title`)},{default:s(()=>[h(`form`,{class:`space-y-5`,onSubmit:ee(Oe,[`prevent`])},[h(`div`,w,[h(`div`,null,[h(`label`,T,d(c.$t(`account.api_tokens.name`)),1),n(h(`input`,{id:`token-name`,"onUpdate:modelValue":u[0]||=e=>l(J).name=e,type:`text`,placeholder:c.$t(`account.api_tokens.name_placeholder`),class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,8,E),[[f,l(J).name]]),l(J).errors.name?(r(),m(`p`,D,d(l(J).errors.name),1)):e(``,!0)]),h(`div`,null,[h(`label`,O,d(c.$t(`account.api_tokens.expires_at`)),1),n(h(`input`,{id:`token-expires`,"onUpdate:modelValue":u[1]||=e=>l(J).expires_at=e,type:`date`,class:`mt-1 block w-full px-3 py-2 border border-field rounded-md shadow-sm focus:outline-none focus:ring-focus focus:border-focus sm:text-sm`},null,512),[[f,l(J).expires_at]]),l(J).errors.expires_at?(r(),m(`p`,k,d(l(J).errors.expires_at),1)):e(``,!0)])]),h(`div`,null,[h(`div`,A,[h(`span`,j,d(c.$t(`account.api_tokens.abilities`)),1),h(`div`,M,[t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[2]||=e=>$(`read`)},{default:s(()=>[o(d(c.$t(`account.api_tokens.select_read_all`)),1)]),_:1}),t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[3]||=e=>$(`write`)},{default:s(()=>[o(d(c.$t(`account.api_tokens.select_all`)),1)]),_:1}),t(_,{type:`button`,size:`sm`,variant:`outline`,onClick:u[4]||=e=>l(J).abilities=[]},{default:s(()=>[o(d(c.$t(`account.api_tokens.clear`)),1)]),_:1})])]),l(J).errors.abilities?(r(),m(`p`,N,d(l(J).errors.abilities),1)):e(``,!0),h(`div`,P,[h(`table`,F,[h(`thead`,I,[h(`tr`,null,[h(`th`,L,d(c.$t(`account.api_tokens.module`)),1),h(`th`,R,d(c.$t(`account.api_tokens.read`)),1),h(`th`,z,d(c.$t(`account.api_tokens.write`)),1)])]),h(`tbody`,B,[(r(!0),m(p,null,i(a.modules,t=>(r(),m(`tr`,{key:t.key},[h(`td`,V,[o(d(t.label)+` `,1),h(`span`,H,d(t.key),1)]),h(`td`,U,[h(`input`,{type:`checkbox`,class:`h-4 w-4`,"aria-label":c.$t(`account.api_tokens.ability_read`,{module:t.label}),checked:Z(`${t.key}:read`),onChange:e=>Q(t.key,`read`)},null,40,W)]),h(`td`,G,[t.writable?(r(),m(`input`,{key:0,type:`checkbox`,class:`h-4 w-4`,"aria-label":c.$t(`account.api_tokens.ability_write`,{module:t.label}),checked:Z(`${t.key}:write`),onChange:e=>Q(t.key,`write`)},null,40,K)):e(``,!0)])]))),128))])])])]),h(`div`,se,[t(_,{type:`submit`,loading:l(J).processing,disabled:l(J).processing},{default:s(()=>[o(d(c.$t(`account.api_tokens.submit`)),1)]),_:1},8,[`loading`,`disabled`])])],32)]),_:1},8,[`title`]),t(v,{title:c.$t(`account.api_tokens.list_title`),"no-padding":``},{default:s(()=>[a.tokens.length===0?(r(),m(`p`,ce,d(c.$t(`account.api_tokens.empty`)),1)):(r(),m(`div`,le,[h(`table`,ue,[h(`thead`,de,[h(`tr`,null,[h(`th`,fe,d(c.$t(`account.api_tokens.name`)),1),h(`th`,pe,d(c.$t(`account.api_tokens.abilities`)),1),h(`th`,me,d(c.$t(`account.api_tokens.owner`)),1),h(`th`,he,d(c.$t(`account.api_tokens.last_used`)),1),h(`th`,ge,d(c.$t(`account.api_tokens.expiry`)),1),u[7]||=h(`th`,{class:`px-4 py-2`},null,-1)])]),h(`tbody`,_e,[(r(!0),m(p,null,i(a.tokens,n=>(r(),m(`tr`,{key:n.id,"data-api-token-row":``},[h(`td`,ve,d(n.name),1),h(`td`,ye,[h(`details`,null,[h(`summary`,be,d(c.$tc(`account.api_tokens.abilities_count`,n.abilities.length)),1),h(`ul`,xe,[(r(!0),m(p,null,i(n.abilities,e=>(r(),m(`li`,{key:e},d(je(e)),1))),128))])])]),h(`td`,Se,[o(d(n.owner),1),h(`div`,Ce,d(n.created_at),1)]),h(`td`,we,d(n.last_used_at||c.$t(`account.api_tokens.never_used`)),1),h(`td`,Te,[n.expires_at?(r(),m(p,{key:0},[o(d(c.$t(`account.api_tokens.until`,{date:n.expires_at})),1),n.expired?(r(),m(`span`,Ee,d(c.$t(`account.api_tokens.expired`)),1)):e(``,!0)],64)):(r(),m(p,{key:1},[o(d(c.$t(`account.api_tokens.no_expiry`)),1)],64))]),h(`td`,q,[t(_,{size:`sm`,variant:`danger`,onClick:e=>X.value=n},{default:s(()=>[o(d(c.$t(`account.api_tokens.revoke`)),1)]),_:1},8,[`onClick`])])]))),128))])])]))]),_:1},8,[`title`]),t(re,{show:X.value!==null,title:c.$t(`account.api_tokens.revoke_title`),onClose:u[6]||=e=>X.value=null},{footer:s(()=>[t(_,{variant:`secondary`,onClick:u[5]||=e=>X.value=null},{default:s(()=>[o(d(c.$t(`common.cancel`)),1)]),_:1}),t(_,{variant:`danger`,onClick:Ae},{default:s(()=>[o(d(c.$t(`account.api_tokens.revoke`)),1)]),_:1})]),default:s(()=>[h(`p`,De,[o(d(c.$t(`account.api_tokens.revoke_confirm_before`))+` `,1),h(`strong`,null,d(X.value?.name),1),o(` `+d(c.$t(`account.api_tokens.revoke_confirm_after`)),1)])]),_:1},8,[`show`,`title`])]))}},Y={class:`mb-6`},X={class:`text-2xl font-bold text-fg`},Z={class:`mt-1 text-sm text-muted`},Q={__name:`Index`,props:{tokens:Array,modules:Array,plainToken:String,docsUrl:String,openApiUrl:String},setup(e){return(n,i)=>(r(),a(g,{title:n.$t(`menu.api_tokens`)},{default:s(()=>[h(`div`,Y,[h(`h1`,X,d(n.$t(`menu.api_tokens`)),1),h(`p`,Z,d(n.$t(`account.api_tokens.subtitle`)),1)]),t(J,{tokens:e.tokens,modules:e.modules,"plain-token":e.plainToken,"docs-url":e.docsUrl,"open-api-url":e.openApiUrl},null,8,[`tokens`,`modules`,`plain-token`,`docs-url`,`open-api-url`])]),_:1},8,[`title`]))}};export{Q as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-By9Fq-LA.js b/packages/admin/dist/assets/Index-CjLWl74m.js similarity index 96% rename from packages/admin/dist/assets/Index-By9Fq-LA.js rename to packages/admin/dist/assets/Index-CjLWl74m.js index a5d82124..200de985 100644 --- a/packages/admin/dist/assets/Index-By9Fq-LA.js +++ b/packages/admin/dist/assets/Index-CjLWl74m.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Y as c,Z as l,et as u,g as d,m as f,s as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout-I1QMPYpW.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminDataTable-BaQwb_6U.js";import{t as b}from"./AdminModal-DNJ_V4iq.js";import{t as x}from"./recordActions-CtRs42tG.js";var S={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},C=[`data-page-title`],w={class:`mt-1 text-sm text-muted`},T={class:`flex flex-wrap items-center gap-2`},E={class:`mb-6`},D={class:`flex gap-4`},O={class:`flex-1 max-w-md`},k=[`placeholder`],A={class:`text-muted`},j={__name:`Index`,props:{routeName:String,createLabel:String,items:Object,columns:Array,filters:Object,title:String,can:{type:Object,default:()=>({})},actions:{type:Array,default:()=>[]},links:{type:Array,default:()=>[]}},setup(j){let M=j,N=Object.fromEntries(Object.entries(M.filters||{}).filter(([e])=>![`search`,`sort`,`direction`].includes(e))),P=M.actions.map(e=>({...e,href:t=>x(M.routeName,e,t)})),F=c(M.filters.search||``),I=c(!1),L=c(null),R=()=>{p.get(route(`${M.routeName}.index`),{...N,search:F.value},{preserveState:!0,preserveScroll:!0})},z=({column:e,direction:t})=>{p.get(route(`${M.routeName}.index`),{...M.filters,sort:e,direction:t},{preserveState:!0,preserveScroll:!0})},B=e=>{p.visit(route(`${M.routeName}.edit`,e.id))},V=e=>{L.value=e,I.value=!0},H=()=>{L.value&&p.delete(route(`${M.routeName}.destroy`,L.value.id),{onSuccess:()=>{I.value=!1,L.value=null}})};return(c,p)=>(r(),a(_,{title:j.title},{default:s(()=>[g(`div`,S,[g(`div`,null,[g(`h1`,{"data-page-title":j.routeName,class:`text-2xl font-bold text-fg`},u(j.title),9,C),g(`p`,w,u(c.$t(`resource.index.total`,{count:j.items.total})),1)]),g(`div`,T,[(r(!0),h(m,null,i(j.links,e=>(r(),a(v,{key:e.name,"data-link":e.name,href:e.href,variant:`secondary`},{default:s(()=>[o(u(e.label),1)]),_:2},1032,[`data-link`,`href`]))),128)),j.can.create===!1?e(``,!0):(r(),a(v,{key:0,"data-action":`create`,href:c.route(`${M.routeName}.create`,l(N))},{default:s(()=>[p[3]||=g(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[g(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),o(` `+u(c.$t(`common.create`)),1)]),_:1},8,[`href`]))])]),g(`div`,E,[g(`div`,D,[g(`div`,O,[n(g(`input`,{"onUpdate:modelValue":p[0]||=e=>F.value=e,type:`text`,placeholder:c.$t(`resource.index.search_placeholder`),"data-search-input":`true`,class:`w-full px-4 py-2 border border-field rounded-lg focus:ring-focus focus:border-focus`,onKeyup:d(R,[`enter`])},null,40,k),[[f,F.value]])]),t(v,{"data-action":`search`,onClick:R,variant:`secondary`},{default:s(()=>[o(u(c.$t(`resource.index.search_button`)),1)]),_:1})])]),t(y,{columns:j.columns,items:j.items,"sort-by":j.filters.sort,"sort-direction":j.filters.direction,"can-delete":j.can.delete!==!1,"row-actions":l(P),onSort:z,onEdit:B,onDelete:V},null,8,[`columns`,`items`,`sort-by`,`sort-direction`,`can-delete`,`row-actions`]),t(b,{show:I.value,title:c.$t(`resource.delete.title`),onClose:p[2]||=e=>I.value=!1},{footer:s(()=>[t(v,{"data-action":`delete-cancel`,variant:`secondary`,onClick:p[1]||=e=>I.value=!1},{default:s(()=>[o(u(c.$t(`common.cancel`)),1)]),_:1}),t(v,{"data-action":`delete-confirm`,variant:`danger`,onClick:H},{default:s(()=>[o(u(c.$t(`common.delete`)),1)]),_:1})]),default:s(()=>[g(`p`,A,u(c.$t(`resource.delete.confirm`)),1)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{j as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,R as i,S as a,T as o,W as s,Y as c,Z as l,et as u,g as d,m as f,s as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout--RXJFj9t.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminDataTable-BaQwb_6U.js";import{t as b}from"./AdminModal-DNJ_V4iq.js";import{t as x}from"./recordActions-CtRs42tG.js";var S={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},C=[`data-page-title`],w={class:`mt-1 text-sm text-muted`},T={class:`flex flex-wrap items-center gap-2`},E={class:`mb-6`},D={class:`flex gap-4`},O={class:`flex-1 max-w-md`},k=[`placeholder`],A={class:`text-muted`},j={__name:`Index`,props:{routeName:String,createLabel:String,items:Object,columns:Array,filters:Object,title:String,can:{type:Object,default:()=>({})},actions:{type:Array,default:()=>[]},links:{type:Array,default:()=>[]}},setup(j){let M=j,N=Object.fromEntries(Object.entries(M.filters||{}).filter(([e])=>![`search`,`sort`,`direction`].includes(e))),P=M.actions.map(e=>({...e,href:t=>x(M.routeName,e,t)})),F=c(M.filters.search||``),I=c(!1),L=c(null),R=()=>{p.get(route(`${M.routeName}.index`),{...N,search:F.value},{preserveState:!0,preserveScroll:!0})},z=({column:e,direction:t})=>{p.get(route(`${M.routeName}.index`),{...M.filters,sort:e,direction:t},{preserveState:!0,preserveScroll:!0})},B=e=>{p.visit(route(`${M.routeName}.edit`,e.id))},V=e=>{L.value=e,I.value=!0},H=()=>{L.value&&p.delete(route(`${M.routeName}.destroy`,L.value.id),{onSuccess:()=>{I.value=!1,L.value=null}})};return(c,p)=>(r(),a(_,{title:j.title},{default:s(()=>[g(`div`,S,[g(`div`,null,[g(`h1`,{"data-page-title":j.routeName,class:`text-2xl font-bold text-fg`},u(j.title),9,C),g(`p`,w,u(c.$t(`resource.index.total`,{count:j.items.total})),1)]),g(`div`,T,[(r(!0),h(m,null,i(j.links,e=>(r(),a(v,{key:e.name,"data-link":e.name,href:e.href,variant:`secondary`},{default:s(()=>[o(u(e.label),1)]),_:2},1032,[`data-link`,`href`]))),128)),j.can.create===!1?e(``,!0):(r(),a(v,{key:0,"data-action":`create`,href:c.route(`${M.routeName}.create`,l(N))},{default:s(()=>[p[3]||=g(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[g(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),o(` `+u(c.$t(`common.create`)),1)]),_:1},8,[`href`]))])]),g(`div`,E,[g(`div`,D,[g(`div`,O,[n(g(`input`,{"onUpdate:modelValue":p[0]||=e=>F.value=e,type:`text`,placeholder:c.$t(`resource.index.search_placeholder`),"data-search-input":`true`,class:`w-full px-4 py-2 border border-field rounded-lg focus:ring-focus focus:border-focus`,onKeyup:d(R,[`enter`])},null,40,k),[[f,F.value]])]),t(v,{"data-action":`search`,onClick:R,variant:`secondary`},{default:s(()=>[o(u(c.$t(`resource.index.search_button`)),1)]),_:1})])]),t(y,{columns:j.columns,items:j.items,"sort-by":j.filters.sort,"sort-direction":j.filters.direction,"can-delete":j.can.delete!==!1,"row-actions":l(P),onSort:z,onEdit:B,onDelete:V},null,8,[`columns`,`items`,`sort-by`,`sort-direction`,`can-delete`,`row-actions`]),t(b,{show:I.value,title:c.$t(`resource.delete.title`),onClose:p[2]||=e=>I.value=!1},{footer:s(()=>[t(v,{"data-action":`delete-cancel`,variant:`secondary`,onClick:p[1]||=e=>I.value=!1},{default:s(()=>[o(u(c.$t(`common.cancel`)),1)]),_:1}),t(v,{"data-action":`delete-confirm`,variant:`danger`,onClick:H},{default:s(()=>[o(u(c.$t(`common.delete`)),1)]),_:1})]),default:s(()=>[g(`p`,A,u(c.$t(`resource.delete.confirm`)),1)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{j as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-waO6UWa5.js b/packages/admin/dist/assets/Index-DEbfZBFs.js similarity index 97% rename from packages/admin/dist/assets/Index-waO6UWa5.js rename to packages/admin/dist/assets/Index-DEbfZBFs.js index 906e7c7d..003ae54d 100644 --- a/packages/admin/dist/assets/Index-waO6UWa5.js +++ b/packages/admin/dist/assets/Index-DEbfZBFs.js @@ -1 +1 @@ -import{C as e,E as t,G as n,I as r,S as i,T as a,W as o,Y as s,et as c,g as l,m as u,s as d,w as f,x as p}from"./dist-MY__znoP.js";import{t as m}from"./AdminLayout-I1QMPYpW.js";import{t as h}from"./AdminButton-Bx141Bs3.js";import{t as g}from"./AdminDataTable-BaQwb_6U.js";import{t as _}from"./AdminModal-DNJ_V4iq.js";var v={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},y={class:`text-2xl font-bold text-fg`},b={class:`mt-1 text-sm text-muted`},x={class:`mb-6`},S={class:`flex gap-4`},C={class:`flex-1 max-w-md`},w=[`placeholder`],T={class:`text-muted`},E={key:0},D={class:`mt-2 text-sm text-danger`},O={__name:`Index`,props:{items:Object,columns:Array,filters:Object,title:String,can:{type:Object,default:()=>({})}},setup(O){let k=O,A=s(k.filters.search||``),j=s(!1),M=s(null),N=()=>{d.get(route(`admin.users.index`),{search:A.value},{preserveState:!0,preserveScroll:!0})},P=({column:e,direction:t})=>{d.get(route(`admin.users.index`),{...k.filters,sort:e,direction:t},{preserveState:!0,preserveScroll:!0})},F=e=>{d.visit(route(`admin.users.edit`,e.id))},I=e=>{M.value=e,j.value=!0},L=()=>{M.value&&d.delete(route(`admin.users.destroy`,M.value.id),{onSuccess:()=>{j.value=!1,M.value=null}})};return(s,d)=>(r(),i(m,{title:O.title},{default:o(()=>[p(`div`,v,[p(`div`,null,[p(`h1`,y,c(O.title),1),p(`p`,b,c(s.$t(`account.users.total`,{count:O.items.total})),1)]),O.can.create===!1?e(``,!0):(r(),i(h,{key:0,"data-action":`create`,href:s.route(`admin.users.create`)},{default:o(()=>[d[3]||=p(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[p(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),a(` `+c(s.$t(`common.create`)),1)]),_:1},8,[`href`]))]),p(`div`,x,[p(`div`,S,[p(`div`,C,[n(p(`input`,{"onUpdate:modelValue":d[0]||=e=>A.value=e,type:`text`,placeholder:s.$t(`account.users.search_placeholder`),class:`w-full px-4 py-2 border border-field rounded-lg focus:ring-focus focus:border-focus`,onKeyup:l(N,[`enter`])},null,40,w),[[u,A.value]])]),t(h,{onClick:N,variant:`secondary`},{default:o(()=>[a(c(s.$t(`common.search`)),1)]),_:1})])]),t(g,{columns:O.columns,items:O.items,"sort-by":O.filters.sort,"sort-direction":O.filters.direction,"can-delete":O.can.delete!==!1,onSort:P,onEdit:F,onDelete:I},null,8,[`columns`,`items`,`sort-by`,`sort-direction`,`can-delete`]),t(_,{show:j.value,title:s.$t(`account.users.delete_title`),onClose:d[2]||=e=>j.value=!1},{footer:o(()=>[t(h,{variant:`secondary`,onClick:d[1]||=e=>j.value=!1},{default:o(()=>[a(c(s.$t(`common.cancel`)),1)]),_:1}),t(h,{variant:`danger`,onClick:L},{default:o(()=>[a(c(s.$t(`common.delete`)),1)]),_:1})]),default:o(()=>[p(`p`,T,[a(c(s.$t(`account.users.delete_confirm`))+` `,1),M.value?(r(),f(`strong`,E,c(M.value.name),1)):e(``,!0)]),p(`p`,D,c(s.$t(`account.users.delete_irreversible`)),1)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{O as default}; \ No newline at end of file +import{C as e,E as t,G as n,I as r,S as i,T as a,W as o,Y as s,et as c,g as l,m as u,s as d,w as f,x as p}from"./dist-MY__znoP.js";import{t as m}from"./AdminLayout--RXJFj9t.js";import{t as h}from"./AdminButton-Bx141Bs3.js";import{t as g}from"./AdminDataTable-BaQwb_6U.js";import{t as _}from"./AdminModal-DNJ_V4iq.js";var v={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},y={class:`text-2xl font-bold text-fg`},b={class:`mt-1 text-sm text-muted`},x={class:`mb-6`},S={class:`flex gap-4`},C={class:`flex-1 max-w-md`},w=[`placeholder`],T={class:`text-muted`},E={key:0},D={class:`mt-2 text-sm text-danger`},O={__name:`Index`,props:{items:Object,columns:Array,filters:Object,title:String,can:{type:Object,default:()=>({})}},setup(O){let k=O,A=s(k.filters.search||``),j=s(!1),M=s(null),N=()=>{d.get(route(`admin.users.index`),{search:A.value},{preserveState:!0,preserveScroll:!0})},P=({column:e,direction:t})=>{d.get(route(`admin.users.index`),{...k.filters,sort:e,direction:t},{preserveState:!0,preserveScroll:!0})},F=e=>{d.visit(route(`admin.users.edit`,e.id))},I=e=>{M.value=e,j.value=!0},L=()=>{M.value&&d.delete(route(`admin.users.destroy`,M.value.id),{onSuccess:()=>{j.value=!1,M.value=null}})};return(s,d)=>(r(),i(m,{title:O.title},{default:o(()=>[p(`div`,v,[p(`div`,null,[p(`h1`,y,c(O.title),1),p(`p`,b,c(s.$t(`account.users.total`,{count:O.items.total})),1)]),O.can.create===!1?e(``,!0):(r(),i(h,{key:0,"data-action":`create`,href:s.route(`admin.users.create`)},{default:o(()=>[d[3]||=p(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[p(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),a(` `+c(s.$t(`common.create`)),1)]),_:1},8,[`href`]))]),p(`div`,x,[p(`div`,S,[p(`div`,C,[n(p(`input`,{"onUpdate:modelValue":d[0]||=e=>A.value=e,type:`text`,placeholder:s.$t(`account.users.search_placeholder`),class:`w-full px-4 py-2 border border-field rounded-lg focus:ring-focus focus:border-focus`,onKeyup:l(N,[`enter`])},null,40,w),[[u,A.value]])]),t(h,{onClick:N,variant:`secondary`},{default:o(()=>[a(c(s.$t(`common.search`)),1)]),_:1})])]),t(g,{columns:O.columns,items:O.items,"sort-by":O.filters.sort,"sort-direction":O.filters.direction,"can-delete":O.can.delete!==!1,onSort:P,onEdit:F,onDelete:I},null,8,[`columns`,`items`,`sort-by`,`sort-direction`,`can-delete`]),t(_,{show:j.value,title:s.$t(`account.users.delete_title`),onClose:d[2]||=e=>j.value=!1},{footer:o(()=>[t(h,{variant:`secondary`,onClick:d[1]||=e=>j.value=!1},{default:o(()=>[a(c(s.$t(`common.cancel`)),1)]),_:1}),t(h,{variant:`danger`,onClick:L},{default:o(()=>[a(c(s.$t(`common.delete`)),1)]),_:1})]),default:o(()=>[p(`p`,T,[a(c(s.$t(`account.users.delete_confirm`))+` `,1),M.value?(r(),f(`strong`,E,c(M.value.name),1)):e(``,!0)]),p(`p`,D,c(s.$t(`account.users.delete_irreversible`)),1)]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{O as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-CJcjrNaO.js b/packages/admin/dist/assets/Index-P5jX14JD.js similarity index 97% rename from packages/admin/dist/assets/Index-CJcjrNaO.js rename to packages/admin/dist/assets/Index-P5jX14JD.js index 928e82fa..c28e70cc 100644 --- a/packages/admin/dist/assets/Index-CJcjrNaO.js +++ b/packages/admin/dist/assets/Index-P5jX14JD.js @@ -1 +1 @@ -import{E as e,I as t,R as n,S as r,T as i,W as a,Y as o,et as s,s as c,v as l,w as u,x as d}from"./dist-MY__znoP.js";import{t as f}from"./AdminLayout-I1QMPYpW.js";import{t as p}from"./AdminButton-Bx141Bs3.js";import{t as m}from"./AdminModal-DNJ_V4iq.js";var h={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},g={"data-page-title":`admin.roles`,class:`text-2xl font-bold text-fg`},_={class:`mt-1 text-sm text-muted`},v={class:`bg-surface rounded-lg shadow overflow-hidden`},y={key:0,class:`p-6 text-sm text-muted`},b={key:1,class:`min-w-full text-sm`},x={class:`bg-surface-alt`},S={class:`px-4 py-2 text-left font-medium text-fg`},C={class:`px-4 py-2 text-left font-medium text-fg`},w={class:`px-4 py-2 text-left font-medium text-fg`},T={class:`divide-y divide-line`},E={class:`px-4 py-2 font-medium text-fg`},D={class:`px-4 py-2 text-fg`},O={class:`px-4 py-2 text-fg`},k={class:`px-4 py-2 text-right whitespace-nowrap`},A={class:`text-muted`},j={__name:`Index`,props:{roles:Array,title:String},setup(j){let M=o(null),N=()=>{c.delete(route(`admin.roles.destroy`,M.value.id),{preserveScroll:!0,onFinish:()=>{M.value=null}})};return(o,c)=>(t(),r(f,{title:j.title},{default:a(()=>[d(`div`,h,[d(`div`,null,[d(`h1`,g,s(j.title),1),d(`p`,_,s(o.$t(`permissions.index_hint`)),1)]),e(p,{"data-action":`create`,href:o.route(`admin.roles.create`)},{default:a(()=>[c[2]||=d(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[d(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),i(` `+s(o.$t(`common.create`)),1)]),_:1},8,[`href`])]),d(`div`,v,[j.roles.length===0?(t(),u(`p`,y,s(o.$t(`permissions.empty`)),1)):(t(),u(`table`,b,[d(`thead`,x,[d(`tr`,null,[d(`th`,S,s(o.$t(`permissions.name`)),1),d(`th`,C,s(o.$t(`permissions.permissions_count`)),1),d(`th`,w,s(o.$t(`permissions.users_count`)),1),c[3]||=d(`th`,{class:`px-4 py-2`},null,-1)])]),d(`tbody`,T,[(t(!0),u(l,null,n(j.roles,n=>(t(),u(`tr`,{key:n.id,"data-role-row":``},[d(`td`,E,s(n.name),1),d(`td`,D,s(n.permissions_count),1),d(`td`,O,s(n.users_count),1),d(`td`,k,[e(p,{size:`sm`,variant:`outline`,"data-action":`edit`,href:o.route(`admin.roles.edit`,n.id)},{default:a(()=>[i(s(o.$t(`common.edit`)),1)]),_:1},8,[`href`]),e(p,{size:`sm`,variant:`danger`,"data-action":`delete`,class:`ml-2`,onClick:e=>M.value=n},{default:a(()=>[i(s(o.$t(`common.delete`)),1)]),_:1},8,[`onClick`])])]))),128))])]))]),e(m,{show:M.value!==null,title:o.$t(`permissions.delete_title`),onClose:c[1]||=e=>M.value=null},{footer:a(()=>[e(p,{variant:`secondary`,onClick:c[0]||=e=>M.value=null},{default:a(()=>[i(s(o.$t(`common.cancel`)),1)]),_:1}),e(p,{variant:`danger`,"data-action":`delete-confirm`,onClick:N},{default:a(()=>[i(s(o.$t(`common.delete`)),1)]),_:1})]),default:a(()=>[d(`p`,A,[d(`strong`,null,s(M.value?.name),1),i(` — `+s(o.$t(`permissions.delete_confirm`)),1)])]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{j as default}; \ No newline at end of file +import{E as e,I as t,R as n,S as r,T as i,W as a,Y as o,et as s,s as c,v as l,w as u,x as d}from"./dist-MY__znoP.js";import{t as f}from"./AdminLayout--RXJFj9t.js";import{t as p}from"./AdminButton-Bx141Bs3.js";import{t as m}from"./AdminModal-DNJ_V4iq.js";var h={class:`mb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4`},g={"data-page-title":`admin.roles`,class:`text-2xl font-bold text-fg`},_={class:`mt-1 text-sm text-muted`},v={class:`bg-surface rounded-lg shadow overflow-hidden`},y={key:0,class:`p-6 text-sm text-muted`},b={key:1,class:`min-w-full text-sm`},x={class:`bg-surface-alt`},S={class:`px-4 py-2 text-left font-medium text-fg`},C={class:`px-4 py-2 text-left font-medium text-fg`},w={class:`px-4 py-2 text-left font-medium text-fg`},T={class:`divide-y divide-line`},E={class:`px-4 py-2 font-medium text-fg`},D={class:`px-4 py-2 text-fg`},O={class:`px-4 py-2 text-fg`},k={class:`px-4 py-2 text-right whitespace-nowrap`},A={class:`text-muted`},j={__name:`Index`,props:{roles:Array,title:String},setup(j){let M=o(null),N=()=>{c.delete(route(`admin.roles.destroy`,M.value.id),{preserveScroll:!0,onFinish:()=>{M.value=null}})};return(o,c)=>(t(),r(f,{title:j.title},{default:a(()=>[d(`div`,h,[d(`div`,null,[d(`h1`,g,s(j.title),1),d(`p`,_,s(o.$t(`permissions.index_hint`)),1)]),e(p,{"data-action":`create`,href:o.route(`admin.roles.create`)},{default:a(()=>[c[2]||=d(`svg`,{class:`w-4 h-4 mr-2`,fill:`none`,viewBox:`0 0 24 24`,stroke:`currentColor`},[d(`path`,{"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-width":`2`,d:`M12 4v16m8-8H4`})],-1),i(` `+s(o.$t(`common.create`)),1)]),_:1},8,[`href`])]),d(`div`,v,[j.roles.length===0?(t(),u(`p`,y,s(o.$t(`permissions.empty`)),1)):(t(),u(`table`,b,[d(`thead`,x,[d(`tr`,null,[d(`th`,S,s(o.$t(`permissions.name`)),1),d(`th`,C,s(o.$t(`permissions.permissions_count`)),1),d(`th`,w,s(o.$t(`permissions.users_count`)),1),c[3]||=d(`th`,{class:`px-4 py-2`},null,-1)])]),d(`tbody`,T,[(t(!0),u(l,null,n(j.roles,n=>(t(),u(`tr`,{key:n.id,"data-role-row":``},[d(`td`,E,s(n.name),1),d(`td`,D,s(n.permissions_count),1),d(`td`,O,s(n.users_count),1),d(`td`,k,[e(p,{size:`sm`,variant:`outline`,"data-action":`edit`,href:o.route(`admin.roles.edit`,n.id)},{default:a(()=>[i(s(o.$t(`common.edit`)),1)]),_:1},8,[`href`]),e(p,{size:`sm`,variant:`danger`,"data-action":`delete`,class:`ml-2`,onClick:e=>M.value=n},{default:a(()=>[i(s(o.$t(`common.delete`)),1)]),_:1},8,[`onClick`])])]))),128))])]))]),e(m,{show:M.value!==null,title:o.$t(`permissions.delete_title`),onClose:c[1]||=e=>M.value=null},{footer:a(()=>[e(p,{variant:`secondary`,onClick:c[0]||=e=>M.value=null},{default:a(()=>[i(s(o.$t(`common.cancel`)),1)]),_:1}),e(p,{variant:`danger`,"data-action":`delete-confirm`,onClick:N},{default:a(()=>[i(s(o.$t(`common.delete`)),1)]),_:1})]),default:a(()=>[d(`p`,A,[d(`strong`,null,s(M.value?.name),1),i(` — `+s(o.$t(`permissions.delete_confirm`)),1)])]),_:1},8,[`show`,`title`])]),_:1},8,[`title`]))}};export{j as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Index-bqKVRXw8.js b/packages/admin/dist/assets/Index-bqKVRXw8.js new file mode 100644 index 00000000..50e9d09c --- /dev/null +++ b/packages/admin/dist/assets/Index-bqKVRXw8.js @@ -0,0 +1 @@ +import{C as e,E as t,G as n,I as r,Q as i,R as a,S as o,T as s,W as c,Y as l,et as u,p as d,s as f,v as p,w as m,x as h}from"./dist-MY__znoP.js";import{t as g}from"./AdminLayout--RXJFj9t.js";import{t as _}from"./AdminButton-Bx141Bs3.js";var v={class:`mb-6`},y={"data-page-title":`admin.cache`,class:`text-2xl font-bold text-gray-900`},b={class:`mt-1 text-sm text-gray-600`},x={class:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6`},S={class:`bg-white rounded-lg shadow p-4`,"data-cache-stat":`rate`},C={class:`text-sm text-gray-600`},w={class:`mt-1 text-2xl font-semibold text-gray-900`},T={class:`mt-1 text-xs text-gray-500`},E={class:`bg-white rounded-lg shadow p-4`,"data-cache-stat":`size`},D={class:`text-sm text-gray-600`},O={class:`mt-1 text-2xl font-semibold text-gray-900`},k={class:`mt-1 text-xs text-gray-500`},A={class:`bg-white rounded-lg shadow p-4`,"data-cache-stat":`store`},j={class:`text-sm text-gray-600`},M={class:`mt-1 text-2xl font-semibold text-gray-900`},N={class:`mt-1 text-xs text-gray-500`},P={class:`bg-white rounded-lg shadow p-4`,"data-cache-stat":`state`},F={class:`text-sm text-gray-600`},I={class:`mt-1 text-xs text-gray-500`},L={class:`bg-white rounded-lg shadow p-6 space-y-6`},R={class:`text-sm text-gray-600`},ee={key:0,class:`flex flex-col sm:flex-row sm:items-end gap-3`},z={class:`flex-1`},B={class:`block text-sm font-medium text-gray-700 mb-1`},V=[`value`],H={key:1,class:`flex flex-col sm:flex-row sm:items-end gap-3`},U={class:`flex-1`},W={class:`block text-sm font-medium text-gray-700 mb-1`},G=[`value`],K={class:`flex flex-wrap gap-3 pt-2 border-t border-gray-100`},q={__name:`Index`,props:{status:Object,modules:Array,sites:Array},setup(q){let J=q,Y=l(J.modules[0]?.key??``),X=l(J.sites[0]?.id??``),Z=l(!1),Q=(e,t={})=>{Z.value=!0,f.post(route(`admin.cache.clear`),{scope:e,...t},{preserveScroll:!0,onFinish:()=>{Z.value=!1}})},$=e=>e==null?`—`:new Intl.NumberFormat().format(e),te=e=>{if(e==null)return`—`;let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r(r(),o(g,{title:l.$t(`menu.cache`)},{default:c(()=>[h(`div`,v,[h(`h1`,y,u(l.$t(`menu.cache`)),1),h(`p`,b,u(l.$t(`cache.subtitle`)),1)]),h(`div`,x,[h(`div`,S,[h(`div`,C,u(l.$t(`cache.hit_rate`)),1),h(`div`,w,u(q.status.rate===null?`—`:`${q.status.rate}%`),1),h(`div`,T,u(l.$t(`cache.hits`))+`: `+u($(q.status.hits))+` · `+u(l.$t(`cache.misses`))+`: `+u($(q.status.misses)),1)]),h(`div`,E,[h(`div`,D,u(l.$t(`cache.size`)),1),h(`div`,O,u(te(q.status.bytes)),1),h(`div`,k,u(l.$t(`cache.entries`))+`: `+u($(q.status.entries)),1)]),h(`div`,A,[h(`div`,j,u(l.$t(`cache.store`)),1),h(`div`,M,u(q.status.driver),1),h(`div`,N,u(q.status.tags?l.$t(`cache.with_tags`):l.$t(`cache.without_tags`)),1)]),h(`div`,P,[h(`div`,F,u(l.$t(`cache.records`)),1),h(`div`,{class:i([`mt-1 text-2xl font-semibold`,q.status.enabled?`text-green-700`:`text-gray-500`])},u(q.status.enabled?l.$t(`cache.on`):l.$t(`cache.off`)),3),h(`div`,I,u(l.$t(`cache.pages`))+`: `+u(q.status.pages?l.$t(`cache.on`):l.$t(`cache.off`)),1)])]),h(`div`,L,[h(`p`,R,u(l.$t(`cache.clear_hint`)),1),q.modules.length?(r(),m(`div`,ee,[h(`label`,z,[h(`span`,B,u(l.$t(`cache.module`)),1),n(h(`select`,{"onUpdate:modelValue":f[0]||=e=>Y.value=e,"data-cache-module":``,class:`w-full rounded-md border-gray-300 text-sm`},[(r(!0),m(p,null,a(q.modules,e=>(r(),m(`option`,{key:e.key,value:e.key},u(e.label),9,V))),128))],512),[[d,Y.value]])]),t(_,{variant:`outline`,"data-action":`clear-module`,disabled:Z.value,onClick:f[1]||=e=>Q(`module`,{module:Y.value})},{default:c(()=>[s(u(l.$t(`cache.clear_module`)),1)]),_:1},8,[`disabled`])])):e(``,!0),q.sites.length>1?(r(),m(`div`,H,[h(`label`,U,[h(`span`,W,u(l.$t(`cache.site`)),1),n(h(`select`,{"onUpdate:modelValue":f[2]||=e=>X.value=e,"data-cache-site":``,class:`w-full rounded-md border-gray-300 text-sm`},[(r(!0),m(p,null,a(q.sites,e=>(r(),m(`option`,{key:e.id,value:e.id},u(e.name),9,G))),128))],512),[[d,X.value]])]),t(_,{variant:`outline`,"data-action":`clear-site`,disabled:Z.value,onClick:f[3]||=e=>Q(`site`,{site:X.value})},{default:c(()=>[s(u(l.$t(`cache.clear_site`)),1)]),_:1},8,[`disabled`])])):e(``,!0),h(`div`,K,[t(_,{variant:`danger`,"data-action":`clear-all`,disabled:Z.value,onClick:f[4]||=e=>Q(`all`)},{default:c(()=>[s(u(l.$t(`cache.clear_all`)),1)]),_:1},8,[`disabled`]),t(_,{variant:`secondary`,"data-action":`reset-stats`,disabled:Z.value,onClick:f[5]||=e=>Q(`stats`)},{default:c(()=>[s(u(l.$t(`cache.reset_stats`)),1)]),_:1},8,[`disabled`])])])]),_:1},8,[`title`]))}};export{q as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/Settings-DiwVH39L.js b/packages/admin/dist/assets/Settings-C2VyFPrB.js similarity index 88% rename from packages/admin/dist/assets/Settings-DiwVH39L.js rename to packages/admin/dist/assets/Settings-C2VyFPrB.js index da199ea9..e04f9bea 100644 --- a/packages/admin/dist/assets/Settings-DiwVH39L.js +++ b/packages/admin/dist/assets/Settings-C2VyFPrB.js @@ -1 +1 @@ -import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Z as c,_ as l,a as u,b as d,et as f,i as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout-I1QMPYpW.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminCard--HubMtUj.js";import{t as b}from"./FormField-BI8KmQxQ.js";import{n as x}from"./contentLocale-BtGD-iBF.js";var S={class:`mb-6`},C={class:`max-w-4xl`},w={"data-page-title":`admin.modules.settings`,class:`text-2xl font-bold text-fg`},T={key:0,class:`mt-1 text-sm text-muted`},E={key:1,"data-settings-site":``,class:`mt-1 text-sm text-muted`},D=[`data-module`],O={class:`space-y-6`},k={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},A={__name:`Settings`,props:{module:Object,description:String,fields:Array,values:Object,site:{type:Object,default:null},title:String},setup(A){let j=A,M={};j.fields.forEach(e=>{M[e.name]=x(e,j.values[e.name])});let N=u(M);r(`formData`,d(()=>N.data()));let P=()=>{N.submit(`put`,route(`admin.modules.settings.update`,j.module.key),{preserveScroll:!0})};return(r,u)=>(n(),a(_,{title:A.title},{default:s(()=>[g(`div`,S,[t(c(p),{href:r.route(`admin.modules.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(f(r.$t(`menu.modules`)),1)]),_:1},8,[`href`])]),g(`div`,C,[g(`h1`,w,f(A.title),1),A.description?(n(),h(`p`,T,f(A.description),1)):e(``,!0),A.site?(n(),h(`p`,E,f(r.$t(`modules.per_site`,{site:A.site.name})),1)):e(``,!0),t(y,{class:`mt-6`},{default:s(()=>[g(`form`,{"data-settings-form":``,"data-module":A.module.key,onSubmit:l(P,[`prevent`])},[g(`div`,O,[(n(!0),h(m,null,i(A.fields,e=>(n(),a(b,{key:e.name,field:e,modelValue:c(N)[e.name],"onUpdate:modelValue":t=>c(N)[e.name]=t,errors:c(N).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))]),g(`div`,k,[t(v,{href:r.route(`admin.modules.index`),variant:`secondary`},{default:s(()=>[o(f(r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(v,{"data-action":`save`,type:`submit`,loading:c(N).processing},{default:s(()=>[o(f(r.$t(`common.save`)),1)]),_:1},8,[`loading`])])],40,D)]),_:1})])]),_:1},8,[`title`]))}};export{A as default}; \ No newline at end of file +import{C as e,E as t,I as n,L as r,R as i,S as a,T as o,W as s,Z as c,_ as l,a as u,b as d,et as f,i as p,v as m,w as h,x as g}from"./dist-MY__znoP.js";import{t as _}from"./AdminLayout--RXJFj9t.js";import{t as v}from"./AdminButton-Bx141Bs3.js";import{t as y}from"./AdminCard--HubMtUj.js";import{t as b}from"./FormField-xD6LELDV.js";import{n as x}from"./contentLocale-BtGD-iBF.js";var S={class:`mb-6`},C={class:`max-w-4xl`},w={"data-page-title":`admin.modules.settings`,class:`text-2xl font-bold text-fg`},T={key:0,class:`mt-1 text-sm text-muted`},E={key:1,"data-settings-site":``,class:`mt-1 text-sm text-muted`},D=[`data-module`],O={class:`space-y-6`},k={class:`flex items-center justify-end space-x-3 pt-6 mt-6 border-t`},A={__name:`Settings`,props:{module:Object,description:String,fields:Array,values:Object,site:{type:Object,default:null},title:String},setup(A){let j=A,M={};j.fields.forEach(e=>{M[e.name]=x(e,j.values[e.name])});let N=u(M);r(`formData`,d(()=>N.data()));let P=()=>{N.submit(`put`,route(`admin.modules.settings.update`,j.module.key),{preserveScroll:!0})};return(r,u)=>(n(),a(_,{title:A.title},{default:s(()=>[g(`div`,S,[t(c(p),{href:r.route(`admin.modules.index`),class:`text-muted hover:text-accent`},{default:s(()=>[o(f(r.$t(`menu.modules`)),1)]),_:1},8,[`href`])]),g(`div`,C,[g(`h1`,w,f(A.title),1),A.description?(n(),h(`p`,T,f(A.description),1)):e(``,!0),A.site?(n(),h(`p`,E,f(r.$t(`modules.per_site`,{site:A.site.name})),1)):e(``,!0),t(y,{class:`mt-6`},{default:s(()=>[g(`form`,{"data-settings-form":``,"data-module":A.module.key,onSubmit:l(P,[`prevent`])},[g(`div`,O,[(n(!0),h(m,null,i(A.fields,e=>(n(),a(b,{key:e.name,field:e,modelValue:c(N)[e.name],"onUpdate:modelValue":t=>c(N)[e.name]=t,errors:c(N).errors},null,8,[`field`,`modelValue`,`onUpdate:modelValue`,`errors`]))),128))]),g(`div`,k,[t(v,{href:r.route(`admin.modules.index`),variant:`secondary`},{default:s(()=>[o(f(r.$t(`common.cancel`)),1)]),_:1},8,[`href`]),t(v,{"data-action":`save`,type:`submit`,loading:c(N).processing},{default:s(()=>[o(f(r.$t(`common.save`)),1)]),_:1},8,[`loading`])])],40,D)]),_:1})])]),_:1},8,[`title`]))}};export{A as default}; \ No newline at end of file diff --git a/packages/admin/dist/assets/app-lI4VKCmX.js b/packages/admin/dist/assets/app-BNjy5Z6H.js similarity index 88% rename from packages/admin/dist/assets/app-lI4VKCmX.js rename to packages/admin/dist/assets/app-BNjy5Z6H.js index b92102cb..982986f2 100644 --- a/packages/admin/dist/assets/app-lI4VKCmX.js +++ b/packages/admin/dist/assets/app-BNjy5Z6H.js @@ -1,2 +1,2 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Index-BzuT6e6D.js","assets/dist-MY__znoP.js","assets/AdminLayout-I1QMPYpW.js","assets/LocaleSwitcher-DdLJ9WTE.js","assets/AdminLayout-QfjingjX.css","assets/AdminButton-Bx141Bs3.js","assets/AdminCard--HubMtUj.js","assets/AdminModal-DNJ_V4iq.js","assets/Login-D_P0ceoZ.js","assets/Index-B0DDRHtS.js","assets/Dashboard-BpfYcZ3c.js","assets/Index-CVtF6Jho.js","assets/Settings-DiwVH39L.js","assets/FormField-BI8KmQxQ.js","assets/FormField-0qI8GE1v.css","assets/contentLocale-BtGD-iBF.js","assets/Edit-D7McI_eD.js","assets/Create-B8v2keK9.js","assets/ContentLocaleSwitcher-BJIieXK-.js","assets/Edit-DKlRxfoE.js","assets/recordActions-CtRs42tG.js","assets/Index-By9Fq-LA.js","assets/AdminDataTable-BaQwb_6U.js","assets/Edit-ppjiZjeT.js","assets/Index-CJcjrNaO.js","assets/Create-DWM7DbLl.js","assets/Edit-BEiwW1oN.js","assets/Index-waO6UWa5.js"])))=>i.map(i=>d[i]); -import{k as e,l as t,o as n,s as r,t as i}from"./dist-MY__znoP.js";var a=`modulepreload`,o=function(e){return`/vendor/atrium/`+e},s={},c=function(e){return e.pathname.endsWith(`.css`)},l=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},u=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),u=i?.nonce||i?.getAttribute(`nonce`);function d(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function f(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=d(t.map(t=>{t=o(t,n);let r=f(t),i=c(r);return l(s,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:a,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,u&&t.setAttribute(`nonce`,u),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},d=String.prototype.replace,f=/%20/g,p={RFC1738:`RFC1738`,RFC3986:`RFC3986`},m={RFC1738:function(e){return d.call(e,f,`+`)},RFC3986:function(e){return String(e)}},h=p.RFC1738;p.RFC3986;var g=p.RFC3986,_=Object.prototype.hasOwnProperty,v=Array.isArray,y=new WeakMap,b=function(e,t){return y.set(e,t),e};function x(e){return y.has(e)}var S=function(e){return y.get(e)},C=function(e,t){y.set(e,t)},w=(function(){let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),T=function(e){for(;e.length>1;){let t=e.pop(),n=t.obj[t.prop];if(v(n)){let e=[];for(let t=0;t=0&&e>S(t)&&C(t,e)}return t},l)},te=function(e){let t=e.replace(/\+/g,` `);try{return decodeURIComponent(t)}catch{return t}},D=1024,ne=function(e,t,n,r){if(e.length===0)return e;let i=e;typeof e==`symbol`?i=Symbol.prototype.toString.call(e):typeof e!=`string`&&(i=String(e));let a=``;for(let e=0;e=D?i.slice(e,e+D):i;if(e+D=55296&&n<=56319&&(t=t.slice(0,-1),--e)}let n=[];for(let e=0;e=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||r===h&&(i===40||i===41)?n[n.length]=t.charAt(e):i<128?n[n.length]=w[i]:i<2048?n[n.length]=w[192|i>>6]+w[128|i&63]:i<55296||i>=57344?n[n.length]=w[224|i>>12]+w[128|i>>6&63]+w[128|i&63]:(e+=1,i=65536+((i&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=w[240|i>>18]+w[128|i>>12&63]+w[128|i>>6&63]+w[128|i&63])}a+=n.join(``)}return a},re=function(e){let t=[{obj:{o:e},prop:`o`}],n=new WeakMap;for(let e=0;en?b(E(a,{plainObjects:r}),a.length-1):a},k=function(e,t){if(v(e)){let n=[];for(let r=0;r0?_.join(`,`)||null:void 0}];else if(j(l))S=l;else{let e=Object.keys(_);S=u?e.sort(u):e}let C=s?t.replace(/\./g,`%2E`):t,w=r&&j(_)&&_.length===1?C+`[]`:C;if(i&&j(_)&&_.length===0)return w+`[]`;for(let t=0;t0?d+u:``}var L=Object.prototype.hasOwnProperty,R=Array.isArray,z={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,comma:!1,decodeDotInKeys:!1,decoder:te,delimiter:`&`,depth:5,duplicates:`combine`,ignoreQueryPrefix:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},B=function(e,t){return e&&typeof e==`string`&&t.comma&&e.indexOf(`,`)>-1?e.split(`,`):e},fe=function(e,t){let n={__proto__:null},r=t.ignoreQueryPrefix?e.replace(/^\?/,``):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=r.split(t.delimiter,i),o=0;for(;o-1&&(c=R(c)?[c]:c),t.comma&&R(c)&&c.length>t.arrayLimit&&(c=O([],c,t.arrayLimit,t.plainObjects));let l=L.call(n,s);l&&t.duplicates===`combine`?n[s]=O(n[s],c,t.arrayLimit,t.plainObjects):l&&t.duplicates!==`last`||(n[s]=c)}return n},pe=function(e,t,n,r){let i=r?t:B(t,n);for(let t=e.length-1;t>=0;--t){let r,a=e[t];if(a===`[]`&&n.parseArrays)r=x(i)?i:n.allowEmptyArrays&&(i===``||n.strictNullHandling&&i===null)?[]:O([],i,n.arrayLimit,n.plainObjects);else{r=n.plainObjects?Object.create(null):{};let e=a.charAt(0)===`[`&&a.charAt(a.length-1)===`]`?a.slice(1,-1):a,t=n.decodeDotInKeys?e.replace(/%2E/g,`.`):e,o=parseInt(t,10),s=!isNaN(o)&&a!==t&&String(o)===t&&o>=0&&n.parseArrays;!n.parseArrays&&t===``?r={0:i}:s&&o<=n.arrayLimit?(r=[],r[o]=i):s?(r[o]=i,b(r,o)):t!==`__proto__`&&(r[t]=i)}i=r}return i},me=function(e,t,n,r){if(!e)return;let i=n.allowDots?e.replace(/\.([^.[]+)/g,`[$1]`):e,a=/(\[[^[\]]*])/,o=/(\[[^[\]]*])/g,s=n.depth>0&&a.exec(i),c=s?i.slice(0,s.index):i,l=[];if(c){if(!n.plainObjects&&L.call(Object.prototype,c)&&!n.allowPrototypes)return;l.push(c)}let u=0;for(;n.depth>0&&(s=o.exec(i))!==null&&u{try{return decodeURIComponent(e)}catch{return e}})}var H=class{constructor(e,t,n){this.name=e,this.definition=t,this.bindings=t.bindings??{},this.wheres=t.wheres??{},this.config=n}get template(){let e=`${this.origin}/${this.definition.uri}`.replace(/\/+$/,``);return e===``?`/`:e}get origin(){return this.config.absolute?this.definition.domain?`${this.config.url.match(/^\w+:\/\//)[0]}${this.definition.domain}${this.config.port?`:${this.config.port}`:``}`:this.config.url:``}get parameterSegments(){return this.template.match(/{[^}?]+\??}/g)?.map(e=>({name:e.replace(/{|\??}/g,``),required:!/\?}$/.test(e)}))??[]}matchesUrl(e){if(!this.definition.methods.includes(`GET`))return!1;let t=this.template.replace(/[.*+$()[\]]/g,`\\$&`).replace(/(\/?){([^}?]*)(\??)}/g,(e,t,n,r)=>{let i=`(?<${n}>${this.wheres[n]?.replace(/(^\^)|(\$$)/g,``)||`[^/?]+`})`;return r?`(${t}${i})?`:`${t}${i}`}).replace(/^\w+:\/\//,``),[n,r]=e.replace(/^\w+:\/\//,``).split(`?`),i=RegExp(`^${t}/?$`).exec(n);if(!i)try{i=RegExp(`^${t}/?$`).exec(decodeURI(n))}catch{}if(i){for(let e in i.groups)typeof i.groups[e]==`string`&&(i.groups[e]=V(i.groups[e]));return{params:i.groups,query:ge(r)}}return!1}compile(e){return this.parameterSegments.length?this.template.replace(/{([^}?]+)(\??)}/g,(t,n,r)=>{if(!r&&[null,void 0].includes(e[n]))throw Error(`Ziggy error: '${n}' parameter is required for route '${this.name}'.`);if(this.wheres[n]&&!RegExp(`^${r?`(${this.wheres[n]})?`:this.wheres[n]}$`).test(e[n]??``))throw Error(`Ziggy error: '${n}' parameter '${e[n]}' does not match required format '${this.wheres[n]}' for route '${this.name}'.`);return encodeURI(e[n]??``).replace(/%7C/g,`|`).replace(/%25/g,`%`).replace(/\$/g,`%24`)}).replace(this.config.absolute?/(\.[^/]+?)(\/\/)/:/(^)(\/\/)/,`$1/`).replace(/\/+$/,``):this.template}};function U(e){"@babel/helpers - typeof";return U=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},U(e)}function _e(e,t){if(U(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(U(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ve(e){var t=_e(e,`string`);return U(t)==`symbol`?t:t+``}function ye(e,t,n){return(t=ve(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function W(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function G(e){for(var t=1;t!this._route.parameterSegments.some(({name:t})=>t===e)).filter(e=>e!==`_query`).reduce((e,t)=>G(G({},e),{},{[t]:this._params[t]}),{});return this._route.compile(this._params)+de(G(G({},e),this._params._query),{addQueryPrefix:!0,arrayFormat:`indices`,encodeValuesOnly:!0,skipNulls:!0,encoder:(e,t)=>typeof e==`boolean`?Number(e):t(e)})}_unresolve(e){e?this._config.absolute&&e.startsWith(`/`)&&(e=this._location().host+e):e=this._currentUrl();let t={},[n,r]=Object.entries(this._config.routes).find(([n,r])=>t=new H(n,r,this._config).matchesUrl(e))||[void 0,void 0];return G(G({name:n},t),{},{route:r})}_currentUrl(){let{host:e,pathname:t,search:n}=this._location();return(this._config.absolute?e+t:t.replace(this._config.url.replace(/^\w*:\/\/[^/]+/,``),``).replace(/^\/+/,`/`))+n}current(e,t){let{name:n,params:r,query:i,route:a}=this._unresolve();if(!e)return n;let o=RegExp(`^${e.replace(/\./g,`\\.`).replace(/\*/g,`.*`)}$`).test(n);if([null,void 0].includes(t)||!o)return o;let s=new H(n,a,this._config);t=this._parse(t,s);let c=G(G({},r),i);if(Object.values(t).every(e=>!e)&&!Object.values(c).some(e=>e!==void 0))return!0;let l=(e,t)=>Object.entries(e).every(([e,n])=>Array.isArray(n)&&Array.isArray(t[e])?n.every(n=>t[e].includes(n)||t[e].includes(V(String(n)))):typeof n==`object`&&typeof t[e]==`object`&&n!==null&&t[e]!==null?l(n,t[e]):t[e]==n||t[e]==V(String(n)));return l(t,c)}_location(){let{host:e=``,pathname:t=``,search:n=``}=typeof window<`u`?window.location:{},r=typeof this._config.location==`string`?new URL(this._config.location):this._config.location;return{host:r?.host??e,pathname:r?.pathname??t,search:r?.search??n}}get params(){let{params:e,query:t}=this._unresolve();return G(G({},e),t)}get routeParams(){return this._unresolve().params}get queryParams(){return this._unresolve().query}has(e){return this._config.routes.hasOwnProperty(e)}_parse(e={},t=this._route){e??={},e=[`string`,`number`].includes(typeof e)?[e]:e;let n=t.parameterSegments.filter(({name:e})=>!this._config.defaults[e]);return Array.isArray(e)?e=e.reduce((e,t,r)=>n[r]?G(G({},e),{},{[n[r].name]:t}):typeof t==`object`?G(G({},e),t):G(G({},e),{},{[t]:``}),{}):n.length===1&&!e.hasOwnProperty(n[0].name)&&(e.hasOwnProperty(Object.values(t.bindings)[0])||e.hasOwnProperty(`id`))&&(e={[n[0].name]:e}),G(G({},this._defaults(t)),this._substituteBindings(e,t))}_defaults(e){return e.parameterSegments.filter(({name:e})=>this._config.defaults[e]).reduce((e,{name:t},n)=>G(G({},e),{},{[t]:this._config.defaults[t]}),{})}_substituteBindings(e,{bindings:t,parameterSegments:n}){return Object.entries(e).reduce((e,[r,i])=>{if(!i||typeof i!=`object`||Array.isArray(i)||!n.some(({name:e})=>e===r))return G(G({},e),{},{[r]:i});let a=i.hasOwnProperty(t[r])?t[r]:i.hasOwnProperty(`id`)?`id`:void 0;if(a===void 0)throw Error(`Ziggy error: object passed as '${r}' parameter is missing route model binding key '${t[r]}'.`);return G(G({},e),{},{[r]:i[a]})},{})}valueOf(){return this.toString()}};function xe(e,t,n,r){let i=new be(e,t,n,r);return e?i.toString():i}var Se={install(e,t){let n=(e,n,r,i=t)=>xe(e,n,r,typeof i==`function`?i():i);parseInt(e.version)>2?(e.config.globalProperties.route=n,e.provide(`route`,n)):e.mixin({methods:{route:n}})}};function Ce(e,t){let n=Math.trunc(t)%10,r=Math.trunc(t)%100;switch(e){case`ja`:case`zh_CN`:case`tr`:case`kk`:case`uz`:return 0;case`fr`:return t===0||t===1?0:1;case`ru`:case`uk`:case`be`:return n===1&&r!==11?0:n>=2&&n<=4&&(r<10||r>=20)?1:2;case`pl`:return t===1?0:n>=2&&n<=4&&(r<12||r>14)?1:2;default:return t===1?0:1}}function K(){return n().props.translations||{}}function we(){return n().props.locale||`en`}function q(e,t){return Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`:${t}`,String(n??``)),e)}function J(e,t={}){let n=K()[e];return typeof n==`string`?q(n,t):e}function Te(e,t,n={}){let r=K()[e];if(typeof r!=`string`)return e;let i=r.split(`|`),a=i[Math.min(Ce(we(),t),i.length-1)];return q(a,{count:t,...n})}var Ee={install(e){e.config.globalProperties.$t=J,e.config.globalProperties.$tc=Te}},De=[`graphite`,`day`,`night`,`sand`,`contrast`],Y=typeof window<`u`&&window.matchMedia?window.matchMedia(`(prefers-color-scheme: dark)`):null,X=null,Oe=e=>e===`system`?Y?.matches?`night`:`graphite`:De.includes(e)?e:`graphite`;function Z(e){if(!e)return;X=e;let t=document.documentElement;t.dataset.themeChoice=e,t.dataset.theme=Oe(e)}Y?.addEventListener(`change`,()=>{X===`system`&&Z(X)});var Q=e=>{let t=e.detail.page.props.locale;t&&(document.documentElement.lang=t.replace(`_`,`-`))};r.on(`success`,Q),r.on(`navigate`,Q);var $=e=>Z(e.detail.page.props.theme);r.on(`success`,$),r.on(`navigate`,$);var ke=Object.assign({"./Pages/Admin/ApiTokens/Index.vue":()=>u(()=>import(`./Index-BzuT6e6D.js`),__vite__mapDeps([0,1,2,3,4,5,6,7])),"./Pages/Admin/Auth/Login.vue":()=>u(()=>import(`./Login-D_P0ceoZ.js`),__vite__mapDeps([8,1,3])),"./Pages/Admin/Backups/Index.vue":()=>u(()=>import(`./Index-B0DDRHtS.js`),__vite__mapDeps([9,1,2,3,4,5,6,7])),"./Pages/Admin/Dashboard.vue":()=>u(()=>import(`./Dashboard-BpfYcZ3c.js`),__vite__mapDeps([10,1,2,3,4])),"./Pages/Admin/Modules/Index.vue":()=>u(()=>import(`./Index-CVtF6Jho.js`),__vite__mapDeps([11,1,2,3,4,5])),"./Pages/Admin/Modules/Settings.vue":()=>u(()=>import(`./Settings-DiwVH39L.js`),__vite__mapDeps([12,1,2,3,4,5,6,13,7,14,15])),"./Pages/Admin/Profile/Edit.vue":()=>u(()=>import(`./Edit-D7McI_eD.js`),__vite__mapDeps([16,1,2,3,4])),"./Pages/Admin/Resource/Create.vue":()=>u(()=>import(`./Create-B8v2keK9.js`),__vite__mapDeps([17,1,2,3,4,5,6,18,13,7,14,15])),"./Pages/Admin/Resource/Edit.vue":()=>u(()=>import(`./Edit-DKlRxfoE.js`),__vite__mapDeps([19,1,2,3,4,5,6,18,13,7,14,15,20])),"./Pages/Admin/Resource/Index.vue":()=>u(()=>import(`./Index-By9Fq-LA.js`),__vite__mapDeps([21,1,2,3,4,5,22,7,20])),"./Pages/Admin/Roles/Edit.vue":()=>u(()=>import(`./Edit-ppjiZjeT.js`),__vite__mapDeps([23,1,2,3,4,5,6])),"./Pages/Admin/Roles/Index.vue":()=>u(()=>import(`./Index-CJcjrNaO.js`),__vite__mapDeps([24,1,2,3,4,5,7])),"./Pages/Admin/Users/Create.vue":()=>u(()=>import(`./Create-DWM7DbLl.js`),__vite__mapDeps([25,1,2,3,4,5,6,13,7,14])),"./Pages/Admin/Users/Edit.vue":()=>u(()=>import(`./Edit-BEiwW1oN.js`),__vite__mapDeps([26,1,2,3,4,5,6,13,7,14])),"./Pages/Admin/Users/Index.vue":()=>u(()=>import(`./Index-waO6UWa5.js`),__vite__mapDeps([27,1,2,3,4,5,22,7]))});i({title:e=>{let t=document.querySelector(`title`)?.dataset.brand||`Atrium`;return e?`${e} — ${t}`:t},resolve:e=>{let t=ke[`./Pages/${e}.vue`];if(!t)throw Error(`Atrium: page "${e}" not found`);return t()},setup({el:n,App:r,props:i,plugin:a}){Z(i.initialPage.props.theme),t({render:()=>e(r,i)}).use(a).use(Se).use(Ee).mount(n)},progress:{color:`var(--atrium-accent)`}});export{J as n,Z as t}; \ No newline at end of file +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Index-C_p9UH4T.js","assets/dist-MY__znoP.js","assets/AdminLayout--RXJFj9t.js","assets/LocaleSwitcher-DdLJ9WTE.js","assets/AdminLayout-QfjingjX.css","assets/AdminButton-Bx141Bs3.js","assets/AdminCard--HubMtUj.js","assets/AdminModal-DNJ_V4iq.js","assets/Login-D_P0ceoZ.js","assets/Index-9-V30Hlc.js","assets/Index-bqKVRXw8.js","assets/Dashboard-BU7gtvAo.js","assets/Index-1mD_GBWn.js","assets/Settings-C2VyFPrB.js","assets/FormField-xD6LELDV.js","assets/FormField-0qI8GE1v.css","assets/contentLocale-BtGD-iBF.js","assets/Edit-D-yhP5A2.js","assets/Create-BxhK0Jvn.js","assets/ContentLocaleSwitcher-BJIieXK-.js","assets/Edit-CHndUQJ2.js","assets/recordActions-CtRs42tG.js","assets/Index-CjLWl74m.js","assets/AdminDataTable-BaQwb_6U.js","assets/Edit-pGNJhUsL.js","assets/Index-P5jX14JD.js","assets/Create-C61-lS2c.js","assets/Edit-DGjzU-uC.js","assets/Index-DEbfZBFs.js"])))=>i.map(i=>d[i]); +import{k as e,l as t,o as n,s as r,t as i}from"./dist-MY__znoP.js";var a=`modulepreload`,o=function(e){return`/vendor/atrium/`+e},s={},c=function(e){return e.pathname.endsWith(`.css`)},l=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},u=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),u=i?.nonce||i?.getAttribute(`nonce`);function d(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function f(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=d(t.map(t=>{t=o(t,n);let r=f(t),i=c(r);return l(s,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:a,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,u&&t.setAttribute(`nonce`,u),document.head.appendChild(t),i)return new Promise((e,n)=>{let i=a=>{t.removeEventListener(`load`,i),t.removeEventListener(`error`,i),a.type===`error`?n(Error(`Unable to preload CSS for ${r}`)):e(a)};t.addEventListener(`load`,i),t.addEventListener(`error`,i)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},d=String.prototype.replace,f=/%20/g,p={RFC1738:`RFC1738`,RFC3986:`RFC3986`},m={RFC1738:function(e){return d.call(e,f,`+`)},RFC3986:function(e){return String(e)}},h=p.RFC1738;p.RFC3986;var g=p.RFC3986,_=Object.prototype.hasOwnProperty,v=Array.isArray,y=new WeakMap,b=function(e,t){return y.set(e,t),e};function x(e){return y.has(e)}var S=function(e){return y.get(e)},C=function(e,t){y.set(e,t)},w=(function(){let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),T=function(e){for(;e.length>1;){let t=e.pop(),n=t.obj[t.prop];if(v(n)){let e=[];for(let t=0;t=0&&e>S(t)&&C(t,e)}return t},l)},te=function(e){let t=e.replace(/\+/g,` `);try{return decodeURIComponent(t)}catch{return t}},D=1024,ne=function(e,t,n,r){if(e.length===0)return e;let i=e;typeof e==`symbol`?i=Symbol.prototype.toString.call(e):typeof e!=`string`&&(i=String(e));let a=``;for(let e=0;e=D?i.slice(e,e+D):i;if(e+D=55296&&n<=56319&&(t=t.slice(0,-1),--e)}let n=[];for(let e=0;e=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||r===h&&(i===40||i===41)?n[n.length]=t.charAt(e):i<128?n[n.length]=w[i]:i<2048?n[n.length]=w[192|i>>6]+w[128|i&63]:i<55296||i>=57344?n[n.length]=w[224|i>>12]+w[128|i>>6&63]+w[128|i&63]:(e+=1,i=65536+((i&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=w[240|i>>18]+w[128|i>>12&63]+w[128|i>>6&63]+w[128|i&63])}a+=n.join(``)}return a},re=function(e){let t=[{obj:{o:e},prop:`o`}],n=new WeakMap;for(let e=0;en?b(E(a,{plainObjects:r}),a.length-1):a},k=function(e,t){if(v(e)){let n=[];for(let r=0;r0?_.join(`,`)||null:void 0}];else if(j(l))S=l;else{let e=Object.keys(_);S=u?e.sort(u):e}let C=s?t.replace(/\./g,`%2E`):t,w=r&&j(_)&&_.length===1?C+`[]`:C;if(i&&j(_)&&_.length===0)return w+`[]`;for(let t=0;t0?d+u:``}var L=Object.prototype.hasOwnProperty,R=Array.isArray,z={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,comma:!1,decodeDotInKeys:!1,decoder:te,delimiter:`&`,depth:5,duplicates:`combine`,ignoreQueryPrefix:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},B=function(e,t){return e&&typeof e==`string`&&t.comma&&e.indexOf(`,`)>-1?e.split(`,`):e},fe=function(e,t){let n={__proto__:null},r=t.ignoreQueryPrefix?e.replace(/^\?/,``):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=r.split(t.delimiter,i),o=0;for(;o-1&&(c=R(c)?[c]:c),t.comma&&R(c)&&c.length>t.arrayLimit&&(c=O([],c,t.arrayLimit,t.plainObjects));let l=L.call(n,s);l&&t.duplicates===`combine`?n[s]=O(n[s],c,t.arrayLimit,t.plainObjects):l&&t.duplicates!==`last`||(n[s]=c)}return n},pe=function(e,t,n,r){let i=r?t:B(t,n);for(let t=e.length-1;t>=0;--t){let r,a=e[t];if(a===`[]`&&n.parseArrays)r=x(i)?i:n.allowEmptyArrays&&(i===``||n.strictNullHandling&&i===null)?[]:O([],i,n.arrayLimit,n.plainObjects);else{r=n.plainObjects?Object.create(null):{};let e=a.charAt(0)===`[`&&a.charAt(a.length-1)===`]`?a.slice(1,-1):a,t=n.decodeDotInKeys?e.replace(/%2E/g,`.`):e,o=parseInt(t,10),s=!isNaN(o)&&a!==t&&String(o)===t&&o>=0&&n.parseArrays;!n.parseArrays&&t===``?r={0:i}:s&&o<=n.arrayLimit?(r=[],r[o]=i):s?(r[o]=i,b(r,o)):t!==`__proto__`&&(r[t]=i)}i=r}return i},me=function(e,t,n,r){if(!e)return;let i=n.allowDots?e.replace(/\.([^.[]+)/g,`[$1]`):e,a=/(\[[^[\]]*])/,o=/(\[[^[\]]*])/g,s=n.depth>0&&a.exec(i),c=s?i.slice(0,s.index):i,l=[];if(c){if(!n.plainObjects&&L.call(Object.prototype,c)&&!n.allowPrototypes)return;l.push(c)}let u=0;for(;n.depth>0&&(s=o.exec(i))!==null&&u{try{return decodeURIComponent(e)}catch{return e}})}var H=class{constructor(e,t,n){this.name=e,this.definition=t,this.bindings=t.bindings??{},this.wheres=t.wheres??{},this.config=n}get template(){let e=`${this.origin}/${this.definition.uri}`.replace(/\/+$/,``);return e===``?`/`:e}get origin(){return this.config.absolute?this.definition.domain?`${this.config.url.match(/^\w+:\/\//)[0]}${this.definition.domain}${this.config.port?`:${this.config.port}`:``}`:this.config.url:``}get parameterSegments(){return this.template.match(/{[^}?]+\??}/g)?.map(e=>({name:e.replace(/{|\??}/g,``),required:!/\?}$/.test(e)}))??[]}matchesUrl(e){if(!this.definition.methods.includes(`GET`))return!1;let t=this.template.replace(/[.*+$()[\]]/g,`\\$&`).replace(/(\/?){([^}?]*)(\??)}/g,(e,t,n,r)=>{let i=`(?<${n}>${this.wheres[n]?.replace(/(^\^)|(\$$)/g,``)||`[^/?]+`})`;return r?`(${t}${i})?`:`${t}${i}`}).replace(/^\w+:\/\//,``),[n,r]=e.replace(/^\w+:\/\//,``).split(`?`),i=RegExp(`^${t}/?$`).exec(n);if(!i)try{i=RegExp(`^${t}/?$`).exec(decodeURI(n))}catch{}if(i){for(let e in i.groups)typeof i.groups[e]==`string`&&(i.groups[e]=V(i.groups[e]));return{params:i.groups,query:ge(r)}}return!1}compile(e){return this.parameterSegments.length?this.template.replace(/{([^}?]+)(\??)}/g,(t,n,r)=>{if(!r&&[null,void 0].includes(e[n]))throw Error(`Ziggy error: '${n}' parameter is required for route '${this.name}'.`);if(this.wheres[n]&&!RegExp(`^${r?`(${this.wheres[n]})?`:this.wheres[n]}$`).test(e[n]??``))throw Error(`Ziggy error: '${n}' parameter '${e[n]}' does not match required format '${this.wheres[n]}' for route '${this.name}'.`);return encodeURI(e[n]??``).replace(/%7C/g,`|`).replace(/%25/g,`%`).replace(/\$/g,`%24`)}).replace(this.config.absolute?/(\.[^/]+?)(\/\/)/:/(^)(\/\/)/,`$1/`).replace(/\/+$/,``):this.template}};function U(e){"@babel/helpers - typeof";return U=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},U(e)}function _e(e,t){if(U(e)!=`object`||!e)return e;var n;if(typeof Symbol<`u`&&(n=e[Symbol.toPrimitive])!==void 0){var r=n.call(e,t||`default`);if(U(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ve(e){var t=_e(e,`string`);return U(t)==`symbol`?t:t+``}function ye(e,t,n){return(t=ve(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function W(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function G(e){for(var t=1;t!this._route.parameterSegments.some(({name:t})=>t===e)).filter(e=>e!==`_query`).reduce((e,t)=>G(G({},e),{},{[t]:this._params[t]}),{});return this._route.compile(this._params)+de(G(G({},e),this._params._query),{addQueryPrefix:!0,arrayFormat:`indices`,encodeValuesOnly:!0,skipNulls:!0,encoder:(e,t)=>typeof e==`boolean`?Number(e):t(e)})}_unresolve(e){e?this._config.absolute&&e.startsWith(`/`)&&(e=this._location().host+e):e=this._currentUrl();let t={},[n,r]=Object.entries(this._config.routes).find(([n,r])=>t=new H(n,r,this._config).matchesUrl(e))||[void 0,void 0];return G(G({name:n},t),{},{route:r})}_currentUrl(){let{host:e,pathname:t,search:n}=this._location();return(this._config.absolute?e+t:t.replace(this._config.url.replace(/^\w*:\/\/[^/]+/,``),``).replace(/^\/+/,`/`))+n}current(e,t){let{name:n,params:r,query:i,route:a}=this._unresolve();if(!e)return n;let o=RegExp(`^${e.replace(/\./g,`\\.`).replace(/\*/g,`.*`)}$`).test(n);if([null,void 0].includes(t)||!o)return o;let s=new H(n,a,this._config);t=this._parse(t,s);let c=G(G({},r),i);if(Object.values(t).every(e=>!e)&&!Object.values(c).some(e=>e!==void 0))return!0;let l=(e,t)=>Object.entries(e).every(([e,n])=>Array.isArray(n)&&Array.isArray(t[e])?n.every(n=>t[e].includes(n)||t[e].includes(V(String(n)))):typeof n==`object`&&typeof t[e]==`object`&&n!==null&&t[e]!==null?l(n,t[e]):t[e]==n||t[e]==V(String(n)));return l(t,c)}_location(){let{host:e=``,pathname:t=``,search:n=``}=typeof window<`u`?window.location:{},r=typeof this._config.location==`string`?new URL(this._config.location):this._config.location;return{host:r?.host??e,pathname:r?.pathname??t,search:r?.search??n}}get params(){let{params:e,query:t}=this._unresolve();return G(G({},e),t)}get routeParams(){return this._unresolve().params}get queryParams(){return this._unresolve().query}has(e){return this._config.routes.hasOwnProperty(e)}_parse(e={},t=this._route){e??={},e=[`string`,`number`].includes(typeof e)?[e]:e;let n=t.parameterSegments.filter(({name:e})=>!this._config.defaults[e]);return Array.isArray(e)?e=e.reduce((e,t,r)=>n[r]?G(G({},e),{},{[n[r].name]:t}):typeof t==`object`?G(G({},e),t):G(G({},e),{},{[t]:``}),{}):n.length===1&&!e.hasOwnProperty(n[0].name)&&(e.hasOwnProperty(Object.values(t.bindings)[0])||e.hasOwnProperty(`id`))&&(e={[n[0].name]:e}),G(G({},this._defaults(t)),this._substituteBindings(e,t))}_defaults(e){return e.parameterSegments.filter(({name:e})=>this._config.defaults[e]).reduce((e,{name:t},n)=>G(G({},e),{},{[t]:this._config.defaults[t]}),{})}_substituteBindings(e,{bindings:t,parameterSegments:n}){return Object.entries(e).reduce((e,[r,i])=>{if(!i||typeof i!=`object`||Array.isArray(i)||!n.some(({name:e})=>e===r))return G(G({},e),{},{[r]:i});let a=i.hasOwnProperty(t[r])?t[r]:i.hasOwnProperty(`id`)?`id`:void 0;if(a===void 0)throw Error(`Ziggy error: object passed as '${r}' parameter is missing route model binding key '${t[r]}'.`);return G(G({},e),{},{[r]:i[a]})},{})}valueOf(){return this.toString()}};function xe(e,t,n,r){let i=new be(e,t,n,r);return e?i.toString():i}var Se={install(e,t){let n=(e,n,r,i=t)=>xe(e,n,r,typeof i==`function`?i():i);parseInt(e.version)>2?(e.config.globalProperties.route=n,e.provide(`route`,n)):e.mixin({methods:{route:n}})}};function Ce(e,t){let n=Math.trunc(t)%10,r=Math.trunc(t)%100;switch(e){case`ja`:case`zh_CN`:case`tr`:case`kk`:case`uz`:return 0;case`fr`:return t===0||t===1?0:1;case`ru`:case`uk`:case`be`:return n===1&&r!==11?0:n>=2&&n<=4&&(r<10||r>=20)?1:2;case`pl`:return t===1?0:n>=2&&n<=4&&(r<12||r>14)?1:2;default:return t===1?0:1}}function K(){return n().props.translations||{}}function we(){return n().props.locale||`en`}function q(e,t){return Object.entries(t).reduce((e,[t,n])=>e.replaceAll(`:${t}`,String(n??``)),e)}function J(e,t={}){let n=K()[e];return typeof n==`string`?q(n,t):e}function Te(e,t,n={}){let r=K()[e];if(typeof r!=`string`)return e;let i=r.split(`|`),a=i[Math.min(Ce(we(),t),i.length-1)];return q(a,{count:t,...n})}var Ee={install(e){e.config.globalProperties.$t=J,e.config.globalProperties.$tc=Te}},De=[`graphite`,`day`,`night`,`sand`,`contrast`],Y=typeof window<`u`&&window.matchMedia?window.matchMedia(`(prefers-color-scheme: dark)`):null,X=null,Oe=e=>e===`system`?Y?.matches?`night`:`graphite`:De.includes(e)?e:`graphite`;function Z(e){if(!e)return;X=e;let t=document.documentElement;t.dataset.themeChoice=e,t.dataset.theme=Oe(e)}Y?.addEventListener(`change`,()=>{X===`system`&&Z(X)});var Q=e=>{let t=e.detail.page.props.locale;t&&(document.documentElement.lang=t.replace(`_`,`-`))};r.on(`success`,Q),r.on(`navigate`,Q);var $=e=>Z(e.detail.page.props.theme);r.on(`success`,$),r.on(`navigate`,$);var ke=Object.assign({"./Pages/Admin/ApiTokens/Index.vue":()=>u(()=>import(`./Index-C_p9UH4T.js`),__vite__mapDeps([0,1,2,3,4,5,6,7])),"./Pages/Admin/Auth/Login.vue":()=>u(()=>import(`./Login-D_P0ceoZ.js`),__vite__mapDeps([8,1,3])),"./Pages/Admin/Backups/Index.vue":()=>u(()=>import(`./Index-9-V30Hlc.js`),__vite__mapDeps([9,1,2,3,4,5,6,7])),"./Pages/Admin/Cache/Index.vue":()=>u(()=>import(`./Index-bqKVRXw8.js`),__vite__mapDeps([10,1,2,3,4,5])),"./Pages/Admin/Dashboard.vue":()=>u(()=>import(`./Dashboard-BU7gtvAo.js`),__vite__mapDeps([11,1,2,3,4])),"./Pages/Admin/Modules/Index.vue":()=>u(()=>import(`./Index-1mD_GBWn.js`),__vite__mapDeps([12,1,2,3,4,5])),"./Pages/Admin/Modules/Settings.vue":()=>u(()=>import(`./Settings-C2VyFPrB.js`),__vite__mapDeps([13,1,2,3,4,5,6,14,7,15,16])),"./Pages/Admin/Profile/Edit.vue":()=>u(()=>import(`./Edit-D-yhP5A2.js`),__vite__mapDeps([17,1,2,3,4])),"./Pages/Admin/Resource/Create.vue":()=>u(()=>import(`./Create-BxhK0Jvn.js`),__vite__mapDeps([18,1,2,3,4,5,6,19,14,7,15,16])),"./Pages/Admin/Resource/Edit.vue":()=>u(()=>import(`./Edit-CHndUQJ2.js`),__vite__mapDeps([20,1,2,3,4,5,6,19,14,7,15,16,21])),"./Pages/Admin/Resource/Index.vue":()=>u(()=>import(`./Index-CjLWl74m.js`),__vite__mapDeps([22,1,2,3,4,5,23,7,21])),"./Pages/Admin/Roles/Edit.vue":()=>u(()=>import(`./Edit-pGNJhUsL.js`),__vite__mapDeps([24,1,2,3,4,5,6])),"./Pages/Admin/Roles/Index.vue":()=>u(()=>import(`./Index-P5jX14JD.js`),__vite__mapDeps([25,1,2,3,4,5,7])),"./Pages/Admin/Users/Create.vue":()=>u(()=>import(`./Create-C61-lS2c.js`),__vite__mapDeps([26,1,2,3,4,5,6,14,7,15])),"./Pages/Admin/Users/Edit.vue":()=>u(()=>import(`./Edit-DGjzU-uC.js`),__vite__mapDeps([27,1,2,3,4,5,6,14,7,15])),"./Pages/Admin/Users/Index.vue":()=>u(()=>import(`./Index-DEbfZBFs.js`),__vite__mapDeps([28,1,2,3,4,5,23,7]))});i({title:e=>{let t=document.querySelector(`title`)?.dataset.brand||`Atrium`;return e?`${e} — ${t}`:t},resolve:e=>{let t=ke[`./Pages/${e}.vue`];if(!t)throw Error(`Atrium: page "${e}" not found`);return t()},setup({el:n,App:r,props:i,plugin:a}){Z(i.initialPage.props.theme),t({render:()=>e(r,i)}).use(a).use(Se).use(Ee).mount(n)},progress:{color:`var(--atrium-accent)`}});export{J as n,Z as t}; \ No newline at end of file diff --git a/packages/admin/dist/assets/app-BncygNAT.css b/packages/admin/dist/assets/app-BncygNAT.css new file mode 100644 index 00000000..5f3e10fa --- /dev/null +++ b/packages/admin/dist/assets/app-BncygNAT.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--tracking-wider:.05em;--leading-tight:1.25;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--font-brand:"Space Grotesk", var(--font-sans)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}html{accent-color:var(--atrium-accent);background-color:var(--atrium-page);color:var(--atrium-fg)}*{--tw-ring-offset-color:var(--atrium-surface)}::placeholder{color:var(--atrium-muted);opacity:1}select:not([multiple]):not([size]){appearance:none;background-color:var(--atrium-surface);background-image:linear-gradient(45deg,#0000 50%,currentColor 50%),linear-gradient(135deg,currentColor 50%,#0000 50%);background-position:calc(100% - 1rem),calc(100% - .6875rem);background-repeat:no-repeat;background-size:.3125rem .3125rem}select option{background-color:var(--atrium-surface);color:var(--atrium-fg)}}@layer components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-4{top:calc(var(--spacing) * 4)}.right-0{right:0}.right-1{right:var(--spacing)}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:0}.left-2{left:calc(var(--spacing) * 2)}.left-2\.5{left:calc(var(--spacing) * 2.5)}.isolate{isolation:isolate}.z-10{z-index:10}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mr-1{margin-right:var(--spacing)}.mr-1\.5{margin-right:calc(var(--spacing) * 1.5)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mr-3{margin-right:calc(var(--spacing) * 3)}.mr-4{margin-right:calc(var(--spacing) * 4)}.-mb-px{margin-bottom:-1px}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-8{margin-bottom:calc(var(--spacing) * 8)}.-ml-0\.5{margin-left:calc(var(--spacing) * -.5)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.ml-1{margin-left:var(--spacing)}.ml-1\.5{margin-left:calc(var(--spacing) * 1.5)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-6{margin-left:calc(var(--spacing) * 6)}.ml-auto{margin-left:auto}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-square{aspect-ratio:1}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-3{height:calc(var(--spacing) * 3)}.h-3\.5{height:calc(var(--spacing) * 3.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-full{height:100%}.h-px{height:1px}.max-h-60{max-height:calc(var(--spacing) * 60)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[90vh\]{max-height:90vh}.max-h-\[min\(36rem\,calc\(100vh-8rem\)\)\]{max-height:min(36rem,100vh - 8rem)}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-3{width:calc(var(--spacing) * 3)}.w-3\.5{width:calc(var(--spacing) * 3.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-20{width:calc(var(--spacing) * 20)}.w-24{width:calc(var(--spacing) * 24)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-\[4\.75rem\]{width:4.75rem}.w-\[22rem\]{width:22rem}.w-auto{width:auto}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-14{max-width:calc(var(--spacing) * 14)}.max-w-56{max-width:calc(var(--spacing) * 56)}.max-w-\[85\%\]{max-width:85%}.max-w-\[90\%\]{max-width:90%}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-full{min-width:100%}.flex-1{flex:1}.flex-none{flex:none}.flex-shrink{flex-shrink:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.border-separate{border-collapse:separate}.border-spacing-0{--tw-border-spacing-x:0px;--tw-border-spacing-y:0px;border-spacing:var(--tw-border-spacing-x) var(--tw-border-spacing-y)}.-translate-x-full{--tw-translate-x:-100%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-0{--tw-translate-y:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-4{--tw-translate-y:calc(var(--spacing) * 4);translate:var(--tw-translate-x) var(--tw-translate-y)}.scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-110{--tw-scale-x:110%;--tw-scale-y:110%;--tw-scale-z:110%;scale:var(--tw-scale-x) var(--tw-scale-y)}.rotate-90{rotate:90deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.transform-gpu{transform:translateZ(0) var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.animate-spin{animation:var(--animate-spin)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-disc{list-style-type:disc}.appearance-none{appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-x-4{column-gap:calc(var(--spacing) * 4)}:where(.-space-x-px>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(-1px * var(--tw-space-x-reverse));margin-inline-end:calc(-1px * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-1>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(var(--spacing) * var(--tw-space-x-reverse));margin-inline-end:calc(var(--spacing) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 4) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-8>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 8) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-3{row-gap:calc(var(--spacing) * 3)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-line>:not(:last-child)){border-color:var(--atrium-line)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-l-md{border-top-left-radius:var(--radius-md);border-bottom-left-radius:var(--radius-md)}.rounded-r-md{border-top-right-radius:var(--radius-md);border-bottom-right-radius:var(--radius-md)}.rounded-b-lg{border-bottom-right-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.rounded-b-xl{border-bottom-right-radius:var(--radius-xl);border-bottom-left-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:var(--atrium-accent)}.border-accent-hover{border-color:var(--atrium-accent-hover)}.border-accent-soft{border-color:var(--atrium-accent-soft)}.border-badge-line{border-color:var(--atrium-badge-line)}.border-current{border-color:currentColor}.border-danger{border-color:var(--atrium-danger)}.border-danger-soft{border-color:var(--atrium-danger-soft)}.border-field{border-color:var(--atrium-field)}.border-focus{border-color:var(--atrium-focus)}.border-line{border-color:var(--atrium-line)}.border-sidebar-line{border-color:var(--atrium-sidebar-line)}.border-success{border-color:var(--atrium-success)}.border-transparent{border-color:#0000}.border-warning-soft-fg{border-color:var(--atrium-warning-soft-fg)}.bg-accent{background-color:var(--atrium-accent)}.bg-accent-hover{background-color:var(--atrium-accent-hover)}.bg-accent-soft{background-color:var(--atrium-accent-soft)}.bg-black\/50{background-color:oklab(0% none none/.5)}.bg-current{background-color:currentColor}.bg-danger{background-color:var(--atrium-danger)}.bg-danger-hover{background-color:var(--atrium-danger-hover)}.bg-danger-soft{background-color:var(--atrium-danger-soft)}.bg-inherit{background-color:inherit}.bg-line{background-color:var(--atrium-line)}.bg-off{background-color:var(--atrium-off)}.bg-page{background-color:var(--atrium-page)}.bg-sidebar{background-color:var(--atrium-sidebar)}.bg-sidebar-active{background-color:var(--atrium-sidebar-active)}.bg-success-soft{background-color:var(--atrium-success-soft)}.bg-surface{background-color:var(--atrium-surface)}.bg-surface-alt{background-color:var(--atrium-surface-alt)}.bg-surface\/75{background-color:var(--atrium-surface)}@supports (color:color-mix(in lab, red, red)){.bg-surface\/75{background-color:color-mix(in oklab, var(--atrium-surface) 75%, transparent)}}.bg-transparent{background-color:#0000}.bg-warning-soft{background-color:var(--atrium-warning-soft)}.bg-white{background-color:#fff}.bg-contain{background-size:contain}.bg-center{background-position:50%}.bg-left{background-position:0}.bg-no-repeat{background-repeat:no-repeat}.fill-accent{fill:var(--atrium-accent)}.fill-fg{fill:var(--atrium-fg)}.fill-mark{fill:var(--atrium-mark)}.fill-mark-accent{fill:var(--atrium-mark-accent)}.fill-surface{fill:var(--atrium-surface)}.object-cover{object-fit:cover}.p-0{padding:0}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-16{padding-block:calc(var(--spacing) * 16)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-3{padding-right:calc(var(--spacing) * 3)}.pr-4{padding-right:calc(var(--spacing) * 4)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-1{padding-bottom:var(--spacing)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-5{padding-left:calc(var(--spacing) * 5)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-9{padding-left:calc(var(--spacing) * 9)}.pl-10{padding-left:calc(var(--spacing) * 10)}.pl-12{padding-left:calc(var(--spacing) * 12)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-brand{font-family:var(--font-brand)}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[11px\]{font-size:11px}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[-0\.01em\]{--tw-tracking:-.01em;letter-spacing:-.01em}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-accent{color:var(--atrium-accent)}.text-accent-hover{color:var(--atrium-accent-hover)}.text-accent-soft-fg{color:var(--atrium-accent-soft-fg)}.text-danger{color:var(--atrium-danger)}.text-danger-soft-fg{color:var(--atrium-danger-soft-fg)}.text-fg{color:var(--atrium-fg)}.text-muted{color:var(--atrium-muted)}.text-off-fg{color:var(--atrium-off-fg)}.text-on-accent{color:var(--atrium-on-accent)}.text-on-danger{color:var(--atrium-on-danger)}.text-sidebar-active-fg{color:var(--atrium-sidebar-active-fg)}.text-sidebar-fg{color:var(--atrium-sidebar-fg)}.text-sidebar-muted{color:var(--atrium-sidebar-muted)}.text-success{color:var(--atrium-success)}.text-success-soft-fg{color:var(--atrium-success-soft-fg)}.text-transparent{color:#0000}.text-warning-soft-fg{color:var(--atrium-warning-soft-fg)}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, )}.underline{text-decoration-line:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.placeholder-muted::placeholder{color:var(--atrium-muted)}.accent-hover{accent-color:var(--atrium-hover)}.opacity-0{opacity:0}.opacity-25{opacity:.25}.opacity-50{opacity:.5}.opacity-75{opacity:.75}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-\[inset_3px_0_0_var\(--atrium-sidebar-accent\)\]{--tw-shadow:inset 3px 0 0 var(--tw-shadow-color,var(--atrium-sidebar-accent));box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-field{--tw-ring-color:var(--atrium-field)}.ring-focus{--tw-ring-color:var(--atrium-focus)}.ring-line{--tw-ring-color:var(--atrium-line)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-75{--tw-duration:75ms;transition-duration:75ms}.duration-100{--tw-duration:.1s;transition-duration:.1s}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-all{-webkit-user-select:all;user-select:all}.ring-inset{--tw-ring-inset:inset}@media (hover:hover){:is(:where(.group):hover .group-hover\:text-fg){color:var(--atrium-fg)}:is(:where(.group):hover .group-hover\:opacity-100){opacity:1}}.file\:mr-4::file-selector-button{margin-right:calc(var(--spacing) * 4)}.file\:rounded-md::file-selector-button{border-radius:var(--radius-md)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-accent-soft::file-selector-button{background-color:var(--atrium-accent-soft)}.file\:px-4::file-selector-button{padding-inline:calc(var(--spacing) * 4)}.file\:py-2::file-selector-button{padding-block:calc(var(--spacing) * 2)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-accent-hover::file-selector-button{color:var(--atrium-accent-hover)}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}@media (hover:hover){.hover\:scale-105:hover{--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x) var(--tw-scale-y)}.hover\:border-fg:hover{border-color:var(--atrium-fg)}.hover\:border-field:hover{border-color:var(--atrium-field)}.hover\:border-focus:hover{border-color:var(--atrium-focus)}.hover\:bg-accent-hover:hover{background-color:var(--atrium-accent-hover)}.hover\:bg-accent-soft:hover{background-color:var(--atrium-accent-soft)}.hover\:bg-danger-hover:hover{background-color:var(--atrium-danger-hover)}.hover\:bg-danger-soft:hover{background-color:var(--atrium-danger-soft)}.hover\:bg-hover:hover{background-color:var(--atrium-hover)}.hover\:bg-sidebar-hover:hover{background-color:var(--atrium-sidebar-hover)}.hover\:text-accent:hover{color:var(--atrium-accent)}.hover\:text-accent-hover:hover{color:var(--atrium-accent-hover)}.hover\:text-accent-soft-fg:hover{color:var(--atrium-accent-soft-fg)}.hover\:text-danger:hover{color:var(--atrium-danger)}.hover\:text-danger-soft-fg:hover{color:var(--atrium-danger-soft-fg)}.hover\:text-fg:hover{color:var(--atrium-fg)}.hover\:text-sidebar-fg:hover{color:var(--atrium-sidebar-fg)}.hover\:underline:hover{text-decoration-line:underline}.hover\:file\:bg-accent-soft:hover::file-selector-button{background-color:var(--atrium-accent-soft)}}.focus\:border-focus:focus{border-color:var(--atrium-focus)}.focus\:ring-1:focus{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-danger:focus{--tw-ring-color:var(--atrium-danger)}.focus\:ring-focus:focus{--tw-ring-color:var(--atrium-focus)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset, ) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-focus:focus-visible{--tw-ring-color:var(--atrium-focus)}.focus-visible\:ring-sidebar-accent:focus-visible{--tw-ring-color:var(--atrium-sidebar-accent)}.focus-visible\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-focus:focus-visible{outline-color:var(--atrium-focus)}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-off:disabled{background-color:var(--atrium-off)}.disabled\:text-muted:disabled{color:var(--atrium-muted)}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}@media (width>=40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:my-8{margin-block:calc(var(--spacing) * 8)}.sm\:block{display:block}.sm\:hidden{display:none}.sm\:inline{display:inline}.sm\:w-full{width:100%}.sm\:max-w-2xl{max-width:var(--container-2xl)}.sm\:max-w-32{max-width:calc(var(--spacing) * 32)}.sm\:max-w-lg{max-width:var(--container-lg)}.sm\:max-w-md{max-width:var(--container-md)}.sm\:max-w-sm{max-width:var(--container-sm)}.sm\:max-w-xl{max-width:var(--container-xl)}.sm\:translate-y-0{--tw-translate-y:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.sm\:scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x) var(--tw-scale-y)}.sm\:scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:items-end{align-items:flex-end}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:calc(var(--spacing) * 2)}.sm\:gap-4{gap:calc(var(--spacing) * 4)}.sm\:px-2{padding-inline:calc(var(--spacing) * 2)}.sm\:px-4{padding-inline:calc(var(--spacing) * 4)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.sm\:text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}}@media (width>=48rem){.md\:block{display:block}:where(.md\:space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}}@media (width>=64rem){.lg\:col-span-2{grid-column:span 2/span 2}.lg\:block{display:block}.lg\:hidden{display:none}.lg\:w-20{width:calc(var(--spacing) * 20)}.lg\:w-64{width:calc(var(--spacing) * 64)}.lg\:translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:gap-3{gap:calc(var(--spacing) * 3)}.lg\:p-6{padding:calc(var(--spacing) * 6)}.lg\:px-2{padding-inline:calc(var(--spacing) * 2)}.lg\:px-6{padding-inline:calc(var(--spacing) * 6)}.lg\:px-8{padding-inline:calc(var(--spacing) * 8)}.lg\:pl-20{padding-left:calc(var(--spacing) * 20)}.lg\:pl-64{padding-left:calc(var(--spacing) * 64)}.lg\:text-center{text-align:center}}@media (width>=80rem){.xl\:max-w-48{max-width:calc(var(--spacing) * 48)}}}@font-face{font-family:Space Grotesk;font-style:normal;font-display:swap;font-weight:600;src:url(/vendor/atrium/assets/space-grotesk-latin-600-normal-DjKNqYRj.woff2)format("woff2"),url(/vendor/atrium/assets/space-grotesk-latin-600-normal-BflQw4A9.woff)format("woff")}:root,[data-theme=graphite]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#111827;--atrium-sidebar-fg:#f9fafb;--atrium-sidebar-muted:#9ca3af;--atrium-sidebar-hover:#1f2937;--atrium-sidebar-active:#1f2937;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#60a5fa;--atrium-sidebar-line:#1f2937;--atrium-page:#f3f4f6;--atrium-surface:#fff;--atrium-surface-alt:#f9fafb;--atrium-hover:#f3f4f6;--atrium-fg:#111827;--atrium-muted:#4b5563;--atrium-line:#e5e7eb;--atrium-field:#7e8691;--atrium-accent:#2563eb;--atrium-accent-hover:#1d4ed8;--atrium-on-accent:#fff;--atrium-accent-soft:#dbeafe;--atrium-accent-soft-fg:#1e40af;--atrium-focus:#2563eb;--atrium-off:#f3f4f6;--atrium-off-fg:#374151;--atrium-badge-line:transparent;--atrium-danger:#c81e1e;--atrium-danger-hover:#991b1b;--atrium-on-danger:#fff;--atrium-danger-soft:#fee2e2;--atrium-danger-soft-fg:#991b1b;--atrium-success:#15803d;--atrium-success-soft:#dcfce7;--atrium-success-soft-fg:#166534;--atrium-warning-soft:#fef3c7;--atrium-warning-soft-fg:#92400e;--atrium-mark:#fff;--atrium-mark-accent:#60a5fa}[data-theme=day]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#fff;--atrium-sidebar-fg:#1f2937;--atrium-sidebar-muted:#64748b;--atrium-sidebar-hover:#f1f5f9;--atrium-sidebar-active:#eef2ff;--atrium-sidebar-active-fg:#3730a3;--atrium-sidebar-accent:#4f46e5;--atrium-sidebar-line:#e2e8f0;--atrium-page:#f8fafc;--atrium-surface:#fff;--atrium-surface-alt:#f8fafc;--atrium-hover:#f1f5f9;--atrium-fg:#0f172a;--atrium-muted:#475569;--atrium-line:#e2e8f0;--atrium-field:#8391a5;--atrium-accent:#4f46e5;--atrium-accent-hover:#4338ca;--atrium-on-accent:#fff;--atrium-accent-soft:#e0e7ff;--atrium-accent-soft-fg:#3730a3;--atrium-focus:#4f46e5;--atrium-off:#f1f5f9;--atrium-off-fg:#334155;--atrium-badge-line:transparent;--atrium-danger:#c81e1e;--atrium-danger-hover:#991b1b;--atrium-on-danger:#fff;--atrium-danger-soft:#fee2e2;--atrium-danger-soft-fg:#991b1b;--atrium-success:#15803d;--atrium-success-soft:#dcfce7;--atrium-success-soft-fg:#166534;--atrium-warning-soft:#fef3c7;--atrium-warning-soft-fg:#92400e;--atrium-mark:#0f172a;--atrium-mark-accent:#4f46e5}[data-theme=night]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--atrium-sidebar:#0a0e14;--atrium-sidebar-fg:#e6eaf0;--atrium-sidebar-muted:#8b95a5;--atrium-sidebar-hover:#141b26;--atrium-sidebar-active:#1a2230;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#8ab4ff;--atrium-sidebar-line:#1a2230;--atrium-page:#0f141b;--atrium-surface:#161d27;--atrium-surface-alt:#121821;--atrium-hover:#1f2733;--atrium-fg:#e6eaf0;--atrium-muted:#a0aaba;--atrium-line:#253041;--atrium-field:#5f6d82;--atrium-accent:#8ab4ff;--atrium-accent-hover:#b0ccff;--atrium-on-accent:#0a0e14;--atrium-accent-soft:#1e2f4d;--atrium-accent-soft-fg:#b9d1ff;--atrium-focus:#8ab4ff;--atrium-off:#222b38;--atrium-off-fg:#c3cbd6;--atrium-badge-line:transparent;--atrium-danger:#ff8a8a;--atrium-danger-hover:#ffb0b0;--atrium-on-danger:#0a0e14;--atrium-danger-soft:#3d1c22;--atrium-danger-soft-fg:#ffc2c2;--atrium-success:#5fd38d;--atrium-success-soft:#173524;--atrium-success-soft-fg:#a6ebc0;--atrium-warning-soft:#3a2e12;--atrium-warning-soft-fg:#fcd98a;--atrium-mark:#fff;--atrium-mark-accent:#8ab4ff}[data-theme=sand]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#1f1a14;--atrium-sidebar-fg:#f5efe6;--atrium-sidebar-muted:#b3a796;--atrium-sidebar-hover:#2b241c;--atrium-sidebar-active:#342b21;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#f2a65a;--atrium-sidebar-line:#342b21;--atrium-page:#f7f3ec;--atrium-surface:#fff;--atrium-surface-alt:#fbf8f3;--atrium-hover:#f1ece4;--atrium-fg:#1f1a14;--atrium-muted:#5c5246;--atrium-line:#e7dfd2;--atrium-field:#958672;--atrium-accent:#a6490a;--atrium-accent-hover:#853a07;--atrium-on-accent:#fff;--atrium-accent-soft:#fce7d2;--atrium-accent-soft-fg:#7a3506;--atrium-focus:#a6490a;--atrium-off:#f1ece4;--atrium-off-fg:#4a4137;--atrium-badge-line:transparent;--atrium-danger:#b42318;--atrium-danger-hover:#912018;--atrium-on-danger:#fff;--atrium-danger-soft:#fde4e1;--atrium-danger-soft-fg:#8a1c12;--atrium-success:#2e7d32;--atrium-success-soft:#e3f2df;--atrium-success-soft-fg:#1f5a23;--atrium-warning-soft:#fbefc5;--atrium-warning-soft-fg:#7a4a06;--atrium-mark:#f5efe6;--atrium-mark-accent:#f2a65a}[data-theme=contrast]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#000;--atrium-sidebar-fg:#fff;--atrium-sidebar-muted:#d4d4d4;--atrium-sidebar-hover:#262626;--atrium-sidebar-active:#ffd400;--atrium-sidebar-active-fg:#000;--atrium-sidebar-accent:#ffd400;--atrium-sidebar-line:#fff;--atrium-page:#fff;--atrium-surface:#fff;--atrium-surface-alt:#fff;--atrium-hover:#fff2a8;--atrium-fg:#000;--atrium-muted:#262626;--atrium-line:#000;--atrium-field:#000;--atrium-accent:#0033a0;--atrium-accent-hover:#001f66;--atrium-on-accent:#fff;--atrium-accent-soft:#ffd400;--atrium-accent-soft-fg:#000;--atrium-focus:#0033a0;--atrium-off:#fff;--atrium-off-fg:#000;--atrium-badge-line:#000;--atrium-danger:#b00020;--atrium-danger-hover:#7a0016;--atrium-on-danger:#fff;--atrium-danger-soft:#ffe0e0;--atrium-danger-soft-fg:#7a0016;--atrium-success:#006b2d;--atrium-success-soft:#d9f5e3;--atrium-success-soft-fg:#003d1a;--atrium-warning-soft:#ffd400;--atrium-warning-soft-fg:#000;--atrium-mark:#fff;--atrium-mark-accent:#ffd400}[data-theme=contrast] .border{border-width:2px}[data-theme=contrast] .border-t{border-top-width:2px}[data-theme=contrast] .border-b{border-bottom-width:2px}[data-theme=contrast] .border-l{border-left-width:2px}[data-theme=contrast] .border-r{border-right-width:2px}[data-theme=contrast] .divide-y>:not(:last-child){border-bottom-width:2px}[data-credit]{--atrium-credit-logo:url(/vendor/atrium/assets/logo-DDS3n-zU.svg)}:where([data-theme=graphite],[data-theme=night],[data-theme=sand],[data-theme=contrast]) [data-credit-on=sidebar],:where([data-theme=night]) [data-credit-on=page]{--atrium-credit-logo:url(/vendor/atrium/assets/logo-white-BqJt87jq.svg)}select:not([multiple]):not([size]){padding-right:2rem}@property --tw-border-spacing-x{syntax:"";inherits:false;initial-value:0}@property --tw-border-spacing-y{syntax:"";inherits:false;initial-value:0}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}} diff --git a/packages/admin/dist/assets/app-BvgWOIqU.css b/packages/admin/dist/assets/app-BvgWOIqU.css deleted file mode 100644 index 0db0d592..00000000 --- a/packages/admin/dist/assets/app-BvgWOIqU.css +++ /dev/null @@ -1,2 +0,0 @@ -/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:block))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-lg:32rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wide:.025em;--tracking-wider:.05em;--leading-tight:1.25;--radius-sm:.25rem;--radius-md:.375rem;--radius-lg:.5rem;--radius-xl:.75rem;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--font-brand:"Space Grotesk", var(--font-sans)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}html{accent-color:var(--atrium-accent);background-color:var(--atrium-page);color:var(--atrium-fg)}*{--tw-ring-offset-color:var(--atrium-surface)}::placeholder{color:var(--atrium-muted);opacity:1}select:not([multiple]):not([size]){appearance:none;background-color:var(--atrium-surface);background-image:linear-gradient(45deg,#0000 50%,currentColor 50%),linear-gradient(135deg,currentColor 50%,#0000 50%);background-position:calc(100% - 1rem),calc(100% - .6875rem);background-repeat:no-repeat;background-size:.3125rem .3125rem}select option{background-color:var(--atrium-surface);color:var(--atrium-fg)}}@layer components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-1{top:var(--spacing)}.top-1\/2{top:50%}.top-2{top:calc(var(--spacing) * 2)}.top-4{top:calc(var(--spacing) * 4)}.right-0{right:0}.right-1{right:var(--spacing)}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-0{left:0}.left-2{left:calc(var(--spacing) * 2)}.left-2\.5{left:calc(var(--spacing) * 2.5)}.isolate{isolation:isolate}.z-10{z-index:10}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.container{width:100%}@media (width>=40rem){.container{max-width:40rem}}@media (width>=48rem){.container{max-width:48rem}}@media (width>=64rem){.container{max-width:64rem}}@media (width>=80rem){.container{max-width:80rem}}@media (width>=96rem){.container{max-width:96rem}}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mr-1{margin-right:var(--spacing)}.mr-1\.5{margin-right:calc(var(--spacing) * 1.5)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mr-3{margin-right:calc(var(--spacing) * 3)}.mr-4{margin-right:calc(var(--spacing) * 4)}.-mb-px{margin-bottom:-1px}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-8{margin-bottom:calc(var(--spacing) * 8)}.-ml-0\.5{margin-left:calc(var(--spacing) * -.5)}.-ml-1{margin-left:calc(var(--spacing) * -1)}.ml-1{margin-left:var(--spacing)}.ml-1\.5{margin-left:calc(var(--spacing) * 1.5)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-3{margin-left:calc(var(--spacing) * 3)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-6{margin-left:calc(var(--spacing) * 6)}.ml-auto{margin-left:auto}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-square{aspect-ratio:1}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-3{height:calc(var(--spacing) * 3)}.h-3\.5{height:calc(var(--spacing) * 3.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-8{height:calc(var(--spacing) * 8)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-full{height:100%}.h-px{height:1px}.max-h-60{max-height:calc(var(--spacing) * 60)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[90vh\]{max-height:90vh}.max-h-\[min\(36rem\,calc\(100vh-8rem\)\)\]{max-height:min(36rem,100vh - 8rem)}.min-h-full{min-height:100%}.min-h-screen{min-height:100vh}.w-0\.5{width:calc(var(--spacing) * .5)}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-2{width:calc(var(--spacing) * 2)}.w-3{width:calc(var(--spacing) * 3)}.w-3\.5{width:calc(var(--spacing) * 3.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-10{width:calc(var(--spacing) * 10)}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-20{width:calc(var(--spacing) * 20)}.w-24{width:calc(var(--spacing) * 24)}.w-56{width:calc(var(--spacing) * 56)}.w-64{width:calc(var(--spacing) * 64)}.w-\[4\.75rem\]{width:4.75rem}.w-\[22rem\]{width:22rem}.w-auto{width:auto}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-14{max-width:calc(var(--spacing) * 14)}.max-w-56{max-width:calc(var(--spacing) * 56)}.max-w-\[85\%\]{max-width:85%}.max-w-\[90\%\]{max-width:90%}.max-w-\[calc\(100vw-2rem\)\]{max-width:calc(100vw - 2rem)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-5{min-width:calc(var(--spacing) * 5)}.min-w-48{min-width:calc(var(--spacing) * 48)}.min-w-full{min-width:100%}.flex-1{flex:1}.flex-none{flex:none}.flex-shrink{flex-shrink:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.border-separate{border-collapse:separate}.border-spacing-0{--tw-border-spacing-x:0px;--tw-border-spacing-y:0px;border-spacing:var(--tw-border-spacing-x) var(--tw-border-spacing-y)}.-translate-x-full{--tw-translate-x:-100%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-0{--tw-translate-y:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-y-4{--tw-translate-y:calc(var(--spacing) * 4);translate:var(--tw-translate-x) var(--tw-translate-y)}.scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.scale-110{--tw-scale-x:110%;--tw-scale-y:110%;--tw-scale-z:110%;scale:var(--tw-scale-x) var(--tw-scale-y)}.rotate-90{rotate:90deg}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.transform-gpu{transform:translateZ(0) var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, )}.animate-spin{animation:var(--animate-spin)}.cursor-move{cursor:move}.cursor-pointer{cursor:pointer}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-disc{list-style-type:disc}.appearance-none{appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0\.5{gap:calc(var(--spacing) * .5)}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-2\.5{gap:calc(var(--spacing) * 2.5)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-x-4{column-gap:calc(var(--spacing) * 4)}:where(.-space-x-px>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(-1px * var(--tw-space-x-reverse));margin-inline-end:calc(-1px * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-1>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(var(--spacing) * var(--tw-space-x-reverse));margin-inline-end:calc(var(--spacing) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-4>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 4) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-8>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 8) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 8) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-3{row-gap:calc(var(--spacing) * 3)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-line>:not(:last-child)){border-color:var(--atrium-line)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-visible{overflow:visible}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-l-md{border-top-left-radius:var(--radius-md);border-bottom-left-radius:var(--radius-md)}.rounded-r-md{border-top-right-radius:var(--radius-md);border-bottom-right-radius:var(--radius-md)}.rounded-b-lg{border-bottom-right-radius:var(--radius-lg);border-bottom-left-radius:var(--radius-lg)}.rounded-b-xl{border-bottom-right-radius:var(--radius-xl);border-bottom-left-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-accent{border-color:var(--atrium-accent)}.border-accent-hover{border-color:var(--atrium-accent-hover)}.border-accent-soft{border-color:var(--atrium-accent-soft)}.border-badge-line{border-color:var(--atrium-badge-line)}.border-current{border-color:currentColor}.border-danger{border-color:var(--atrium-danger)}.border-danger-soft{border-color:var(--atrium-danger-soft)}.border-field{border-color:var(--atrium-field)}.border-focus{border-color:var(--atrium-focus)}.border-line{border-color:var(--atrium-line)}.border-sidebar-line{border-color:var(--atrium-sidebar-line)}.border-success{border-color:var(--atrium-success)}.border-transparent{border-color:#0000}.border-warning-soft-fg{border-color:var(--atrium-warning-soft-fg)}.bg-accent{background-color:var(--atrium-accent)}.bg-accent-hover{background-color:var(--atrium-accent-hover)}.bg-accent-soft{background-color:var(--atrium-accent-soft)}.bg-black\/50{background-color:oklab(0% none none/.5)}.bg-current{background-color:currentColor}.bg-danger{background-color:var(--atrium-danger)}.bg-danger-hover{background-color:var(--atrium-danger-hover)}.bg-danger-soft{background-color:var(--atrium-danger-soft)}.bg-inherit{background-color:inherit}.bg-line{background-color:var(--atrium-line)}.bg-off{background-color:var(--atrium-off)}.bg-page{background-color:var(--atrium-page)}.bg-sidebar{background-color:var(--atrium-sidebar)}.bg-sidebar-active{background-color:var(--atrium-sidebar-active)}.bg-success-soft{background-color:var(--atrium-success-soft)}.bg-surface{background-color:var(--atrium-surface)}.bg-surface-alt{background-color:var(--atrium-surface-alt)}.bg-surface\/75{background-color:var(--atrium-surface)}@supports (color:color-mix(in lab, red, red)){.bg-surface\/75{background-color:color-mix(in oklab, var(--atrium-surface) 75%, transparent)}}.bg-transparent{background-color:#0000}.bg-warning-soft{background-color:var(--atrium-warning-soft)}.bg-contain{background-size:contain}.bg-center{background-position:50%}.bg-left{background-position:0}.bg-no-repeat{background-repeat:no-repeat}.fill-accent{fill:var(--atrium-accent)}.fill-fg{fill:var(--atrium-fg)}.fill-mark{fill:var(--atrium-mark)}.fill-mark-accent{fill:var(--atrium-mark-accent)}.fill-surface{fill:var(--atrium-surface)}.object-cover{object-fit:cover}.p-0{padding:0}.p-0\.5{padding:calc(var(--spacing) * .5)}.p-1{padding:var(--spacing)}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:var(--spacing)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-12{padding-block:calc(var(--spacing) * 12)}.py-16{padding-block:calc(var(--spacing) * 16)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-6{padding-top:calc(var(--spacing) * 6)}.pr-2{padding-right:calc(var(--spacing) * 2)}.pr-3{padding-right:calc(var(--spacing) * 3)}.pr-4{padding-right:calc(var(--spacing) * 4)}.pr-10{padding-right:calc(var(--spacing) * 10)}.pb-1{padding-bottom:var(--spacing)}.pl-3{padding-left:calc(var(--spacing) * 3)}.pl-4{padding-left:calc(var(--spacing) * 4)}.pl-5{padding-left:calc(var(--spacing) * 5)}.pl-6{padding-left:calc(var(--spacing) * 6)}.pl-8{padding-left:calc(var(--spacing) * 8)}.pl-9{padding-left:calc(var(--spacing) * 9)}.pl-10{padding-left:calc(var(--spacing) * 10)}.pl-12{padding-left:calc(var(--spacing) * 12)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-brand{font-family:var(--font-brand)}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[11px\]{font-size:11px}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-\[-0\.01em\]{--tw-tracking:-.01em;letter-spacing:-.01em}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-accent{color:var(--atrium-accent)}.text-accent-hover{color:var(--atrium-accent-hover)}.text-accent-soft-fg{color:var(--atrium-accent-soft-fg)}.text-danger{color:var(--atrium-danger)}.text-danger-soft-fg{color:var(--atrium-danger-soft-fg)}.text-fg{color:var(--atrium-fg)}.text-muted{color:var(--atrium-muted)}.text-off-fg{color:var(--atrium-off-fg)}.text-on-accent{color:var(--atrium-on-accent)}.text-on-danger{color:var(--atrium-on-danger)}.text-sidebar-active-fg{color:var(--atrium-sidebar-active-fg)}.text-sidebar-fg{color:var(--atrium-sidebar-fg)}.text-sidebar-muted{color:var(--atrium-sidebar-muted)}.text-success{color:var(--atrium-success)}.text-success-soft-fg{color:var(--atrium-success-soft-fg)}.text-transparent{color:#0000}.text-warning-soft-fg{color:var(--atrium-warning-soft-fg)}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, )}.underline{text-decoration-line:underline}.antialiased{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.placeholder-muted::placeholder{color:var(--atrium-muted)}.accent-hover{accent-color:var(--atrium-hover)}.opacity-0{opacity:0}.opacity-25{opacity:.25}.opacity-50{opacity:.5}.opacity-75{opacity:.75}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-2xl{--tw-shadow:0 25px 50px -12px var(--tw-shadow-color,#00000040);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-\[inset_3px_0_0_var\(--atrium-sidebar-accent\)\]{--tw-shadow:inset 3px 0 0 var(--tw-shadow-color,var(--atrium-sidebar-accent));box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring,.ring-1{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-2{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-field{--tw-ring-color:var(--atrium-field)}.ring-focus{--tw-ring-color:var(--atrium-focus)}.ring-line{--tw-ring-color:var(--atrium-line)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, )}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-75{--tw-duration:75ms;transition-duration:75ms}.duration-100{--tw-duration:.1s;transition-duration:.1s}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in{--tw-ease:var(--ease-in);transition-timing-function:var(--ease-in)}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.ease-out{--tw-ease:var(--ease-out);transition-timing-function:var(--ease-out)}.select-all{-webkit-user-select:all;user-select:all}.ring-inset{--tw-ring-inset:inset}@media (hover:hover){:is(:where(.group):hover .group-hover\:text-fg){color:var(--atrium-fg)}:is(:where(.group):hover .group-hover\:opacity-100){opacity:1}}.file\:mr-4::file-selector-button{margin-right:calc(var(--spacing) * 4)}.file\:rounded-md::file-selector-button{border-radius:var(--radius-md)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-accent-soft::file-selector-button{background-color:var(--atrium-accent-soft)}.file\:px-4::file-selector-button{padding-inline:calc(var(--spacing) * 4)}.file\:py-2::file-selector-button{padding-block:calc(var(--spacing) * 2)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-accent-hover::file-selector-button{color:var(--atrium-accent-hover)}.last\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}@media (hover:hover){.hover\:scale-105:hover{--tw-scale-x:105%;--tw-scale-y:105%;--tw-scale-z:105%;scale:var(--tw-scale-x) var(--tw-scale-y)}.hover\:border-fg:hover{border-color:var(--atrium-fg)}.hover\:border-field:hover{border-color:var(--atrium-field)}.hover\:border-focus:hover{border-color:var(--atrium-focus)}.hover\:bg-accent-hover:hover{background-color:var(--atrium-accent-hover)}.hover\:bg-accent-soft:hover{background-color:var(--atrium-accent-soft)}.hover\:bg-danger-hover:hover{background-color:var(--atrium-danger-hover)}.hover\:bg-danger-soft:hover{background-color:var(--atrium-danger-soft)}.hover\:bg-hover:hover{background-color:var(--atrium-hover)}.hover\:bg-sidebar-hover:hover{background-color:var(--atrium-sidebar-hover)}.hover\:text-accent:hover{color:var(--atrium-accent)}.hover\:text-accent-hover:hover{color:var(--atrium-accent-hover)}.hover\:text-accent-soft-fg:hover{color:var(--atrium-accent-soft-fg)}.hover\:text-danger:hover{color:var(--atrium-danger)}.hover\:text-danger-soft-fg:hover{color:var(--atrium-danger-soft-fg)}.hover\:text-fg:hover{color:var(--atrium-fg)}.hover\:text-sidebar-fg:hover{color:var(--atrium-sidebar-fg)}.hover\:underline:hover{text-decoration-line:underline}.hover\:file\:bg-accent-soft:hover::file-selector-button{background-color:var(--atrium-accent-soft)}}.focus\:border-focus:focus{border-color:var(--atrium-focus)}.focus\:ring-1:focus{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-danger:focus{--tw-ring-color:var(--atrium-danger)}.focus\:ring-focus:focus{--tw-ring-color:var(--atrium-focus)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset, ) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset, ) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-focus:focus-visible{--tw-ring-color:var(--atrium-focus)}.focus-visible\:ring-sidebar-accent:focus-visible{--tw-ring-color:var(--atrium-sidebar-accent)}.focus-visible\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\:outline-focus:focus-visible{outline-color:var(--atrium-focus)}.focus-visible\:ring-inset:focus-visible{--tw-ring-inset:inset}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-off:disabled{background-color:var(--atrium-off)}.disabled\:text-muted:disabled{color:var(--atrium-muted)}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-50:disabled{opacity:.5}@media (width>=40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:my-8{margin-block:calc(var(--spacing) * 8)}.sm\:block{display:block}.sm\:hidden{display:none}.sm\:inline{display:inline}.sm\:w-full{width:100%}.sm\:max-w-2xl{max-width:var(--container-2xl)}.sm\:max-w-32{max-width:calc(var(--spacing) * 32)}.sm\:max-w-lg{max-width:var(--container-lg)}.sm\:max-w-md{max-width:var(--container-md)}.sm\:max-w-sm{max-width:var(--container-sm)}.sm\:max-w-xl{max-width:var(--container-xl)}.sm\:translate-y-0{--tw-translate-y:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.sm\:scale-95{--tw-scale-x:95%;--tw-scale-y:95%;--tw-scale-z:95%;scale:var(--tw-scale-x) var(--tw-scale-y)}.sm\:scale-100{--tw-scale-x:100%;--tw-scale-y:100%;--tw-scale-z:100%;scale:var(--tw-scale-x) var(--tw-scale-y)}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.sm\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-2{gap:calc(var(--spacing) * 2)}.sm\:gap-4{gap:calc(var(--spacing) * 4)}.sm\:px-2{padding-inline:calc(var(--spacing) * 2)}.sm\:px-4{padding-inline:calc(var(--spacing) * 4)}.sm\:px-6{padding-inline:calc(var(--spacing) * 6)}.sm\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.sm\:text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}}@media (width>=48rem){.md\:block{display:block}:where(.md\:space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}}@media (width>=64rem){.lg\:col-span-2{grid-column:span 2/span 2}.lg\:block{display:block}.lg\:hidden{display:none}.lg\:w-20{width:calc(var(--spacing) * 20)}.lg\:w-64{width:calc(var(--spacing) * 64)}.lg\:translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:gap-3{gap:calc(var(--spacing) * 3)}.lg\:p-6{padding:calc(var(--spacing) * 6)}.lg\:px-2{padding-inline:calc(var(--spacing) * 2)}.lg\:px-6{padding-inline:calc(var(--spacing) * 6)}.lg\:px-8{padding-inline:calc(var(--spacing) * 8)}.lg\:pl-20{padding-left:calc(var(--spacing) * 20)}.lg\:pl-64{padding-left:calc(var(--spacing) * 64)}.lg\:text-center{text-align:center}}@media (width>=80rem){.xl\:max-w-48{max-width:calc(var(--spacing) * 48)}}}@font-face{font-family:Space Grotesk;font-style:normal;font-display:swap;font-weight:600;src:url(/vendor/atrium/assets/space-grotesk-latin-600-normal-DjKNqYRj.woff2)format("woff2"),url(/vendor/atrium/assets/space-grotesk-latin-600-normal-BflQw4A9.woff)format("woff")}:root,[data-theme=graphite]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#111827;--atrium-sidebar-fg:#f9fafb;--atrium-sidebar-muted:#9ca3af;--atrium-sidebar-hover:#1f2937;--atrium-sidebar-active:#1f2937;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#60a5fa;--atrium-sidebar-line:#1f2937;--atrium-page:#f3f4f6;--atrium-surface:#fff;--atrium-surface-alt:#f9fafb;--atrium-hover:#f3f4f6;--atrium-fg:#111827;--atrium-muted:#4b5563;--atrium-line:#e5e7eb;--atrium-field:#7e8691;--atrium-accent:#2563eb;--atrium-accent-hover:#1d4ed8;--atrium-on-accent:#fff;--atrium-accent-soft:#dbeafe;--atrium-accent-soft-fg:#1e40af;--atrium-focus:#2563eb;--atrium-off:#f3f4f6;--atrium-off-fg:#374151;--atrium-badge-line:transparent;--atrium-danger:#c81e1e;--atrium-danger-hover:#991b1b;--atrium-on-danger:#fff;--atrium-danger-soft:#fee2e2;--atrium-danger-soft-fg:#991b1b;--atrium-success:#15803d;--atrium-success-soft:#dcfce7;--atrium-success-soft-fg:#166534;--atrium-warning-soft:#fef3c7;--atrium-warning-soft-fg:#92400e;--atrium-mark:#fff;--atrium-mark-accent:#60a5fa}[data-theme=day]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#fff;--atrium-sidebar-fg:#1f2937;--atrium-sidebar-muted:#64748b;--atrium-sidebar-hover:#f1f5f9;--atrium-sidebar-active:#eef2ff;--atrium-sidebar-active-fg:#3730a3;--atrium-sidebar-accent:#4f46e5;--atrium-sidebar-line:#e2e8f0;--atrium-page:#f8fafc;--atrium-surface:#fff;--atrium-surface-alt:#f8fafc;--atrium-hover:#f1f5f9;--atrium-fg:#0f172a;--atrium-muted:#475569;--atrium-line:#e2e8f0;--atrium-field:#8391a5;--atrium-accent:#4f46e5;--atrium-accent-hover:#4338ca;--atrium-on-accent:#fff;--atrium-accent-soft:#e0e7ff;--atrium-accent-soft-fg:#3730a3;--atrium-focus:#4f46e5;--atrium-off:#f1f5f9;--atrium-off-fg:#334155;--atrium-badge-line:transparent;--atrium-danger:#c81e1e;--atrium-danger-hover:#991b1b;--atrium-on-danger:#fff;--atrium-danger-soft:#fee2e2;--atrium-danger-soft-fg:#991b1b;--atrium-success:#15803d;--atrium-success-soft:#dcfce7;--atrium-success-soft-fg:#166534;--atrium-warning-soft:#fef3c7;--atrium-warning-soft-fg:#92400e;--atrium-mark:#0f172a;--atrium-mark-accent:#4f46e5}[data-theme=night]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--atrium-sidebar:#0a0e14;--atrium-sidebar-fg:#e6eaf0;--atrium-sidebar-muted:#8b95a5;--atrium-sidebar-hover:#141b26;--atrium-sidebar-active:#1a2230;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#8ab4ff;--atrium-sidebar-line:#1a2230;--atrium-page:#0f141b;--atrium-surface:#161d27;--atrium-surface-alt:#121821;--atrium-hover:#1f2733;--atrium-fg:#e6eaf0;--atrium-muted:#a0aaba;--atrium-line:#253041;--atrium-field:#5f6d82;--atrium-accent:#8ab4ff;--atrium-accent-hover:#b0ccff;--atrium-on-accent:#0a0e14;--atrium-accent-soft:#1e2f4d;--atrium-accent-soft-fg:#b9d1ff;--atrium-focus:#8ab4ff;--atrium-off:#222b38;--atrium-off-fg:#c3cbd6;--atrium-badge-line:transparent;--atrium-danger:#ff8a8a;--atrium-danger-hover:#ffb0b0;--atrium-on-danger:#0a0e14;--atrium-danger-soft:#3d1c22;--atrium-danger-soft-fg:#ffc2c2;--atrium-success:#5fd38d;--atrium-success-soft:#173524;--atrium-success-soft-fg:#a6ebc0;--atrium-warning-soft:#3a2e12;--atrium-warning-soft-fg:#fcd98a;--atrium-mark:#fff;--atrium-mark-accent:#8ab4ff}[data-theme=sand]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#1f1a14;--atrium-sidebar-fg:#f5efe6;--atrium-sidebar-muted:#b3a796;--atrium-sidebar-hover:#2b241c;--atrium-sidebar-active:#342b21;--atrium-sidebar-active-fg:#fff;--atrium-sidebar-accent:#f2a65a;--atrium-sidebar-line:#342b21;--atrium-page:#f7f3ec;--atrium-surface:#fff;--atrium-surface-alt:#fbf8f3;--atrium-hover:#f1ece4;--atrium-fg:#1f1a14;--atrium-muted:#5c5246;--atrium-line:#e7dfd2;--atrium-field:#958672;--atrium-accent:#a6490a;--atrium-accent-hover:#853a07;--atrium-on-accent:#fff;--atrium-accent-soft:#fce7d2;--atrium-accent-soft-fg:#7a3506;--atrium-focus:#a6490a;--atrium-off:#f1ece4;--atrium-off-fg:#4a4137;--atrium-badge-line:transparent;--atrium-danger:#b42318;--atrium-danger-hover:#912018;--atrium-on-danger:#fff;--atrium-danger-soft:#fde4e1;--atrium-danger-soft-fg:#8a1c12;--atrium-success:#2e7d32;--atrium-success-soft:#e3f2df;--atrium-success-soft-fg:#1f5a23;--atrium-warning-soft:#fbefc5;--atrium-warning-soft-fg:#7a4a06;--atrium-mark:#f5efe6;--atrium-mark-accent:#f2a65a}[data-theme=contrast]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--atrium-sidebar:#000;--atrium-sidebar-fg:#fff;--atrium-sidebar-muted:#d4d4d4;--atrium-sidebar-hover:#262626;--atrium-sidebar-active:#ffd400;--atrium-sidebar-active-fg:#000;--atrium-sidebar-accent:#ffd400;--atrium-sidebar-line:#fff;--atrium-page:#fff;--atrium-surface:#fff;--atrium-surface-alt:#fff;--atrium-hover:#fff2a8;--atrium-fg:#000;--atrium-muted:#262626;--atrium-line:#000;--atrium-field:#000;--atrium-accent:#0033a0;--atrium-accent-hover:#001f66;--atrium-on-accent:#fff;--atrium-accent-soft:#ffd400;--atrium-accent-soft-fg:#000;--atrium-focus:#0033a0;--atrium-off:#fff;--atrium-off-fg:#000;--atrium-badge-line:#000;--atrium-danger:#b00020;--atrium-danger-hover:#7a0016;--atrium-on-danger:#fff;--atrium-danger-soft:#ffe0e0;--atrium-danger-soft-fg:#7a0016;--atrium-success:#006b2d;--atrium-success-soft:#d9f5e3;--atrium-success-soft-fg:#003d1a;--atrium-warning-soft:#ffd400;--atrium-warning-soft-fg:#000;--atrium-mark:#fff;--atrium-mark-accent:#ffd400}[data-theme=contrast] .border{border-width:2px}[data-theme=contrast] .border-t{border-top-width:2px}[data-theme=contrast] .border-b{border-bottom-width:2px}[data-theme=contrast] .border-l{border-left-width:2px}[data-theme=contrast] .border-r{border-right-width:2px}[data-theme=contrast] .divide-y>:not(:last-child){border-bottom-width:2px}[data-credit]{--atrium-credit-logo:url(/vendor/atrium/assets/logo-DDS3n-zU.svg)}:where([data-theme=graphite],[data-theme=night],[data-theme=sand],[data-theme=contrast]) [data-credit-on=sidebar],:where([data-theme=night]) [data-credit-on=page]{--atrium-credit-logo:url(/vendor/atrium/assets/logo-white-BqJt87jq.svg)}select:not([multiple]):not([size]){padding-right:2rem}@property --tw-border-spacing-x{syntax:"";inherits:false;initial-value:0}@property --tw-border-spacing-y{syntax:"";inherits:false;initial-value:0}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-scale-x{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-y{syntax:"*";inherits:false;initial-value:1}@property --tw-scale-z{syntax:"*";inherits:false;initial-value:1}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}} diff --git a/packages/admin/dist/manifest.json b/packages/admin/dist/manifest.json index 0a30ed63..0e4362bb 100644 --- a/packages/admin/dist/manifest.json +++ b/packages/admin/dist/manifest.json @@ -20,8 +20,8 @@ "_dist-MY__znoP.js" ] }, - "_AdminLayout-I1QMPYpW.js": { - "file": "assets/AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js": { + "file": "assets/AdminLayout--RXJFj9t.js", "name": "AdminLayout", "imports": [ "_dist-MY__znoP.js", @@ -54,13 +54,13 @@ "file": "assets/FormField-0qI8GE1v.css", "src": "_FormField-0qI8GE1v.css" }, - "_FormField-BI8KmQxQ.js": { - "file": "assets/FormField-BI8KmQxQ.js", + "_FormField-xD6LELDV.js": { + "file": "assets/FormField-xD6LELDV.js", "name": "FormField", "imports": [ "_dist-MY__znoP.js", "resources/js/app.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminModal-DNJ_V4iq.js", "_AdminButton-Bx141Bs3.js" ], @@ -107,13 +107,13 @@ "src": "resources/images/alvesoft/logo.svg" }, "resources/js/Pages/Admin/ApiTokens/Index.vue": { - "file": "assets/Index-BzuT6e6D.js", + "file": "assets/Index-C_p9UH4T.js", "name": "Index", "src": "resources/js/Pages/Admin/ApiTokens/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "resources/js/app.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", @@ -131,102 +131,113 @@ ] }, "resources/js/Pages/Admin/Backups/Index.vue": { - "file": "assets/Index-B0DDRHtS.js", + "file": "assets/Index-9-V30Hlc.js", "name": "Index", "src": "resources/js/Pages/Admin/Backups/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", "_AdminModal-DNJ_V4iq.js" ] }, + "resources/js/Pages/Admin/Cache/Index.vue": { + "file": "assets/Index-bqKVRXw8.js", + "name": "Index", + "src": "resources/js/Pages/Admin/Cache/Index.vue", + "isDynamicEntry": true, + "imports": [ + "_dist-MY__znoP.js", + "_AdminLayout--RXJFj9t.js", + "_AdminButton-Bx141Bs3.js" + ] + }, "resources/js/Pages/Admin/Dashboard.vue": { - "file": "assets/Dashboard-BpfYcZ3c.js", + "file": "assets/Dashboard-BU7gtvAo.js", "name": "Dashboard", "src": "resources/js/Pages/Admin/Dashboard.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js" + "_AdminLayout--RXJFj9t.js" ] }, "resources/js/Pages/Admin/Modules/Index.vue": { - "file": "assets/Index-CVtF6Jho.js", + "file": "assets/Index-1mD_GBWn.js", "name": "Index", "src": "resources/js/Pages/Admin/Modules/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js" ] }, "resources/js/Pages/Admin/Modules/Settings.vue": { - "file": "assets/Settings-DiwVH39L.js", + "file": "assets/Settings-C2VyFPrB.js", "name": "Settings", "src": "resources/js/Pages/Admin/Modules/Settings.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", - "_FormField-BI8KmQxQ.js", + "_FormField-xD6LELDV.js", "_contentLocale-BtGD-iBF.js" ] }, "resources/js/Pages/Admin/Profile/Edit.vue": { - "file": "assets/Edit-D7McI_eD.js", + "file": "assets/Edit-D-yhP5A2.js", "name": "Edit", "src": "resources/js/Pages/Admin/Profile/Edit.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js" + "_AdminLayout--RXJFj9t.js" ] }, "resources/js/Pages/Admin/Resource/Create.vue": { - "file": "assets/Create-B8v2keK9.js", + "file": "assets/Create-BxhK0Jvn.js", "name": "Create", "src": "resources/js/Pages/Admin/Resource/Create.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", "_ContentLocaleSwitcher-BJIieXK-.js", - "_FormField-BI8KmQxQ.js", + "_FormField-xD6LELDV.js", "_contentLocale-BtGD-iBF.js" ] }, "resources/js/Pages/Admin/Resource/Edit.vue": { - "file": "assets/Edit-DKlRxfoE.js", + "file": "assets/Edit-CHndUQJ2.js", "name": "Edit", "src": "resources/js/Pages/Admin/Resource/Edit.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", "_ContentLocaleSwitcher-BJIieXK-.js", - "_FormField-BI8KmQxQ.js", + "_FormField-xD6LELDV.js", "_contentLocale-BtGD-iBF.js", "_recordActions-CtRs42tG.js" ] }, "resources/js/Pages/Admin/Resource/Index.vue": { - "file": "assets/Index-By9Fq-LA.js", + "file": "assets/Index-CjLWl74m.js", "name": "Index", "src": "resources/js/Pages/Admin/Resource/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminDataTable-BaQwb_6U.js", "_AdminModal-DNJ_V4iq.js", @@ -234,71 +245,71 @@ ] }, "resources/js/Pages/Admin/Roles/Edit.vue": { - "file": "assets/Edit-ppjiZjeT.js", + "file": "assets/Edit-pGNJhUsL.js", "name": "Edit", "src": "resources/js/Pages/Admin/Roles/Edit.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", "resources/js/app.js" ] }, "resources/js/Pages/Admin/Roles/Index.vue": { - "file": "assets/Index-CJcjrNaO.js", + "file": "assets/Index-P5jX14JD.js", "name": "Index", "src": "resources/js/Pages/Admin/Roles/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminModal-DNJ_V4iq.js" ] }, "resources/js/Pages/Admin/Users/Create.vue": { - "file": "assets/Create-DWM7DbLl.js", + "file": "assets/Create-C61-lS2c.js", "name": "Create", "src": "resources/js/Pages/Admin/Users/Create.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", - "_FormField-BI8KmQxQ.js" + "_FormField-xD6LELDV.js" ] }, "resources/js/Pages/Admin/Users/Edit.vue": { - "file": "assets/Edit-BEiwW1oN.js", + "file": "assets/Edit-DGjzU-uC.js", "name": "Edit", "src": "resources/js/Pages/Admin/Users/Edit.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminCard--HubMtUj.js", - "_FormField-BI8KmQxQ.js" + "_FormField-xD6LELDV.js" ] }, "resources/js/Pages/Admin/Users/Index.vue": { - "file": "assets/Index-waO6UWa5.js", + "file": "assets/Index-DEbfZBFs.js", "name": "Index", "src": "resources/js/Pages/Admin/Users/Index.vue", "isDynamicEntry": true, "imports": [ "_dist-MY__znoP.js", - "_AdminLayout-I1QMPYpW.js", + "_AdminLayout--RXJFj9t.js", "_AdminButton-Bx141Bs3.js", "_AdminDataTable-BaQwb_6U.js", "_AdminModal-DNJ_V4iq.js" ] }, "resources/js/app.js": { - "file": "assets/app-lI4VKCmX.js", + "file": "assets/app-BNjy5Z6H.js", "name": "app", "src": "resources/js/app.js", "isEntry": true, @@ -309,6 +320,7 @@ "resources/js/Pages/Admin/ApiTokens/Index.vue", "resources/js/Pages/Admin/Auth/Login.vue", "resources/js/Pages/Admin/Backups/Index.vue", + "resources/js/Pages/Admin/Cache/Index.vue", "resources/js/Pages/Admin/Dashboard.vue", "resources/js/Pages/Admin/Modules/Index.vue", "resources/js/Pages/Admin/Modules/Settings.vue", @@ -323,7 +335,7 @@ "resources/js/Pages/Admin/Users/Index.vue" ], "css": [ - "assets/app-BvgWOIqU.css" + "assets/app-BncygNAT.css" ], "assets": [ "assets/space-grotesk-latin-600-normal-DjKNqYRj.woff2", From 0bca82b56951914964d6a27f893f0c77e7c83088 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:11:36 +0300 Subject: [PATCH 09/10] test(theme): page timings off in the theme tests, so a random prune does not add a query to the counted ones --- packages/theme/tests/TestCase.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/theme/tests/TestCase.php b/packages/theme/tests/TestCase.php index 05bab96a..090c0977 100644 --- a/packages/theme/tests/TestCase.php +++ b/packages/theme/tests/TestCase.php @@ -43,6 +43,9 @@ protected function defineEnvironment($app): void // a translated code are JSON queries, different on each. $target = env('DB_CONNECTION'); $config->set('database.default', in_array($target, ['mysql', 'pgsql'], true) ? $target : 'testing'); + // Recording a page's timing prunes old rows on one request in a + // hundred: an extra query the query-counting tests must not see. + $config->set('atrium.dashboard.timings.enabled', false); $config->set('atrium.seo.title_suffix', ' | Demo shop'); $config->set('atrium.public_urls', [ Product::class => ['prefix' => 'catalog', 'tree' => ProductSection::class, 'parent' => 'section_id'], From 2512e1b19d9b9dabaa093ac0d26a1eb5c12f8ce9 Mon Sep 17 00:00:00 2001 From: Pisarev Alexei <6171687+xiregroup@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:40:32 +0300 Subject: [PATCH 10/10] test(theme): a warm list or product page runs no queries at all --- packages/theme/tests/CachedPagesTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/theme/tests/CachedPagesTest.php b/packages/theme/tests/CachedPagesTest.php index 9c41235c..b918c031 100644 --- a/packages/theme/tests/CachedPagesTest.php +++ b/packages/theme/tests/CachedPagesTest.php @@ -18,7 +18,7 @@ /** * The theme's pages of a cached module: a list costs the same queries for - * any number of records, a warm product page almost none, and nothing is + * any number of records, a warm page none at all, and nothing is * stale after a save. */ final class CachedPagesTest extends TestCase @@ -50,7 +50,7 @@ public function test_a_list_page_costs_the_same_queries_for_any_number_of_record $this->assertSame($few, $many); } - public function test_a_warm_product_page_runs_at_most_two_queries(): void + public function test_a_warm_product_page_runs_no_queries(): void { $this->products(1); $url = '/catalog/computers/laptops/product-1'; @@ -58,17 +58,17 @@ public function test_a_warm_product_page_runs_at_most_two_queries(): void $queries = $this->queries(fn () => $this->get($url)->assertOk()->assertSee('Product 1')); - $this->assertLessThanOrEqual(2, $queries); + $this->assertSame(0, $queries); } - public function test_a_warm_list_page_runs_at_most_two_queries(): void + public function test_a_warm_list_page_runs_no_queries(): void { $this->products(5); $this->get('/catalog')->assertOk(); $queries = $this->queries(fn () => $this->get('/catalog')->assertOk()->assertSee('Product 5')); - $this->assertLessThanOrEqual(2, $queries); + $this->assertSame(0, $queries); } public function test_a_save_shows_on_the_list_and_the_page_at_once(): void