commit a2a48d7ce2b14279f80ff5142f20d58ec887ce76 Author: deploy-bot Date: Fri Dec 4 11:06:52 2026 +0000 v0.6.0 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c6e7377 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,112 @@ +# Changelog + +Every release has a section here, named after its version (for example `v0.1.0 - 2026-12-04`, as a second-level +heading). The release pull request to `production` is stopped by PR CI when its section is missing, and the text of +the section is the text of the release in Gitea. + +## v0.6.0 - 2026-12-04 + +- Per account: the face of the manager (the whole one or the simple one) is stored on the account and wins over what its rights give; an administrator sets it + on the accounts screen, an account with `manager.switch` (or `manager.full`) sets it itself. The language (Dutch or English) is a choice in the profile + and applies on the server too, inside the manager only. New migration: `locale` and `tutorial` on the user settings. +- The tour: an administrator switches it on for an account (accounts screen); the account gets it at its next load, and finishing or skipping it is stored + (`PUT /manager/profile/tutorial`), so it does not come back until it is switched on again. +- The simple face, made usable: posts, pages, media and the lists of `manager.resources` are marked `simple` by default (so with `simple_view` on, a simple + account has something to work with), menu items and lists take a `hint` (a line of explanation), a field takes `advanced` (left out of the simple face) + and `help` (shown under the field). The simple face has a start page of big buttons with a line of explanation, and bigger type and calmer spacing everywhere. +- The tour: a playful walk through the manager with a mascot (a card beside what it points at, steps for exactly what this account sees, Back/Next, dots). + It can be stopped at any moment (the cross, Escape or the link) and that is remembered per account, whether it was finished or not; it comes back only when + an administrator switches it on again, and an account that has had it can start it again ("Show the tour", in the menu and the profile). The pictures are + `resources/mascot/.webp|png` (or a folder of the site: `manager.mascot.path`); a picture that is missing is a paw. A module adds steps with `tutorial()`. + +## v0.5.2 - 2026-12-04 + +- The mirror for Packagist gets a clean tree per release (no tests, `ui/`, `dev/`, `TOKENS.md`, `.gitea/` or agent files), with no history and no + branch, so `composer require` installs less and this repository can be private. `mirror_tags.sh`, with tests; `out/` is export-ignored too. + +## v0.5.1 - 2026-12-04 + +- Packagist shows only the releases: the Release workflow pushes the tags to a mirror (`iriks-it/laravel-manager-packagist`) that has only a `production` branch with a note (no `composer.json`, so no version), + and Packagist reads that, so the `dev-…` versions of every branch are gone. + +## v0.5.0 - 2026-12-04 + +- Names that can move: `route_name` for the route-name prefix, `tables` for a table of its own per short name (on top of `table_prefix`), + `IriksIT\Manager\Support\Names` to ask for either. The defaults are the names of every earlier version. +- `manager:import posts|pages|reviews` copies the rows of a table of the site into the package (read-only on the source, repeatable, + `--dry-run`, column mapping). +- Server texts are translatable: menu, permission labels and sections, theme names, audit summaries and the main messages go through `__()`, + and the package ships `resources/lang/nl.json`. A site's own `lang/.json` wins. +- Fix: the audit log and the bot counter strip the configured route-name prefix, not a fixed `manager.`. +- Menu: sections, icons and order, changeable from `manager.menu` (items and links of the site's own). The old item shape stays valid. +- Simple view (`simple_view`, off by default): permissions `manager.full` and `manager.switch`, a remembered choice per account (new migration + adds `view` to the user settings) and a switch in the menu. +- Pages with fields: definitions in `manager.pages.definitions` (types text, textarea, markdown, lines, media, url, number, date, toggle, + select), `Page::contentFor($slug)` for the public site, and screens to edit them and to make free pages (new migration: `meta_description` + and `content` on the pages table). The field definitions (`Support\Fields`) and the form component are shared with what comes next. +- Lists without code: `manager.resources` makes a menu item, list, form, validation and permissions (`.view`, `.manage`) from field + definitions, kept in a model of the site or in the new `manager_records` table (new module `resources`, on by default, nothing registered + without definitions). +- Screens of the site's own: `manager.extensions` loads JavaScript modules next to the manager; `window.IriksManager` offers `register`, `api`, + `Vue` and the shared components, and `resources/dist/vue.js` maps `import 'vue'` to the Vue of the screens. A browser that opens a manager + address without a route of the package gets the screens (an HTML request only). +- History: a new module `revisions` (on by default, `MANAGER_REVISIONS`) keeps the state of every saved post and page with who and what changed, + shows it on the screens and puts an earlier state back (`revisions.view`, `revisions.restore`; new table `manager_revisions`). More models can + join with `manager.revisions.types`. +- Editor: Markdown fields get a toolbar, photos from the media library and a server-rendered preview (`POST /manager/markdown`); the media + library gets a click-to-set focus point with a square preview. (No cropping or rotating: the file stays as uploaded.) +- Statistics: `` puts the counting script (`/pulse/pulse.js`, no cookies, honours Do Not Track) in the public pages of a site. +- Login checks: `manager.login.checks` (contract `LoginCheck`, base class `BaseLoginCheck`) adds fields and checks before and after the password; + Cloudflare Turnstile is built in (two env keys). No two-factor login in the package itself. +- Roles of the host: `manager.permissions` (`mode` groups/host/merge, `roles` map or a `resolver` implementing `PermissionResolver`) lets a site + with its own roles say what an account may do; groups stay the default. +- CI: nothing runs weekly any more, and Trivy no longer runs in the jobs (the runner disk filled up with its database). `composer audit` stays in every + pull request and every release; Trivy scans production from the homelab, every night and after every release. The nightly dependency round of the + homelab replaces the weekly *Dependency updates* workflow (and `update_dependencies.py`); its `renovate/*` pull requests may go to `production` and + become a patch release of their own (one a night at most, none while a release branch is open). +- `manager:doctor` has a `names` check: it warns when the site uses a route name or an address of the manager and says to set `route_name` or `path`. + +## v0.4.0 - 2026-12-04 + +- Screens in the package: a small Vue app on the JSON routes, built and served by the package (a site needs no Node). Login, logout and + profile for an app that has none, a dashboard and menu, and screens for accounts, groups, media (with a picker for covers), posts, + categories and tags, the audit log with bans, and statistics. Pages and reviews show a read-only list. `MANAGER_UI=none` keeps only the + JSON routes. The default middleware is now `['web', 'manager.auth']` (a published config that still says `auth` keeps working). +- Themes: `dark` and `light`, your own as a JSON file (`php artisan manager:make-theme`) or in the config, chosen per account in the + profile (new table `manager_user_settings`; `MANAGER_THEME`, `MANAGER_USER_THEMES`). Every value is checked before it reaches a page. +- For AI agents: `php artisan manager:install` (no questions), `php artisan manager:doctor --json` (checks the setup, says how to fix + it, non-zero exit on failure), a step-by-step guide (`resources/ai/INTEGRATION.md`) and a Laravel Boost guideline. Modules report + their tables with `tables()`. +- PR CI: a job that type-checks and builds the screens and fails when the committed `resources/dist` is out of date. + +## v0.3.0 - 2026-12-04 + +- The Packagist step submits the package itself when Packagist does not know it yet (the update call answered 404), instead + of failing until someone submits it by hand. + +## v0.2.0 - 2026-12-04 + +- CI: the composer cache and three tries for the install in every job, so a hiccup of a download no longer breaks a run. +- Audit log (module `audit`, off by default): logins and failed logins, changes, opened pages and refusals, with the + address and the browser. Modules name their routes with the new `actions()` and `views()`. +- Address bans: by hand, for a group of addresses, or by itself after too many failed logins; optionally for the + whole app. `manager:unban` and `manager:audit-prune`. +- Statistics (module `statistics`, off by default): page views and time on a page without cookies or stored addresses, sources, + devices, programs, comparisons and CSV export. Which pages count is up to the site. +- Breaking for a module that implements `Contract\Module` without extending `BaseModule`: the contract gained + `actions()`, `views()` and `middleware()`. +- Weekly workflow *Dependency updates*: widens the version constraints in `composer.json` for a new release of a dependency, as a pull request to the open release branch. +- `dev/token-usage-hermes.py`: the same rows per model for work done by a Hermes agent; the token script also counts the advisor. +- `CLAUDE.md` and the rules shared with the other IriksIT repos in `AGENTS.md`. + +## v0.1.0 - 2026-12-04 + +First version. + +- The module registry, with a switch per part of the manager. A part that is off has no routes, tables, menu + item or permissions. +- Users: accounts, groups and permissions (a permission can need another), and `manager:create-user`. +- Media: the library on a Laravel disk and the public file route `/media-files/{id}/{name}/view`. +- Posts: drafts, scheduling, Markdown, categories and tags. +- MIT license; the development cycle with release branches, tags and Packagist, and CI with tests, `composer audit` + and Trivy. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3dbecaf --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Iriks IT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..70ecce2 --- /dev/null +++ b/README.md @@ -0,0 +1,296 @@ +# iriks-it/laravel-manager + +A modular backend for Laravel sites. Install it, switch on the parts the site needs, done. + +```bash +composer require iriks-it/laravel-manager +php artisan vendor:publish --tag=manager-config +php artisan migrate +``` + +Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager lives at `/manager` +(`MANAGER_PATH`) behind the `web` and `auth` middleware (`config/manager.php`). + +## Set up with an AI agent + +```bash +php artisan manager:install --modules=users,media,posts --user-model="App\Models\User" +php artisan manager:doctor --json # non-zero exit when something is wrong; each problem has a `fix` +``` + +`resources/ai/INTEGRATION.md` is a step-by-step guide for an agent; `resources/boost/guidelines/core.blade.php` +is picked up by Laravel Boost. + +## Screens and themes + +The package brings its own screens (a small Vue app on the JSON routes, already built: your app needs no Node). They also +give an app without a login a login and a profile. `MANAGER_UI=none` turns them off, for an app that builds its own screens +on the JSON routes. A browser that opens a manager address gets the page; anything that asks for JSON gets the data. + +- **Looks.** Built in are `dark` and `light`. `MANAGER_THEME` is what everyone sees until they choose; with + `MANAGER_USER_THEMES=true` (default) each account picks its own in its profile. +- **The house style of the site.** `php artisan manager:make-theme acme --brand=#e4002b --name="Acme" --logo=/img/logo.svg --font="Inter, sans-serif"` + writes `resources/manager-themes/acme.json`; set `MANAGER_THEME=acme`. A theme is colours, a radius, fonts, a name and a logo, and every + value is checked, so a theme file can never put CSS or markup in the page. Themes can also be listed in `manager.themes`. +- **Not built yet:** a theme editor in the manager (themes are files for now), and screens for modules your own site adds (they show a notice). +- **Working on the screens:** the sources are in `ui/`; `npm ci && npm run build` there writes `resources/dist`, which is committed + (PR CI fails when it is out of date). + +## Modules + +| Key | What | Default | +|---|---|---| +| `users` | Accounts, groups and permissions | on | +| `media` | Media library | on | +| `pages` | Page texts | on | +| `posts` | Posts | on | +| `reviews` | Reviews | off | +| `audit` | Audit log and address bans | off | +| `statistics` | Visitor statistics | off | +| `resources` | Lists defined in config (`manager.resources`) | on (nothing without definitions) | +| `revisions` | History of posts and pages, with restore | on | + +Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`, +`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`, `MANAGER_REVISIONS`. A module that is off has **no routes, no tables, no menu item and no permissions**: +its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when +that one is off. + +## Language + +The texts the server makes (menu, permission and section labels, theme names, audit summaries and the messages of the JSON routes) go through Laravel's `__()` with the English text as the key. The package ships `resources/lang/nl.json`; the screens follow `app()->getLocale()`. A site translates more, or words things differently, with its own `lang/.json`: that file wins over the package. Audit lines are written in the language of the request that made them. + +## The menu and the simple view + +A module's menu item is `['label' =>, 'route' =>, 'permission' =>]` and may add `section` (a heading), `icon` (`home`, `file`, `image`, `users`, `group`, `chart`, `shield`, `star`, `tag`, `link`, `cog`), `order` (lower first, default 100), `simple` and `new_tab`. A site changes the menu without code in `config/manager.php`: `menu.items` by route name without the prefix (`'posts.index' => ['order' => 10, 'section' => 'Content', 'hidden' => false]`) and `menu.links` for items of its own (`['label' => 'Leads', 'url' => '/manager/leads', 'permission' => null]`). + +`simple_view` (`MANAGER_SIMPLE_VIEW=true`) adds a simple face next to the full one, for an owner who only needs a few screens. Two permissions appear in the group form: `manager.full` (everything; super admins have it) and `manager.switch` (starts simple and may switch; the choice is remembered per account and the menu has a button for it). Every other account always gets the simple face: only the items marked `simple`. It limits the menu, not the access: the routes still check their own permissions. Turning it on makes accounts without `manager.full` or `manager.switch` see only the simple items, so give the groups what they need first. + +## Your own lists and screens + +**Lists without code.** `manager.resources` turns a definition into a menu item, a list, a form, validation and the permissions `.view` and `.manage`, for things like a menu, socials, services, testimonials or leads: + +```php +'resources' => [ + 'services' => [ + 'label' => 'Services', 'singular' => 'Service', + 'model' => App\Models\Service::class, // the records live in a model of the site; leave it out to use the package's own table + 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], + 'fields' => ['name' => ['type' => 'text', 'required' => true], 'price' => ['type' => 'number'], 'photo' => ['type' => 'media']], + ], +], +``` + +The field keys are the attributes of the model (the definition is the whitelist: nothing else is written); without a model the values are kept as JSON in `manager_records`. Field types are the ones of the pages. Names that belong to a module (`posts`, `pages`, `media`, ...) are refused. + +**Screens of your own.** List a JavaScript module in `manager.extensions` (a path of your site, or https). The manager loads it before it shows anything and puts `window.IriksManager` in reach: `Vue`, `boot`, `api`, `t`, `flash`, `navigate`, `register` and the components `Link`, `FormFields`, `Icon` and `MediaPicker`. `register('^/leads$', Component, { data: true })` shows `Component` at `/manager/leads`, with the JSON of that same address (or of `source`) as props; an address of yours needs a route for the data, and a menu item through `manager.menu.links`. Build your bundle with `vue` left external (`build.rollupOptions.external: ['vue']`): the manager points `import 'vue'` at its own Vue, so your components share its reactivity. A browser that opens a manager address without a route of the package gets the screens (which show yours, or "no screen yet"); a request for data gets a plain 404. + +## A site with data and names of its own + +The package never maps its queries onto other tables: every screen assumes its own columns. What it does give you is room to coexist and a way to move data in. + +- `route_name` (default `manager`): the prefix of the route names. A site that already has `manager.*` routes sets, for example, `'route_name' => 'cms'`; the menu and the screens follow. Use `IriksIT\Manager\Support\Names::route('posts.index')` in code of your own. +- `table_prefix` (default `manager_`) and `tables` (`['media' => 'site_files']`): the names of the tables. Set them before the first `migrate`; the package does not rename a table that exists. +- `php artisan manager:import posts --table=articles --map=title=headline --map=body=content [--dry-run] [--connection=...] [--limit=...]` copies the rows of a table of the site into `posts`, `pages` or `reviews`. The source is only read, and running it again updates the rows it made (found by slug, or by author and text for reviews). `--map` is `package_column=source_column`. Put the settings in `manager.import.` (`table`, `connection`, `map`) to run it without options. Tags may be JSON or a comma separated list; a row without the required text is skipped and reported. + +## Your own module + +Implement `IriksIT\Manager\Contracts\Module` (or extend `Modules\BaseModule`), keep `routes.php` and a +`migrations/` folder next to the class, and add the class to `available` in the config. + +## Users module + +Accounts and groups. `HasManagerAccess` on the host `User` model gives it `managerGroups()`, +`managerPermissions()`, `hasManagerPermission()`, `managerOutranks()` and `managerMayGive()`. +Keep `is_super_admin` out of `$fillable`: nobody becomes a super admin through a form. + +```bash +php artisan manager:create-user # the only way to make a super admin +``` + +- A group is a name plus permissions; a permission that needs another one (`posts.publish` needs + `posts.write`) brings it along. Permissions of a module that is off are ignored. +- Whoever manages accounts only touches accounts that need nothing more than their own rights, and + only hands out groups that give nothing they lack themselves. +- `groups.manage` is a gate for super admins only, not a permission of a group. +- The package defines one gate per permission and **no `Gate::before`**: it never answers for the + abilities of your own app. +- **A site with roles of its own** (decided in 0.5.0: groups stay the default, the site's roles are added next to them). + `manager.permissions.mode` is `groups` (default), `host` (the groups are ignored) or `merge` (both). The site says what a role may do + with `roles` (`['editor' => ['posts.view', 'posts.write'], 'owner' => ['*']]`, read from the attribute `role_attribute`: a string, a + list or a relation with a `name`) or with a `resolver` class that implements `IriksIT\Manager\Contracts\PermissionResolver`. Values + that are no permission of an active module are ignored and what a permission needs is added. A super admin may always do everything. + The group screens still work in `host` mode but give nothing. +- The migration adds `is_super_admin` to your users table (the table of `manager.user_model`). It + promotes nobody. + +## Checks on the login + +The login of the screens can ask for more. Write a class that extends `IriksIT\Manager\Support\Login\BaseLoginCheck` (the contract is `IriksIT\Manager\Contracts\LoginCheck`) and list it in `manager.login.checks`: + +- `fields()`: extra inputs on the form (`['name' => 'code', 'type' => 'text', 'label' => 'Code', 'autocomplete' => 'one-time-code']`); +- `before($request)`: runs before the password is looked at: a captcha; +- `after($request, $user)`: runs when the email and password are right and before anyone is logged in: a second factor. Refuse by throwing a `ValidationException`; the attempt then counts as a failed login, so the audit log and the bans see it. + +**Cloudflare Turnstile** is built in: set `MANAGER_TURNSTILE_SITE_KEY` and `MANAGER_TURNSTILE_SECRET` and the widget appears and is checked (a token that cannot be checked refuses the login). The widget loads a script from `challenges.cloudflare.com`; a strict Content-Security-Policy has to allow it. **There is no two-factor login in the package itself**: `after()` is the place for it, the code to make and keep the secrets is the site's. These checks belong to the login of the screens (`MANAGER_UI=package`); an app with its own login keeps its own. + +## Media module + +Files live on a Laravel filesystem disk (`manager.media.disk`); each row remembers its own disk. + +- Manager (behind `manager.middleware`): `GET /manager/media`, `/manager/media/items`, `POST`, + `PUT /{id}`, `DELETE /{id}`. Limits (total room, file size, extensions) are in `manager.media.*`. +- Visitors: `GET /media-files/{id}/{filename}/view`, outside the manager, no session. ETag, byte + ranges, `nosniff`, and only images, video and PDF are shown inline. Rate limiter `media-files`. +- Where a file is used: other modules or your app register a source with + `app(IriksIT\Manager\Support\MediaUsage::class)->register(fn () => $texts)`. Posts and Pages do. +- No SVG: it can carry scripts. + +## Pages module + +Pages are texts with keys, so the public site reads them and the owner edits them without code. Define a page in `config/manager.php`: + +```php +'pages' => ['definitions' => ['home' => ['title' => 'Home', 'fields' => [ + 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text', 'default' => 'Welcome', 'max' => 120], + 'intro' => ['label' => 'Story', 'type' => 'markdown'], + 'photo' => ['label' => 'Photo', 'type' => 'media'], +]]]], +``` + +and read it with `IriksIT\Manager\Models\Page::contentFor('home')`: the stored values over the defaults, so a page that was never saved still has all its keys. Field types: `text`, `textarea`, `markdown`, `lines`, `media`, `url`, `number`, `date`, `toggle` and `select` (with `options`); `required`, `default`, `max`, `help` and `rules` work on all. The screens make the form, and the server validates and cleans every value by its type (a media or url value must be an address of the site or http(s)). A page without a definition is a free page with one Markdown text, a description for search engines and a publish switch; it can be made and removed in the screens. Permission: `pages.edit`. The definitions are shared code (`IriksIT\Manager\Support\Fields`), so other records can use them. + +## Posts module + +Posts written in Markdown, with drafts, scheduling, categories and tags. + +- Routes under `/manager`: `posts` (list, `create`, `{id}/edit`, `{id}/preview`, update, `{id}/online`, + delete) and `labels` (categories and tags: make, rename, merge, remove). Rights: `posts.view`, `write`, + `publish`, `delete`, `labels`. +- Who may not publish only saves drafts, and cannot change or delete a post that is live or scheduled. +- A post is a draft (`published_at` null), scheduled (in the future) or published. For your public pages: + `IriksIT\Manager\Models\Post::published()`, `toCard()` and `IriksIT\Manager\Support\Markdown::toHtml()` + (raw HTML is escaped, external links open in a new window). The package has no public post routes: the + host decides what a visitor sees. +- Categories offered in the form: `manager.posts.categories`, the ones in use, the ones made by hand and + whatever your site adds with + `app(IriksIT\Manager\Modules\Posts\PostLabels::class)->suggestCategories(fn () => $titles)`. +- Covers and bodies count as use of a media file. + +## The editor + +Texts in Markdown (posts, free pages and `markdown` fields) have a toolbar (bold, italic, heading, list, quote, link), a **Photo** button that puts a picture from the media library into the text, and a **Preview** that is rendered by the server the way the site renders it (raw HTML is escaped; `POST /manager/markdown`, not written in the audit log). In the media library a click on a picture sets its **focus point** (`focus_x`, `focus_y`, 0 to 1): the part that must stay in view when the site crops it, shown in a square preview. There is no cropping or rotating in the manager: the file is kept as it was uploaded, and the site crops with the focus point. + +## History module + +Every save of a post or a page keeps its state (`manager_revisions`, the newest 50 per record, `manager.revisions.keep`), with who saved it and which fields changed; saving the same state again keeps nothing. The post and page screens show the history, and `revisions.restore` puts an earlier state back, which is a save like any other (so what was there is in the history too). Whether a post is on the site (`published_at`) and whether a page is published is not part of the history: going back in time never publishes or hides anything. A live post can only be put back by someone who may publish. Permissions: `revisions.view` (and the permission to see that kind of text) and `revisions.restore` (and the permission to write it). A site adds its own models with `manager.revisions.types`, e.g. `'services' => ['model' => App\\Models\\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']`. `MANAGER_REVISIONS=false` turns the module off. + +## Audit module + +Off by default: it stores IP addresses and browser lines, so a site switches it on knowingly and says so in its +privacy policy (`MANAGER_AUDIT=true`). + +- **The log**: logins, logouts and failed logins (from Laravel's own `Login`, `Logout` and `Failed` events, so it + works with any login the host has), every change in the manager, every page that is opened (not twice within + five minutes) and every refusal. Only the account, the address and the browser line are kept, and for an action + the fields its module listed, never what was typed into a form. The log is read with `audit.view`. +- **Names**: a module says what its routes are called in the log with `actions()` and `views()`; a test fails on a + manager route without a name. +- **Bans** (`audit.manage`): ban an address by hand, for a time or until lifted, or a whole group of addresses + (notes put addresses in a group). After too many failed logins an address is banned by itself (the rules are set + in the manager). A banned address gets a 403 (429 for an automatic ban) on every manager route. Put the + `manager.not-banned` middleware on the login routes of your app too. A site that is locked out lifts the ban + with `php artisan manager:unban {ip}`. +- **Behind a proxy**: set up trusted proxies (or `MANAGER_NEVER_BAN`) before switching the module on. Without + them every visitor shares one address, and one bad actor can lock the whole manager out. Failed logins on any + guard count towards the automatic ban. +- **Whole-site bans**: with `MANAGER_AUDIT_WHOLE_SITE_BANS=true` a ban can also keep an address off the whole app. + That adds a global middleware that is answered from the cache. +- **Config** (`manager.audit`): `never_ban` (`MANAGER_NEVER_BAN`, comma-separated: your own addresses), and + `max_keep_days` (`MANAGER_AUDIT_MAX_KEEP_DAYS`, 90): the longest the log may be kept, which your privacy policy + has to agree with. `manager:audit-prune` runs daily and deletes old lines and ended bans; notes stay until removed. + +## Statistics module + +Off by default (`MANAGER_STATISTICS=true`). The site's own visitor statistics, with no cookie and no stored IP address: +a visitor is a code made of the address, the browser and a random key that is deleted after a day (`manager:forget-visitor-keys`, +scheduled daily), so a code cannot be traced back afterwards. A browser that sends `DNT` or `Sec-GPC` is not counted. + +- **The script**: put `` once in the layout of the public site (`:spa="true"` for a site with a client-side router). It loads `/pulse/pulse.js` (about 2 kB, plain JavaScript, no cookies or storage), reports the page and the time it was in view, and does nothing for a browser with Do Not Track or Global Privacy Control. With the module off the component prints nothing. Behind a Content-Security-Policy allow that one script address. +- **Reporting** (what the script does, for a site that wants to do it itself): the pages of your site `POST` to `/pulse/view` (`{path, referrer, via, campaign}`, answers `{token}`) and, when the + visitor leaves, `/pulse/leave` (`{token, seconds}`). No session, rate limited (`manager.statistics.per_minute`). +- **Which pages count**: only addresses you name, so nobody can fill the statistics with made-up ones: + `manager.statistics.pages`, the posts under `manager.statistics.posts_path` (published ones only), and anything else through + `app(IriksIT\Manager\Modules\Statistics\CountedPages::class)->register(fn (string $path) => ...)`. +- **Programs**: the pages served to search engines, crawlers and previews are counted per day, program and page (no address, no browser + line), by a middleware the module adds to the `web` group (`manager.statistics.count_bots`). +- **The report** (`statistics.view`): visitors, visits, page views, time, bounce rate, a comparison with another period, pages, posts, + sources and channels, devices, heatmap, programs; `GET /manager/statistics?range=30d` and a CSV per sheet + (`/manager/statistics/export?sheet=days|pages|sources|bots`). +- **Country** only when `manager.statistics.country_header` names a header (Cloudflare: `CF-IPCountry`). + +## State of this version + +Done: module registry and switches, permissions per module, users (accounts, groups, command, roles of the host), media (library and +public file route, focus point), posts (with categories and tags), pages with fields, lists defined in config, the history with restore, +the audit log with bans, the statistics (with the counting script), the built-in screens for all of these (with a login, checks on the +login, a profile and the simple view), an editor, themes, translations, a site's own bundle of screens, the import of existing data, and +the install and doctor commands for AI agents. `composer test` runs the tests. + +Reviews are still a read-only list. The answers of every action are JSON in the shape the screens use, so an app can build its own screens +with `MANAGER_UI=none`. Not in the package: two-factor login (the login checks are the place for it), cropping or rotating pictures, a theme editor. + +## Development cycle + +``` +develop ── feature/*, fix/* ──► release/vX.Y.Z ──► production ──► tag vX.Y.Z ──► Packagist + ▲ (pull request, (collects the (pull request, │ + │ merges by itself) features) merged by hand) │ + └──────────────────────── sync: production into develop ◄─────────────────────────┘ +``` + +1. **Start a release:** Actions → *Start release* → version (`0.2.0`). That makes `release/v0.2.0` from `develop`. +2. **Features:** branch `feature/…` or `fix/…` from `develop`, open a pull request to the release branch. It + merges by itself when *PR CI* is green. Every pull request adds its row to `TOKENS.md`. +3. **Ready:** add a section `## v0.2.0 - date` to `CHANGELOG.md` and open a pull request from the release branch + to `production`. A person merges it. +4. **Release (automatic, on the merge):** tests and audit once more, the tag `v0.2.0` and a Gitea release with the + changelog text, Packagist is told, and `production` is merged into `develop`. + +Nobody opens a pull request to `develop`, and `production` and the release branches take no direct pushes. + +| When | What runs | +|---|---| +| Pull request to a release branch or to production | *flow* (right branches, version above the latest tag, changelog section, tests of these scripts), *ledger* (`TOKENS.md`), *test* (Pint, Pest with the newest and the oldest dependencies, `composer validate`), *security* (`composer audit`: the job fails on any advisory). The check `PR CI / pr-ci` is green when all are. | +| Push to production | verify (Pest, `composer audit`), tag and release, the tags to the mirror `laravel-manager-packagist`, Packagist, sync develop; then the homelab scans production with Trivy | +| Every night | the homelab scans every repository with Trivy (03:00) and updates its dependencies (04:00): nothing runs weekly in this repository | +| Every night | *Prune branches*: removes `feature/*` and `fix/*` branches whose last commit is over 30 days old and that have no open pull request (a branch of a pull request can be restored from it in Gitea) | + +### Security and updates + +Nothing here runs on a weekly schedule; the checks hang on the moments that matter, and the homelab does the rest every night. + +- **Every pull request:** `composer audit` (it fails on any advisory). +- **Every release:** `composer audit` again on the merge to `production`. +- **After every release to production:** Trivy scans `production` from the homelab (LXC 120, no database to download in a job). +- **Every night:** Trivy scans every repository of the organisation (03:00), and the dependency round (04:00) opens a pull request + `renovate/deps-DATE` straight to `production` for updates that have been public for 48 hours. PR CI tests it, and when it is + merged the Release workflow makes a patch release of it (v0.5.0 → v0.5.1, text from the pull request), tells Packagist and syncs `develop`: + one a night at most. While a release branch is open there is no patch release; the update goes out with that release. A critical advisory on the installed version skips the 48 hours. + +Packagist reads the mirror `iriks-it/laravel-manager-packagist`, not this repository, because it shows every branch of the +repository it reads as a `dev-…` version. For every release the Release workflow (`.gitea/scripts/mirror_tags.sh`) puts a clean +tree on the mirror: what `git archive` of the tag gives, so without what `.gitattributes` marks `export-ignore` (tests, `ui/`, +`dev/`, `TOKENS.md`, `.gitea/`, the agent files), as a commit with no history and no branch, and pushes only its tag. The mirror +has one branch, `production`, that only holds a note (no `composer.json`, so no version); nothing else is ever pushed there. Packagist +and `composer require` only see the mirror, so this repository can be private. (Versions up to v0.5.1 on the mirror are the full tree.) + +Secrets of the repository for this: `DEPLOY_TOKEN` (the organisation has it), and `PACKAGIST_USERNAME` and +`PACKAGIST_TOKEN` (until they are set that step only says so). When Packagist does not know the package yet, that step +submits it through the create-package API; after that it only tells Packagist about each new tag. + +## What Composer installs + +`.gitattributes` leaves what only belongs to the repository out of the package (`export-ignore`): `.gitea/`, +`dev/`, `scripts/`, `tests/`, `TOKENS.md`, `AGENTS.md`, `phpunit.xml` and the dotfiles. They stay in the repository. +Packagist builds the archive from `git archive`, so what a site installs is `src/`, `config/`, `routes/`, +`resources/`, `composer.json`, `README.md` and `CHANGELOG.md`. Check it with `git archive HEAD | tar -t`. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..1a195bc --- /dev/null +++ b/composer.json @@ -0,0 +1,58 @@ +{ + "name": "iriks-it/laravel-manager", + "description": "A modular backend (manager) for Laravel sites: users, media, pages, posts, reviews. Every part can be switched on or off.", + "type": "library", + "license": "MIT", + "keywords": ["laravel", "manager", "cms", "admin", "modules"], + "require": { + "php": "^8.4", + "illuminate/auth": "^13.0", + "illuminate/cache": "^13.0", + "illuminate/console": "^13.0", + "illuminate/contracts": "^13.0", + "illuminate/database": "^13.0", + "illuminate/filesystem": "^13.0", + "illuminate/http": "^13.0", + "illuminate/routing": "^13.0", + "illuminate/support": "^13.0", + "illuminate/validation": "^13.0", + "league/commonmark": "^2.6" + }, + "require-dev": { + "orchestra/testbench": "^11.0", + "pestphp/pest": "^5.0", + "laravel/pint": "^1.15" + }, + "autoload": { + "psr-4": { + "IriksIT\\Manager\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "IriksIT\\Manager\\Tests\\": "tests/" + } + }, + "extra": { + "laravel": { + "providers": [ + "IriksIT\\Manager\\ManagerServiceProvider" + ], + "aliases": { + "Manager": "IriksIT\\Manager\\Facades\\Manager" + } + } + }, + "scripts": { + "test": "pest", + "lint": "pint --test" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "minimum-stability": "stable", + "prefer-stable": true +} diff --git a/config/manager.php b/config/manager.php new file mode 100644 index 0000000..44f5c1a --- /dev/null +++ b/config/manager.php @@ -0,0 +1,253 @@ + env('MANAGER_PATH', 'manager'), + + /* + | Middleware around every manager route. Authentication of the manager itself + | is left to the host app: use the guard it already has. + */ + 'middleware' => ['web', 'manager.auth'], + + /* + | The screens. `package`: the manager brings its own (a Vue app, built, served by the package; it also gives a login and + | a profile when the app has none). `none`: only the JSON API, for an app that builds its own screens. + */ + 'ui' => env('MANAGER_UI', 'package'), + + /* + | The name in the menu and on the login screen. + */ + 'name' => env('MANAGER_NAME'), + + /* + | Looks. `theme` is what everyone gets until they choose; `user_themes` lets each account pick its own (profile). + | A theme is a set of colours, a radius and fonts: built in are `dark` and `light`; the site's own live as JSON files in + | `themes_path` (make one with `php artisan manager:make-theme`) or here in `themes`, by key. + */ + 'theme' => env('MANAGER_THEME', 'dark'), + 'user_themes' => (bool) env('MANAGER_USER_THEMES', true), + 'themes_path' => null, // default: resources/manager-themes of the app + 'themes' => [], + + /* + | The Eloquent model of the people who log in. Must use IriksIT\Manager\Concerns\HasManagerAccess. + */ + 'user_model' => env('MANAGER_USER_MODEL', 'App\\Models\\User'), + + /* + | The modules this manager knows. Add your own class here to give a site its own part. + */ + 'available' => [ + Modules\Users\UsersModule::class, + Modules\Media\MediaModule::class, + Modules\Pages\PagesModule::class, + Modules\Posts\PostsModule::class, + Modules\Reviews\ReviewsModule::class, + Modules\Audit\AuditModule::class, + Modules\Statistics\StatisticsModule::class, + Modules\Resources\ResourcesModule::class, + Modules\Revisions\RevisionsModule::class, + ], + + /* + | Switch a part on or off per site. A key left out falls back to the default of the + | module: users and media are on, everything else is off. A module that is off has no + | routes, no tables (its migrations are not loaded), no menu item and no permissions. + */ + 'modules' => [ + 'users' => true, + 'media' => true, + 'pages' => env('MANAGER_PAGES', true), + 'posts' => env('MANAGER_POSTS', true), + 'reviews' => env('MANAGER_REVIEWS', false), + 'audit' => env('MANAGER_AUDIT', false), + 'statistics' => env('MANAGER_STATISTICS', false), + 'resources' => true, + 'revisions' => env('MANAGER_REVISIONS', true), + ], + + /* + | The media library. Files live on a Laravel filesystem disk; each media row remembers + | its own disk, so a file stays where it was uploaded when `disk` changes later. + */ + 'media' => [ + 'disk' => env('MANAGER_MEDIA_DISK', 'public'), + + // How much room the library has in total, in GB. An upload that would go over it is refused. + 'max_total_gb' => (float) env('MANAGER_MEDIA_MAX_TOTAL_GB', 15), + + // Largest single upload in MB. PHP and the web server must allow it too + // (upload_max_filesize, post_max_size, client_max_body_size). + 'max_file_mb' => (int) env('MANAGER_MEDIA_MAX_FILE_MB', 40), + + // File extensions the library accepts. SVG is deliberately missing: it can carry scripts. + 'extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif', 'pdf', 'mp4', 'webm'], + + // Visitors loading files per minute per address (the `media-files` rate limiter). + 'per_minute' => 600, + ], + + /* + | Posts. `categories` are always offered in the post form, next to the ones in use and the + | ones made by hand; a site can offer more through PostLabels::suggestCategories(). + */ + 'posts' => [ + 'categories' => ['General'], + ], + + /* + | Markdown in posts: hosts besides APP_URL whose links do not open in a new window. + */ + 'markdown' => [ + 'internal_hosts' => [], + ], + + /* + | The audit log and the bans (module `audit`). + */ + 'audit' => [ + // Addresses that are never banned, by hand or by themselves: your own, so a slip or a rule + // that is too strict never locks you out. Comma-separated in MANAGER_NEVER_BAN. + 'never_ban' => array_values(array_filter(array_map('trim', explode(',', (string) env('MANAGER_NEVER_BAN', ''))))), + + // The longest the log may be kept, in days. Set it to what your privacy policy promises. + 'max_keep_days' => (int) env('MANAGER_AUDIT_MAX_KEEP_DAYS', 90), + + // Let a ban "for the whole site" work: the middleware then runs on every request of the app. + 'whole_site_bans' => (bool) env('MANAGER_AUDIT_WHOLE_SITE_BANS', false), + ], + + /* + | The visitor statistics (module `statistics`). + */ + 'statistics' => [ + // The addresses of the public site that count as a page. Anything else is ignored, so + // nobody can fill the statistics with made-up addresses. Posts and other kinds of pages + // come from `posts_path` or a resolver: app(CountedPages::class)->register(fn ($path) => ...). + 'pages' => ['/'], + + // The address under which the posts live (`/blog` for `/blog/my-post`); null: posts are not counted. + 'posts_path' => null, + + // Where the public pages report a view (POST {pulse_path}/view and {pulse_path}/leave). + 'pulse_path' => 'pulse', + + // Reports per minute per address. + 'per_minute' => 120, + + // The request header with the country code of the visitor, e.g. CF-IPCountry behind Cloudflare. Null: no country. + 'country_header' => env('MANAGER_STATISTICS_COUNTRY_HEADER'), + + // Count the pages served to programs (search engines, crawlers) by adding a middleware to the `web` group. + 'count_bots' => (bool) env('MANAGER_STATISTICS_COUNT_BOTS', true), + ], + + /* + | Pages with fields (module `pages`): per slug a title and the fields the screens make a form of, and the + | public site reads with `IriksIT\Manager\Models\Page::contentFor('home')`: + | 'definitions' => ['home' => ['title' => 'Home', 'fields' => [ + | 'hero_title' => ['label' => 'Title on the photo', 'type' => 'text'], + | 'intro' => ['label' => 'Story', 'type' => 'markdown'], + | 'photo' => ['label' => 'Photo', 'type' => 'media'], + | ]]]. + | Types: text, textarea, markdown, lines, media, url, number, date, toggle, select (with `options`). + */ + 'pages' => ['definitions' => []], + + /* + | Lists the site manages without code of its own: a form, a list, permissions (`.view`, `.manage`) + | and a menu item for each. `model` keeps the records in a model of the site (the field keys are its + | attributes); without it they go into the package's own table. Fields: see `pages`. + | A `hint` is the line under the item on the simple start page. + | 'services' => ['label' => 'Services', 'hint' => 'What you offer', 'singular' => 'Service', 'model' => App\Models\Service::class, + | 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => ['name' => ['type' => 'text', 'required' => true], ...]] + */ + 'resources' => [], + + /* + | A bundle of the site's own screens: JavaScript modules (a path of the site, or https) the manager loads next to its own, + | after it has started. They add screens with `IriksManager.register('^/leads$', Component, { data: true })`, and may + | `import { ref } from 'vue'` when the build leaves `vue` external. See README, "Your own screens". + */ + 'extensions' => [], + + /* + | The history of posts and pages (module `revisions`): `keep` states per record, more `types` of the site's own + | (['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']]), + | and `skip` for model classes that should not have one. + */ + 'revisions' => ['keep' => 50, 'types' => [], 'skip' => []], + + /* + | More a login asks for. `checks`: classes that implement IriksIT\Manager\Contracts\LoginCheck (extend + | IriksIT\Manager\Support\Login\BaseLoginCheck): a field of the form, something to check before the password is + | tried (a captcha) or after it was right (a second factor). Cloudflare Turnstile is built in and turns itself on + | when both of its keys are set. These apply to the login of the manager's own screens. + */ + 'login' => [ + 'checks' => [], + 'turnstile' => ['site_key' => env('MANAGER_TURNSTILE_SITE_KEY'), 'secret' => env('MANAGER_TURNSTILE_SECRET')], + ], + + /* + | Who may do what. `groups` (default): the groups of the package. A site that has roles of its own can say it itself: + | `host` takes the permissions only from the site, `merge` adds them to what the groups give. The site's side is a + | `resolver` class (IriksIT\Manager\Contracts\PermissionResolver), or, simpler, `roles` per role name (`*` is + | everything) read from the attribute `role_attribute` of the account (a string, a list or a relation with a `name`). + | 'roles' => ['editor' => ['posts.view', 'posts.write'], 'owner' => ['*']]. A super admin may always do everything. + */ + 'permissions' => ['mode' => env('MANAGER_PERMISSIONS', 'groups'), 'resolver' => null, 'roles' => [], 'role_attribute' => 'role'], + + /* + | The menu. `items` changes what a module gives, by the route name without the prefix: + | 'posts.index' => ['order' => 10, 'section' => 'Content', 'icon' => 'file', 'simple' => true, 'hidden' => false]. + | `links` adds items of the site's own: ['label' => 'Leads', 'url' => '/manager/leads', 'permission' => null, + | 'section' => ..., 'icon' => ..., 'order' => ..., 'simple' => ..., 'new_tab' => ...]. + | Icons: home, file, image, users, group, chart, shield, star, tag, link, cog. + */ + 'menu' => ['items' => [], 'links' => []], + + /* + | A simple face of the manager next to the full one. With this on, the permissions `manager.full` and + | `manager.switch` exist: an account with the first (or a super admin) gets everything; one with the + | second starts simple and may switch; all others always get the simple face, which shows only the + | menu items marked `simple`. Off: everyone sees the whole menu. + */ + 'simple_view' => (bool) env('MANAGER_SIMPLE_VIEW', false), + + /* + | The pictures of the tour: a folder with `welcome`, `point`, `calm`, `write`, `photos`, `pages`, `undo`, `oops`, `party`, `profile` and + | `peek` (`.webp` or `.png`). Null: the set of the package. A picture that is missing is replaced by a paw. + */ + 'mascot' => ['path' => null], + + /* + | Prefix for the tables of the package. + */ + 'table_prefix' => 'manager_', + + /* + | A table with a name of its own, by short name (`posts`, `pages`, `media`, ...): wins over the prefix. + | Set it before the first migrate; the package never renames a table that exists. + */ + 'tables' => [], + + /* + | Prefix of the route names (`manager.posts.index`). Change it when the site already has `manager.*` + | routes; menu items and screens follow by themselves. + */ + 'route_name' => 'manager', + + /* + | Where `php artisan manager:import ` reads from, so it needs no options: + | 'posts' => ['table' => 'articles', 'connection' => null, 'map' => ['title' => 'headline']]. + */ + 'import' => [], +]; diff --git a/database/migrations/2026_12_05_000001_create_manager_user_settings.php b/database/migrations/2026_12_05_000001_create_manager_user_settings.php new file mode 100644 index 0000000..6fd06c3 --- /dev/null +++ b/database/migrations/2026_12_05_000001_create_manager_user_settings.php @@ -0,0 +1,26 @@ +getTable(); + + Schema::create(Names::table('user_settings'), function (Blueprint $table) use ($users) { + $table->id(); + $table->foreignId('user_id')->unique()->constrained($users)->cascadeOnDelete(); + $table->string('theme', 60)->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('user_settings')); + } +}; diff --git a/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php b/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php new file mode 100644 index 0000000..df4cecb --- /dev/null +++ b/database/migrations/2026_12_06_000001_add_view_to_manager_user_settings.php @@ -0,0 +1,24 @@ +string('view', 10)->nullable()->after('theme'); + }); + } + + public function down(): void + { + Schema::table(Names::table('user_settings'), function (Blueprint $table) { + $table->dropColumn('view'); + }); + } +}; diff --git a/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php b/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php new file mode 100644 index 0000000..9ca6724 --- /dev/null +++ b/database/migrations/2026_12_07_000001_add_locale_and_tutorial_to_manager_user_settings.php @@ -0,0 +1,25 @@ +string('locale', 5)->nullable()->after('view'); + $table->string('tutorial', 10)->nullable()->after('locale'); + }); + } + + public function down(): void + { + Schema::table(Names::table('user_settings'), function (Blueprint $table) { + $table->dropColumn(['locale', 'tutorial']); + }); + } +}; diff --git a/resources/ai/INTEGRATION.md b/resources/ai/INTEGRATION.md new file mode 100644 index 0000000..8f8e750 --- /dev/null +++ b/resources/ai/INTEGRATION.md @@ -0,0 +1,39 @@ +# Integrating iriks-it/laravel-manager (guide for AI agents) + +Goal: the manager runs in this Laravel app and `php artisan manager:doctor --json` says `"ok": true`. Do the steps in +order and never edit files inside `vendor/`. + +1. `composer require iriks-it/laravel-manager` + (A version that is not on Packagist yet: first `composer config repositories.manager --json '{"type":"path","url":"/path/to/laravel-manager","options":{"symlink":false}}'`, then require `@dev`.) +2. Pick the modules. `users` and `media` are on; `pages` and `posts` are on by default; `reviews`, `audit` and `statistics` are off + (audit and statistics store visitor data: only switch them on when the owner says so). +3. `php artisan manager:install --modules=users,media,posts --user-model="App\Models\User"` + It writes the `MANAGER_*` switches to `.env` and publishes `config/manager.php`. Add `--path=admin` to move the URL. + It does not run the check itself (this process still has the old config): that is step 7. +4. Add the trait to the user model: `use \IriksIT\Manager\Concerns\HasManagerAccess;`. Never put `is_super_admin` in `$fillable`. +5. `php artisan config:clear && php artisan migrate && php artisan storage:link` (a new process, so it sees the switches of step 3). +6. Create the first super admin: `php artisan manager:create-user --name="..." --email="..." --password="<12+ chars>"`. +7. `php artisan manager:doctor --json`. Every check must be `ok` or an understood `warn`; each `fail` and `warn` has a `fix`. + Repeat until `"ok": true`. + +Facts that matter: +- A site that already has `manager.*` route names, `manager_*` tables or its own posts and pages: `manager:doctor` has a `names` check that says + so. Set `route_name`, `table_prefix` or `tables` in `config/manager.php` before the first `migrate`, then copy what exists with + `php artisan manager:import posts|pages|reviews --table= --map== --dry-run` (the source is only read). +- What the site's own content looks like is configuration, not code: `manager.pages.definitions` (texts with keys, read with `Page::contentFor('slug')`), + `manager.resources` (lists such as services or testimonials, in a model of the site or the package's table) and `manager.menu` (order, sections, + icons, own links). A screen that needs code is a JavaScript module in `manager.extensions`; it registers with `IriksManager.register`. +- Who may do what: the groups of the package, or the roles of the site (`manager.permissions`); more on the login: `manager.login.checks`, Turnstile + with two env keys. The public pages count visits with `` when `statistics` is on. +- The screens are part of the package (`MANAGER_UI=package`, the default): open `/manager` in a browser. The app does not need a + login of its own: when it has no route named `login`, the manager's own login at `/manager/login` is used. With + `MANAGER_UI=none` there are only the JSON routes. +- A browser address gets the screens, a request with `Accept: application/json` gets the data. To call the JSON routes from a + script: `GET /manager/login` once for the `XSRF-TOKEN` cookie, then `POST /manager/login` with header `X-XSRF-TOKEN` (the cookie + value, URL-decoded), `Accept: application/json` and body `{"email": "...", "password": "..."}`; the answer is `{"redirect": "/manager"}`. +- The look: `MANAGER_THEME=dark|light` or your own (`php artisan manager:make-theme acme --brand=#e4002b --name="Acme" --logo=/img/logo.svg`, + then `MANAGER_THEME=acme`). Each account can pick its own in its profile (`MANAGER_USER_THEMES=false` stops that). +- Anything that is off has no routes, tables or permissions. A module that needs another one fails at boot when that one is off. +- Do not add site-specific code to the package: a site's own part is its own module class (`Contracts\Module`, extend + `Modules\BaseModule`, add it to `manager.available`). +- Behind a proxy set trusted proxies before switching `audit` on. diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php new file mode 100644 index 0000000..59914dd --- /dev/null +++ b/resources/boost/guidelines/core.blade.php @@ -0,0 +1,10 @@ +## iriks-it/laravel-manager + +A modular backend (users, media, pages, posts, reviews, audit, statistics, resources, revisions) installed as a package. + +- To integrate it, follow `vendor/iriks-it/laravel-manager/resources/ai/INTEGRATION.md` step by step. +- Set it up with `php artisan manager:install --modules=... --user-model=...`, then `config:clear`, `migrate`, `storage:link`; verify in a new process with `php artisan manager:doctor --json` (non-zero exit on failure, every problem has a `fix`). +- The screens come with the package (`MANAGER_UI`), including a login when the app has none; themes: `php artisan manager:make-theme`, `MANAGER_THEME`. +- The user model needs the `HasManagerAccess` trait; `is_super_admin` is never mass assignable. The first super admin comes from `php artisan manager:create-user`. +- The site's content is configuration: `manager.pages.definitions`, `manager.resources`, `manager.menu`, `manager.permissions`, `manager.login.checks`; code only as a JavaScript module in `manager.extensions`. Existing data comes in with `php artisan manager:import`. +- Switch parts with `MANAGER_=true|false`; never edit `vendor/`. Site-specific parts are your own `Module` class. diff --git a/resources/dist/manager.css b/resources/dist/manager.css new file mode 100644 index 0000000..2dbeb41 --- /dev/null +++ b/resources/dist/manager.css @@ -0,0 +1,3 @@ +/*! 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-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking: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}}}@layer theme{:root,:host{--font-sans:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-500:oklch(63.7% .237 25.331);--color-emerald-500:oklch(69.6% .17 162.48);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--container-sm:24rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-3xl:48rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--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;--leading-snug:1.375;--leading-relaxed:1.625;--radius-sm:.25rem;--radius-lg:.5rem;--radius-xl:.75rem;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif);--default-mono-font-family:var(--font-mono)}}@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}}@layer components{.m-card{background:var(--m-panel);border:1px solid var(--m-line);border-radius:var(--m-radius,.5rem)}.m-btn{border-radius:var(--m-radius,.5rem);cursor:pointer;border:1px solid #0000;align-items:center;gap:.4rem;padding:.5rem .9rem;font-size:.875rem;font-weight:600;transition:filter .15s;display:inline-flex}.m-btn:disabled{opacity:.5;cursor:not-allowed}.m-btn-primary{background:var(--m-brand);color:#fff}.m-btn-primary:hover:not(:disabled){filter:brightness(1.1)}.m-btn-secondary{background:var(--m-panel-2);border-color:var(--m-line);color:var(--m-text)}.m-btn-secondary:hover:not(:disabled){filter:brightness(1.15)}.m-btn-danger{color:#ef4444;background:0 0;border-color:#ef444466}.m-label{color:var(--m-muted);margin-bottom:.25rem;font-size:.8rem;font-weight:600;display:block}.m-input{border-radius:var(--m-radius,.5rem);border:1px solid var(--m-line);background:var(--m-ink);width:100%;color:var(--m-text);padding:.5rem .7rem;font-size:.9rem}.m-input:focus{outline:2px solid var(--m-brand);outline-offset:1px}.m-error{color:#ef4444;margin-top:.25rem;font-size:.8rem}.m-prose{overflow-wrap:anywhere;line-height:1.6}.m-prose>*+*{margin-top:.75rem}.m-prose h1,.m-prose h2,.m-prose h3{font-family:var(--m-font-display,inherit);font-weight:700;line-height:1.25}.m-prose h1{font-size:1.5rem}.m-prose h2{font-size:1.25rem}.m-prose h3{font-size:1.1rem}.m-prose ul{padding-left:1.25rem;list-style:outside}.m-prose ol{padding-left:1.25rem;list-style:decimal}.m-prose blockquote{border-left:3px solid var(--m-line);color:var(--m-muted);padding-left:.75rem}.m-prose a{text-decoration:underline}.m-prose img{border-radius:.5rem;max-width:100%;height:auto}.m-prose code{font-family:ui-monospace,monospace;font-size:.9em}.m-help{color:var(--m-muted);margin-top:.25rem;font-size:.75rem}.m-badge{background:var(--m-panel-2);border:1px solid var(--m-line);border-radius:999px;padding:.1rem .55rem;font-size:.7rem;font-weight:600;display:inline-block}}@layer utilities{.pointer-events-none{pointer-events:none}.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}.inset-0{inset:0}.inset-x-0{inset-inline:0}.inset-y-0{inset-block:0}.top-0{top:0}.top-3{top:calc(var(--spacing) * 3)}.right-3{right:calc(var(--spacing) * 3)}.right-5{right:calc(var(--spacing) * 5)}.bottom-4{bottom:calc(var(--spacing) * 4)}.bottom-5{bottom:calc(var(--spacing) * 5)}.left-0{left:0}.left-1\/2{left:50%}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.mx-auto{margin-inline:auto}.my-3{margin-block:calc(var(--spacing) * 3)}.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-10{margin-top:calc(var(--spacing) * 10)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.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-1{margin-left:calc(var(--spacing) * -1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1}.h-1\.5{height:calc(var(--spacing) * 1.5)}.h-2{height:calc(var(--spacing) * 2)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-14{height:calc(var(--spacing) * 14)}.h-16{height:calc(var(--spacing) * 16)}.h-24{height:calc(var(--spacing) * 24)}.h-40{height:calc(var(--spacing) * 40)}.h-full{height:100%}.max-h-\[85vh\]{max-height:85vh}.min-h-40{min-height:calc(var(--spacing) * 40)}.min-h-screen{min-height:100vh}.w-1\.5{width:calc(var(--spacing) * 1.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-8{width:calc(var(--spacing) * 8)}.w-9{width:calc(var(--spacing) * 9)}.w-16{width:calc(var(--spacing) * 16)}.w-32{width:calc(var(--spacing) * 32)}.w-60{width:calc(var(--spacing) * 60)}.w-\[min\(24rem\,calc\(100vw-2rem\)\)\]{width:min(24rem,100vw - 2rem)}.w-auto{width:auto}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-\[12rem\]{max-width:12rem}.max-w-md{max-width:var(--container-md)}.max-w-sm{max-width:var(--container-sm)}.max-w-xl{max-width:var(--container-xl)}.max-w-xs{max-width:var(--container-xs)}.min-w-0{min-width:0}.min-w-3{min-width:calc(var(--spacing) * 3)}.min-w-\[10rem\]{min-width:10rem}.min-w-px{min-width:1px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-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)}.-scale-x-100{--tw-scale-x:calc(100% * -1);scale:var(--tw-scale-x) var(--tw-scale-y)}.cursor-crosshair{cursor:crosshair}.cursor-pointer{cursor:pointer}.resize{resize:both}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.place-items-center{place-items:center}.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}.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-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-5{gap:calc(var(--spacing) * 5)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-px{gap:1px}: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-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(.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(--m-line)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.rounded-full{border-radius:2147483647px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-sm{border-radius:var(--radius-sm)}.rounded-xl{border-radius:var(--radius-xl)}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.border{border-style:var(--tw-border-style);border-width:1px}.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-l-4{border-left-style:var(--tw-border-style);border-left-width:4px}.border-brand{border-color:var(--m-brand)}.border-line{border-color:var(--m-line)}.border-white{border-color:var(--color-white)}.border-l-emerald-500{border-left-color:var(--color-emerald-500)}.border-l-red-500{border-left-color:var(--color-red-500)}.bg-black\/60{background-color:#0009}@supports (color:color-mix(in lab, red, red)){.bg-black\/60{background-color:color-mix(in oklab, var(--color-black) 60%, transparent)}}.bg-brand,.bg-brand\/15{background-color:var(--m-brand)}@supports (color:color-mix(in lab, red, red)){.bg-brand\/15{background-color:color-mix(in oklab, var(--m-brand) 15%, transparent)}}.bg-brand\/60{background-color:var(--m-brand)}@supports (color:color-mix(in lab, red, red)){.bg-brand\/60{background-color:color-mix(in oklab, var(--m-brand) 60%, transparent)}}.bg-line{background-color:var(--m-line)}.bg-panel{background-color:var(--m-panel)}.bg-panel-2{background-color:var(--m-panel-2)}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-1\.5{padding:calc(var(--spacing) * 1.5)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.p-6{padding:calc(var(--spacing) * 6)}.p-7{padding:calc(var(--spacing) * 7)}.\!px-2{padding-inline:calc(var(--spacing) * 2)!important}.\!px-3{padding-inline:calc(var(--spacing) * 3)!important}.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-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.\!py-1{padding-block:var(--spacing)!important}.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-3{padding-block:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-14{padding-top:calc(var(--spacing) * 14)}.pt-20{padding-top:calc(var(--spacing) * 20)}.pr-6{padding-right:calc(var(--spacing) * 6)}.pb-1{padding-bottom:var(--spacing)}.pb-16{padding-bottom:calc(var(--spacing) * 16)}.text-left{text-align:left}.font-display{font-family:var(--m-font-display,var(--m-font,ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif))}.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-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))}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-snug{--tw-leading:var(--leading-snug);line-height:var(--leading-snug)}.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-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-pre-wrap{white-space:pre-wrap}.text-brand{color:var(--m-brand)}.text-emerald-500{color:var(--color-emerald-500)}.text-muted{color:var(--m-muted)}.text-red-500{color:var(--color-red-500)}.text-text{color:var(--m-text)}.uppercase{text-transform:uppercase}.italic{font-style:italic}.underline{text-decoration-line:underline}.opacity-50{opacity:.5}.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-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{--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)}.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-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))}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){:is(:where(.group):hover .group-hover\:text-brand){color:var(--m-brand)}.hover\:border-brand:hover{border-color:var(--m-brand)}.hover\:bg-text\/5:hover{background-color:var(--m-text)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-text\/5:hover{background-color:color-mix(in oklab, var(--m-text) 5%, transparent)}}.hover\:bg-text\/10:hover{background-color:var(--m-text)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-text\/10:hover{background-color:color-mix(in oklab, var(--m-text) 10%, transparent)}}.hover\:text-text:hover{color:var(--m-text)}}@media (width>=40rem){.sm\:col-span-2{grid-column:span 2/span 2}.sm\:w-64{width:calc(var(--spacing) * 64)}.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-\[1fr_1fr_auto\]{grid-template-columns:1fr 1fr auto}.sm\:items-end{align-items:flex-end}}@media (width>=48rem){.md\:top-1\/2{top:50%}.md\:bottom-auto{bottom:auto}.md\:ml-60{margin-left:calc(var(--spacing) * 60)}.md\:flex{display:flex}.md\:hidden{display:none}.md\:translate-x-0{--tw-translate-x:0px;translate:var(--tw-translate-x) var(--tw-translate-y)}.md\:-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:px-8{padding-inline:calc(var(--spacing) * 8)}.md\:pt-0{padding-top:0}.md\:pt-8{padding-top:calc(var(--spacing) * 8)}}@media (width>=64rem){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}}}html,body{background:var(--m-ink);color:var(--m-text);font-family:var(--font-sans)}html.is-simple{font-size:112.5%}html.is-simple .m-btn{padding:.7rem 1.2rem;font-size:1rem}html.is-simple .m-input{padding:.7rem .9rem;font-size:1rem}html.is-simple .m-label{margin-bottom:.35rem;font-size:.95rem}html.is-simple .m-help{font-size:.85rem}html.is-simple main{line-height:1.6}.m-tile{flex-direction:column;gap:.5rem;padding:1.5rem;transition:border-color .15s,transform .15s;display:flex}.m-tile:hover{border-color:var(--m-brand);transform:translateY(-2px)}.m-spot{box-shadow:0 0 0 9999px #0009, 0 0 0 2px var(--m-brand)}@media (prefers-reduced-motion:no-preference){.m-bob{animation:2.6s ease-in-out infinite m-bob}@keyframes m-bob{0%,to{transform:translateY(0)}50%{transform:translateY(-4px)}}}.m-glow{background:radial-gradient(circle at 50% 55%, var(--m-brand), transparent 68%)}@supports (color:color-mix(in lab, red, red)){.m-glow{background:radial-gradient(circle at 50% 55%, color-mix(in srgb, var(--m-brand) 30%, transparent), transparent 68%)}}@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-space-y-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-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} +/*$vite$:1*/ \ No newline at end of file diff --git a/resources/dist/manager.js b/resources/dist/manager.js new file mode 100644 index 0000000..134cac1 --- /dev/null +++ b/resources/dist/manager.js @@ -0,0 +1,7 @@ +var e=Object.defineProperty,t=(t,n)=>{let r=Object.setPrototypeOf({},null);for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&1||e(r,Symbol.toStringTag,{value:`Module`}),n&2?r:Object.preventExtensions(r)};function n(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var r={},i=[],a=()=>{},o=()=>!1,s=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),c=e=>e.startsWith(`onUpdate:`),l=Object.assign,u=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},d=Object.prototype.hasOwnProperty,f=(e,t)=>d.call(e,t),p=Array.isArray,m=e=>C(e)===`[object Map]`,h=e=>C(e)===`[object Set]`,g=e=>C(e)===`[object Date]`,_=e=>C(e)===`[object RegExp]`,v=e=>typeof e==`function`,y=e=>typeof e==`string`,b=e=>typeof e==`symbol`,x=e=>typeof e==`object`&&!!e,S=e=>(x(e)||v(e))&&v(e.then)&&v(e.catch),ee=Object.prototype.toString,C=e=>ee.call(e),te=e=>C(e).slice(8,-1),w=e=>C(e)===`[object Object]`,T=e=>y(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,ne=n(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),re=1e4,ie=e=>{let t=Object.create(null),n=0;return(r=>{let i=t[r];return i===void 0?(++n>re&&(t=Object.create(null),n=1),t[r]=e(r)):i})},ae=/-\w/g,E=ie(e=>e.replace(ae,e=>e.slice(1).toUpperCase())),oe=/\B([A-Z])/g,se=ie(e=>e.replace(oe,`-$1`).toLowerCase()),ce=ie(e=>e.charAt(0).toUpperCase()+e.slice(1)),le=ie(e=>e?`on${ce(e)}`:``),D=(e,t)=>!Object.is(e,t),ue=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},fe=e=>{let t=parseFloat(e);return isNaN(t)?e:t},pe=e=>{let t=y(e)?Number(e):NaN;return isNaN(t)?e:t},me,he=()=>me||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{},ge=n(`Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol`);function _e(e){if(p(e)){let t={};for(let n=0;ne.startsWith(`/*`)?``:e).split(ve).forEach(e=>{if(e){let n=e.split(ye);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function O(e){let t=``;if(y(e))t=e;else if(p(e))for(let n=0;nAe(e,t))}function Me(e){return Object.getPrototypeOf(e)===null&&e[Symbol.toPrimitive]==null&&typeof e.toString!=`function`&&typeof e.valueOf!=`function`?C(e):String(e)}var Ne=e=>!!(e&&e.__v_isRef===!0),k=e=>y(e)?e:e==null?``:p(e)||x(e)&&(e.toString===ee||!v(e.toString))?Ne(e)?k(e.value):JSON.stringify(e,Pe,2):String(e),Pe=(e,t)=>Ne(t)?Pe(e,t.value):m(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[Fe(t,r)+` =>`]=n,e),{})}:h(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>Fe(e))}:b(t)?Fe(t):x(t)&&!p(t)&&!w(t)?String(t):t,Fe=(e,t=``)=>b(e)?`Symbol(${e.description??t})`:e;function Ie(e){return e==null?`initial`:typeof e==`string`?e===``?` `:e:String(e)}var Le,Re=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&Le&&(Le.active?(this.parent=Le,this.index=(Le.scopes||(Le.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes){let n=this.scopes.slice();for(e=0,t=n.length;e0&&--this._on===0){if(Le===this)Le=this.prevScope;else{let e=Le;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t0)return;if(Ke){let e=Ke;for(Ke=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;Ge;){let t=Ge;for(Ge=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function Xe(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Ze(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),et(r),tt(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function Qe(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&($e(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function $e(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===lt)||(e.globalVersion=lt,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Qe(e))))return;e.flags|=2;let t=e.dep,n=A,r=it;A=e,it=!0;try{Xe(e);let n=e.fn(e._value);(t.version===0||D(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{A=n,it=r,Ze(e),e.flags&=-3}}function et(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)et(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function tt(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}function nt(e,t){e.effect instanceof Ue&&(e=e.effect.fn);let n=new Ue(e);t&&l(n,t);try{n.run()}catch(e){throw n.stop(),e}let r=n.run.bind(n);return r.effect=n,r}function rt(e){e.effect.stop()}var it=!0,at=[];function ot(){at.push(it),it=!1}function st(){let e=at.pop();it=e===void 0||e}function ct(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=A;A=void 0;try{t()}finally{A=e}}}var lt=0,ut=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},dt=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!A||!it||A===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==A)t=this.activeLink=new ut(A,this),A.deps?(t.prevDep=A.depsTail,A.depsTail.nextDep=t,A.depsTail=t):A.deps=A.depsTail=t,ft(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=A.depsTail,t.nextDep=void 0,A.depsTail.nextDep=t,A.depsTail=t,A.deps===t&&(A.deps=e)}return t}trigger(e){this.version++,lt++,this.notify(e)}notify(e){Je();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{Ye()}}};function ft(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)ft(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var pt=new WeakMap,mt=Symbol(``),ht=Symbol(``),gt=Symbol(``);function _t(e,t,n){if(it&&A){let t=pt.get(e);t||pt.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new dt),r.map=t,r.key=n),r.track()}}function vt(e,t,n,r,i,a){let o=pt.get(e);if(!o){lt++;return}let s=e=>{e&&e.trigger()};if(Je(),t===`clear`)o.forEach(s);else{let i=p(e),a=i&&T(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===gt||!b(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(gt)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(mt)),m(e)&&s(o.get(ht)));break;case`delete`:i||(s(o.get(mt)),m(e)&&s(o.get(ht)));break;case`set`:m(e)&&s(o.get(mt))}}Ye()}function yt(e,t){let n=pt.get(e);return n&&n.get(t)}function bt(e){let t=j(e);return t===e||(_t(t,`iterate`,gt),dn(e))?t:un(e)?ln(e)?t.map(e=>hn(mn(e))):t.map(hn):t.map(mn)}function xt(e){return _t(e=j(e),`iterate`,gt),e}var St=e=>hn(mn(e));function Ct(e){return un(e)?ln(e)?St:hn:mn}var wt={__proto__:null,[Symbol.iterator](){return Tt(this,Symbol.iterator,Ct(this))},concat(...e){return bt(this).concat(...e.map(e=>p(e)?bt(e):e))},entries(){let e=Ct(this);return Tt(this,`entries`,t=>(t[1]=e(t[1]),t))},every(e,t){return Ot(this,`every`,e,t,void 0,arguments)},filter(e,t){return Ot(this,`filter`,e,t,e=>e.map(Ct(this)),arguments)},find(e,t){return Ot(this,`find`,e,t,e=>Ct(this)(e),arguments)},findIndex(e,t){return Ot(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return Ot(this,`findLast`,e,t,e=>Ct(this)(e),arguments)},findLastIndex(e,t){return Ot(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return Ot(this,`forEach`,e,t,void 0,arguments)},includes(...e){return At(this,`includes`,e)},indexOf(...e){return At(this,`indexOf`,e)},join(e){return bt(this).join(e)},lastIndexOf(...e){return At(this,`lastIndexOf`,e)},map(e,t){return Ot(this,`map`,e,t,void 0,arguments)},pop(){return jt(this,`pop`)},push(...e){return jt(this,`push`,e)},reduce(e,...t){return kt(this,`reduce`,e,t)},reduceRight(e,...t){return kt(this,`reduceRight`,e,t)},shift(){return jt(this,`shift`)},some(e,t){return Ot(this,`some`,e,t,void 0,arguments)},splice(...e){return jt(this,`splice`,e)},toReversed(){return bt(this).toReversed()},toSorted(e){return bt(this).toSorted(e)},toSpliced(...e){return bt(this).toSpliced(...e)},unshift(...e){return jt(this,`unshift`,e)},values(){return Tt(this,`values`,Ct(this))}};function Tt(e,t,n){let r=xt(e),i=r[t],a=i.call(r);if(r!==e&&!dn(e)){if(a[Symbol.toStringTag]===`Array Iterator`){let e=Object.create(Object.getPrototypeOf(a));return e.next=()=>Et(a.next(),n),i!==Dt[t]&&Object.defineProperties(e,{return:{get(){let e=a.return;return typeof e==`function`?e.bind(a):e}},throw:{get(){let e=a.throw;return typeof e==`function`?e.bind(a):e}}}),e}a._next=a.next,a.next=()=>Et(a._next(),n)}return a}function Et(e,t){return e.done||(e.value=t(e.value)),e}var Dt=Array.prototype;function Ot(e,t,n,r,i,a){let o=xt(e),s=o!==e&&!dn(e),c=o[t];if(c!==Dt[t]){let t=c.apply(e,a);return s?mn(t):t}let l=n;if(o!==e){if(s){let t=Ct(e);l=function(r,i){return n.call(this,t(r),i,e)}}else n.length>2&&(l=function(t,r){return n.call(this,t,r,e)})}let u=c.call(o,l,r);return s&&i?i(u):u}function kt(e,t,n,r){let i=xt(e),a=i!==e&&!dn(e),o=n,s=!1;if(i!==e){if(a){let t=Ct(e);s=r.length===0,o=function(r,i,a){return s&&(s=!1,r=t(r)),n.call(this,r,t(i),a,e)}}else n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)})}let c=i[t](o,...r);return s?Ct(e)(c):c}function At(e,t,n){let r=j(e);_t(r,`iterate`,gt);let i=r[t](...n);return(i===-1||i===!1)&&fn(n[0])?(n[0]=j(n[0]),r[t](...n)):i}function jt(e,t,n=[]){ot(),Je();let r=j(e)[t].apply(e,n);return Ye(),st(),r}var Mt=n(`__proto__,__v_isRef,__isVue`),Nt=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(b));function Pt(e){b(e)||(e=String(e));let t=j(this);return _t(t,`has`,e),t.hasOwnProperty(e)}var Ft=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?tn:en:i?$t:Qt).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=p(e);if(!r){let e;if(a&&(e=wt[t]))return e;if(t===`hasOwnProperty`)return Pt}let o=Reflect.get(e,t,M(e)?e:n);if((b(t)?Nt.has(t):Mt(t))||(r||_t(e,`get`,t),i))return o;if(M(o)){let e=a&&T(t)?o:o.value;return r&&x(e)?on(e):e}return x(o)?r?on(o):rn(o):o}},It=class extends Ft{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=p(e)&&T(t);if(!this._isShallow){let e=un(i);if(!dn(n)&&!un(n)&&(i=j(i),n=j(n)),!a&&M(i)&&!M(n))return e||(i.value=n),!0}let o=a?Number(t)e,Ut=e=>Reflect.getPrototypeOf(e);function Wt(e,t,n){return function(...r){let i=this.__v_raw,a=j(i),o=m(a),s=e===`entries`||e===Symbol.iterator&&o,c=e===`keys`&&o,u=i[e](...r),d=n?Ht:t?hn:mn;return!t&&_t(a,`iterate`,c?ht:mt),l(Object.create(u),{next(){let{value:e,done:t}=u.next();return t?{value:e,done:t}:{value:s?[d(e[0]),d(e[1])]:d(e),done:t}}})}}function Gt(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function Kt(e,t){let n={get(n){let r=this.__v_raw,i=j(r),a=j(n);e||(D(n,a)&&_t(i,`get`,n),_t(i,`get`,a));let{has:o}=Ut(i),s=t?Ht:e?hn:mn;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&_t(j(t),`iterate`,mt),t.size},has(t){let n=this.__v_raw,r=j(n),i=j(t);return e||(D(t,i)&&_t(r,`has`,t),_t(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=j(a),s=t?Ht:e?hn:mn;return!e&&_t(o,`iterate`,mt),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return l(n,e?{add:Gt(`add`),set:Gt(`set`),delete:Gt(`delete`),clear:Gt(`clear`)}:{add(e){let n=j(this),r=Ut(n),i=j(e),a=!t&&!dn(e)&&!un(e)?i:e;return r.has.call(n,a)||D(e,a)&&r.has.call(n,e)||D(i,a)&&r.has.call(n,i)||(n.add(a),vt(n,`add`,a,a)),this},set(e,n){t||dn(n)||un(n)||(n=j(n));let r=j(this),{has:i,get:a}=Ut(r),o=i.call(r,e);o||=(e=j(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?D(n,s)&&vt(r,`set`,e,n,s):vt(r,`add`,e,n),this},delete(e){let t=j(this),{has:n,get:r}=Ut(t),i=n.call(t,e);i||=(e=j(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&vt(t,`delete`,e,void 0,a),o},clear(){let e=j(this),t=e.size!==0,n=e.clear();return t&&vt(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=Wt(r,e,t)}),n}function qt(e,t){let n=Kt(e,t);return(r,i,a)=>i===`__v_isReactive`?!e:i===`__v_isReadonly`?e:i===`__v_isShallow`?t:i===`__v_raw`?r:Reflect.get(f(n,i)&&i in r?n:r,i,a)}var Jt={get:qt(!1,!1)},Yt={get:qt(!1,!0)},Xt={get:qt(!0,!1)},Zt={get:qt(!0,!0)},Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,tn=new WeakMap;function nn(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function rn(e){return un(e)?e:cn(e,!1,Rt,Jt,Qt)}function an(e){return cn(e,!1,Bt,Yt,$t)}function on(e){return cn(e,!0,zt,Xt,en)}function sn(e){return cn(e,!0,Vt,Zt,tn)}function cn(e,t,n,r,i){if(!x(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=nn(te(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function ln(e){return un(e)?ln(e.__v_raw):!!(e&&e.__v_isReactive)}function un(e){return!!(e&&e.__v_isReadonly)}function dn(e){return!!(e&&e.__v_isShallow)}function fn(e){return e?!!e.__v_raw:!1}function j(e){let t=e&&e.__v_raw;return t?j(t):e}function pn(e){return!f(e,`__v_skip`)&&Object.isExtensible(e)&&de(e,`__v_skip`,!0),e}var mn=e=>x(e)?rn(e):e,hn=e=>x(e)?on(e):e;function M(e){return e?e.__v_isRef===!0:!1}function N(e){return _n(e,!1)}function gn(e){return _n(e,!0)}function _n(e,t){return M(e)?e:new vn(e,t)}var vn=class{constructor(e,t){this.dep=new dt,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:j(e),this._value=t?e:mn(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||dn(e)||un(e);e=n?e:j(e),D(e,t)&&(this._rawValue=e,this._value=n?e:mn(e),this.dep.trigger())}};function yn(e){e.dep&&e.dep.trigger()}function P(e){return M(e)?e.value:e}function bn(e){return v(e)?e():P(e)}var xn={get:(e,t,n)=>t===`__v_raw`?e:P(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return M(i)&&!M(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function Sn(e){return ln(e)?e:new Proxy(e,xn)}var Cn=class{constructor(e){this.__v_isRef=!0,this._value=void 0;let t=this.dep=new dt,{get:n,set:r}=e(t.track.bind(t),t.trigger.bind(t));this._get=n,this._set=r}get value(){return this._value=this._get()}set value(e){this._set(e)}};function wn(e){return new Cn(e)}function Tn(e){let t=p(e)?Array(e.length):{};for(let n in e)t[n]=kn(e,n);return t}var En=class{constructor(e,t,n){this._object=e,this._defaultValue=n,this.__v_isRef=!0,this._value=void 0,this._key=b(t)?t:String(t),this._raw=j(e);let r=!0,i=e;if(!p(e)||b(this._key)||!T(this._key))do r=!fn(i)||dn(i);while(r&&(i=i.__v_raw));this._shallow=r}get value(){let e=this._object[this._key];return this._shallow&&(e=P(e)),this._value=e===void 0?this._defaultValue:e}set value(e){if(this._shallow&&M(this._raw[this._key])){let t=this._object[this._key];if(M(t)){t.value=e;return}}this._object[this._key]=e}get dep(){return yt(this._raw,this._key)}},Dn=class{constructor(e){this._getter=e,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}};function On(e,t,n){return M(e)?e:v(e)?new Dn(e):x(e)&&arguments.length>1?kn(e,t,n):N(e)}function kn(e,t,n){return new En(e,t,n)}var An=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new dt(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=lt-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&A!==this)return qe(this,!0),!0}get value(){let e=this.dep.track();return $e(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function jn(e,t,n=!1){let r,i;return v(e)?r=e:(r=e.get,i=e.set),new An(r,i,n)}var Mn={GET:`get`,HAS:`has`,ITERATE:`iterate`},Nn={SET:`set`,ADD:`add`,DELETE:`delete`,CLEAR:`clear`},Pn={},Fn=new WeakMap,In=void 0;function Ln(){return In}function Rn(e,t=!1,n=In){if(n){let t=Fn.get(n);t||Fn.set(n,t=[]),t.push(e)}}function zn(e,t,n=r){let{immediate:i,deep:o,once:s,scheduler:c,augmentJob:l,call:d,onStop:f}=n,m=e=>o?e:dn(e)||o===!1||o===0?Bn(e,1):Bn(e),h,g,_,y,b=!1,x=!1;if(M(e)?(g=()=>e.value,b=dn(e)):ln(e)?(g=()=>m(e),b=!0):p(e)?(x=!0,b=e.some(e=>ln(e)||dn(e)),g=()=>e.map(e=>{if(M(e))return e.value;if(ln(e))return m(e);if(v(e))return d?d(e,2):e()})):g=v(e)?t?d?()=>d(e,2):e:()=>{if(_){ot();try{_()}finally{st()}}let t=In;In=h;try{return d?d(e,3,[y]):e(y)}finally{In=t}}:a,t&&o){let e=g,t=o===!0?1/0:o;g=()=>Bn(e(),x?t+1:t)}let S=Be(),ee=()=>{h.stop(),S&&S.active&&u(S.effects,h)},C=!1;if(s&&t){let e=t;t=(...t)=>{C=!0;try{return e(...t)}finally{ee()}}}let te=x?Array(e.length).fill(Pn):Pn,w=e=>{if(!C&&h.flags&1&&(h.dirty||e)){if(t){let n=h.run();if(e||o||b||(x?n.some((e,t)=>D(e,te[t])):D(n,te))){let e=In;ot();try{_&&_(),In=h;let e=[n,te===Pn?void 0:x&&te[0]===Pn?[]:te,y];te=n,d?d(t,3,e):t(...e)}finally{In=e,st()}}}else h.run()}};return l&&l(w),h=new Ue(g),h.scheduler=c?()=>c(w,!1):w,y=e=>Rn(e,!1,h),_=h.onStop=()=>{let e=Fn.get(h);if(e){if(d)d(e,4);else for(let t of e)t();Fn.delete(h)}},f&&(h.onStop=()=>{_(),f()}),t?i?w(!0):te=h.run():c?c(w.bind(null,!0),!0):h.run(),ee.pause=h.pause.bind(h),ee.resume=h.resume.bind(h),ee.stop=ee,ee}function Bn(e,t=1/0,n){if(t<=0||!x(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,M(e))Bn(e.value,t,n);else if(p(e)){if(ln(e)&&!un(e)&&!dn(e)){let r=j(e);_t(r,`iterate`,gt);for(let e=0;e{Bn(e,t,n)});else if(w(e)){for(let r in e)Bn(e[r],t,n);let r=j(e);for(let i of Object.getOwnPropertySymbols(r))Object.prototype.propertyIsEnumerable.call(r,i)&&Bn(e[i],t,n)}return e}var Vn=[];function Hn(e){Vn.push(e)}function Un(){Vn.pop()}function Wn(e,t){}var Gn={SETUP_FUNCTION:0,0:`SETUP_FUNCTION`,RENDER_FUNCTION:1,1:`RENDER_FUNCTION`,NATIVE_EVENT_HANDLER:5,5:`NATIVE_EVENT_HANDLER`,COMPONENT_EVENT_HANDLER:6,6:`COMPONENT_EVENT_HANDLER`,VNODE_HOOK:7,7:`VNODE_HOOK`,DIRECTIVE_HOOK:8,8:`DIRECTIVE_HOOK`,TRANSITION_HOOK:9,9:`TRANSITION_HOOK`,APP_ERROR_HANDLER:10,10:`APP_ERROR_HANDLER`,APP_WARN_HANDLER:11,11:`APP_WARN_HANDLER`,FUNCTION_REF:12,12:`FUNCTION_REF`,ASYNC_COMPONENT_LOADER:13,13:`ASYNC_COMPONENT_LOADER`,SCHEDULER:14,14:`SCHEDULER`,COMPONENT_UPDATE:15,15:`COMPONENT_UPDATE`,APP_UNMOUNT_CLEANUP:16,16:`APP_UNMOUNT_CLEANUP`},Kn={sp:`serverPrefetch hook`,bc:`beforeCreate hook`,c:`created hook`,bm:`beforeMount hook`,m:`mounted hook`,bu:`beforeUpdate hook`,u:`updated`,bum:`beforeUnmount hook`,um:`unmounted hook`,a:`activated hook`,da:`deactivated hook`,ec:`errorCaptured hook`,rtc:`renderTracked hook`,rtg:`renderTriggered hook`,0:`setup function`,1:`render function`,2:`watcher getter`,3:`watcher callback`,4:`watcher cleanup function`,5:`native event handler`,6:`component event handler`,7:`vnode hook`,8:`directive hook`,9:`transition hook`,10:`app errorHandler`,11:`app warnHandler`,12:`ref function`,13:`async component loader`,14:`scheduler flush`,15:`component update`,16:`app unmount cleanup function`};function qn(e,t,n,r){try{return r?e(...r):e()}catch(e){Yn(e,t,n)}}function Jn(e,t,n,r){if(v(e)){let i=qn(e,t,n,r);return i&&S(i)&&i.catch(e=>{Yn(e,t,n,void 0,!0)}),i}if(p(e)){let i=[];for(let a=0;a>>1,i=Zn[r],a=pr(i);a=pr(n)?Zn.push(e):Zn.splice(ar(t),0,e),e.flags|=1,sr()}}function sr(){rr||=nr.then(mr)}function cr(e){if(!p(e))er&&e.id===-1?er.splice(tr+1,0,e):e.flags&1||($n.push(e),e.flags|=1);else for(let t=0;t=t))continue;Zn.splice(r,1),r=e?r-1:Qn,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function ur(e,t,n=0){if($n.length){let e=$n,r=0;if(t){e=[];for(let i=0;i<$n.length;i++){let a=$n[i];(a.i===void 0?t.has(a):!a.i||a.i.uidpr(e)-pr(t));if($n.length=r,er){for(let e=0;ee.id==null?e.flags&2?-1:1/0:e.id;function mr(e){try{for(Qn=0;Qnhr.emit(e,...t)),gr=[]):typeof window<`u`&&window.HTMLElement&&!(window.navigator?.userAgent)?.includes(`jsdom`)?((t.__VUE_DEVTOOLS_HOOK_REPLAY__=t.__VUE_DEVTOOLS_HOOK_REPLAY__||[]).push(e=>{_r(e,t)}),setTimeout(()=>{hr||(t.__VUE_DEVTOOLS_HOOK_REPLAY__=null,gr=[])},3e3)):gr=[]}var vr=null,yr=null;function br(e){let t=vr;return vr=e,yr=e&&e.type.__scopeId||null,t}function xr(e){yr=e}function Sr(){yr=null}var Cr=e=>F;function F(e,t=vr,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&Cs(-1);let i=br(t),a=ys.length,o;try{o=e(...n)}finally{for(let e=ys.length;e>a;e--)xs();br(i),r._d&&Cs(1)}return o};return r._n=!0,r._c=!0,r._d=!0,r}function I(e,t){if(vr===null)return e;let n=cc(vr),i=e.dirs||=[];for(let e=0;e1)return n&&v(t)?t.call(r&&r.proxy):t}}function Dr(){return!!(Ws()||lo)}var Or=Symbol.for(`v-scx`),kr=()=>Er(Or);function Ar(e,t){return Pr(e,null,t)}function jr(e,t){return Pr(e,null,{flush:`post`})}function Mr(e,t){return Pr(e,null,{flush:`sync`})}function Nr(e,t,n){return Pr(e,t,n)}function Pr(e,t,n=r){let{immediate:i,deep:o,flush:s,once:c}=n,u=l({},n),d=t&&i||!t&&s!==`post`,f;if(Xs){if(s===`sync`){let e=kr();f=e.__watcherHandles||=[]}else if(!d){let e=()=>{};return e.stop=a,e.resume=a,e.pause=a,e}}let p=Us,m;if(p&&Be()!==p.scope){if(p.scope.active){let e=p.scope.run(()=>new Re);e.run(()=>Ve(()=>Promise.resolve().then(()=>{p=null,m&&(m.i=null)}))),u.onStop=()=>e.stop()}else p=null}u.call=(e,t,n)=>Jn(e,p,t,n);let h=!1;s===`post`?u.scheduler=e=>{e.i=p,z(e,p&&p.suspense)}:s!==`sync`&&(h=!0,u.scheduler=(e,t)=>{t?e():or(e)}),u.augmentJob=e=>{m=e,t&&(e.flags|=4),h&&(e.flags|=2,p&&(e.id=p.uid,e.i=p))};let g=zn(e,t,u);return Xs&&(f?f.push(g):d&&g()),g}function Fr(e,t,n){let r=this.proxy,i=y(e)?e.includes(`.`)?Ir(r,e):()=>r[e]:e.bind(r,r),a;v(t)?a=t:(a=t.handler,n=t);let o=qs(this),s=Pr(i,a.bind(r),n);return o(),s}function Ir(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;ee.__isTeleport,Br=e=>e&&(e.disabled||e.disabled===``),Vr=e=>e&&(e.defer||e.defer===``),Hr=e=>typeof SVGElement<`u`&&e instanceof SVGElement,Ur=e=>typeof MathMLElement==`function`&&e instanceof MathMLElement,Wr=(e,t)=>{let n=e&&e.to;return y(n)?t?t(n):null:n},Gr={name:`Teleport`,__isTeleport:!0,process(e,t,n,r,i,a,o,s,c,l){let{mc:u,pc:d,pbc:f,o:{insert:p,querySelector:m,createText:h,createComment:g,parentNode:_}}=l,v=Br(t.props),{dynamicChildren:y}=t,b=(e,t,n)=>{e.shapeFlag&16&&u(e.children,t,n,i,a,o,s,c)},x=(e=t)=>{let n=Br(e.props),r=e.target=Wr(e.props,m),a=Xr(r,e,h,p);r&&(o!==`svg`&&Hr(r)?o=`svg`:o!==`mathml`&&Ur(r)&&(o=`mathml`),i&&i.isCE&&(i.ce._teleportTargets||(i.ce._teleportTargets=new Set)).add(r),n||(b(e,r,a),Yr(e,!1)))},S=e=>{let t=()=>{if(Lr.get(e)===t){if(Lr.delete(e),Br(e.props)){let t=_(e.el)||n;b(e,t,e.anchor),Yr(e,!0)}x(e)}};Lr.set(e,t),z(t,a)};if(e==null){let e=t.el=h(``),i=t.anchor=h(``);if(p(e,n,r),p(i,n,r),Vr(t.props)||a&&a.pendingBranch){S(t);return}v&&(b(t,n,i),Yr(t,!0)),x()}else{t.el=e.el;let r=t.anchor=e.anchor,u=Lr.get(e);if(u){u.flags|=8,Lr.delete(e),S(t);return}t.targetStart=e.targetStart;let p=t.target=e.target,h=t.targetAnchor=e.targetAnchor,g=Br(e.props),_=g?n:p,b=g?r:h;if(o===`svg`||Hr(p)?o=`svg`:(o===`mathml`||Ur(p))&&(o=`mathml`),y?(f(e.dynamicChildren,y,_,i,a,o,s),Yo(e,t,!0)):c||d(e,t,_,b,i,a,o,s,!1),v)g?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):Kr(t,n,r,l,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){let e=Wr(t.props,m);e&&(t.target=e,Kr(t,e,null,l,0))}else g&&Kr(t,p,h,l,1);Yr(t,v)}},remove(e,t,n,{um:r,o:{remove:i}},a){let{shapeFlag:o,children:s,anchor:c,targetStart:l,targetAnchor:u,target:d,props:f}=e,p=Br(f),m=a||!p,h=Lr.get(e);if(h&&(h.flags|=8,Lr.delete(e)),d&&(i(l),i(u)),a&&i(c),!h&&(p||d)&&o&16)for(let e=0;e{e.isMounted=!0}),sa(()=>{e.isUnmounting=!0}),e}var ei=[Function,Array],ti={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:ei,onEnter:ei,onAfterEnter:ei,onEnterCancelled:ei,onBeforeLeave:ei,onLeave:ei,onAfterLeave:ei,onLeaveCancelled:ei,onBeforeAppear:ei,onAppear:ei,onAfterAppear:ei,onAppearCancelled:ei},ni={name:`BaseTransition`,props:ti,setup(e,{slots:t}){let n=Ws(),r=$r();return()=>{let i=t.default&&ui(t.default(),!0),a=i&&i.length?ri(i):n.subTree?J():void 0;if(!a)return;let o=j(e),{mode:s}=o;if(r.isLeaving)return si(a);let c=ci(a);if(!c)return si(a);let l=oi(c,o,r,n);c.type!==V&&li(c,l);let u=n.subTree&&ci(n.subTree);if(u&&u.type!==V&&!Es(u,c)&&di(n.subTree)){let e=oi(u,o,r,n);if(li(u,e),s===`out-in`&&c.type!==V)return r.isLeaving=!0,e.afterLeave=()=>{if(r.isLeaving=!1,!(n.job.flags&8)){if(n.effect.flags&2){let e=()=>{n.job.flags&8||n.update()};e.i=n,or(e)}else n.update()}delete e.afterLeave,u=void 0},si(a);s===`in-out`&&c.type!==V?e.delayLeave=(t,n,i)=>{let a=ai(r,u);a[String(u.key)]=u,t[Zr]=()=>{n(),t[Zr]=void 0,delete l.delayedLeave,delete e.delayLeave,u=void 0},l.delayedLeave=()=>{i(),delete l.delayedLeave,delete e.delayLeave,u=void 0}}:u=void 0}else u&&=void 0;return a}}};function ri(e){let t=e[0];if(e.length>1){for(let n of e)if(n.type!==V){t=n;break}}return t}var ii=ni;function ai(e,t){let{leavingVNodes:n}=e,r=n.get(t.type);return r||(r=Object.create(null),n.set(t.type,r)),r}function oi(e,t,n,r){let{appear:i,mode:a,persisted:o=!1,onBeforeEnter:s,onEnter:c,onAfterEnter:l,onEnterCancelled:u,onBeforeLeave:d,onLeave:f,onAfterLeave:m,onLeaveCancelled:h,onBeforeAppear:g,onAppear:_,onAfterAppear:v,onAppearCancelled:y}=t,b=String(e.key),x=ai(n,e),S=(e,t)=>{e&&Jn(e,r,9,t)},ee=(e,t)=>{let n=t[1];S(e,t),p(e)?e.every(e=>e.length<=1)&&n():e.length<=1&&n()},C={mode:a,persisted:o,beforeEnter(t){let r=s;if(!n.isMounted){if(i)r=g||s;else return}t[Zr]&&t[Zr](!0);let a=x[b];if(a&&Es(e,a)){let e=a.el[Zr];if(!e){let t=di(a);e=t&&t.el[Zr]}e&&e()}S(r,[t])},enter(e){if(e[Zr]){C.delayedLeave&&C.delayedLeave();return}let t=c,r=l,a=u;if(!n.isMounted){if(i)t=_||c,r=v||l,a=y||u;else return}let o=!1;e[Qr]=t=>{o||(o=!0,S(t?a:r,[e]),C.delayedLeave&&C.delayedLeave(),e[Qr]=void 0)};let s=e[Qr].bind(null,!1);t?ee(t,[e,s]):s()},leave(t,r){let i=String(e.key);if(t[Qr]&&t[Qr](!0),n.isUnmounting)return r();S(d,[t]);let a=!1;t[Zr]=n=>{a||(a=!0,r(),S(n?h:m,[t]),t[Zr]=void 0,x[i]===e&&delete x[i])};let o=t[Zr].bind(null,!1);x[i]=e,f?ee(f,[t,o]):o()},clone(e){let i=oi(e,t,n,r);return i.afterLeave=()=>{C.afterLeave&&C.afterLeave()},i.delayLeave=(e,t,n)=>{C.delayLeave?C.delayLeave(e,t,n):n()},i.delayedLeave=()=>{C.delayedLeave&&C.delayedLeave()},i}};return C}function si(e){if(Ki(e))return e=Ms(e),e.children=null,e}function ci(e){if(!Ki(e))return zr(e.type)&&e.children?ri(e.children):e;if(e.component)return e.component.subTree;let{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&v(n.default))return n.default()}}function li(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;let n=e.component.subTree;li(zr(n.type)&&ci(n)||n,t)}else if(e.shapeFlag&128){let n=e.suspense;if(n){let e=n.isHydrating?n.pendingBranch:n.activeBranch;e&&li(e,t.clone(e))}else e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)}else if(e.transition=t,e.type===B&&p(e.children)){let n=vo(e.children,!1);n&&li(n,t)}}function ui(e,t=!1,n){let r=[],i=0;for(let a=0;a1)for(let e=0;en.value,set:e=>n.value=e})}return n}function hi(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var gi=new WeakMap;function _i(e,t,n,i,a=!1){if(p(e)){e.forEach((e,r)=>_i(e,t&&(p(t)?t[r]:t),n,i,a));return}if(Ui(i)&&!a){i.shapeFlag&512&&i.type.__asyncResolved&&i.component.subTree.component&&_i(e,t,n,i.component.subTree);return}let s=i.shapeFlag&4?cc(i.component):i.el,c=a?null:s,{i:l,r:d}=e,m=t&&t.r,h=l.refs===r?l.refs={}:l.refs,g=l.setupState,_=j(g),b=g===r?o:e=>!hi(h,e)&&f(_,e),x=(e,t)=>!(t&&hi(h,t));if(m!=null&&m!==d){if(vi(t),y(m))h[m]=null,b(m)&&(g[m]=null);else if(M(m)){let e=t;x(m,e.k)&&(m.value=null),e.k&&(h[e.k]=null)}}if(v(d))qn(d,l,12,[c,h]);else{let t=y(d),r=M(d);if(t||r){let i=()=>{if(e.f){let n=t?b(d)?g[d]:h[d]:x(d)||!e.k?d.value:h[e.k];if(a)p(n)&&u(n,s);else if(p(n))n.includes(s)||n.push(s);else if(t)h[d]=[s],b(d)&&(g[d]=h[d]);else{let t=[s];x(d,e.k)&&(d.value=t),e.k&&(h[e.k]=t)}}else t?(h[d]=c,b(d)&&(g[d]=c)):r&&(x(d,e.k)&&(d.value=c),e.k&&(h[e.k]=c))};if(c){let t=()=>{i(),gi.delete(e)};t.id=-1,gi.set(e,t),z(t,n)}else vi(e),i()}}}function vi(e){let t=gi.get(e);t&&(t.flags|=8,gi.delete(e))}var yi=!1,bi=()=>{yi||=(console.error(`Hydration completed but contains mismatches.`),!0)},xi=e=>e.namespaceURI.includes(`svg`)&&e.tagName!==`foreignObject`,Si=e=>e.namespaceURI.includes(`MathML`),Ci=e=>{if(e.nodeType===1){if(xi(e))return`svg`;if(Si(e))return`mathml`}},wi=e=>e.nodeType===8;function Ti(e){let{mt:t,p:n,o:{patchProp:r,createText:i,nextSibling:a,parentNode:o,remove:c,insert:l,createComment:u}}=e,d=(e,t)=>{t.hasChildNodes()?(f(t.firstChild,e,null,null,null),ur(),t._vnode=e):(n(null,e,t),ur(),t._vnode=e)},f=(n,r,s,c,u,d=!1)=>{d||=!!r.dynamicChildren;let b=wi(n)&&n.data===`[`,x=()=>g(n,r,s,c,u,b),{type:S,ref:ee,shapeFlag:C,patchFlag:te}=r,w=n.nodeType;r.el=n,te===-2&&(d=!1,r.dynamicChildren=null);let T=null;switch(S){case _s:w===3?(n.data!==r.children&&(bi(),n.data=r.children),T=a(n)):r.children===``?(l(r.el=i(``),o(n),n),T=n):T=x();break;case V:y(n)?(T=a(n),v(r.el=n.content.firstChild,n,s)):T=w!==8||b?x():a(n);break;case vs:if(b&&(n=a(n),w=n.nodeType),w===1||w===3){T=n;let e=!r.children.length;for(let t=0;t{o||=!!t.dynamicChildren;let{type:l,dynamicProps:u,props:d,patchFlag:f,shapeFlag:p,dirs:h,transition:g}=t,_=l===`input`||l===`option`,b=!!u;if(_||b||f!==-1||g&&l!==`template`&&y(e)){h&&wr(t,null,n,`created`);let l=!1;if(y(e)){l=Jo(null,g)&&n&&n.vnode.props&&n.vnode.props.appear;let r=e.content.firstChild;if(l){let e=r.getAttribute(`class`);e&&(r.$cls=e),g.beforeEnter(r)}v(r,e,n),t.el=e=r}if(p&16&&!(d&&(d.innerHTML||d.textContent))){let r=m(e.firstChild,t,e,n,i,a,o);for(r&&!Ai(e,1)&&bi();r;){let e=r;r=r.nextSibling,c(e)}}else if(p&8){let n=t.children;n[0]===` +`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,` +`)&&(Ai(e,0)||bi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||s(a)&&!ne(a)||a[0]===`.`||t&&!ne(a)||u&&u.includes(a)){if(Di(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&ln(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Rs(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ms(()=>{x&&Rs(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u,d)=>{u||=!!t.dynamicChildren;let p=t.children,m=p.length,h=t.type===B,g=!1;for(let t=0;t{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&wi(f)&&f.data===`]`?a(t.anchor=f):(bi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,s,l)=>{if(Mi(e,t)||bi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)c(n);else break}}let u=a(e),d=o(e);return c(e),n(null,t,d,u,r,i,Ci(d),s),r&&r.vnode.el===e&&(r.vnode.el=t.el,wo(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&wi(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ei=new Set([`src`,`srcset`,`href`,`poster`]);function Di(e,t,n){return Ei.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Oi=`data-allow-mismatch`,ki={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function Ai(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Oi);)e=e.parentElement;return ji(e&&e.getAttribute(Oi),t)}function ji(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(ki[t])}}function Mi(e,t){return Ai(e.parentElement,1)||Ni(e)||Pi(t)}function Ni(e){return e.nodeType===1&&ji(e.getAttribute(Oi),1)}function Pi({props:e}){let t=e&&e[Oi];return typeof t==`string`&&ji(t,1)}var Fi=he().requestIdleCallback||(e=>setTimeout(e,1)),Ii=he().cancelIdleCallback||(e=>clearTimeout(e)),Li=(e=1e4)=>t=>{let n=Fi(t,{timeout:e});return()=>Ii(n)};function Ri(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t0&&r0&&n0&&i(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e),i=e=>{if(Ri(e))return t(),r.disconnect(),!1;if(getComputedStyle(e).display===`contents`){for(let t=0;t{if(e instanceof Element)return i(e)}),()=>r.disconnect()},Bi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Vi=(e=[])=>(t,n)=>{y(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Hi(e,t){if(wi(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(wi(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Ui=e=>!!e.type.__asyncLoader;function Wi(e){v(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return L({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Hi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Us;if(pi(e),u)return()=>Gi(u,e);let t=t=>{l=null,Yn(t,e,13,!r,!0)};if(s&&e.suspense||Xs)return p().then(t=>()=>Gi(t,e)).catch(e=>(t(e),()=>r?K(r,{error:e}):null));let a=N(!1),c=N(),d=N(!!i),f,m;return Ve(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Ki(e.parent.vnode)&&e.parent.update())}).catch(n=>{e.isUnmounted?l=null:(t(n),c.value=n)}),()=>{if(a.value&&u)return Gi(u,e);if(c.value&&r)return K(r,{error:c.value});if(n&&!d.value)return Gi(n,e)}}})}function Gi(e,t){let{ref:n,props:r,children:i,ce:a}=t.vnode,o=K(e,r,i);return o.ref=n,o.ce=a,delete t.vnode.ce,o}var Ki=e=>e.type.__isKeepAlive,qi={name:`KeepAlive`,__isKeepAlive:!0,props:{include:[String,RegExp,Array],exclude:[String,RegExp,Array],max:[String,Number]},setup(e,{slots:t}){let n=Ws(),r=n.ctx;if(!r.renderer)return()=>{let e=t.default&&t.default();return e&&e.length===1?e[0]:e};let i=new Map,a=new Set,o=null,s=n.suspense,{renderer:{p:c,m:l,um:u,o:{createElement:d}}}=r,f=d(`div`);r.activate=(e,t,n,r,i)=>{let a=e.component;l(e,t,n,0,s),c(a.vnode,e,t,n,a,s,r,e.slotScopeIds,i),z(()=>{a.isDeactivated=!1,a.a&&ue(a.a);let t=e.props&&e.props.onVnodeMounted;t&&Rs(t,a.parent,e)},s)},r.deactivate=e=>{let t=i.get(e.key==null?e.type:e.key);if(!t||t.component!==e.component)return!1;let n=e.component;return Qo(n.m),Qo(n.a),l(e,f,null,1,s),z(()=>{n.da&&ue(n.da);let t=e.props&&e.props.onVnodeUnmounted;t&&Rs(t,n.parent,e),n.isDeactivated=!0},s),!0};function p(e){$i(e),u(e,n,s,!0)}function m(e){i.forEach((t,n)=>{let r=lc(Ui(t)?t.type.__asyncResolved||{}:t.type);r&&!e(r)&&h(n)})}function h(e){let t=i.get(e);t&&(!o||!Es(t,o))?p(t):o&&(o.key==null?o.type:o.key)===e&&($i(o),t&&$i(t)),i.delete(e),a.delete(e)}Nr(()=>[e.include,e.exclude],([e,t])=>{e&&m(t=>Ji(e,t)),t&&m(e=>!Ji(t,e))},{flush:`post`,deep:!0});let g=null,_=()=>{if(g!=null){if(es(n.subTree.type)){let e=()=>{let e=ea(n.subTree);e.component&&i.set(g,e)};n.subTree.suspense.pendingBranch?z(e,n.subTree.suspense):e()}else i.set(g,ea(n.subTree))}};return ia(_),oa(_),sa(()=>{i.forEach(e=>{let{subTree:t,suspense:r}=n,i=ea(t);if(e.type===i.type&&e.key===i.key){$i(i);let e=i.component.da;e&&z(e,r)}else p(e)})}),()=>{if(g=null,!t.default)return o=null;let n=t.default(),r=n[0];if(n.length>1)return o=null,n;if(!Ts(r)||!(r.shapeFlag&4)&&!(r.shapeFlag&128))return o=null,r;let s=ea(r);if(s.type===V)return o=null,s;let c=s.type,l=lc(Ui(s)?s.type.__asyncResolved||{}:c),{include:u,exclude:d,max:f}=e;if(u&&(!l||!Ji(u,l))||d&&l&&Ji(d,l))return s.shapeFlag&=-257,o=s,r;let p=s.key==null?c:s.key,m=i.get(p);return s.el&&(s=Ms(s),r.shapeFlag&128&&(r.ssContent=s)),g=p,m?(s.el=m.el,s.component=m.component,s.transition&&li(s,s.transition),s.shapeFlag|=512,a.delete(p),a.add(p)):(a.add(p),f&&a.size>parseInt(f,10)&&h(a.values().next().value)),s.shapeFlag|=256,o=s,es(r.type)?r:s}}};function Ji(e,t){return p(e)?e.some(e=>Ji(e,t)):y(e)?e.split(`,`).includes(t):_(e)?(e.lastIndex=0,e.test(t)):!1}function Yi(e,t){Zi(e,`a`,t)}function Xi(e,t){Zi(e,`da`,t)}function Zi(e,t,n=Us){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if(ta(t,r,n),n){let e=n.parent;for(;e&&e.parent;)Ki(e.parent.vnode)&&Qi(r,t,n,e),e=e.parent}}function Qi(e,t,n,r){let i=ta(t,e,r,!0),a=ta(`um`,()=>u(r[t],i),n);a.flags=16}function $i(e){e.shapeFlag&=-257,e.shapeFlag&=-513}function ea(e){return e.shapeFlag&128?e.ssContent:e}function ta(e,t,n=Us,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{ot();let i=qs(n),a=Jn(t,n,e,r);return i(),st(),a};return r?i.unshift(a):i.push(a),a}}var na=e=>(t,n=Us)=>{Xs&&e!==`sp`||ta(e,(...e)=>t(...e),n)},ra=na(`bm`),ia=na(`m`),aa=na(`bu`),oa=na(`u`),sa=na(`bum`),ca=na(`um`),la=na(`sp`),ua=na(`rtg`),da=na(`rtc`);function fa(e,t=Us){ta(`ec`,e,t)}var pa=`components`,ma=`directives`;function ha(e,t){return ya(pa,e,!0,t)||e}var ga=Symbol.for(`v-ndc`);function _a(e){return y(e)?ya(pa,e,!1)||e:e||ga}function va(e){return ya(ma,e)}function ya(e,t,n=!0,r=!1){let i=vr||Us;if(i){let n=i.type;if(e===pa){let e=lc(n,!1);if(e&&(e===t||e===E(t)||e===ce(E(t))))return n}let a=ba(i[e]||n[e],t)||ba(i.appContext[e],t);return!a&&r?n:a}}function ba(e,t){return e&&(e[t]||e[E(t)]||e[ce(E(t))])}function R(e,t,n,r){let i,a=n&&n[r],o=p(e);if(o||y(e)){let n=o&&ln(e),r=!1,s=!1;n&&(r=!dn(e),s=un(e),e=xt(e)),i=Array(e.length);for(let n=0,o=e.length;nt(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r{let t=r.fn(...e);return t&&(t.key=r.key),t}:r.fn)}return e}function Sa(e,t,n,r,i,a){if(n??={},vr.ce||vr.parent&&Ui(vr.parent)&&vr.parent.ce){let e=a!=null&&n.key==null?l({},n,{key:a}):n,i=Object.keys(e).length>0;return t!=="default"&&(e.name=t),H(),W(B,null,[K(`slot`,e,r&&r())],i?-2:64)}let o=e[t];o&&o._c&&(o._d=!1);let s=ys.length;H();let c;try{let i=o&&Ca(o(n)),s=n.key||a||i&&i.key;c=W(B,{key:(s&&!b(s)?s:`_${t}`)+(!i&&r?`_fb`:``)},i||(r?r():[]),i&&e._===1?64:-2)}catch(e){for(let e=ys.length;e>s;e--)xs();throw e}finally{o&&o._c&&(o._d=!0)}return!i&&c.scopeId&&(c.slotScopeIds=[c.scopeId+`-s`]),c}function Ca(e){return e.some(e=>!Ts(e)||!(e.type===V||e.type===B&&!Ca(e.children)))?e:null}function wa(e,t){let n={};for(let r in e)n[t&&/[A-Z]/.test(r)?`on:${r}`:le(r)]=e[r];return n}var Ta=e=>e?Ys(e)?cc(e):Ta(e.parent):null,Ea=l(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Ta(e.parent),$root:e=>Ta(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Xa(e),$forceUpdate:e=>e.f||=()=>{or(e.update)},$nextTick:e=>e.n||=ir.bind(e.proxy),$watch:e=>Fr.bind(e)}),Da=(e,t)=>e!==r&&!e.__isScriptSetup&&f(e,t),Oa={get({_:e},t){if(t===`__v_skip`)return!0;let{ctx:n,setupState:i,data:a,props:o,accessCache:s,type:c,appContext:l}=e;if(t[0]!==`$`){let e=s[t];if(e!==void 0)switch(e){case 1:return i[t];case 2:return a[t];case 4:return n[t];case 3:return o[t]}else if(Da(i,t))return s[t]=1,i[t];else if(a!==r&&f(a,t))return s[t]=2,a[t];else if(f(o,t))return s[t]=3,o[t];else if(n!==r&&f(n,t))return s[t]=4,n[t];else Ga&&(s[t]=0)}let u=Ea[t],d,p;if(u)return t===`$attrs`&&_t(e.attrs,`get`,``),u(e);if((d=c.__cssModules)&&(d=d[t]))return d;if(n!==r&&f(n,t))return s[t]=4,n[t];if(p=l.config.globalProperties,f(p,t))return p[t]},set({_:e},t,n){let{data:i,setupState:a,ctx:o}=e;return Da(a,t)?(a[t]=n,!0):i!==r&&f(i,t)?(i[t]=n,!0):f(e.props,t)||t[0]===`$`&&t.slice(1)in e?!1:(o[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:i,appContext:a,props:o,type:s}},c){let l;return!!(n[c]||e!==r&&c[0]!==`$`&&f(e,c)||Da(t,c)||f(o,c)||f(i,c)||f(Ea,c)||f(a.config.globalProperties,c)||(l=s.__cssModules)&&l[c])},defineProperty(e,t,n){return n.get==null?f(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}},ka=l({},Oa,{get(e,t){if(t!==Symbol.unscopables)return Oa.get(e,t,e)},has(e,t){return t[0]!==`_`&&!ge(t)}});function Aa(){return null}function ja(){return null}function Ma(e){}function Na(e){}function Pa(){return null}function Fa(){}function Ia(e,t){return null}function La(){return za(`useSlots`).slots}function Ra(){return za(`useAttrs`).attrs}function za(e){let t=Ws();return t.setupContext||=sc(t)}function Ba(e){return p(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}function Va(e,t){let n=Ba(e);for(let e in t){if(e.startsWith(`__skip`))continue;let r=n[e];r?p(r)||v(r)?r=n[e]={type:r,default:t[e]}:r.default=t[e]:r===null&&(r=n[e]={default:t[e]}),r&&t[`__skip_${e}`]&&(r.skipFactory=!0)}return n}function Ha(e,t){return!e||!t?e||t:p(e)&&p(t)?e.concat(t):l({},Ba(e),Ba(t))}function Ua(e,t){let n={};for(let r in e)t.includes(r)||Object.defineProperty(n,r,{enumerable:!0,get:()=>e[r]});return n}function Wa(e){let t=Ws(),n=Xs,r=e();Js(),n&&Ks(!1);let i=()=>{qs(t),n&&Ks(!0)},a=()=>{Ws()!==t&&t.scope.off(),Js(),n&&Ks(!1)};return S(r)&&(r=r.catch(e=>{throw i(),Promise.resolve().then(()=>Promise.resolve().then(a)),e})),[r,()=>{i(),Promise.resolve().then(a)}]}var Ga=!0;function Ka(e){let t=Xa(e),n=e.proxy,r=e.ctx;Ga=!1,t.beforeCreate&&Ja(t.beforeCreate,e,`bc`);let{data:i,computed:o,methods:s,watch:c,provide:l,inject:u,created:d,beforeMount:f,mounted:m,beforeUpdate:h,updated:g,activated:_,deactivated:y,beforeDestroy:b,beforeUnmount:S,destroyed:ee,unmounted:C,render:te,renderTracked:w,renderTriggered:T,errorCaptured:ne,serverPrefetch:re,expose:ie,inheritAttrs:ae,components:E,directives:oe,filters:se}=t;if(u&&qa(u,r,null),s)for(let e in s){let t=s[e];v(t)&&(r[e]=t.bind(n))}if(i){let t=i.call(n,n);x(t)&&(e.data=rn(t))}if(Ga=!0,o)for(let e in o){let t=o[e],i=dc({get:v(t)?t.bind(n,n):v(t.get)?t.get.bind(n,n):a,set:!v(t)&&v(t.set)?t.set.bind(n):a});Object.defineProperty(r,e,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e})}if(c)for(let e in c)Ya(c[e],r,n,e);if(l){let e=v(l)?l.call(n):l;Reflect.ownKeys(e).forEach(t=>{Tr(t,e[t])})}d&&Ja(d,e,`c`);function ce(e,t){p(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(ce(ra,f),ce(ia,m),ce(aa,h),ce(oa,g),ce(Yi,_),ce(Xi,y),ce(fa,ne),ce(da,w),ce(ua,T),ce(sa,S),ce(ca,C),ce(la,re),p(ie)){if(ie.length){let t=e.exposed||={};ie.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={}}te&&e.render===a&&(e.render=te),ae!=null&&(e.inheritAttrs=ae),E&&(e.components=E),oe&&(e.directives=oe),re&&pi(e)}function qa(e,t,n=a){p(e)&&(e=to(e));for(let n in e){let r=e[n],i;i=x(r)?`default`in r?Er(r.from||n,r.default,!0):Er(r.from||n):Er(r),M(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function Ja(e,t,n){Jn(p(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function Ya(e,t,n,r){let i=r.includes(`.`)?Ir(n,r):()=>n[r];if(y(e)){let n=t[e];v(n)&&Nr(i,n)}else if(v(e))Nr(i,e.bind(n));else if(x(e)){if(p(e))e.forEach(e=>Ya(e,t,n,r));else{let r=v(e.handler)?e.handler.bind(n):t[e.handler];v(r)&&Nr(i,r,e)}}}function Xa(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>Za(c,e,o,!0)),Za(c,t,o)),x(t)&&a.set(t,c),c}function Za(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&Za(e,a,n,!0),i&&i.forEach(t=>Za(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=Qa[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var Qa={data:$a,props:io,emits:io,methods:ro,computed:ro,beforeCreate:no,created:no,beforeMount:no,mounted:no,beforeUpdate:no,updated:no,beforeDestroy:no,beforeUnmount:no,destroyed:no,unmounted:no,activated:no,deactivated:no,errorCaptured:no,serverPrefetch:no,components:ro,directives:ro,watch:ao,provide:$a,inject:eo};function $a(e,t){return t?e?function(){return l(v(e)?e.call(this,this):e,v(t)?t.call(this,this):t)}:t:e}function eo(e,t){return ro(to(e),to(t))}function to(e){if(p(e)){let t={};for(let n=0;n{let l,u=r,d;return Mr(()=>{let t=e[a];D(l,t)&&(l=t,c())}),{get(){return s(),n.get?n.get(l):l},set(e){let s=n.set?n.set(e):e;if(!D(s,l)&&!(u!==r&&D(e,u)))return;let f=i.vnode.props,p=!!(f&&(t in f||a in f||o in f)&&(`onUpdate:${t}`in f||`onUpdate:${a}`in f||`onUpdate:${o}`in f));p||(l=e,c()),i.emit(`update:${t}`,s),D(e,u)&&(D(e,s)&&!D(s,d)||p&&u!==r&&!D(s,l))&&c(),u=e,d=s}}});return c[Symbol.iterator]=()=>{let e=0;return{next(){return e<2?{value:e++?s||r:c,done:!1}:{done:!0}}}},c}var fo=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${E(t)}Modifiers`]||e[`${se(t)}Modifiers`];function po(e,t,...n){if(e.isUnmounted)return;let i=e.vnode.props||r,a=n,o=t.startsWith(`update:`),s=o&&fo(i,t.slice(7));s&&(s.trim&&(a=n.map(e=>y(e)?e.trim():e)),s.number&&(a=a.map(fe)));let c,l=i[c=le(t)]||i[c=le(E(t))];!l&&o&&(l=i[c=le(se(t))]),l&&Jn(l,e,6,a);let u=i[c+`Once`];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[c])return;e.emitted[c]=!0,Jn(u,e,6,a)}}var mo=new WeakMap;function ho(e,t,n=!1){let r=n?mo:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},s=!1;if(!v(e)){let r=e=>{let n=ho(e,t,!0);n&&(s=!0,l(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!s?(x(e)&&r.set(e,null),null):(p(a)?a.forEach(e=>o[e]=null):l(o,a),x(e)&&r.set(e,o),o)}function go(e,t){return!e||!s(t)?!1:(t=t.slice(2),t=t===`Once`?t:t.replace(/Once$/,``),f(e,t[0].toLowerCase()+t.slice(1))||f(e,se(t))||f(e,t))}function _o(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:o,attrs:s,emit:l,render:u,renderCache:d,props:f,data:p,setupState:m,ctx:h,inheritAttrs:g}=e,_=br(e),v,y;try{if(n.shapeFlag&4){let e=i||r,t=e;v=Ps(u.call(t,e,d,f,m,p,h)),y=s}else{let e=t;v=Ps(e.length>1?e(f,{attrs:s,slots:o,emit:l}):e(f,null)),y=t.props?s:yo(s)}}catch(t){ys.length=0,Yn(t,e,1),v=K(V)}let b=v;if(y&&g!==!1){let e=Object.keys(y),{shapeFlag:t}=b;e.length&&t&7&&(a&&e.some(c)&&(y=bo(y,a)),b=Ms(b,y,!1,!0))}return n.dirs&&(b=Ms(b,null,!1,!0),b.dirs=b.dirs?b.dirs.concat(n.dirs):n.dirs),n.transition&&li(zr(b.type)&&ci(b)||b,n.transition),v=b,br(_),v}function vo(e,t=!0){let n;for(let t=0;t{let t;for(let n in e)(n===`class`||n===`style`||s(n))&&((t||={})[n]=e[n]);return t},bo=(e,t)=>{let n={};for(let r in e)c(r)&&r.slice(9)in t||(n[r]=e[r]);return n};function xo(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?So(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;tObject.create(To),Do=e=>Object.getPrototypeOf(e)===To;function Oo(e,t,n,r=!1){let i={},a=Eo();e.propsDefaults=Object.create(null),Ao(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);e.props=n?r?i:an(i):e.type.props?i:a,e.attrs=a}function ko(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=j(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r{d=!0;let[n,r]=No(e,t,!0);l(c,n),r&&u.push(...r)};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}if(!s&&!d)return x(e)&&a.set(e,i),i;if(p(s))for(let e=0;ee===`_`||e===`_ctx`||e===`$stable`,Io=e=>p(e)?e.map(Ps):[Ps(e)],Lo=(e,t,n)=>{if(t._n)return t;let r=F((...e)=>Io(t(...e)),n);return r._c=!1,r},Ro=(e,t,n)=>{let r=e._ctx;for(let n in e){if(Fo(n))continue;let i=e[n];if(v(i))t[n]=Lo(n,i,r);else if(i!=null){let e=Io(i);t[n]=()=>e}}},zo=(e,t)=>{let n=Io(t);e.slots.default=()=>n},Bo=(e,t,n)=>{for(let r in t)(n||!Fo(r))&&(e[r]=t[r])},Vo=(e,t,n)=>{let r=e.slots=Eo();if(e.vnode.shapeFlag&32){let e=t._;e?(Bo(r,t,n),n&&de(r,`_`,e,!0)):Ro(t,r)}else t&&zo(e,t)},Ho=(e,t,n)=>{let{vnode:i,slots:a}=e,o=!0,s=r;if(i.shapeFlag&32){let e=t._;e?n&&e===1?o=!1:Bo(a,t,n):(o=!t.$stable,Ro(t,a)),s=t}else t&&(zo(e,t),s={default:1});if(o)for(let e in a)!Fo(e)&&s[e]==null&&delete a[e]},z=ms;function Uo(e){return Go(e)}function Wo(e){return Go(e,Ti)}function Go(e,t){let n=he();n.__VUE__=!0;let{insert:o,remove:s,patchProp:c,createElement:l,createText:u,createComment:d,setText:f,setElementText:p,parentNode:m,nextSibling:h,setScopeId:g=a,insertStaticContent:_}=e,v=(e,t,n,r=null,a=null,o=null,s=void 0,c=null,l=!!t.dynamicChildren)=>{if(e===t)return;e&&!Es(e,t)&&(r=xe(e),ge(e,a,o,!0),e=null),t.patchFlag===-2&&(l=!1,t.dynamicChildren=null),t.dynamicChildren&&e&&e.dynamicChildren&&e.dynamicChildren.hasOnce&&(t.dynamicChildren===i&&(t.dynamicChildren=[]),t.dynamicChildren.hasOnce=!0);let{type:u,ref:d,shapeFlag:f}=t;switch(u){case _s:y(e,t,n,r);break;case V:b(e,t,n,r);break;case vs:e??x(t,n,r,s);break;case B:E(e,t,n,r,a,o,s,c,l);break;default:f&1?C(e,t,n,r,a,o,s,c,l):f&6?oe(e,t,n,r,a,o,s,c,l):(f&64||f&128)&&u.process(e,t,n,r,a,o,s,c,l,Se)}d!=null&&a?_i(d,e&&e.ref,o,t||e,!t):d==null&&e&&e.ref!=null&&_i(e.ref,null,o,e,!0)},y=(e,t,n,r)=>{if(e==null)o(t.el=u(t.children),n,r);else{let n=t.el=e.el;t.children!==e.children&&f(n,t.children)}},b=(e,t,n,r)=>{e==null?o(t.el=d(t.children||``),n,r):t.el=e.el},x=(e,t,n,r)=>{[e.el,e.anchor]=_(e.children,t,n,r,e.el,e.anchor)},S=({el:e,anchor:t},n,r)=>{let i;for(;e&&e!==t;)i=h(e),o(e,n,r),e=i;o(t,n,r)},ee=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=h(e),s(e),e=n;s(t)},C=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)te(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),re(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},te=(e,t,n,r,i,a,s,u)=>{let d,f,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(d=e.el=l(e.type,a,m&&m.is,m),h&8?p(d,e.children):h&16&&T(e.children,d,null,r,i,Ko(e,a),s,u),_&&wr(e,null,r,`created`),w(d,e,e.scopeId,s,r),m){for(let e in m)e!==`value`&&!ne(e)&&c(d,e,null,m[e],a,r);`value`in m&&c(d,`value`,null,m.value,a),(f=m.onVnodeBeforeMount)&&Rs(f,r,e)}_&&wr(e,null,r,`beforeMount`);let v=Jo(i,g);v?g.beforeEnter(d):g&&!g.persisted&&(d[ns]=!0),o(d,t,n),((f=m&&m.onVnodeMounted)||v||_)&&z(()=>{try{f&&Rs(f,r,e),v&&g.enter(d),_&&wr(e,null,r,`mounted`)}finally{}},i)},w=(e,t,n,r,i)=>{if(n&&g(e,n),r)for(let t=0;t{for(let l=c;l{let l=t.el=e.el,{patchFlag:u,dynamicChildren:d,dirs:f}=t;u|=e.patchFlag&16;let m=e.props||r,h=t.props||r,g;if(n&&qo(n,!1),(g=h.onVnodeBeforeUpdate)&&Rs(g,n,t,e),f&&wr(t,e,n,`beforeUpdate`),n&&qo(n,!0),d&&(!e.dynamicChildren||e.dynamicChildren.length!==d.length)&&(u=0,s=!1,d=null),(m.innerHTML&&h.innerHTML==null||m.textContent&&h.textContent==null)&&p(l,``),d?ie(e.dynamicChildren,d,l,n,i,Ko(t,a),o):s||de(e,t,l,null,n,i,Ko(t,a),o,!1),u>0){if(u&16)ae(l,m,h,n,a);else if(u&2&&m.class!==h.class&&c(l,`class`,null,h.class,a),u&4&&c(l,`style`,m.style,h.style,a),u&8){let e=t.dynamicProps;for(let t=0;t{g&&Rs(g,n,t,e),f&&wr(t,e,n,`updated`)},i)},ie=(e,t,n,r,i,a,o)=>{for(let s=0;s{if(t!==n){if(t!==r)for(let r in t)!ne(r)&&!(r in n)&&c(e,r,t[r],null,a,i);for(let r in n){if(ne(r))continue;let o=n[r],s=t[r];o!==s&&r!==`value`&&c(e,r,s,o,a,i)}`value`in n&&c(e,`value`,t.value,n.value,a)}},E=(e,t,n,r,i,a,s,c,l)=>{let d=t.el=e?e.el:u(``),f=t.anchor=e?e.anchor:u(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(c=c?c.concat(h):h),e==null?(o(d,n,r),o(f,n,r),T(t.children||[],n,f,i,a,s,c,l)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(ie(e.dynamicChildren,m,n,i,a,s,c),(t.key!=null||i&&t===i.subTree)&&Yo(e,t,!0)):de(e,t,n,f,i,a,s,c,l)},oe=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):se(t,n,r,i,a,o,c):ce(e,t,c)},se=(e,t,n,r,i,a,o)=>{let s=e.component=Hs(e,r,i);if(Ki(e)&&(s.ctx.renderer=Se),Zs(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,le,o,a),!e.el){let r=s.subTree=K(V);b(null,r,t,n),e.placeholder=r.el}}else le(s,e,t,n,i,a,o)},ce=(e,t,n)=>{let r=t.component=e.component;if(xo(e,t,n)){if(r.asyncDep&&!r.asyncResolved){t.el=e.el,t.placeholder=e.placeholder,D(r,t,n);return}r.next=t,r.update()}else t.el=e.el,t.placeholder=e.placeholder,r.vnode=t},le=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=Zo(e);if(n){t&&(t.el=c.el,D(e,t,o)),n.asyncDep.then(()=>{let t=()=>{e.job.flags&8||(i&&i.pendingBranch?z(t,i):l())};t.flags=48,z(t,i)});return}}let u=t,d;qo(e,!1),t?(t.el=c.el,D(e,t,o)):t=c,n&&ue(n),(d=t.props&&t.props.onVnodeBeforeUpdate)&&Rs(d,s,t,c),qo(e,!0);let f=_o(e),p=e.subTree;e.subTree=f,v(p,f,m(p.el||$o(p)),xe(p),e,i,a),t.el=f.el,u===null&&wo(e,f.el),r&&z(r,i),(d=t.props&&t.props.onVnodeUpdated)&&z(()=>Rs(d,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=Ui(t);if(qo(e,!1),l&&ue(l),!m&&(o=c&&c.onVnodeBeforeMount)&&Rs(o,d,t),qo(e,!0),s&&we){let t=()=>{e.subTree=_o(e),we(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=_o(e);v(null,o,n,r,e,i,a),t.el=o.el}if(u&&z(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;z(()=>Rs(o,d,e),i)}(t.shapeFlag&256||d&&Ui(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&z(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new Ue(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>or(u),qo(e,!0),l()},D=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,ko(e,t.props,r,n),Ho(e,t.children,n),ot(),lr(e),st()},de=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,u=e?e.shapeFlag:0,d=t.children,{patchFlag:f,shapeFlag:m}=t;if(f>0){if(f&128){pe(l,d,n,r,i,a,o,s,c);return}if(f&256){fe(l,d,n,r,i,a,o,s,c);return}}m&8?(u&16&&be(l,i,a),d!==l&&p(n,d)):u&16?m&16?pe(l,d,n,r,i,a,o,s,c):be(l,i,a,!0):(u&8&&p(n,``),m&16&&T(d,n,r,i,a,o,s,c))},fe=(e,t,n,r,a,o,s,c,l)=>{e||=i,t||=i;let u=e.length,d=t.length,f=Math.min(u,d),p=0;for(;pd?be(e,a,o,!0,!1,f):T(t,n,r,a,o,s,c,l,f)},pe=(e,t,n,r,a,o,s,c,l)=>{let u=0,d=t.length,f=e.length-1,p=d-1;for(;u<=f&&u<=p;){let r=e[u],i=t[u]=l?Fs(t[u]):Ps(t[u]);if(Es(r,i))v(r,i,n,null,a,o,s,c,l);else break;u++}for(;u<=f&&u<=p;){let r=e[f],i=t[p]=l?Fs(t[p]):Ps(t[p]);if(Es(r,i))v(r,i,n,null,a,o,s,c,l);else break;f--,p--}if(u>f){if(u<=p){let e=p+1,i=ep)for(;u<=f;)ge(e[u],a,o,!0),u++;else{let m=u,h=u,g=new Map;for(u=h;u<=p;u++){let e=t[u]=l?Fs(t[u]):Ps(t[u]);e.key!=null&&g.set(e.key,u)}let _,y=0,b=p-h+1,x=!1,S=0,ee=Array(b);for(u=0;u=b){ge(r,a,o,!0);continue}let i;if(r.key!=null)i=g.get(r.key);else for(_=h;_<=p;_++)if(ee[_-h]===0&&Es(r,t[_])){i=_;break}i===void 0?ge(r,a,o,!0):(ee[i-h]=u+1,i>=S?S=i:x=!0,v(r,t[i],n,null,a,o,s,c,l),y++)}let C=x?Xo(ee):i;for(_=C.length-1,u=b-1;u>=0;u--){let e=h+u,i=t[e],f=t[e+1],p=e+1{let{el:a,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6)me(e.component.subTree,t,n,r);else if(d&128)e.suspense.move(t,n,r);else if(d&64)c.move(e,t,n,Se);else if(c===B){o(a,t,n);for(let e=0;el.enter(a),i));else{let{leave:r,delayLeave:i,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?s(a):o(a,t,n)},d=()=>{let e=a._isLeaving||!!a[Zr];a._isLeaving&&a[Zr](!0),l.persisted&&!e?u():r(a,()=>{u(),c&&c()})};i?i(a,u,d):d()}}else o(a,t,n)},ge=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if((d===-2||l&&l.hasOnce)&&(i=!1),s!=null&&(ot(),_i(s,null,n,e,!0),st()),p==null||e.ctx&&e.ctx!==t||(t.renderCache[p]=void 0),u&256&&t.ctx.deactivate(e))return;let h=u&1&&f,g=!Ui(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&Rs(_,t,e),u&6)ye(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&wr(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,Se,r):l&&!l.hasOnce&&(a!==B||d>0&&d&64)?be(l,t,n,!1,!0):(a===B&&d&384||!i&&u&16)&&be(c,t,n),r&&_e(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&z(()=>{_&&Rs(_,t,e),h&&wr(e,null,t,`unmounted`),v&&(e.el=null)},n)},_e=e=>{let{type:t,el:n,anchor:r,transition:i}=e,a=t===B;if(a&&!i){ve(n,r);return}if(t===vs){ee(e),i&&!i.persisted&&i.afterLeave&&i.afterLeave();return}let o=a?di(e):e,c=()=>{a?m(n)&&ve(n,r):s(n),i&&!i.persisted&&i.afterLeave&&i.afterLeave()};if(o&&o.shapeFlag&1&&i&&!i.persisted){let{leave:e,delayLeave:t}=i,n=o.el,r=()=>e(n,c);t?t(n,c,r):r()}else c()},ve=(e,t)=>{let n;for(;e!==t;)n=h(e),s(e),e=n;s(t)},ye=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;Qo(c),Qo(l),r&&ue(r),i.stop(),a?(a.flags|=8,ge(o,e,t,n)):o&&(o.transition=e.vnode.transition,ge(o,e,t,n)),s&&z(s,t);let u=()=>{e.isUnmounted=!0};u.flags=16,z(u,t)},be=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o{if(e.shapeFlag&6)return xe(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=h(e.anchor||e.el),n=t&&t[Rr];return n?h(n):t},O=(e,t,n)=>{fr(()=>{e==null?t._vnode&&ge(t._vnode,null,null,!0):v(t._vnode||null,e,t,null,null,null,n),t._vnode=e},e&&t._vnode?void 0:e&&e.component?e.component.uid:Vs())},Se={p:v,um:ge,m:me,r:_e,mt:se,mc:T,pc:de,pbc:ie,n:xe,o:e},Ce,we;return t&&([Ce,we]=t(Se)),{render:O,hydrate:Ce,createApp:co(O,Ce)}}function Ko({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function qo({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Jo(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Yo(e,t,n=!1){let r=e.children,i=t.children;if(p(r)&&p(i))for(let e=0;e>1,e[n[s]]0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function Zo(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Zo(t)}function Qo(e){if(e)for(let t=0;te.__isSuspense,ts=0,ns=Symbol(`_deferredEnter`),rs={name:`Suspense`,__isSuspense:!0,process(e,t,n,r,i,a,o,s,c,l){if(e==null)ss(t,n,r,i,a,o,s,c,l);else{let u=e.suspense;if(a&&a.deps>0&&!a.isHydrating){let n=u.parentComponent;if(n&&n.suspense===a&&n.suspenseId!==a.pendingId?a.pendingBranch&&!Es(t.ssContent,u.pendingBranch||u.activeBranch):!u.isInFallback){t.suspense=u,u.vnode=t,t.el=e.el;return}}cs(e,t,n,r,i,o,s,c,l)}},hydrate:us,normalize:ds};function is(e,t){let n=e.props&&e.props[t];v(n)&&n()}function as(e){let t=[];os(e,t,!0),t.length&&cr(t)}function os(e,t,n){let{el:r,transition:i,children:a,shapeFlag:o}=e;if(o&6)os(e.component.subTree,t,n);else if(!(o&192)&&(o&1&&(!n&&r&&r[ns]&&(r[ns]=void 0,i&&!i.persisted&&(i.beforeEnter(r),t.push(()=>i.enter(r)))),n=!1),o&16))for(let e=0;e0?(is(e,`onPending`),is(e,`onFallback`),l(null,e.ssFallback,t,n,r,null,a,o),hs(f,e.ssFallback)):f.resolve(!1,!0)}function cs(e,t,n,r,i,a,o,s,{p:c,um:l,o:{createElement:u}}){let d=t.suspense=e.suspense;d.vnode=t,t.el=e.el;let f=t.ssContent,p=t.ssFallback,{activeBranch:m,pendingBranch:h,isInFallback:g,isHydrating:_}=d;if(h)d.pendingBranch=f,Es(h,f)?(d.deps++,c(h,f,_?n:d.hiddenContainer,null,i,d,a,o,s),d.deps--,d.deps<=0?d.resolve():g&&!_&&!d.isFallbackMountPending&&(c(m,p,n,r,i,null,a,o,s),hs(d,p))):(d.pendingId=ts++,_?(d.isHydrating=!1,d.activeBranch=h):l(h,i,d),d.deps=0,ps(d),d.hiddenContainer=u(`div`),g?(c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0?d.resolve():d.isFallbackMountPending||(c(m,p,n,r,i,null,a,o,s),hs(d,p))):m&&Es(m,f)?(c(m,f,n,r,i,d,a,o,s),d.resolve(!0),d.pendingId=ts++,d.deps=0):(c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0&&d.resolve()));else if(m&&Es(m,f))c(m,f,n,r,i,d,a,o,s),hs(d,f);else if(is(t,`onPending`),d.pendingBranch=f,d.pendingId=ts++,c(null,f,d.hiddenContainer,null,i,d,a,o,s),d.deps<=0)d.resolve();else{let{timeout:e}=d;e>0?d.timeoutTimer=setTimeout(()=>{d.timeoutTimer=void 0,d.fallback(d.vnode.ssFallback)},e):e===0&&d.fallback(p)}}function ls(e,t,n,r,i,a,o,s,c,l,u=!1){let{p:d,m:f,um:p,n:m,o:{parentNode:h,remove:g}}=l,_,v=gs(e);v&&t&&t.pendingBranch&&(_=t.pendingId,t.deps++);let y=e.props?pe(e.props.timeout):void 0,b=a,x={vnode:e,parent:t,parentComponent:n,namespace:o,container:r,hiddenContainer:i,deps:0,pendingId:ts++,timeout:typeof y==`number`?y:-1,timeoutTimer:void 0,activeBranch:null,isFallbackMountPending:!1,pendingBranch:null,isInFallback:!u,isHydrating:u,isUnmounted:!1,effects:[],resolve(e=!1,n=!1){let{vnode:r,activeBranch:i,pendingBranch:o,pendingId:s,effects:c,parentComponent:l,container:u,isInFallback:d}=x,g=x.parent;for(;g&&!g.pendingBranch;)g=g.parent;let y=!1;if(x.isHydrating)x.isHydrating=!1;else if(!e){y=i&&o.transition&&o.transition.mode===`out-in`;let e=!1;y&&(i.transition.afterLeave=()=>{if(s===x.pendingId&&!x.isUnmounted){as(o),f(o,u,a===b&&!e?m(i):a,0);let t=!1;if(g){let e=u,n;for(;n=h(e);)e=n;t=e===g.hiddenContainer}t||cr(c),d&&r.ssFallback&&(r.ssFallback.el=null)}}),i&&!x.isFallbackMountPending&&(h(i.el||$o(i))===u&&(a=m(i),e=!0),p(i,l,x,!0),!y&&d&&r.ssFallback&&z(()=>r.ssFallback.el=null,x)),y||(as(o),f(o,u,a,0))}clearTimeout(x.timeoutTimer),x.timeoutTimer=void 0,x.isFallbackMountPending=!1,hs(x,o),x.pendingBranch=null,x.isInFallback=!1;let S=0;for(let e=0;e{if(x.isFallbackMountPending=!1,x.isUnmounted||!x.isInFallback)return;let e=x.vnode.ssFallback;d(null,e,i,o,r,null,a,s,c),hs(x,e)},u=e.transition&&e.transition.mode===`out-in`;u&&(x.isFallbackMountPending=!0,n.transition.afterLeave=l),x.isInFallback=!0,p(n,r,null,!0),u||l()},move(e,t,n){x.activeBranch&&f(x.activeBranch,e,t,n),x.container=e},next(){return x.activeBranch&&m(x.activeBranch)},registerDep(e,t,n,r){let i=!!x.pendingBranch;i&&x.deps++;let a=e.vnode.el,o=i=>{e.asyncResolved=!0;let{vnode:o}=e;$s(e,i,!1),a&&(o.el=a);let s=!a&&e.subTree.el;t(e,o,h(a||e.subTree.el),a?null:m(e.subTree),x,r,n),s&&(o.placeholder=null,g(s)),wo(e,o.el)};e.asyncDep.catch(t=>(e.scope.active&&Yn(t,e,0,!1,!0),()=>null)).then(t=>{if(e.isUnmounted||x.isUnmounted)return;let n=i&&x.pendingId===e.suspenseId;if(Js(),!e.scope.active)n&&--x.deps===0&&x.resolve();else if(!n&&x.pendingBranch){let n=()=>{e.isUnmounted||x.isUnmounted||!e.scope.active||(x.pendingBranch?ms(n,x):o(t))};n.flags=48,ms(n,x)}else o(t),n&&--x.deps===0&&x.resolve()})},unmount(e,t){if(x.isUnmounted=!0,clearTimeout(x.timeoutTimer),x.timeoutTimer=void 0,_!==void 0){let e=x.parent,t=_;_=void 0,cr(()=>{e.pendingId===t&&!e.isUnmounted&&--e.deps===0&&e.resolve()})}x.activeBranch&&p(x.activeBranch,n,e,t),x.pendingBranch&&(p(x.pendingBranch,n,x,t),ps(x))}};return x}function us(e,t,n,r,i,a,o,s,c){let l=t.suspense=ls(t,r,n,e.parentNode,document.createElement(`div`),null,i,a,o,s,!0),u=c(e,l.pendingBranch=t.ssContent,n,l,a,o);return l.deps===0&&l.resolve(!1,!0),u}function ds(e){let{shapeFlag:t,children:n}=e,r=t&32;e.ssContent=fs(r?n.default:n),e.ssFallback=r?fs(n.fallback):K(V)}function fs(e){let t;if(v(e)){let n=Ss&&e._c;n&&(e._d=!1,H()),e=e(),n&&(e._d=!0,t=bs,xs())}return p(e)&&(e=vo(e)),e=Ps(e),t&&!e.dynamicChildren&&(e.dynamicChildren=t.filter(t=>t!==e)),e}function ps(e){let{effects:t}=e;for(let e=0;e0?bs||i:null,xs(),Ss>0&&bs&&bs.push(e),e}function U(e,t,n,r,i,a){return ws(G(e,t,n,r,i,a,!0))}function W(e,t,n,r,i){return ws(K(e,t,n,r,i,!0))}function Ts(e){return e?e.__v_isVNode===!0:!1}function Es(e,t){return e.type===t.type&&e.key===t.key}function Ds(e){}var Os=({key:e})=>e??null,ks=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:y(e)||M(e)||v(e)?{i:vr,r:e,k:t,f:!!n}:e);function G(e,t=null,n=null,r=0,i=null,a=e===B?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Os(t),ref:t&&ks(t),scopeId:yr,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:vr};return s?(Is(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=y(n)?8:16),Ss>0&&!o&&bs&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&bs.push(c),c}var K=As;function As(e,t=null,n=null,r=0,i=null,a=!1){if(e&&e!==ga||(e=V),Ts(e)){let r=Ms(e,t,!0);return n&&Is(r,n),Ss>0&&!a&&bs&&(r.shapeFlag&6?bs[bs.indexOf(e)]=r:bs.push(r)),r.patchFlag=-2,r}if(uc(e)&&(e=e.__vccOpts),t){t=js(t);let{class:e,style:n}=t;e&&!y(e)&&(t.class=O(e)),x(n)&&(fn(n)&&!p(n)&&(n=l({},n)),t.style=_e(n))}let o=y(e)?1:es(e)?128:zr(e)?64:x(e)?4:v(e)?2:0;return G(e,t,n,r,i,o,a,!0)}function js(e){return e?fn(e)?l({},e):Do(e)?l({},e[ac]||e):e:null}function Ms(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?Ls(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&Os(l),ref:t&&t.ref?n&&a?p(a)?a.concat(ks(t)):[a,ks(t)]:ks(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==B?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Ms(e.ssContent),ssFallback:e.ssFallback&&Ms(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce,cacheIndex:e.cacheIndex};return c&&r&&li(u,c.clone(u)),u}function q(e=` `,t=0){return K(_s,null,e,t)}function Ns(e,t){let n=K(vs,null,e);return n.staticCount=t,n}function J(e=``,t=!1){return t?(H(),W(V,null,e)):K(V,null,e)}function Ps(e){return e==null||typeof e==`boolean`?K(V):p(e)?K(B,null,e.slice()):Ts(e)?Fs(e):K(_s,null,String(e))}function Fs(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Ms(e)}function Is(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(p(t))n=16;else if(typeof t==`object`){if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),Is(e,n()),n._c&&(n._d=!0));return}{n=32;let r=t._;!r&&!Do(t)?t._ctx=vr:r===3&&vr&&(vr.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}}else if(v(t)){if(r&65){Is(e,{default:t});return}t={default:t,_ctx:vr},n=32}else t=String(t),r&64?(n=16,t=[q(t)]):n=8;e.children=t,e.shapeFlag|=n}function Ls(...e){let t={};for(let n=0;nUs||vr,Gs,Ks;{let e=he(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};Gs=t(`__VUE_INSTANCE_SETTERS__`,e=>Us=e),Ks=t(`__VUE_SSR_SETTERS__`,e=>Xs=e)}var qs=e=>{let t=Us;return Gs(e),e.scope.on(),()=>{e.scope.off(),Gs(t)}},Js=()=>{Us&&Us.scope.off(),Gs(null)};function Ys(e){return e.vnode.shapeFlag&4}var Xs=!1;function Zs(e,t=!1,n=!1){t&&Ks(t);let{props:r,children:i}=e.vnode,a=Ys(e);Oo(e,r,a,t),Vo(e,i,n||t);let o=a?Qs(e,t):void 0;return t&&Ks(!1),o}function Qs(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,Oa);let{setup:r}=n;if(r){ot();let n=e.setupContext=r.length>1?sc(e):null,i=qs(e),a=qn(r,e,0,[e.props,n]),o=S(a);if(st(),i(),(o||e.sp)&&!Ui(e)&&pi(e),o){if(a.then(Js,Js),t)return a.then(n=>{Ks(!0);try{$s(e,n,t)}finally{Ks(!1)}}).catch(t=>{Yn(t,e,0,void 0,!0),e.ssrRender=(e,t)=>t(``)});e.asyncDep=a}else $s(e,a,t)}else ic(e,t)}function $s(e,t,n){v(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:x(t)&&(e.setupState=Sn(t)),ic(e,n)}var ec,tc;function nc(e){ec=e,tc=e=>{e.render._rc&&(e.withProxy=new Proxy(e.ctx,ka))}}var rc=()=>!ec;function ic(e,t,n){let r=e.type;if(!e.render){if(!t&&ec&&!r.render){let t=r.template||Xa(e).template;if(t){let{isCustomElement:n,compilerOptions:i}=e.appContext.config,{delimiters:a,compilerOptions:o}=r,s=l(l({isCustomElement:n,delimiters:a},i),o);r.render=ec(t,s)}}e.render=r.render||a,tc&&tc(e)}{let t=qs(e);ot();try{Ka(e)}finally{st(),t()}}}var ac=Symbol(),oc={get(e,t){return _t(e,`get`,``),t===ac?e:e[t]}};function sc(e){return{attrs:new Proxy(e.attrs,oc),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function cc(e){return e.exposed?e.exposeProxy||=new Proxy(Sn(pn(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Ea)return Ea[n](e)},has(e,t){return t in e||t in Ea}}):e.proxy}function lc(e,t=!0){return v(e)?e.displayName||e.name:e.name||t&&e.__name}function uc(e){return v(e)&&`__vccOpts`in e}var dc=(e,t)=>jn(e,t,Xs);function fc(e,t,n){try{Cs(-1);let r=arguments.length;return r===2?x(t)&&!p(t)?Ts(t)?K(e,null,[t]):K(e,t):K(e,null,t):(r>3?n=Array.prototype.slice.call(arguments,2):r===3&&Ts(n)&&(n=[n]),K(e,t,n))}finally{Cs(1)}}function pc(){}function mc(e,t,n,r){let i=n[r];if(i&&hc(i,e))return i;let a=t();return a.memo=e.slice(),a.cacheIndex=r,n[r]=a}function hc(e,t){let n=e.memo;if(n.length!=t.length)return!1;for(let e=0;e0&&bs&&bs.push(e),!0}var gc=`3.5.47`,_c=a,vc=Kn,yc=hr,bc=_r,xc={createComponentInstance:Hs,setupComponent:Zs,renderComponentRoot:_o,setCurrentRenderingInstance:br,isVNode:Ts,normalizeVNode:Ps,getComponentPublicInstance:cc,ensureValidVNode:Ca,pushWarningContext:Hn,popWarningContext:Un},Sc=void 0,Cc=typeof window<`u`&&window.trustedTypes;if(Cc)try{Sc=Cc.createPolicy(`vue`,{createHTML:e=>e})}catch{}var wc=Sc?e=>Sc.createHTML(e):e=>e,Tc=`http://www.w3.org/2000/svg`,Ec=`http://www.w3.org/1998/Math/MathML`,Dc=typeof document<`u`?document:null,Oc=Dc&&Dc.createElement(`template`),kc={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?Dc.createElementNS(Tc,e):t===`mathml`?Dc.createElementNS(Ec,e):n?Dc.createElement(e,{is:n}):Dc.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>Dc.createTextNode(e),createComment:e=>Dc.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Dc.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),i!==a&&(i=i.nextSibling););else{Oc.innerHTML=wc(r===`svg`?`${e}`:r===`mathml`?`${e}`:e);let i=Oc.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Ac=`transition`,jc=`animation`,Mc=Symbol(`_vtc`),Nc={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Pc=l({},ti,Nc),Fc=(e=>(e.displayName=`Transition`,e.props=Pc,e))((e,{slots:t})=>fc(ii,Rc(e),t)),Ic=(e,t=[])=>{p(e)?e.forEach(e=>e(...t)):e&&e(...t)},Lc=e=>e?p(e)?e.some(e=>e.length>1):e.length>1:!1;function Rc(e){let t={};for(let n in e)n in Nc||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:u=o,appearToClass:d=s,leaveFromClass:f=`${n}-leave-from`,leaveActiveClass:p=`${n}-leave-active`,leaveToClass:m=`${n}-leave-to`}=e,h=zc(i),g=h&&h[0],_=h&&h[1],{onBeforeEnter:v,onEnter:y,onEnterCancelled:b,onLeave:x,onLeaveCancelled:S,onBeforeAppear:ee=v,onAppear:C=y,onAppearCancelled:te=b}=t,w=(e,t,n,r)=>{e._enterResolve=void 0,e._enterCancelled=r,Hc(e,t?d:s),Hc(e,t?u:o),n&&n()},T=(e,t)=>{e._leaveResolve=void 0,e._isLeaving=!1,Hc(e,f),Hc(e,m),Hc(e,p),t&&t()},ne=e=>(t,n)=>{let i=e?C:y,o=()=>{t._enterResolve===o&&w(t,e,n)};t._enterResolve=o,Ic(i,[t,o]),Uc(()=>{Hc(t,e?c:a),t._enterResolve===o&&(Vc(t,e?d:s),Lc(i)||Gc(t,r,g,o))})};return l(t,{onBeforeEnter(e){Ic(v,[e]),Vc(e,a),Vc(e,o)},onBeforeAppear(e){Ic(ee,[e]),Vc(e,c),Vc(e,u)},onEnter:ne(!1),onAppear:ne(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>{e._leaveResolve===n&&T(e,t)};e._leaveResolve=n,Vc(e,f),e._enterCancelled?(Vc(e,p),Yc(e)):(Yc(e),Vc(e,p)),Uc(()=>{e._leaveResolve===n&&(Hc(e,f),Vc(e,m),Lc(x)||Gc(e,r,_,n))}),Ic(x,[e,n])},onEnterCancelled(e){w(e,!1,void 0,!0),Ic(b,[e])},onAppearCancelled(e){w(e,!0,void 0,!0),Ic(te,[e])},onLeaveCancelled(e){T(e),Ic(S,[e])}})}function zc(e){if(e==null)return null;if(x(e))return[Bc(e.enter),Bc(e.leave)];{let t=Bc(e);return[t,t]}}function Bc(e){return pe(e)}function Vc(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[Mc]||(e[Mc]=new Set)).add(t)}function Hc(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[Mc];n&&(n.delete(t),n.size||(e[Mc]=void 0))}function Uc(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var Wc=0;function Gc(e,t,n,r){let i=e._endId=++Wc,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=Kc(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u(n[e]||``).split(`, `),i=r(`${Ac}Delay`),a=r(`${Ac}Duration`),o=qc(i,a),s=r(`${jc}Delay`),c=r(`${jc}Duration`),l=qc(s,c),u=null,d=0,f=0;t===Ac?o>0&&(u=Ac,d=o,f=a.length):t===jc?l>0&&(u=jc,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?Ac:jc:null,f=u?u===Ac?a.length:c.length:0);let p=u===Ac&&/\b(?:transform|all)(?:,|$)/.test(r(`${Ac}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function qc(e,t){for(;e.lengthJc(t)+Jc(e[n])))}function Jc(e){return e===`auto`?0:Number(e.slice(0,-1).replace(`,`,`.`))*1e3}function Yc(e){return(e?e.ownerDocument:document).body.offsetHeight}function Xc(e,t,n){let r=e[Mc];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var Zc=Symbol(`_vod`),Qc=Symbol(`_vsh`),$c={name:`show`,beforeMount(e,{value:t},{transition:n}){e[Zc]=e.style.display===`none`?``:e.style.display,n&&t?n.beforeEnter(e):el(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:r}){!t!=!n&&(r?t?(r.beforeEnter(e),el(e,!0),r.enter(e)):r.leave(e,()=>{el(e,!1)}):el(e,t))},beforeUnmount(e,{value:t}){el(e,t)}};function el(e,t){e.style.display=t?e[Zc]:`none`,e[Qc]=!t}function tl(){$c.getSSRProps=({value:e})=>{if(!e)return{style:{display:`none`}}}}var nl=Symbol(``);function rl(e){let t=Ws();if(!t)return;let n=(n=e(t.proxy))=>{Array.from(document.querySelectorAll(`[data-v-owner="${t.uid}"]`)).forEach(e=>ll(e,n))},r={uid:String(t.uid),update:n};Ve(()=>r.update=void 0),t.ut=(e,t)=>{e&&(e[il]=[t,r],ol(e),al(e)),n()};let i=()=>{let r=e(t.proxy);t.ce?ll(t.ce,r):cl(t.subTree,r),n(r)};aa(()=>{cr(i)}),ia(()=>{Nr(i,a,{flush:`post`});let e=new MutationObserver(i);e.observe(t.subTree.el.parentNode,{childList:!0}),ca(()=>e.disconnect())})}var il=Symbol(``);function al(e,t){let[n,r]=e[il],i;if(r.update)for(let a=e;a&&a!==n;a=a.nextSibling)a.nodeType===1&&(!t||(t===!0||t.has(a))&&(a.getAttribute(`data-v-owner`)||r.uid)===r.uid)&&(a.setAttribute(`data-v-owner`,r.uid),i=r.update);return i}function ol(e){let t=e.parentNode;if(t){let n=t[il];n||(n=t[il]=new Set,new MutationObserver(sl).observe(t,{childList:!0})),n.add(e)}}function sl(e,t){let n=e[0].target,r=n[il],i=new Set;for(let{addedNodes:t}of e)t.forEach(e=>i.add(e));let a=new Set;r.forEach(e=>{e.parentNode===n?i.size&&a.add(al(e,i)):(r.delete(e),ol(e),a.add(al(e,!0)))}),a.forEach(e=>e&&e()),r.size||(t.disconnect(),n[il]=void 0)}function cl(e,t){if(e.shapeFlag&128){let n=e.suspense;e=n.activeBranch,n.pendingBranch&&!n.isHydrating&&n.effects.push(()=>{cl(n.activeBranch,t)})}for(;e.component;)e=e.component.subTree;if(e.shapeFlag&1&&e.el)ll(e.el,t);else if(e.type===B)e.children.forEach(e=>cl(e,t));else if(e.type===vs){let{el:n,anchor:r}=e;for(;n&&(ll(n,t),n!==r);)n=n.nextSibling}}function ll(e,t){if(e.nodeType===1){let n=e.style,r=``;for(let e in t){let i=Ie(t[e]);n.setProperty(`--${e}`,i),r+=`--${e}: ${i};`}n[nl]=r}}var ul=/(?:^|;)\s*display\s*:/;function dl(e,t,n){let r=e.style,i=y(n),a=!1;if(n&&!i){if(t){if(y(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??pl(r,t,``)}else for(let e in t)n[e]??pl(r,e,``)}for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?pl(r,i,``):_l(e,i,!y(t)&&t?t[i]:void 0,o)||pl(r,i,o)}}else if(i){if(t!==n){let e=r[nl];e&&(n+=`;`+e),r.cssText=n,a=ul.test(n)}}else t&&e.removeAttribute(`style`);Zc in e&&(i&&t===n||(e[Zc]=a?r.display:``),e[Qc]&&(r.display=`none`))}var fl=/\s*!important$/;function pl(e,t,n){if(p(n))n.forEach(n=>pl(e,t,n));else if(n??=``,t.startsWith(`--`))fl.test(n)?e.setProperty(t,n.replace(fl,``),`important`):e.setProperty(t,n);else{let r=gl(e,t);fl.test(n)?e.setProperty(se(r),n.replace(fl,``),`important`):e[r]=n}}var ml=[`Webkit`,`Moz`,`ms`],hl={};function gl(e,t){let n=hl[t];if(n)return n;let r=E(t);if(r!==`filter`&&r in e)return hl[t]=r;r=ce(r);for(let n=0;nOl||=(kl.then(()=>Ol=0),Date.now());function jl(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(p(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;ne.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Nl=(e,t,n,r,i,a)=>{let o=i===`svg`;t===`class`?Xc(e,r,o):t===`style`?dl(e,n,r):s(t)?c(t)||wl(e,t,n,r,a):(t[0]===`.`?(t=t.slice(1),1):t[0]===`^`?(t=t.slice(1),0):Pl(e,t,r,o))?(bl(e,t,r),e.tagName.includes(`-`)||t!==`value`&&t!==`checked`&&t!==`selected`||yl(e,t,r,o,a,t!==`value`)):e._isVueCE&&(Fl(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!y(r)))?bl(e,E(t),r,a,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),yl(e,t,r,o))};function Pl(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&Ml(t)&&v(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return Ml(t)&&y(n)?!1:t in e}function Fl(e,t){let n=e._def.props;if(!n)return!1;let r=E(t);return Array.isArray(n)?n.some(e=>E(e)===r):Object.keys(n).some(e=>E(e)===r)}var Il={};function Ll(e,t,n){let r=L(e,t);w(r)&&(r=l({},r,t));class i extends Bl{constructor(e){super(r,e,n)}}return i.def=r,i}var Rl=((e,t)=>Ll(e,t,Iu)),zl=typeof HTMLElement<`u`?HTMLElement:class{},Bl=class e extends zl{constructor(e,t={},n=Fu){super(),this._def=e,this._props=t,this._createApp=n,this._isVueCE=!0,this._instance=null,this._app=null,this._nonce=this._def.nonce,this._connected=!1,this._resolved=!1,this._patching=!1,this._dirty=!1,this._numberProps=null,this._styleChildren=new WeakSet,this._styleAnchors=new WeakMap,this._ob=null,this.shadowRoot&&n!==Fu?this._root=this.shadowRoot:e.shadowRoot===!1?this._root=this:(this.attachShadow(l({},e.shadowRootOptions,{mode:`open`})),this._root=this.shadowRoot)}connectedCallback(){if(!this.isConnected)return;!this.shadowRoot&&!this._resolved&&this._parseSlots(),this._connected=!0;let t=this;for(;t&&=t.assignedSlot||t.parentNode||t.host;)if(t instanceof e){this._parent=t;break}this._instance||(this._resolved?this._mount(this._def):t&&t._pendingResolve?this._pendingResolve=t._pendingResolve.then(()=>{if(this._pendingResolve=void 0,this.isConnected)return this._resolveDef()}):this._resolveDef())}_setParent(e=this._parent){e&&(this._instance.parent=e._instance,this._inheritParentContext(e))}_inheritParentContext(e=this._parent){e&&this._app&&Object.setPrototypeOf(this._app._context.provides,e._instance.provides)}disconnectedCallback(){this._connected=!1,ir(()=>{this._connected||(this._ob&&=(this._ob.disconnect(),null),this._app&&this._app.unmount(),this._instance&&(this._instance.ce=void 0),this._app=this._instance=null,this._teleportTargets&&=(this._teleportTargets.clear(),void 0))})}_processMutations(e){for(let t of e)this._setAttr(t.attributeName)}_resolveDef(){if(this._pendingResolve)return this._pendingResolve;for(let e=0;e{this._resolved=!0,this._pendingResolve=void 0;let{props:n,styles:r}=e,i;if(n&&!p(n))for(let e in n){let t=n[e];(t===Number||t&&t.type===Number)&&(e in this._props&&(this._props[e]=pe(this._props[e])),(i||=Object.create(null))[E(e)]=!0)}this._numberProps=i,this._resolveProps(e),this.shadowRoot&&this._applyStyles(r),this._connected&&this._mount(e)},t=this._def.__asyncLoader;if(t)return this._pendingResolve=t().then(t=>{t.configureApp=this._def.configureApp,e(this._def=t,!0)}),this._pendingResolve;e(this._def)}_mount(e){this._app=this._createApp(e),this._inheritParentContext(),e.configureApp&&e.configureApp(this._app),this._app._ceVNode=this._createVNode(),this._app.mount(this._root);let t=this._instance&&this._instance.exposed;if(t)for(let e in t)f(this,e)||Object.defineProperty(this,e,{get:()=>P(t[e])})}_resolveProps(e){let{props:t}=e,n=p(t)?t:Object.keys(t||{});for(let e of Object.keys(this))e[0]!==`_`&&n.includes(e)&&this._setProp(e,this[e]);for(let e of n.map(E))Object.defineProperty(this,e,{get(){return this._getProp(e)},set(t){this._setProp(e,t,!0,!this._patching)}})}_setAttr(e){if(e.startsWith(`data-v-`))return;let t=this.hasAttribute(e),n=t?this.getAttribute(e):Il,r=E(e);t&&this._numberProps&&this._numberProps[r]&&(n=pe(n)),this._setProp(r,n,!1,!0)}_getProp(e){return this._props[e]}_setProp(e,t,n=!0,r=!1){if(t!==this._props[e]&&(this._dirty=!0,t===Il?delete this._props[e]:(this._props[e]=t,e===`key`&&this._app&&(this._app._ceVNode.key=t)),r&&this._instance&&this._update(),n)){let n=this._ob;n&&(this._processMutations(n.takeRecords()),n.disconnect()),t===!0?this.setAttribute(se(e),``):typeof t==`string`||typeof t==`number`?this.setAttribute(se(e),t+``):t||this.removeAttribute(se(e)),n&&n.observe(this,{attributes:!0})}}_update(){let e=this._createVNode();this._app&&(e.appContext=this._app._context),Nu(e,this._root)}_createVNode(){let e={};this.shadowRoot||(e.onVnodeMounted=e.onVnodeUpdated=this._renderSlots.bind(this));let t=K(this._def,l(e,this._props));return this._instance||(t.ce=e=>{this._instance=e,e.ce=this,e.isCE=!0;let t=(e,t)=>{this.dispatchEvent(new CustomEvent(e,w(t[0])?l({detail:t},t[0]):{detail:t}))};e.emit=(e,...n)=>{t(e,n),se(e)!==e&&t(se(e),n)},this._setParent()}),t}_applyStyles(e,t,n){if(!e)return;if(t){if(t===this._def||this._styleChildren.has(t))return;this._styleChildren.add(t)}let r=this._nonce,i=this.shadowRoot,a=n?this._getStyleAnchor(n)||this._getStyleAnchor(this._def):this._getRootStyleInsertionAnchor(i),o=null;for(let s=e.length-1;s>=0;s--){let c=document.createElement(`style`);r&&c.setAttribute(`nonce`,r),c.textContent=e[s],i.insertBefore(c,o||a),o=c,s===0&&(n||this._styleAnchors.set(this._def,c),t&&this._styleAnchors.set(t,c))}}_getStyleAnchor(e){if(!e)return null;let t=this._styleAnchors.get(e);return t&&t.parentNode===this.shadowRoot?t:(t&&this._styleAnchors.delete(e),null)}_getRootStyleInsertionAnchor(e){for(let t=0;t(delete e.props.mode,e))({name:`TransitionGroup`,props:l({},Pc,{tag:String,moveClass:String}),setup(e,{slots:t}){let n=Ws(),r=$r(),i,a,o,s,c=()=>(s===void 0&&(s=i.length>0&&iu(i[0].el,n.vnode.el,Zl(e))),s);return oa(()=>{if(Jl.delete(n),!c()){i=[],o=void 0;return}let t=Zl(e);i.forEach(Xl);let r=o&&ru(o,n.vnode.el);o=void 0,i.forEach(e=>Ql(e,r));let a=i.filter($l);Yc(n.vnode.el),a.forEach(e=>{let n=e.el,r=n.style;Vc(n,t),r.transform=r.webkitTransform=r.transitionDuration=``;let i=n[Kl]=e=>{e&&e.target!==n||(!e||e.propertyName.endsWith(`transform`))&&(n.removeEventListener(`transitionend`,i),n[Kl]=null,Hc(n,t))};n.addEventListener(`transitionend`,i)}),i=[]}),()=>{let l=j(e),u=Rc(l),d=l.tag||B;if(i=[],s=void 0,a)for(let e=0;ee.willMove()&&e.item.contains(t));return n&&eu(n.item,n)}function iu(e,t,n){let r=e.cloneNode(),i=e[Mc];i&&i.forEach(e=>{e.split(/\s+/).forEach(e=>e&&r.classList.remove(e))}),n.split(/\s+/).forEach(e=>e&&r.classList.add(e)),r.style.display=`none`;let a=t.nodeType===1?t:t.parentNode;a.appendChild(r);let{hasTransform:o}=Kc(r);return a.removeChild(r),o}var au=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return p(t)?e=>ue(t,e):t};function ou(e){e.target.composing=!0}function su(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var cu=Symbol(`_assign`),lu=Symbol(`_initialValue`);function uu(e,t,n){return t&&(e=e.trim()),n&&(e=fe(e)),e}var Y={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e.parentNode&&(e.type===`text`?e[lu]=e.defaultValue.replace(/[\r\n]/g,``):e.type===`textarea`&&(e[lu]=e.defaultValue.replace(/\r\n?/g,` +`))),e[cu]=au(i);let a=r||i.props&&i.props.type===`number`;xl(e,t?`change`:`input`,t=>{t.target.composing||e[cu](uu(e.value,n,a))}),(n||a)&&xl(e,`change`,()=>{e.value=uu(e.value,n,a)}),t||(xl(e,`compositionstart`,ou),xl(e,`compositionend`,su),xl(e,`change`,su))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[lu];delete e[lu],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[cu](uu(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[cu]=au(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?fe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},du={deep:!0,created(e,t,n){e[cu]=au(n),xl(e,`change`,()=>{let t=e._modelValue,n=_u(e),r=e.checked,i=e[cu];if(p(t)){let e=je(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(h(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(vu(e,r))})},mounted:fu,beforeUpdate(e,t,n){e[cu]=au(n),fu(e,t,n)}};function fu(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(p(t))i=je(t,r.props.value)>-1;else if(h(t))i=t.has(r.props.value);else{if(t===n)return;i=Ae(t,vu(e,!0))}e.checked!==i&&(e.checked=i)}var pu={created(e,{value:t},n){e.checked=Ae(t,n.props.value),e[cu]=au(n),xl(e,`change`,()=>{e[cu](_u(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[cu]=au(r),t!==n&&(e.checked=Ae(t,r.props.value))}},mu={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,xl(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?fe(_u(e)):_u(e)),r=e.multiple,i=r?h(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?p(i)?t.slice():t:i];try{e[cu](i)}finally{ir(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[cu]=au(r)},mounted(e,{value:t,modifiers:{number:n}}){gu(e,t,n)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[cu]=au(n)},updated(e,{value:t,modifiers:{number:n}}){let r=e._pendingValue;e._pendingValue=void 0,r&&r[0]===e.multiple&&hu(t,r[1],r[0])||gu(e,t,n)}};function hu(e,t,n){if(!n||p(e))return Ae(e,t);if(h(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function gu(e,t,n=!1){let r=e.multiple,i=p(t);if(!r||i||h(t)){for(let a=0,o=e.options.length;aString(e)===String(s)):je(t,s)>-1}else o.selected=t.has(s)||n&&typeof s==`string`&&t.has(fe(s))}else if(Ae(_u(o),t)){e.selectedIndex!==a&&(e.selectedIndex=a);return}}!r&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function _u(e){return`_value`in e?e._value:e.value}function vu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var yu={created(e,t,n){xu(e,t,n,null,`created`)},mounted(e,t,n){xu(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){xu(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){xu(e,t,n,r,`updated`)}};function bu(e,t){switch(e){case`SELECT`:return mu;case`TEXTAREA`:return Y;default:switch(t){case`checkbox`:return du;case`radio`:return pu;default:return Y}}}function xu(e,t,n,r,i){let a=bu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function Su(){Y.getSSRProps=({value:e})=>({value:e}),pu.getSSRProps=({value:e},t)=>{if(t.props&&Ae(t.props.value,e))return{checked:!0}},du.getSSRProps=({value:e},t)=>{if(p(e)){if(t.props&&je(e,t.props.value)>-1)return{checked:!0}}else if(h(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},yu.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=bu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var Cu=[`ctrl`,`shift`,`alt`,`meta`],wu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>Cu.some(n=>e[`${n}Key`]&&!t.includes(n))},Tu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e{let n=e._withKeys||={},r=t.join(`.`),i=n[r];if(i)return i;let a=t.some(e=>e===`left`||e===`right`);return n[r]=(n=>{if(!(`key`in n))return a?e(n):void 0;let r=se(n.key);if(t.some(e=>e===r||Eu[e]===r))return e(n)})},Ou=l({patchProp:Nl},kc),ku,Au=!1;function ju(){return ku||=Uo(Ou)}function Mu(){return ku=Au?ku:Wo(Ou),Au=!0,ku}var Nu=((...e)=>{ju().render(...e)}),Pu=((...e)=>{Mu().hydrate(...e)}),Fu=((...e)=>{let t=ju().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Ru(e);if(!r)return;let i=t._component;v(i)||i.render||i.template||(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,Lu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),Iu=((...e)=>{let t=Mu().createApp(...e),{mount:n}=t;return t.mount=e=>{let t=Ru(e);if(t)return n(t,!0,Lu(t))},t});function Lu(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function Ru(e){return y(e)?document.querySelector(e):e}var zu=!1,Bu=()=>{zu||(zu=!0,Su(),tl())},Vu=t({BaseTransition:()=>ii,BaseTransitionPropsValidators:()=>ti,Comment:()=>V,DeprecationTypes:()=>null,EffectScope:()=>Re,ErrorCodes:()=>Gn,ErrorTypeStrings:()=>vc,Fragment:()=>B,KeepAlive:()=>qi,ReactiveEffect:()=>Ue,Static:()=>vs,Suspense:()=>rs,Teleport:()=>Jr,Text:()=>_s,TrackOpTypes:()=>Mn,Transition:()=>Fc,TransitionGroup:()=>Yl,TriggerOpTypes:()=>Nn,VueElement:()=>Bl,assertNumber:()=>Wn,callWithAsyncErrorHandling:()=>Jn,callWithErrorHandling:()=>qn,camelize:()=>E,capitalize:()=>ce,cloneVNode:()=>Ms,compatUtils:()=>null,compile:()=>Hu,computed:()=>dc,createApp:()=>Fu,createBlock:()=>W,createCommentVNode:()=>J,createElementBlock:()=>U,createElementVNode:()=>G,createHydrationRenderer:()=>Wo,createPropsRestProxy:()=>Ua,createRenderer:()=>Uo,createSSRApp:()=>Iu,createSlots:()=>xa,createStaticVNode:()=>Ns,createTextVNode:()=>q,createVNode:()=>K,customRef:()=>wn,defineAsyncComponent:()=>Wi,defineComponent:()=>L,defineCustomElement:()=>Ll,defineEmits:()=>ja,defineExpose:()=>Ma,defineModel:()=>Fa,defineOptions:()=>Na,defineProps:()=>Aa,defineSSRCustomElement:()=>Rl,defineSlots:()=>Pa,devtools:()=>yc,effect:()=>nt,effectScope:()=>ze,getCurrentInstance:()=>Ws,getCurrentScope:()=>Be,getCurrentWatcher:()=>Ln,getTransitionRawChildren:()=>ui,guardReactiveProps:()=>js,h:()=>fc,handleError:()=>Yn,hasInjectionContext:()=>Dr,hydrate:()=>Pu,hydrateOnIdle:()=>Li,hydrateOnInteraction:()=>Vi,hydrateOnMediaQuery:()=>Bi,hydrateOnVisible:()=>zi,initCustomFormatter:()=>pc,initDirectivesForSSR:()=>Bu,inject:()=>Er,isMemoSame:()=>hc,isProxy:()=>fn,isReactive:()=>ln,isReadonly:()=>un,isRef:()=>M,isRuntimeOnly:()=>rc,isShallow:()=>dn,isVNode:()=>Ts,markRaw:()=>pn,mergeDefaults:()=>Va,mergeModels:()=>Ha,mergeProps:()=>Ls,nextTick:()=>ir,nodeOps:()=>kc,normalizeClass:()=>O,normalizeProps:()=>Se,normalizeStyle:()=>_e,onActivated:()=>Yi,onBeforeMount:()=>ra,onBeforeUnmount:()=>sa,onBeforeUpdate:()=>aa,onDeactivated:()=>Xi,onErrorCaptured:()=>fa,onMounted:()=>ia,onRenderTracked:()=>da,onRenderTriggered:()=>ua,onScopeDispose:()=>Ve,onServerPrefetch:()=>la,onUnmounted:()=>ca,onUpdated:()=>oa,onWatcherCleanup:()=>Rn,openBlock:()=>H,patchProp:()=>Nl,popScopeId:()=>Sr,provide:()=>Tr,proxyRefs:()=>Sn,pushScopeId:()=>xr,queuePostFlushCb:()=>cr,reactive:()=>rn,readonly:()=>on,ref:()=>N,registerRuntimeCompiler:()=>nc,render:()=>Nu,renderList:()=>R,renderSlot:()=>Sa,resolveComponent:()=>ha,resolveDirective:()=>va,resolveDynamicComponent:()=>_a,resolveFilter:()=>null,resolveTransitionHooks:()=>oi,setBlockTracking:()=>Cs,setDevtoolsHook:()=>bc,setTransitionHooks:()=>li,shallowReactive:()=>an,shallowReadonly:()=>sn,shallowRef:()=>gn,ssrContextKey:()=>Or,ssrUtils:()=>xc,stop:()=>rt,toDisplayString:()=>k,toHandlerKey:()=>le,toHandlers:()=>wa,toRaw:()=>j,toRef:()=>On,toRefs:()=>Tn,toValue:()=>bn,transformVNodeArgs:()=>Ds,triggerRef:()=>yn,unref:()=>P,useAttrs:()=>Ra,useCssModule:()=>Ul,useCssVars:()=>rl,useHost:()=>Vl,useId:()=>fi,useModel:()=>uo,useSSRContext:()=>kr,useShadowRoot:()=>Hl,useSlots:()=>La,useTemplateRef:()=>mi,useTransitionState:()=>$r,vModelCheckbox:()=>du,vModelDynamic:()=>yu,vModelRadio:()=>pu,vModelSelect:()=>mu,vModelText:()=>Y,vShow:()=>$c,version:()=>gc,warn:()=>_c,watch:()=>Nr,watchEffect:()=>Ar,watchPostEffect:()=>jr,watchSyncEffect:()=>Mr,withAsyncContext:()=>Wa,withCtx:()=>F,withDefaults:()=>Ia,withDirectives:()=>I,withKeys:()=>Du,withMemo:()=>mc,withModifiers:()=>Tu,withScopeId:()=>Cr}),Hu=()=>{},Uu=class extends Error{status;body;constructor(e,t){super(t?.message??`HTTP ${e}`),this.status=e,this.body=t}get errors(){return Object.fromEntries(Object.entries(this.body?.errors??{}).map(([e,t])=>[e,t[0]]))}},X=JSON.parse(document.getElementById(`manager-boot`).textContent);function Wu(){let e=document.cookie.match(/(?:^|; )XSRF-TOKEN=([^;]+)/);return e?decodeURIComponent(e[1]):``}async function Gu(e,t,n){let r=await fetch(t,{method:e,credentials:`same-origin`,headers:{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,"X-XSRF-TOKEN":Wu(),...n===void 0?{}:{"Content-Type":`application/json`}},body:n===void 0?void 0:JSON.stringify(n)}),i=r.status===204?null:await r.json().catch(()=>null);if(!r.ok)throw new Uu(r.status,i);return i}async function Ku(e,t){let n=await fetch(e,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"X-Requested-With":`XMLHttpRequest`,"X-XSRF-TOKEN":Wu()},body:t}),r=await n.json().catch(()=>null);if(!n.ok)throw new Uu(n.status,r);return r}var Z={get:e=>Gu(`GET`,e),post:(e,t={})=>Gu(`POST`,e,t),put:(e,t={})=>Gu(`PUT`,e,t),delete:(e,t)=>Gu(`DELETE`,e,t)};function qu(e){let t=rn({values:{...e},errors:{},busy:!1,async send(e,n){t.busy=!0,t.errors={};try{return await Z[e](n,t.values)}catch(e){if(e instanceof Uu&&e.status===422)return t.errors=e.errors,null;throw e}finally{t.busy=!1}}});return t}var Ju={Dashboard:`Dashboard`,"Log in":`Inloggen`,"Log out":`Uitloggen`,Email:`E-mailadres`,Password:`Wachtwoord`,"Keep me logged in":`Ingelogd blijven`,"Logging in…":`Bezig met inloggen…`,"Log in to manage the site.":`Log in om de site te beheren.`,"My account":`Mijn account`,Name:`Naam`,"Email address":`E-mailadres`,"What you may do":`Wat je mag`,"Super admin: everything":`Super admin: alles`,"Not in a group yet":`Nog in geen groep`,"New password":`Nieuw wachtwoord`,"Leave empty to keep the password you have.":`Laat leeg om je wachtwoord te houden.`,"Current password":`Huidig wachtwoord`,"At least 12 characters.":`Minstens 12 tekens.`,"New password, once more":`Nieuw wachtwoord, nogmaals`,Save:`Opslaan`,"Saving…":`Bezig met opslaan…`,"Saved.":`Opgeslagen.`,Look:`Uiterlijk`,Theme:`Thema`,Posts:`Berichten`,"New post":`Nieuw bericht`,Title:`Titel`,Status:`Status`,Category:`Categorie`,Edit:`Bewerken`,Delete:`Verwijderen`,"Put online":`Online zetten`,"Take offline":`Offline halen`,Draft:`Concept`,Scheduled:`Ingepland`,Published:`Gepubliceerd`,"Are you sure?":`Weet je het zeker?`,"No posts yet.":`Nog geen berichten.`,"Address (slug)":`Adres (slug)`,Summary:`Samenvatting`,"Text (Markdown)":`Tekst (Markdown)`,"Cover image":`Omslagafbeelding`,"Tags (comma separated)":`Tags (met komma's)`,Featured:`Uitgelicht`,Publish:`Publiceren`,"Publish at":`Publiceren op`,Menu:`Menu`,"Click the part of the picture that must stay in view.":`Klik op het deel van de foto dat in beeld moet blijven.`,"Focus point":`Scherpstelpunt`,Clear:`Wissen`,Formatting:`Opmaak`,Bold:`Vet`,Italic:`Cursief`,Heading:`Kop`,List:`Lijst`,Quote:`Citaat`,Link:`Link`,bold:`vet`,italic:`cursief`,text:`tekst`,Photo:`Foto`,Write:`Schrijven`,Preview:`Voorbeeld`,History:`Geschiedenis`,Now:`Nu`,"Put back":`Terugzetten`,"Put this version back? The text now is kept in the history.":`Deze versie terugzetten? De tekst van nu blijft bewaard in de geschiedenis.`,"The earlier version is back.":`De eerdere versie is terug.`,New:`Nieuw`,"New page":`Nieuwe pagina`,"Description for search engines":`Omschrijving voor zoekmachines`,"One per line.":`Eén per regel.`,"Show everything":`Alles tonen`,"Simple view":`Simpele weergave`,"Loading…":`Laden…`,"You may not open this page.":`Je mag deze pagina niet openen.`,"Something went wrong. Try again.":`Er ging iets mis. Probeer het opnieuw.`,"This page has no screen in the manager yet.":`Deze pagina heeft nog geen scherm in de manager.`,"Go to the dashboard":`Naar het dashboard`,"The page expired. Reload it and try again.":`De pagina is verlopen. Laad hem opnieuw en probeer het nog eens.`,Back:`Terug`,Accounts:`Accounts`,"New account":`Nieuw account`,you:`jij`,"Super admin":`Super admin`,Groups:`Groepen`,Cancel:`Annuleren`,"New group":`Nieuwe groep`,Description:`Omschrijving`,accounts:`accounts`,"Categories and tags":`Categorieën en tags`,Categories:`Categorieën`,Tags:`Tags`,Add:`Toevoegen`,Rename:`Hernoemen`,"New name":`Nieuwe naam`,Pages:`Pagina's`,Reviews:`Reviews`,"Nothing here yet.":`Hier is nog niets.`,Previous:`Vorige`,Next:`Volgende`,Media:`Media`,"Choose an image":`Kies een afbeelding`,"No images yet.":`Nog geen afbeeldingen.`,"Uploaded.":`Geüpload.`,Upload:`Uploaden`,"Uploading…":`Bezig met uploaden…`,"This file is in use. Delete it anyway?":`Dit bestand is in gebruik. Toch verwijderen?`,"Largest file":`Grootste bestand`,"Alternative text":`Alternatieve tekst`,Used:`Gebruikt`,"No files yet.":`Nog geen bestanden.`,Choose:`Kiezen`,"Audit log":`Auditlog`,"Addresses banned":`Geblokkeerde adressen`,"Logins (24 h)":`Logins (24 u)`,"Failed logins (24 h)":`Mislukte logins (24 u)`,"Refused (24 h)":`Geweigerd (24 u)`,all:`alles`,logins:`logins`,failed:`mislukt`,actions:`acties`,viewed:`bekeken`,refused:`geweigerd`,bans:`blokkades`,Search:`Zoeken`,Account:`Account`,Everyone:`Iedereen`,Filter:`Filteren`,Someone:`Iemand`,banned:`geblokkeerd`,Ban:`Blokkeren`,Bans:`Blokkades`,"Minutes (0 = until lifted)":`Minuten (0 = tot opgeheven)`,Reason:`Reden`,"Whole site":`Hele site`,"No bans.":`Geen blokkades.`,automatic:`automatisch`,"whole site":`hele site`,hits:`pogingen`,Lift:`Opheffen`,Rules:`Regels`,"until lifted":`tot opgeheven`,"Ban an address by itself after too many failed logins":`Een adres zelf blokkeren na te veel mislukte logins`,"Failed logins":`Mislukte logins`,"Within minutes":`Binnen minuten`,"Ban for minutes (0 = until lifted)":`Blokkeren voor minuten (0 = tot opgeheven)`,"Keep the log (days)":`Log bewaren (dagen)`,"Notes about addresses":`Notities over adressen`,Group:`Groep`,Note:`Notitie`,Statistics:`Statistieken`,"compared with":`vergeleken met`,Visitors:`Bezoekers`,Visits:`Bezoeken`,"Page views":`Paginaweergaven`,"Average time":`Gemiddelde tijd`,"Bounce rate":`Bouncepercentage`,Channels:`Kanalen`,Sources:`Bronnen`,Countries:`Landen`,Devices:`Apparaten`,Browsers:`Browsers`,Systems:`Systemen`,Direct:`Direct`,"When people visit":`Wanneer mensen komen`,Programs:`Programma's`,Download:`Downloaden`,Open:`Openen`,"Created.":`Aangemaakt.`,"Deleted.":`Verwijderd.`,Language:`Taal`,"What this account sees":`Wat dit account ziet`,"What its rights give":`Wat zijn rechten geven`,"The simple manager":`De simpele manager`,"The whole manager":`De hele manager`,"Hi :name!":`Hoi :name!`,"What would you like to do today? Take your time and pick one.":`Wat wil je vandaag doen? Neem je tijd en kies er één.`,"Show the tour the next time this account opens the manager":`Toon de rondleiding de volgende keer dat dit account de manager opent`,"Hi :name! Welcome!":`Hoi :name! Welkom!`,"I will show you around in a few small steps. Looking around cannot break anything, and you can stop whenever you like: press the cross.":`Ik laat je in een paar kleine stapjes zien waar alles staat. Rondkijken kan niks stuk maken, en je kunt altijd stoppen: druk op het kruisje.`,"This is the menu":`Dit is het menu`,"Everything you can do lives here. Press a name and you are there.":`Alles wat je kunt doen staat hier. Druk op een naam en je bent er.`,"Your start page":`Je startpagina`,"Lost? Press Dashboard, at the top of the menu, and you are back here. Nice and calm.":`Even kwijt? Druk op Dashboard, bovenaan het menu, en je bent weer hier. Lekker rustig.`,"Write news":`Nieuws schrijven`,"Here you write articles and news for your website. Keep it as a draft until you are happy, then put it online.":`Hier schrijf je berichten en nieuws voor je website. Laat het een concept tot je tevreden bent, en zet het dan online.`,"Your photos":`Je foto's`,"All photos and files live here. Upload them once and use them in posts and pages.":`Alle foto's en bestanden staan hier. Upload ze één keer en gebruik ze in berichten en pagina's.`,"Your pages":`Je pagina's`,"Change the texts and photos of the pages of your website here.":`Pas hier de teksten en foto's van de pagina's van je website aan.`,"Changed your mind?":`Bedacht je het anders?`,"Every time you save a post or a page I keep the old version. You can always put an earlier one back.":`Elke keer dat je een bericht of pagina bewaart, bewaar ik de oude versie. Je kunt altijd een eerdere terugzetten.`,"Something went wrong?":`Gaat er iets mis?`,"A message tells you what. Read it, fix it and try again. Nothing is deleted without asking you first.":`Een melding vertelt wat. Lees hem, los het op en probeer het nog eens. Er wordt niks verwijderd zonder dat ik het eerst vraag.`,"Your own corner":`Je eigen hoekje`,"Here you choose your language and your colours, and change your password.":`Hier kies je je taal en je kleuren, en verander je je wachtwoord.`,"That is it!":`Dat was het!`,"Want to see this again? Press Show the tour in the menu. Have fun!":`Wil je dit nog eens zien? Druk op Rondleiding tonen in het menu. Veel plezier!`,"Stop the tour":`Rondleiding stoppen`,Tour:`Rondleiding`,"The tour":`De rondleiding`,"Show the tour":`Rondleiding tonen`,Done:`Klaar`},Yu={};function Xu(e){Yu=e.toLowerCase().startsWith(`nl`)?Ju:{}}function Q(e,t){let n=Yu[e]??e;return t?n.replace(/:(\w+)/g,(e,n)=>n in t?String(t[n]):e):n}var Zu=[`d`],Qu=L({__name:`Icon`,props:{name:{},big:{type:Boolean}},setup(e){let t={home:`M3 11l9-8 9 8v9a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z`,file:`M7 3h7l5 5v13H7zM14 3v5h5`,image:`M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M9 9h.01`,users:`M16 20v-1a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v1M10 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6M20 20v-1a3 3 0 0 0-2-2.8M16 5.2a3 3 0 0 1 0 5.6`,group:`M3 7h18v12H3zM8 7V5h8v2`,chart:`M4 20V10M10 20V4M16 20v-8M22 20H2`,shield:`M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z`,star:`M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z`,tag:`M3 12V4h8l10 10-8 8zM7.5 8h.01`,link:`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`,cog:`M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6M19 12a7 7 0 0 0-.1-1.2l2-1.5-2-3.4-2.3.9a7 7 0 0 0-2-1.2L14.2 3h-4l-.4 2.6a7 7 0 0 0-2 1.2l-2.3-.9-2 3.4 2 1.5A7 7 0 0 0 5 12c0 .4 0 .8.1 1.2l-2 1.5 2 3.4 2.3-.9a7 7 0 0 0 2 1.2l.4 2.6h4l.4-2.6a7 7 0 0 0 2-1.2l2.3.9 2-3.4-2-1.5c.1-.4.1-.8.1-1.2`};return(n,r)=>e.name&&t[e.name]?(H(),U(`svg`,{key:0,class:O(e.big?`h-8 w-8 shrink-0`:`h-4 w-4 shrink-0`),viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.8`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`},[G(`path`,{d:t[e.name]},null,8,Zu)],2)):J(``,!0)}}),$u=[`href`],ed=L({__name:`Link`,props:{href:{}},setup(e){function t(e,t){e.metaKey||e.ctrlKey||e.shiftKey||e.button!==0||(e.preventDefault(),U1(t))}return(n,r)=>(H(),U(`a`,{href:e.href,onClick:r[0]||=n=>t(n,e.href)},[Sa(n.$slots,`default`)],8,$u))}}),td={key:0,class:`mx-auto max-w-3xl pt-4`},nd={class:`font-display text-3xl font-bold`},rd={class:`mb-8 mt-2 text-lg text-muted`},id={class:`grid gap-4 sm:grid-cols-2`},ad={class:`text-xl font-bold`},od={key:0,class:`text-muted`},sd={class:`font-display mb-6 text-2xl font-bold`},cd={class:`mb-4 text-muted`},ld={class:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`},ud=L({__name:`Dashboard`,props:{navigation:{}},setup(e){function t(e){return e.icon?e.icon:e.href.endsWith(`/media`)?`image`:e.href.endsWith(`/posts`)||e.href.endsWith(`/pages`)?`file`:`star`}let n=X.view===`simple`,r=(X.user?.name??``).split(` `)[0];return(i,a)=>n?(H(),U(`div`,td,[G(`h1`,nd,k(P(Q)(`Hi :name!`,{name:P(r)})),1),G(`p`,rd,k(P(Q)(`What would you like to do today? Take your time and pick one.`)),1),G(`div`,id,[(H(!0),U(B,null,R(e.navigation,e=>(H(),W(ed,{key:e.href,href:e.href,class:`m-card m-tile`},{default:F(()=>[K(Qu,{name:t(e),big:``,class:`text-brand`},null,8,[`name`]),G(`span`,ad,k(P(Q)(e.label)),1),e.hint?(H(),U(`span`,od,k(P(Q)(e.hint)),1)):J(``,!0)]),_:2},1032,[`href`]))),128))])])):(H(),U(B,{key:1},[G(`h1`,sd,k(P(Q)(`Dashboard`)),1),G(`p`,cd,k(P(X).user?.name),1),G(`div`,ld,[(H(!0),U(B,null,R(e.navigation,e=>(H(),W(ed,{key:e.href,href:e.href,class:`m-card block p-5 font-semibold transition hover:border-brand`},{default:F(()=>[q(k(P(Q)(e.label)),1)]),_:2},1032,[`href`]))),128))])],64))}}),dd={class:`m-card max-w-xl p-6`},fd={class:`text-sm`},pd=L({__name:`Fallback`,setup(e){return(e,t)=>(H(),U(`div`,dd,[G(`p`,fd,k(P(Q)(`This page has no screen in the manager yet.`)),1),K(ed,{href:P(X).base,class:`m-btn m-btn-secondary mt-4`},{default:F(()=>[q(k(P(Q)(`Go to the dashboard`)),1)]),_:1},8,[`href`])]))}}),md={class:`grid min-h-screen place-items-center px-4`},hd=[`src`],gd={class:`font-display text-2xl font-bold`},_d={class:`mt-1 text-sm text-muted`},vd={class:`mt-6`},yd={for:`email`,class:`m-label`},bd={key:0,class:`m-error`},xd={class:`mt-4`},Sd={for:`password`,class:`m-label`},Cd={key:0,class:`m-error`},wd={key:0,class:`mt-4`},Td={key:0,class:`m-error`},Ed={key:1,class:`mt-4`},Dd=[`for`],Od=[`id`,`onUpdate:modelValue`,`type`,`autocomplete`,`required`],kd={key:0,class:`m-error`},Ad={class:`mt-4 flex items-center gap-2 text-sm text-muted`},jd=[`disabled`],Md=L({__name:`Login`,setup(e){let t=X.login_fields??[],n=qu({email:``,password:``,remember:!1,...Object.fromEntries(t.map(e=>[e.name,``]))}),r=N(null),i;ia(()=>{let e=t.find(e=>e.type===`turnstile`);if(!e)return;let a=()=>{i=window.turnstile.render(r.value,{sitekey:e.site_key,callback:t=>n.values[e.name]=t})};if(window.turnstile)a();else{let e=document.createElement(`script`);e.src=`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`,e.async=!0,e.onload=a,document.head.appendChild(e)}});async function a(){let e=await n.send(`post`,X.base+`/login`);e?window.location.assign(e.redirect):(n.values.password=``,i!==void 0&&window.turnstile.reset(i),t.filter(e=>e.type===`turnstile`).forEach(e=>n.values[e.name]=``))}return(e,i)=>(H(),U(`div`,md,[G(`form`,{class:`m-card w-full max-w-sm p-7`,onSubmit:Tu(a,[`prevent`])},[P(X).logo?(H(),U(`img`,{key:0,src:P(X).logo,alt:``,class:`mb-4 h-9 w-auto`},null,8,hd)):J(``,!0),G(`h1`,gd,k(P(X).name),1),G(`p`,_d,k(P(Q)(`Log in to manage the site.`)),1),G(`div`,vd,[G(`label`,yd,k(P(Q)(`Email`)),1),I(G(`input`,{id:`email`,"onUpdate:modelValue":i[0]||=e=>P(n).values.email=e,type:`email`,autocomplete:`username`,required:``,autofocus:``,class:`m-input`},null,512),[[Y,P(n).values.email]]),P(n).errors.email?(H(),U(`p`,bd,k(P(n).errors.email),1)):J(``,!0)]),G(`div`,xd,[G(`label`,Sd,k(P(Q)(`Password`)),1),I(G(`input`,{id:`password`,"onUpdate:modelValue":i[1]||=e=>P(n).values.password=e,type:`password`,autocomplete:`current-password`,required:``,class:`m-input`},null,512),[[Y,P(n).values.password]]),P(n).errors.password?(H(),U(`p`,Cd,k(P(n).errors.password),1)):J(``,!0)]),(H(!0),U(B,null,R(P(t),e=>(H(),U(B,{key:e.name},[e.type===`turnstile`?(H(),U(`div`,wd,[G(`div`,{ref_for:!0,ref:e=>r.value=e},null,512),P(n).errors[e.name]?(H(),U(`p`,Td,k(P(n).errors[e.name]),1)):J(``,!0)])):(H(),U(`div`,Ed,[G(`label`,{for:`login-`+e.name,class:`m-label`},k(P(Q)(e.label??e.name)),9,Dd),I(G(`input`,{id:`login-`+e.name,"onUpdate:modelValue":t=>P(n).values[e.name]=t,type:e.type===`password`||e.type===`number`?e.type:`text`,autocomplete:e.autocomplete,required:e.required,class:`m-input`},null,8,Od),[[yu,P(n).values[e.name]]]),P(n).errors[e.name]?(H(),U(`p`,kd,k(P(n).errors[e.name]),1)):J(``,!0)]))],64))),128)),G(`label`,Ad,[I(G(`input`,{"onUpdate:modelValue":i[2]||=e=>P(n).values.remember=e,type:`checkbox`},null,512),[[du,P(n).values.remember]]),q(` `+k(P(Q)(`Keep me logged in`)),1)]),G(`button`,{type:`submit`,class:`m-btn m-btn-primary mt-6 w-full justify-center`,disabled:P(n).busy},k(P(n).busy?P(Q)(`Logging in…`):P(Q)(`Log in`)),9,jd)],32)]))}}),Nd={class:`m-card max-h-[85vh] w-full max-w-3xl overflow-y-auto p-5`,role:`dialog`,"aria-modal":`true`},Pd={class:`mb-4 flex items-center justify-between`},Fd={class:`font-display text-lg font-bold`},Id={key:0,class:`text-sm text-muted`},Ld={key:1,class:`text-sm text-muted`},Rd={key:2,class:`grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4`},zd=[`onClick`],Bd=[`src`,`alt`],Vd={class:`block truncate px-2 py-1 text-xs`},Hd=L({__name:`MediaPicker`,emits:[`pick`,`close`],setup(e,{emit:t}){let n=t,r=N([]),i=N(!0);return ia(async()=>{try{r.value=(await Z.get(`${X.base}/media/items`)).items.filter(e=>e.is_image)}finally{i.value=!1}}),(e,t)=>(H(),U(`div`,{class:`fixed inset-0 z-50 grid place-items-center bg-black/60 p-4`,onClick:t[1]||=Tu(e=>n(`close`),[`self`])},[G(`div`,Nd,[G(`div`,Pd,[G(`h2`,Fd,k(P(Q)(`Choose an image`)),1),G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:t[0]||=e=>n(`close`)},k(P(Q)(`Cancel`)),1)]),i.value?(H(),U(`p`,Id,k(P(Q)(`Loading…`)),1)):r.value.length?(H(),U(`div`,Rd,[(H(!0),U(B,null,R(r.value,e=>(H(),U(`button`,{key:e.id,type:`button`,class:`overflow-hidden rounded-lg border border-line text-left hover:border-brand`,onClick:t=>n(`pick`,e.url,e)},[G(`img`,{src:e.url,alt:e.name,loading:`lazy`,class:`aspect-square w-full object-cover`},null,8,Bd),G(`span`,Vd,k(e.name),1)],8,zd))),128))])):(H(),U(`p`,Ld,k(P(Q)(`No images yet.`)),1))])]))}}),Ud=[`aria-label`],Wd=[`disabled`,`title`],Gd=[`disabled`,`title`],Kd=[`disabled`,`title`],qd=[`disabled`,`title`],Jd=[`disabled`,`title`],Yd=[`disabled`,`title`],Xd=[`disabled`],Zd={class:`ml-auto flex gap-1`},Qd=[`id`,`value`,`rows`,`required`,`maxlength`],$d={key:0,class:`m-input min-h-40 overflow-auto`},ef={key:0,class:`text-sm text-muted`},tf=[`innerHTML`],nf=L({__name:`MarkdownEditor`,props:{modelValue:{},id:{},rows:{},required:{type:Boolean},maxlength:{}},emits:[`update:modelValue`],setup(e,{emit:t}){let n=e,r=t,i=N(null),a=N(`write`),o=N(``),s=N(!1),c=N(!1),l=X.permissions.includes(`media.view`);function u(e,t=e,a=``){let o=i.value,s=o.selectionStart,c=o.selectionEnd,l=n.modelValue.slice(s,c)||a,u=n.modelValue.slice(0,s)+e+l+t+n.modelValue.slice(c);r(`update:modelValue`,u),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+e.length,s+e.length+l.length)})}function d(e){let t=i.value,a=n.modelValue.lastIndexOf(` +`,t.selectionStart-1)+1,o=t.selectionEnd,s=n.modelValue.slice(a,o).split(` +`).map(t=>e+t).join(` +`);r(`update:modelValue`,n.modelValue.slice(0,a)+s+n.modelValue.slice(o)),requestAnimationFrame(()=>t.focus())}function f(e,t){c.value=!1;let a=(t?.alt||t?.name||``).replace(/[[\]]/g,``),o=i.value,s=o.selectionStart,l=`![${a}](${e})`;r(`update:modelValue`,n.modelValue.slice(0,s)+l+n.modelValue.slice(o.selectionEnd)),requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(s+l.length,s+l.length)})}async function p(e){if(a.value=e,e===`preview`){s.value=!0;try{o.value=(await Z.post(`${X.base}/markdown`,{text:n.modelValue})).html}finally{s.value=!1}}}return(t,n)=>(H(),U(`div`,null,[G(`div`,{class:`mb-2 flex flex-wrap items-center gap-1`,role:`toolbar`,"aria-label":P(Q)(`Formatting`)},[G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 font-bold`,disabled:a.value===`preview`,title:P(Q)(`Bold`),onClick:n[0]||=e=>u(`**`,`**`,P(Q)(`bold`))},`B`,8,Wd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1 italic`,disabled:a.value===`preview`,title:P(Q)(`Italic`),onClick:n[1]||=e=>u(`*`,`*`,P(Q)(`italic`))},`I`,8,Gd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Heading`),onClick:n[2]||=e=>d(`## `)},`H`,8,Kd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`List`),onClick:n[3]||=e=>d(`- `)},`•`,8,qd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Quote`),onClick:n[4]||=e=>d(`> `)},`”`,8,Jd),G(`button`,{type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,title:P(Q)(`Link`),onClick:n[5]||=e=>u(`[`,`](https://)`,P(Q)(`text`))},`🔗`,8,Yd),P(l)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary !px-2 !py-1`,disabled:a.value===`preview`,onClick:n[6]||=e=>c.value=!0},k(P(Q)(`Photo`)),9,Xd)):J(``,!0),G(`span`,Zd,[G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`write`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[7]||=e=>p(`write`)},k(P(Q)(`Write`)),3),G(`button`,{type:`button`,class:O([`m-btn !px-3 !py-1`,a.value===`preview`?`m-btn-primary`:`m-btn-secondary`]),onClick:n[8]||=e=>p(`preview`)},k(P(Q)(`Preview`)),3)])],8,Ud),I(G(`textarea`,{id:e.id,ref_key:`area`,ref:i,value:e.modelValue,rows:e.rows??14,required:e.required,maxlength:e.maxlength,class:`m-input font-mono`,onInput:n[9]||=e=>r(`update:modelValue`,e.target.value)},null,40,Qd),[[$c,a.value===`write`]]),a.value===`preview`?(H(),U(`div`,$d,[s.value?(H(),U(`p`,ef,k(P(Q)(`Loading…`)),1)):(H(),U(`div`,{key:1,class:`m-prose`,innerHTML:o.value},null,8,tf))])):J(``,!0),c.value?(H(),W(Hd,{key:1,onPick:f,onClose:n[10]||=e=>c.value=!1})):J(``,!0)]))}}),rf={class:`m-card mt-6 max-w-3xl p-5`},af={class:`font-display text-lg font-bold`},of={key:0,class:`mt-2 text-sm text-muted`},sf={key:1,class:`mt-2 text-sm text-muted`},cf={key:2,class:`mt-3 divide-y divide-line`},lf={class:`flex flex-wrap items-center justify-between gap-2`},uf=[`aria-expanded`,`onClick`],df={class:`font-semibold`},ff={key:0,class:`text-muted`},pf={key:1,class:`m-badge ml-2`},mf={class:`block text-xs text-muted`},hf=[`onClick`],gf={key:0,class:`mt-2 space-y-2 text-sm`},_f={class:`text-xs font-semibold uppercase tracking-wide text-muted`},vf={class:`whitespace-pre-wrap break-words`},yf=L({__name:`RevisionsPanel`,props:{type:{},id:{}},setup(e){let t=e,n=N([]),r=N(!1),i=N(null),a=N(!0),o=`${X.base}/revisions/${t.type}/${t.id}`;ia(async()=>{try{let e=await Z.get(o);n.value=e.revisions,r.value=e.can_restore}finally{a.value=!1}});async function s(e){window.confirm(Q(`Put this version back? The text now is kept in the history.`))&&(await Z.post(`${o}/${e.id}/restore`),B1(Q(`The earlier version is back.`)),await W1())}let c=e=>new Date(e).toLocaleString(X.locale||void 0);return(e,t)=>(H(),U(`section`,rf,[G(`h2`,af,k(P(Q)(`History`)),1),a.value?(H(),U(`p`,of,k(P(Q)(`Loading…`)),1)):n.value.length?(H(),U(`ul`,cf,[(H(!0),U(B,null,R(n.value,e=>(H(),U(`li`,{key:e.id,class:`py-3`},[G(`div`,lf,[G(`button`,{type:`button`,class:`text-left text-sm`,"aria-expanded":i.value===e.id,onClick:t=>i.value=i.value===e.id?null:e.id},[G(`span`,df,k(c(e.created_at)),1),e.user?(H(),U(`span`,ff,` · `+k(e.user),1)):J(``,!0),e.current?(H(),U(`span`,pf,k(P(Q)(`Now`)),1)):J(``,!0),G(`span`,mf,k(e.changed.join(`, `)),1)],8,uf),r.value&&!e.current?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>s(e)},k(P(Q)(`Put back`)),9,hf)):J(``,!0)]),i.value===e.id?(H(),U(`dl`,gf,[(H(!0),U(B,null,R(e.values,(e,t)=>(H(),U(`div`,{key:t},[G(`dt`,_f,k(t),1),G(`dd`,vf,k(e),1)]))),128))])):J(``,!0)]))),128))])):(H(),U(`p`,sf,k(P(Q)(`Nothing here yet.`)),1))]))}}),bf={class:`mb-6 flex items-center justify-between gap-3`},xf={class:`font-display text-2xl font-bold`},Sf={for:`title`,class:`m-label`},Cf={key:0,class:`m-error`},wf={class:`grid gap-5 sm:grid-cols-2`},Tf={for:`slug`,class:`m-label`},Ef={key:0,class:`m-error`},Df={for:`category`,class:`m-label`},Of={id:`categories`},kf=[`value`],Af={for:`excerpt`,class:`m-label`},jf={key:0,class:`m-error`},Mf={for:`body`,class:`m-label`},Nf={key:0,class:`m-error`},Pf={class:`grid gap-5 sm:grid-cols-2`},Ff={for:`cover`,class:`m-label`},If={class:`flex gap-2`},Lf={for:`tags`,class:`m-label`},Rf={id:`known-tags`},zf=[`value`],Bf={class:`flex flex-wrap items-center gap-6`},Vf={class:`flex items-center gap-2 text-sm`},Hf={key:0,class:`flex items-center gap-2 text-sm`},Uf={key:1},Wf={for:`at`,class:`m-label`},Gf=[`disabled`],Kf=L({__name:`PostForm`,props:{post:{},categories:{},known_tags:{}},setup(e){let t=e.post,n=qu({title:t?.title??``,slug:t?.slug??``,excerpt:t?.excerpt??``,body:t?.body??``,cover_image:t?.cover_image??``,category:t?.category??``,tags:t?.tags??[],is_featured:t?.is_featured??!1,is_published:t?.is_published??!1,published_at:t?.published_at??``}),r=N(!1),i=(t?.tags??[]).join(`, `);async function a(){n.values.tags=i.split(`,`).map(e=>e.trim()).filter(Boolean),(t?await n.send(`put`,`${X.base}/posts/${t.id}`):await n.send(`post`,`${X.base}/posts`))&&(B1(Q(t?`Saved.`:`Created.`)),U1(`${X.base}/posts`))}return(o,s)=>(H(),U(B,null,[G(`div`,bf,[G(`h1`,xf,k(P(t)?P(t).title:P(Q)(`New post`)),1),K(ed,{href:P(X).base+`/posts`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Back`)),1)]),_:1},8,[`href`])]),G(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Tu(a,[`prevent`])},[G(`div`,null,[G(`label`,Sf,k(P(Q)(`Title`)),1),I(G(`input`,{id:`title`,"onUpdate:modelValue":s[0]||=e=>P(n).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.title]]),P(n).errors.title?(H(),U(`p`,Cf,k(P(n).errors.title),1)):J(``,!0)]),G(`div`,wf,[G(`div`,null,[G(`label`,Tf,k(P(Q)(`Address (slug)`)),1),I(G(`input`,{id:`slug`,"onUpdate:modelValue":s[1]||=e=>P(n).values.slug=e,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.slug]]),P(n).errors.slug?(H(),U(`p`,Ef,k(P(n).errors.slug),1)):J(``,!0)]),G(`div`,null,[G(`label`,Df,k(P(Q)(`Category`)),1),I(G(`input`,{id:`category`,"onUpdate:modelValue":s[2]||=e=>P(n).values.category=e,list:`categories`,maxlength:`60`,class:`m-input`},null,512),[[Y,P(n).values.category]]),G(`datalist`,Of,[(H(!0),U(B,null,R(e.categories,e=>(H(),U(`option`,{key:e,value:e},null,8,kf))),128))])])]),G(`div`,null,[G(`label`,Af,k(P(Q)(`Summary`)),1),I(G(`textarea`,{id:`excerpt`,"onUpdate:modelValue":s[3]||=e=>P(n).values.excerpt=e,rows:`2`,maxlength:`500`,class:`m-input`},null,512),[[Y,P(n).values.excerpt]]),P(n).errors.excerpt?(H(),U(`p`,jf,k(P(n).errors.excerpt),1)):J(``,!0)]),G(`div`,null,[G(`label`,Mf,k(P(Q)(`Text (Markdown)`)),1),K(nf,{id:`body`,modelValue:P(n).values.body,"onUpdate:modelValue":s[4]||=e=>P(n).values.body=e,required:``},null,8,[`modelValue`]),P(n).errors.body?(H(),U(`p`,Nf,k(P(n).errors.body),1)):J(``,!0)]),G(`div`,Pf,[G(`div`,null,[G(`label`,Ff,k(P(Q)(`Cover image`)),1),G(`div`,If,[I(G(`input`,{id:`cover`,"onUpdate:modelValue":s[5]||=e=>P(n).values.cover_image=e,maxlength:`2048`,class:`m-input`},null,512),[[Y,P(n).values.cover_image]]),P(X).permissions.includes(`media.view`)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary shrink-0`,onClick:s[6]||=e=>r.value=!0},k(P(Q)(`Choose`)),1)):J(``,!0)])]),G(`div`,null,[G(`label`,Lf,k(P(Q)(`Tags (comma separated)`)),1),I(G(`input`,{id:`tags`,"onUpdate:modelValue":s[7]||=e=>M(i)?i.value=e:i=e,list:`known-tags`,class:`m-input`},null,512),[[Y,P(i)]]),G(`datalist`,Rf,[(H(!0),U(B,null,R(e.known_tags,e=>(H(),U(`option`,{key:e,value:e},null,8,zf))),128))])])]),G(`div`,Bf,[G(`label`,Vf,[I(G(`input`,{"onUpdate:modelValue":s[8]||=e=>P(n).values.is_featured=e,type:`checkbox`},null,512),[[du,P(n).values.is_featured]]),q(` `+k(P(Q)(`Featured`)),1)]),P(X).permissions.includes(`posts.publish`)?(H(),U(`label`,Hf,[I(G(`input`,{"onUpdate:modelValue":s[9]||=e=>P(n).values.is_published=e,type:`checkbox`},null,512),[[du,P(n).values.is_published]]),q(` `+k(P(Q)(`Publish`)),1)])):J(``,!0),P(n).values.is_published?(H(),U(`div`,Uf,[G(`label`,Wf,k(P(Q)(`Publish at`)),1),I(G(`input`,{id:`at`,"onUpdate:modelValue":s[10]||=e=>P(n).values.published_at=e,type:`datetime-local`,class:`m-input`},null,512),[[Y,P(n).values.published_at]])])):J(``,!0)]),G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(n).busy},k(P(n).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,Gf)],32),P(t)&&P(X).permissions.includes(`revisions.view`)?(H(),W(yf,{key:0,type:`posts`,id:P(t).id},null,8,[`id`])):J(``,!0),r.value?(H(),W(Hd,{key:1,onPick:s[11]||=e=>{P(n).values.cover_image=e,r.value=!1},onClose:s[12]||=e=>r.value=!1})):J(``,!0)],64))}}),qf={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},Jf={class:`font-display text-2xl font-bold`},Yf={key:0,class:`m-card p-5 text-sm text-muted`},Xf={key:1,class:`m-card divide-y divide-line`},Zf={class:`min-w-0`},Qf={class:`truncate font-semibold`},$f={class:`mt-1 flex items-center gap-2 text-xs text-muted`},ep={class:`m-badge`},tp={key:0},np={class:`flex gap-2`},rp=[`onClick`],ip=[`onClick`],ap=L({__name:`PostsIndex`,props:{posts:{}},setup(e){let t={draft:`Draft`,scheduled:`Scheduled`,published:`Published`};async function n(e){await Z.put(`${X.base}/posts/${e.id}/online`,{online:e.status!==`published`}),await W1()}async function r(e){window.confirm(Q(`Are you sure?`))&&(await Z.delete(`${X.base}/posts/${e.id}`),B1(Q(`Deleted.`)),await W1())}return(i,a)=>(H(),U(B,null,[G(`div`,qf,[G(`h1`,Jf,k(P(Q)(`Posts`)),1),P(X).permissions.includes(`posts.write`)?(H(),W(ed,{key:0,href:P(X).base+`/posts/create`,class:`m-btn m-btn-primary`},{default:F(()=>[q(k(P(Q)(`New post`)),1)]),_:1},8,[`href`])):J(``,!0)]),e.posts.length?(H(),U(`ul`,Xf,[(H(!0),U(B,null,R(e.posts,e=>(H(),U(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[G(`div`,Zf,[G(`p`,Qf,k(e.title),1),G(`p`,$f,[G(`span`,ep,k(P(Q)(t[e.status])),1),e.category?(H(),U(`span`,tp,k(e.category),1)):J(``,!0)])]),G(`div`,np,[P(X).permissions.includes(`posts.publish`)&&e.can_change?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>n(e)},k(e.status===`published`?P(Q)(`Take offline`):P(Q)(`Put online`)),9,rp)):J(``,!0),e.can_change?(H(),W(ed,{key:1,href:`${P(X).base}/posts/${e.id}/edit`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Edit`)),1)]),_:1},8,[`href`])):J(``,!0),e.can_delete?(H(),U(`button`,{key:2,type:`button`,class:`m-btn m-btn-danger`,onClick:t=>r(e)},k(P(Q)(`Delete`)),9,ip)):J(``,!0)])]))),128))])):(H(),U(`p`,Yf,k(P(Q)(`No posts yet.`)),1))],64))}}),op=[`src`],sp=L({__name:`Mascot`,props:{name:{},flip:{type:Boolean},size:{}},setup(e){return(t,n)=>(H(),U(`img`,{src:P(X).mascot+e.name,alt:``,class:O([`m-mascot select-none object-contain`,e.flip?`-scale-x-100`:``]),style:_e({width:(e.size??112)+`px`,height:(e.size??112)+`px`}),draggable:`false`},null,14,op))}}),cp={class:`font-display mb-6 text-2xl font-bold`},lp={for:`name`,class:`m-label`},up={key:0,class:`m-error`},dp={class:`m-label`},fp={class:`text-sm`},pp={class:`m-label`},mp={class:`flex flex-wrap gap-1.5`},hp={key:0,class:`m-badge`},gp={key:0,class:`m-badge`},_p={key:0,class:`rounded-lg border border-line p-4`},vp={class:`px-1.5 text-sm font-semibold`},yp={class:`mt-1 flex flex-wrap gap-3`},bp=[`onUpdate:modelValue`,`value`],xp={class:`flex`},Sp={key:0,class:`m-error`},Cp={key:1,class:`rounded-lg border border-line p-4`},wp={class:`px-1.5 text-sm font-semibold`},Tp={class:`mt-1 flex flex-wrap gap-3`},Ep=[`onUpdate:modelValue`,`value`],Dp={key:0,class:`m-error`},Op={class:`space-y-4 rounded-lg border border-line p-4`},kp={class:`px-1.5 text-sm font-semibold`},Ap={class:`m-help`},jp={for:`current_password`,class:`m-label`},Mp={key:0,class:`m-error`},Np={for:`password`,class:`m-label`},Pp={class:`m-help`},Fp={key:0,class:`m-error`},Ip={for:`password_confirmation`,class:`m-label`},Lp={key:2,class:`flex items-center gap-3 rounded-lg border border-line p-4`},Rp={class:`text-sm font-semibold`},zp=[`disabled`],Bp=L({__name:`Profile`,props:{profile:{}},setup(e){let t=e,n=qu({name:t.profile.name,theme:t.profile.theme,locale:t.profile.locale,current_password:``,password:``,password_confirmation:``});async function r(){await n.send(`put`,X.base+`/profile`)&&(B1(Q(`Saved.`)),(n.values.theme!==X.theme||n.values.locale!==X.locale)&&window.location.reload(),n.values.current_password=n.values.password=n.values.password_confirmation=``)}return(t,i)=>(H(),U(B,null,[G(`h1`,cp,k(P(Q)(`My account`)),1),G(`form`,{class:`m-card max-w-xl space-y-5 p-5`,onSubmit:Tu(r,[`prevent`])},[G(`div`,null,[G(`label`,lp,k(P(Q)(`Name`)),1),I(G(`input`,{id:`name`,"onUpdate:modelValue":i[0]||=e=>P(n).values.name=e,type:`text`,required:``,maxlength:`255`,class:`m-input`,autocomplete:`name`},null,512),[[Y,P(n).values.name]]),P(n).errors.name?(H(),U(`p`,up,k(P(n).errors.name),1)):J(``,!0)]),G(`div`,null,[G(`span`,dp,k(P(Q)(`Email address`)),1),G(`p`,fp,k(e.profile.email),1)]),G(`div`,null,[G(`span`,pp,k(P(Q)(`What you may do`)),1),G(`p`,mp,[e.profile.is_super_admin?(H(),U(`span`,hp,k(P(Q)(`Super admin: everything`)),1)):(H(),U(B,{key:1},[(H(!0),U(B,null,R(e.profile.groups,e=>(H(),U(`span`,{key:e,class:`m-badge`},k(e),1))),128)),e.profile.groups.length?J(``,!0):(H(),U(`span`,gp,k(P(Q)(`Not in a group yet`)),1))],64))])]),e.profile.themes.length?(H(),U(`fieldset`,_p,[G(`legend`,vp,k(P(Q)(`Look`)),1),G(`div`,yp,[(H(!0),U(B,null,R(e.profile.themes,e=>(H(),U(`label`,{key:e.key,class:O([`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm`,P(n).values.theme===e.key?`border-brand`:`border-line`])},[I(G(`input`,{"onUpdate:modelValue":e=>P(n).values.theme=e,type:`radio`,name:`theme`,value:e.key,class:`sr-only`},null,8,bp),[[pu,P(n).values.theme]]),G(`span`,xp,[(H(),U(B,null,R([`ink`,`panel`,`brand`],t=>G(`span`,{key:t,class:`h-4 w-4 border border-line`,style:_e({background:e.colors[t]})},null,4)),64))]),q(` `+k(e.label),1)],2))),128))]),P(n).errors.theme?(H(),U(`p`,Sp,k(P(n).errors.theme),1)):J(``,!0)])):J(``,!0),e.profile.locales.length?(H(),U(`fieldset`,Cp,[G(`legend`,wp,k(P(Q)(`Language`)),1),G(`div`,Tp,[(H(!0),U(B,null,R(e.profile.locales,e=>(H(),U(`label`,{key:e,class:O([`flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm`,P(n).values.locale===e?`border-brand`:`border-line`])},[I(G(`input`,{"onUpdate:modelValue":e=>P(n).values.locale=e,type:`radio`,name:`locale`,value:e,class:`sr-only`},null,8,Ep),[[pu,P(n).values.locale]]),q(` `+k(e===`nl`?`Nederlands`:`English`),1)],2))),128))]),P(n).errors.locale?(H(),U(`p`,Dp,k(P(n).errors.locale),1)):J(``,!0)])):J(``,!0),G(`fieldset`,Op,[G(`legend`,kp,k(P(Q)(`New password`)),1),G(`p`,Ap,k(P(Q)(`Leave empty to keep the password you have.`)),1),G(`div`,null,[G(`label`,jp,k(P(Q)(`Current password`)),1),I(G(`input`,{id:`current_password`,"onUpdate:modelValue":i[1]||=e=>P(n).values.current_password=e,type:`password`,class:`m-input`,autocomplete:`current-password`},null,512),[[Y,P(n).values.current_password]]),P(n).errors.current_password?(H(),U(`p`,Mp,k(P(n).errors.current_password),1)):J(``,!0)]),G(`div`,null,[G(`label`,Np,k(P(Q)(`New password`)),1),I(G(`input`,{id:`password`,"onUpdate:modelValue":i[2]||=e=>P(n).values.password=e,type:`password`,minlength:`12`,maxlength:`200`,class:`m-input`,autocomplete:`new-password`},null,512),[[Y,P(n).values.password]]),G(`p`,Pp,k(P(Q)(`At least 12 characters.`)),1),P(n).errors.password?(H(),U(`p`,Fp,k(P(n).errors.password),1)):J(``,!0)]),G(`div`,null,[G(`label`,Ip,k(P(Q)(`New password, once more`)),1),I(G(`input`,{id:`password_confirmation`,"onUpdate:modelValue":i[3]||=e=>P(n).values.password_confirmation=e,type:`password`,maxlength:`200`,class:`m-input`,autocomplete:`new-password`},null,512),[[Y,P(n).values.password_confirmation]])])]),P(X).tutorial_state?(H(),U(`div`,Lp,[K(sp,{name:`peek`,size:64}),G(`div`,null,[G(`p`,Rp,k(P(Q)(`The tour`)),1),G(`button`,{type:`button`,class:`text-sm text-brand underline`,onClick:i[4]||=e=>P($).tour=!0},k(P(Q)(`Show the tour`)),1)])])):J(``,!0),G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(n).busy},k(P(n).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,zp)],32)],64))}}),Vp={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},Hp={class:`font-display text-2xl font-bold`},Up={class:`grid gap-4 sm:grid-cols-2`},Wp={class:`m-label`,for:`a-name`},Gp={key:0,class:`m-error`},Kp={class:`m-label`,for:`a-email`},qp={key:0,class:`m-error`},Jp={class:`m-label`,for:`a-pass`},Yp=[`required`],Xp={class:`m-help`},Zp={key:0,class:`m-error`},Qp={key:0},$p={class:`m-label`},em=[`value`,`disabled`],tm={key:1},nm={class:`m-label`},rm={class:`flex items-center gap-2 py-0.5 text-sm`},im={class:`flex items-center gap-2 py-0.5 text-sm`},am={class:`flex items-center gap-2 py-0.5 text-sm`},om={class:`flex items-center gap-2 text-sm`},sm={class:`flex gap-2`},cm=[`disabled`],lm={class:`m-card divide-y divide-line`},um={class:`min-w-0`},dm={class:`truncate font-semibold`},fm={key:0,class:`text-xs font-normal text-muted`},pm={class:`truncate text-xs text-muted`},mm={class:`mt-1 flex flex-wrap gap-1`},hm={key:0,class:`m-badge`},gm={class:`flex gap-2`},_m=[`onClick`],vm=[`onClick`],ym=L({__name:`AccountsIndex`,props:{accounts:{},groups:{}},setup(e){let t=N(null),n=qu({name:``,email:``,password:``,groups:[],view:``,tutorial:!1});function r(e){t.value=e,n.errors={},n.values.name=e===`new`?``:e.name,n.values.email=e===`new`?``:e.email,n.values.password=``,n.values.groups=e===`new`?[]:e.groups.map(e=>e.id),n.values.view=e===`new`?``:e.view??``,n.values.tutorial=e!==`new`&&e.tutorial===`pending`}async function i(){let e=t.value;(e===`new`?await n.send(`post`,`${X.base}/accounts`):await n.send(`put`,`${X.base}/accounts/${e.id}`))&&(B1(Q(`Saved.`)),t.value=null,await W1())}async function a(e){window.confirm(Q(`Are you sure?`))&&(await Z.delete(`${X.base}/accounts/${e.id}`),B1(Q(`Deleted.`)),await W1())}return(o,s)=>(H(),U(B,null,[G(`div`,Vp,[G(`h1`,Hp,k(P(Q)(`Accounts`)),1),G(`button`,{type:`button`,class:`m-btn m-btn-primary`,onClick:s[0]||=e=>r(`new`)},k(P(Q)(`New account`)),1)]),t.value?(H(),U(`form`,{key:0,class:`m-card mb-6 max-w-2xl space-y-4 p-5`,onSubmit:Tu(i,[`prevent`])},[G(`div`,Up,[G(`div`,null,[G(`label`,Wp,k(P(Q)(`Name`)),1),I(G(`input`,{id:`a-name`,"onUpdate:modelValue":s[1]||=e=>P(n).values.name=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.name]]),P(n).errors.name?(H(),U(`p`,Gp,k(P(n).errors.name),1)):J(``,!0)]),G(`div`,null,[G(`label`,Kp,k(P(Q)(`Email address`)),1),I(G(`input`,{id:`a-email`,"onUpdate:modelValue":s[2]||=e=>P(n).values.email=e,type:`email`,required:``,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.email]]),P(n).errors.email?(H(),U(`p`,qp,k(P(n).errors.email),1)):J(``,!0)])]),G(`div`,null,[G(`label`,Jp,k(P(Q)(`Password`)),1),I(G(`input`,{id:`a-pass`,"onUpdate:modelValue":s[3]||=e=>P(n).values.password=e,type:`password`,minlength:`12`,maxlength:`200`,required:t.value===`new`,class:`m-input`,autocomplete:`new-password`},null,8,Yp),[[Y,P(n).values.password]]),G(`p`,Xp,k(t.value===`new`?P(Q)(`At least 12 characters.`):P(Q)(`Leave empty to keep the password you have.`)),1),P(n).errors.password?(H(),U(`p`,Zp,k(P(n).errors.password),1)):J(``,!0)]),e.groups.length?(H(),U(`fieldset`,Qp,[G(`legend`,$p,k(P(Q)(`Groups`)),1),(H(!0),U(B,null,R(e.groups,e=>(H(),U(`label`,{key:e.id,class:O([`flex items-center gap-2 py-0.5 text-sm`,e.can_give?``:`opacity-50`])},[I(G(`input`,{"onUpdate:modelValue":s[4]||=e=>P(n).values.groups=e,type:`checkbox`,value:e.id,disabled:!e.can_give},null,8,em),[[du,P(n).values.groups]]),q(` `+k(e.name),1)],2))),128))])):J(``,!0),P(X).simple_view?(H(),U(`fieldset`,tm,[G(`legend`,nm,k(P(Q)(`What this account sees`)),1),G(`label`,rm,[I(G(`input`,{"onUpdate:modelValue":s[5]||=e=>P(n).values.view=e,type:`radio`,value:``},null,512),[[pu,P(n).values.view]]),q(` `+k(P(Q)(`What its rights give`)),1)]),G(`label`,im,[I(G(`input`,{"onUpdate:modelValue":s[6]||=e=>P(n).values.view=e,type:`radio`,value:`simple`},null,512),[[pu,P(n).values.view]]),q(` `+k(P(Q)(`The simple manager`)),1)]),G(`label`,am,[I(G(`input`,{"onUpdate:modelValue":s[7]||=e=>P(n).values.view=e,type:`radio`,value:`full`},null,512),[[pu,P(n).values.view]]),q(` `+k(P(Q)(`The whole manager`)),1)])])):J(``,!0),G(`label`,om,[I(G(`input`,{"onUpdate:modelValue":s[8]||=e=>P(n).values.tutorial=e,type:`checkbox`},null,512),[[du,P(n).values.tutorial]]),q(` `+k(P(Q)(`Show the tour the next time this account opens the manager`)),1)]),G(`div`,sm,[G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(n).busy},k(P(n).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,cm),G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:s[9]||=e=>t.value=null},k(P(Q)(`Cancel`)),1)])],32)):J(``,!0),G(`ul`,lm,[(H(!0),U(B,null,R(e.accounts,e=>(H(),U(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[G(`div`,um,[G(`p`,dm,[q(k(e.name)+` `,1),e.is_you?(H(),U(`span`,fm,`(`+k(P(Q)(`you`))+`)`,1)):J(``,!0)]),G(`p`,pm,k(e.email),1),G(`p`,mm,[e.is_super_admin?(H(),U(`span`,hm,k(P(Q)(`Super admin`)),1)):J(``,!0),(H(!0),U(B,null,R(e.groups,e=>(H(),U(`span`,{key:e.id,class:`m-badge`},k(e.name),1))),128))])]),G(`div`,gm,[e.can_change?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>r(e)},k(P(Q)(`Edit`)),9,_m)):J(``,!0),e.can_delete?(H(),U(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:t=>a(e)},k(P(Q)(`Delete`)),9,vm)):J(``,!0)])]))),128))])],64))}}),bm={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},xm={class:`font-display text-2xl font-bold`},Sm={class:`m-label`,for:`g-name`},Cm={key:0,class:`m-error`},wm={class:`m-label`,for:`g-desc`},Tm={class:`px-1 text-sm font-semibold`},Em=[`value`,`onChange`],Dm={class:`flex gap-2`},Om=[`disabled`],km={key:1,class:`m-card p-5 text-sm text-muted`},Am={key:2,class:`m-card divide-y divide-line`},jm={class:`min-w-0`},Mm={class:`font-semibold`},Nm={class:`text-xs font-normal text-muted`},Pm={key:0,class:`text-xs text-muted`},Fm={class:`flex gap-2`},Im=[`onClick`],Lm=[`onClick`],Rm=L({__name:`GroupsIndex`,props:{groups:{},catalogue:{}},setup(e){let t=e,n=N(null),r=qu({name:``,description:``,permissions:[]}),i=t.catalogue.flatMap(e=>e.permissions);function a(e){n.value=e,r.errors={},r.values.name=e===`new`?``:e.name,r.values.description=e===`new`?``:e.description??``,r.values.permissions=e===`new`?[]:[...e.permissions]}function o(e){r.values.permissions.includes(e.value)?r.values.permissions=[...new Set([...r.values.permissions,...e.needs])]:r.values.permissions=r.values.permissions.filter(t=>!i.find(e=>e.value===t)?.needs.includes(e.value))}async function s(){let e=n.value;(e===`new`?await r.send(`post`,`${X.base}/groups`):await r.send(`put`,`${X.base}/groups/${e.id}`))&&(B1(Q(`Saved.`)),n.value=null,await W1())}async function c(e){window.confirm(Q(`Are you sure?`))&&(await Z.delete(`${X.base}/groups/${e.id}`),B1(Q(`Deleted.`)),await W1())}return(t,i)=>(H(),U(B,null,[G(`div`,bm,[G(`h1`,xm,k(P(Q)(`Groups`)),1),G(`button`,{type:`button`,class:`m-btn m-btn-primary`,onClick:i[0]||=e=>a(`new`)},k(P(Q)(`New group`)),1)]),n.value?(H(),U(`form`,{key:0,class:`m-card mb-6 max-w-3xl space-y-4 p-5`,onSubmit:Tu(s,[`prevent`])},[G(`div`,null,[G(`label`,Sm,k(P(Q)(`Name`)),1),I(G(`input`,{id:`g-name`,"onUpdate:modelValue":i[1]||=e=>P(r).values.name=e,required:``,maxlength:`60`,class:`m-input`},null,512),[[Y,P(r).values.name]]),P(r).errors.name?(H(),U(`p`,Cm,k(P(r).errors.name),1)):J(``,!0)]),G(`div`,null,[G(`label`,wm,k(P(Q)(`Description`)),1),I(G(`textarea`,{id:`g-desc`,"onUpdate:modelValue":i[2]||=e=>P(r).values.description=e,rows:`2`,maxlength:`500`,class:`m-input`},null,512),[[Y,P(r).values.description]])]),(H(!0),U(B,null,R(e.catalogue,e=>(H(),U(`fieldset`,{key:e.section,class:`rounded-lg border border-line p-3`},[G(`legend`,Tm,k(e.section),1),(H(!0),U(B,null,R(e.permissions,e=>(H(),U(`label`,{key:e.value,class:`flex items-center gap-2 py-0.5 text-sm`},[I(G(`input`,{"onUpdate:modelValue":i[3]||=e=>P(r).values.permissions=e,type:`checkbox`,value:e.value,onChange:t=>o(e)},null,40,Em),[[du,P(r).values.permissions]]),q(` `+k(e.label),1)]))),128))]))),128)),G(`div`,Dm,[G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(r).busy},k(P(r).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,Om),G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:i[4]||=e=>n.value=null},k(P(Q)(`Cancel`)),1)])],32)):J(``,!0),e.groups.length?(H(),U(`ul`,Am,[(H(!0),U(B,null,R(e.groups,e=>(H(),U(`li`,{key:e.id,class:`flex flex-wrap items-center justify-between gap-3 p-4`},[G(`div`,jm,[G(`p`,Mm,[q(k(e.name)+` `,1),G(`span`,Nm,`· `+k(e.accounts)+` `+k(P(Q)(`accounts`)),1)]),e.description?(H(),U(`p`,Pm,k(e.description),1)):J(``,!0)]),G(`div`,Fm,[G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:t=>a(e)},k(P(Q)(`Edit`)),9,Im),G(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:t=>c(e)},k(P(Q)(`Delete`)),9,Lm)])]))),128))])):(H(),U(`p`,km,k(P(Q)(`Nothing here yet.`)),1))],64))}}),zm={class:`font-display mb-6 text-2xl font-bold`},Bm={key:0,class:`m-error mb-4`},Vm={class:`grid gap-6 md:grid-cols-2`},Hm={class:`mb-3 font-semibold`},Um=[`onSubmit`],Wm=[`onUpdate:modelValue`,`aria-label`],Gm={type:`submit`,class:`m-btn m-btn-primary`},Km={class:`divide-y divide-line`},qm={class:`min-w-0 truncate`},Jm={class:`text-xs text-muted`},Ym={class:`flex gap-1`},Xm=[`onClick`],Zm=[`onClick`],Qm=L({__name:`LabelsIndex`,props:{categories:{},tags:{}},setup(e){let t=[{type:`category`,title:`Categories`},{type:`tag`,title:`Tags`}],n=N({category:``,tag:``}),r=N(``);async function i(e){r.value=``;try{await e(),await W1()}catch(e){if(e instanceof Uu&&e.status===422)r.value=Object.values(e.errors)[0]??e.message;else throw e}}let a=e=>i(async()=>{await Z.post(`${X.base}/labels`,{type:e,name:n.value[e]}),n.value[e]=``,B1(Q(`Created.`))}),o=(e,t)=>{let n=window.prompt(Q(`New name`),t);return n&&n!==t?i(()=>Z.put(`${X.base}/labels`,{type:e,name:t,new_name:n})):void 0},s=(e,t)=>window.confirm(Q(`Are you sure?`))?i(()=>Z.delete(`${X.base}/labels`,{type:e,name:t})):void 0;return(i,c)=>(H(),U(B,null,[G(`h1`,zm,k(P(Q)(`Categories and tags`)),1),r.value?(H(),U(`p`,Bm,k(r.value),1)):J(``,!0),G(`div`,Vm,[(H(),U(B,null,R(t,t=>G(`section`,{key:t.type,class:`m-card p-4`},[G(`h2`,Hm,k(P(Q)(t.title)),1),G(`form`,{class:`mb-3 flex gap-2`,onSubmit:Tu(e=>a(t.type),[`prevent`])},[I(G(`input`,{"onUpdate:modelValue":e=>n.value[t.type]=e,required:``,maxlength:`60`,class:`m-input`,"aria-label":P(Q)(t.title)},null,8,Wm),[[Y,n.value[t.type]]]),G(`button`,Gm,k(P(Q)(`Add`)),1)],40,Um),G(`ul`,Km,[(H(!0),U(B,null,R(t.type===`category`?e.categories:e.tags,e=>(H(),U(`li`,{key:e.name,class:`flex items-center justify-between gap-2 py-2 text-sm`},[G(`span`,qm,[q(k(e.name)+` `,1),G(`span`,Jm,`· `+k(e.posts),1)]),G(`span`,Ym,[G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:n=>o(t.type,e.name)},k(P(Q)(`Rename`)),9,Xm),G(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:n=>s(t.type,e.name)},k(P(Q)(`Delete`)),9,Zm)])]))),128))])])),64))])],64))}}),$m={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},eh={class:`font-display text-2xl font-bold`},th=[`accept`,`disabled`],nh=[`title`],rh={class:`h-2 overflow-hidden rounded-full bg-panel-2`},ih={class:`m-help`},ah={key:0,class:`w-full shrink-0 sm:w-64`},oh=[`src`,`alt`],sh={class:`m-help`},ch={class:`mt-2 flex items-center gap-2`},lh=[`src`],uh={class:`min-w-0 flex-1 space-y-3`},dh={class:`m-label`,for:`m-name`},fh=[`disabled`],ph={key:0,class:`m-error`},mh={key:0},hh={class:`m-label`,for:`m-alt`},gh=[`disabled`],_h={class:`m-help`},vh={key:0},yh={key:1},bh={class:`m-help break-all`},xh={class:`flex gap-2`},Sh=[`disabled`],Ch={key:1,class:`m-card p-5 text-sm text-muted`},wh={key:2,class:`grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5`},Th=[`onClick`],Eh=[`src`,`alt`],Dh={key:1,class:`grid aspect-square w-full place-items-center text-xs text-muted`},Oh={class:`block truncate px-2 py-1.5 text-xs`},kh=L({__name:`MediaLibrary`,props:{items:{},max_file_mb:{},extensions:{},storage:{}},setup(e){let t=e=>X.permissions.includes(e),n=N(!1),r=N(null),i=qu({name:``,alt:``,focus_x:null,focus_y:null}),a=e=>e>1e6?`${(e/1e6).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1e3))} kB`;function o(e){r.value=e,i.errors={},i.values.name=e.name,i.values.alt=e.alt??``,i.values.focus_x=e.focus_x,i.values.focus_y=e.focus_y}function s(e){if(!t(`media.edit`))return;let n=e.currentTarget.getBoundingClientRect();i.values.focus_x=Math.round(Math.min(1,Math.max(0,(e.clientX-n.left)/n.width))*1e3)/1e3,i.values.focus_y=Math.round(Math.min(1,Math.max(0,(e.clientY-n.top)/n.height))*1e3)/1e3}let c=(e,t)=>`${(e??.5)*100}% ${(t??.5)*100}%`;async function l(e){let t=e.target;n.value=!0;try{for(let e of Array.from(t.files??[])){let t=new FormData;t.append(`file`,e),await Ku(`${X.base}/media`,t)}B1(Q(`Uploaded.`)),await W1()}catch(e){B1(e instanceof Uu?Object.values(e.errors)[0]??e.message:Q(`Something went wrong. Try again.`),!0)}finally{n.value=!1,t.value=``}}async function u(){r.value&&await i.send(`put`,`${X.base}/media/${r.value.id}`)&&(B1(Q(`Saved.`)),r.value=null,await W1())}async function d(e){let t=e.usage_count>0?Q(`This file is in use. Delete it anyway?`):Q(`Are you sure?`);window.confirm(t)&&(await Z.delete(`${X.base}/media/${e.id}`),r.value=null,B1(Q(`Deleted.`)),await W1())}return(f,p)=>(H(),U(B,null,[G(`div`,$m,[G(`h1`,eh,k(P(Q)(`Media`)),1),t(`media.upload`)?(H(),U(`label`,{key:0,class:O([`m-btn m-btn-primary cursor-pointer`,n.value?`opacity-50`:``])},[q(k(n.value?P(Q)(`Uploading…`):P(Q)(`Upload`))+` `,1),G(`input`,{type:`file`,multiple:``,class:`sr-only`,accept:e.extensions.map(e=>`.`+e).join(`,`),disabled:n.value,onChange:l},null,40,th)],2)):J(``,!0)]),G(`div`,{class:`mb-6 max-w-md`,title:`${a(e.storage.used)} / ${a(e.storage.limit)}`},[G(`div`,rh,[G(`div`,{class:`h-full bg-brand`,style:_e({width:Math.min(100,e.storage.used/Math.max(1,e.storage.limit)*100)+`%`})},null,4)]),G(`p`,ih,k(a(e.storage.used))+` / `+k(a(e.storage.limit))+` · `+k(P(Q)(`Largest file`))+`: `+k(e.max_file_mb)+` MB`,1)],8,nh),r.value?(H(),U(`form`,{key:0,class:`m-card mb-6 flex max-w-3xl flex-wrap gap-5 p-5`,onSubmit:Tu(u,[`prevent`])},[r.value.is_image?(H(),U(`div`,ah,[G(`div`,{class:O([`relative`,t(`media.edit`)?`cursor-crosshair`:``]),onClick:s},[G(`img`,{src:r.value.url,alt:r.value.alt??``,class:`w-full rounded-lg`,draggable:`false`},null,8,oh),P(i).values.focus_x===null?J(``,!0):(H(),U(`span`,{key:0,class:`pointer-events-none absolute h-5 w-5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white bg-brand/60 shadow`,style:_e({left:(P(i).values.focus_x??0)*100+`%`,top:(P(i).values.focus_y??0)*100+`%`})},null,4))],2),G(`p`,sh,k(t(`media.edit`)?P(Q)(`Click the part of the picture that must stay in view.`):P(Q)(`Focus point`)),1),G(`div`,ch,[G(`img`,{src:r.value.url,alt:``,class:`h-16 w-16 rounded-lg object-cover`,style:_e({objectPosition:c(P(i).values.focus_x,P(i).values.focus_y)})},null,12,lh),t(`media.edit`)&&P(i).values.focus_x!==null?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:p[0]||=e=>P(i).values.focus_x=P(i).values.focus_y=null},k(P(Q)(`Clear`)),1)):J(``,!0)])])):J(``,!0),G(`div`,uh,[G(`div`,null,[G(`label`,dh,k(P(Q)(`Name`)),1),I(G(`input`,{id:`m-name`,"onUpdate:modelValue":p[1]||=e=>P(i).values.name=e,required:``,maxlength:`250`,class:`m-input`,disabled:!t(`media.edit`)},null,8,fh),[[Y,P(i).values.name]]),P(i).errors.name?(H(),U(`p`,ph,k(P(i).errors.name),1)):J(``,!0)]),r.value.is_image?(H(),U(`div`,mh,[G(`label`,hh,k(P(Q)(`Alternative text`)),1),I(G(`input`,{id:`m-alt`,"onUpdate:modelValue":p[2]||=e=>P(i).values.alt=e,maxlength:`500`,class:`m-input`,disabled:!t(`media.edit`)},null,8,gh),[[Y,P(i).values.alt]])])):J(``,!0),G(`p`,_h,[q(k(r.value.mime_type)+` · `+k(a(r.value.size)),1),r.value.width?(H(),U(`span`,vh,` · `+k(r.value.width)+`×`+k(r.value.height),1)):J(``,!0),q(` · `+k(P(Q)(`Used`))+`: `+k(r.value.usage_count),1),r.value.uploaded_by?(H(),U(`span`,yh,` · `+k(r.value.uploaded_by),1)):J(``,!0)]),G(`p`,bh,k(r.value.url),1),G(`div`,xh,[t(`media.edit`)?(H(),U(`button`,{key:0,type:`submit`,class:`m-btn m-btn-primary`,disabled:P(i).busy},k(P(Q)(`Save`)),9,Sh)):J(``,!0),t(`media.delete`)?(H(),U(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:p[3]||=e=>d(r.value)},k(P(Q)(`Delete`)),1)):J(``,!0),G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,onClick:p[4]||=e=>r.value=null},k(P(Q)(`Cancel`)),1)])])],32)):J(``,!0),e.items.length?(H(),U(`div`,wh,[(H(!0),U(B,null,R(e.items,e=>(H(),U(`button`,{key:e.id,type:`button`,class:O([`m-card overflow-hidden text-left transition hover:border-brand`,r.value?.id===e.id?`border-brand`:``]),onClick:t=>o(e)},[e.is_image?(H(),U(`img`,{key:0,src:e.url,alt:e.alt??``,loading:`lazy`,class:`aspect-square w-full object-cover`},null,8,Eh)):(H(),U(`span`,Dh,k(e.mime_type),1)),G(`span`,Oh,k(e.name),1)],10,Th))),128))])):(H(),U(`p`,Ch,k(P(Q)(`No files yet.`)),1))],64))}}),Ah={class:`font-display mb-6 text-2xl font-bold`},jh={class:`mb-6 grid grid-cols-2 gap-3 md:grid-cols-4`},Mh={class:`text-2xl font-bold`},Nh={class:`m-help`},Ph={class:`mb-4 flex flex-wrap gap-2`},Fh=[`onClick`],Ih=[`placeholder`,`aria-label`],Lh=[`aria-label`],Rh={value:``},zh=[`value`],Bh={type:`submit`,class:`m-btn m-btn-secondary`},Vh={key:0,class:`m-card p-5 text-sm text-muted`},Hh={key:1,class:`m-card divide-y divide-line`},Uh={class:`min-w-0`},Wh={class:`font-semibold`},Gh={key:1},Kh={class:`text-xs text-muted`},qh={class:`flex gap-2`},Jh={key:0,class:`m-badge`},Yh=[`onClick`],Xh={key:2,class:`mt-4 flex items-center gap-2`},Zh={class:`text-sm text-muted`},Qh={class:`font-display mb-3 mt-10 text-xl font-bold`},$h={class:`m-label`,for:`b-min`},eg={class:`min-w-[10rem] flex-1`},tg={class:`m-label`,for:`b-why`},ng={key:0,class:`flex items-center gap-2 text-sm`},rg={type:`submit`,class:`m-btn m-btn-danger`},ig={key:1,class:`m-error w-full`},ag={key:4,class:`text-sm text-muted`},og={key:5,class:`m-card divide-y divide-line`},sg={class:`font-semibold`},cg={key:0,class:`m-badge`},lg={key:1,class:`m-badge`},ug={class:`text-xs text-muted`},dg=[`onClick`],fg={class:`font-display mb-3 mt-10 text-xl font-bold`},pg={class:`flex items-center gap-2 text-sm sm:col-span-2`},mg={class:`m-label`,for:`r-max`},hg={class:`m-label`,for:`r-win`},gg={class:`m-label`,for:`r-ban`},_g={class:`m-label`,for:`r-keep`},vg=[`max`],yg={class:`m-help`},bg={class:`sm:col-span-2`},xg=[`disabled`],Sg={class:`font-display mb-3 mt-10 text-xl font-bold`},Cg={class:`m-label`,for:`n-group`},wg={class:`min-w-[10rem] flex-1`},Tg={class:`m-label`,for:`n-note`},Eg={type:`submit`,class:`m-btn m-btn-secondary`},Dg={key:0,class:`m-error w-full`},Og={key:0,class:`m-card divide-y divide-line text-sm`},kg={key:0,class:`m-badge`},Ag=L({__name:`AuditLog`,props:{entries:{},pagination:{},filters:{},accounts:{},summary:{},bans:{},notes:{},settings:{},max_keep_days:{},can_manage:{type:Boolean},my_ip:{},never_banned:{},whole_site_bans:{type:Boolean}},setup(e){let t=e,n=[`all`,`logins`,`failed`,`actions`,`viewed`,`refused`,`bans`],r=rn({q:t.filters.q,ip:t.filters.ip,user:t.filters.user??``}),i=e=>new Date(e).toLocaleString();function a(e){let n=new URLSearchParams,i={show:t.filters.show,q:r.q,ip:r.ip,user:r.user,...e};for(let[e,t]of Object.entries(i))t!==``&&t!==`all`&&t!==1&&n.set(e,String(t));U1(`${X.base}/audit${n.size?`?`+n:``}`)}let o=qu({ip:``,minutes:1440,reason:``,whole_site:!1});async function s(e){e&&(o.values.ip=e);let t=await o.send(`post`,`${X.base}/audit/bans`);t&&(B1(t.message),o.values.ip=o.values.reason=``,await W1())}async function c(e){B1((await Z.delete(`${X.base}/audit/bans/${e.id}`)).message),await W1()}let l=qu({...t.settings});async function u(){await l.send(`put`,`${X.base}/audit/settings`)&&(B1(Q(`Saved.`)),await W1())}let d=qu({ip:``,group:``,note:``});async function f(){await d.send(`put`,`${X.base}/audit/notes`)&&(B1(Q(`Saved.`)),d.values.ip=d.values.group=d.values.note=``,await W1())}let p=e=>e.expires_at?i(e.expires_at):Q(`until lifted`);return(t,m)=>(H(),U(B,null,[G(`h1`,Ah,k(P(Q)(`Audit log`)),1),G(`div`,jh,[(H(!0),U(B,null,R(e.summary,(e,t)=>(H(),U(`div`,{key:t,class:`m-card p-4`},[G(`p`,Mh,k(e),1),G(`p`,Nh,k(P(Q)(t===`banned`?`Addresses banned`:t===`logins`?`Logins (24 h)`:t===`failed`?`Failed logins (24 h)`:`Refused (24 h)`)),1)]))),128))]),G(`nav`,Ph,[(H(),U(B,null,R(n,t=>G(`button`,{key:t,type:`button`,class:O([`m-btn`,e.filters.show===t?`m-btn-primary`:`m-btn-secondary`]),onClick:e=>a({show:t,page:1})},k(P(Q)(t)),11,Fh)),64))]),G(`form`,{class:`mb-4 flex flex-wrap gap-2`,onSubmit:m[3]||=Tu(e=>a({page:1}),[`prevent`])},[I(G(`input`,{"onUpdate:modelValue":m[0]||=e=>r.q=e,class:`m-input max-w-xs`,placeholder:P(Q)(`Search`),"aria-label":P(Q)(`Search`)},null,8,Ih),[[Y,r.q]]),I(G(`input`,{"onUpdate:modelValue":m[1]||=e=>r.ip=e,class:`m-input max-w-[12rem]`,placeholder:`IP`,"aria-label":`IP`},null,512),[[Y,r.ip]]),I(G(`select`,{"onUpdate:modelValue":m[2]||=e=>r.user=e,class:`m-input max-w-[12rem]`,"aria-label":P(Q)(`Account`)},[G(`option`,Rh,k(P(Q)(`Everyone`)),1),(H(!0),U(B,null,R(e.accounts,e=>(H(),U(`option`,{key:e.id,value:e.id},k(e.name),9,zh))),128))],8,Lh),[[mu,r.user]]),G(`button`,Bh,k(P(Q)(`Filter`)),1)],32),e.entries.length?(H(),U(`ul`,Hh,[(H(!0),U(B,null,R(e.entries,t=>(H(),U(`li`,{key:t.id,class:`flex flex-wrap items-start justify-between gap-3 p-4 text-sm`},[G(`div`,Uh,[G(`p`,Wh,[q(k(t.summary)+` `,1),t.subject?(H(),U(B,{key:0},[m[19]||=q(` · `,-1),t.subject.url?(H(),W(ed,{key:0,href:t.subject.url,class:`underline`},{default:F(()=>[q(k(t.subject.label),1)]),_:2},1032,[`href`])):(H(),U(`span`,Gh,k(t.subject.label),1))],64)):J(``,!0)]),G(`p`,Kh,k(i(t.at))+` · `+k(t.who??t.email??P(Q)(`Someone`))+` · `+k(t.ip)+` · `+k(t.browser),1)]),G(`span`,qh,[t.banned?(H(),U(`span`,Jh,k(P(Q)(`banned`)),1)):J(``,!0),e.can_manage&&t.ip&&!t.banned&&!t.never_banned&&t.ip!==e.my_ip?(H(),U(`button`,{key:1,type:`button`,class:`m-btn m-btn-danger`,onClick:e=>s(t.ip)},k(P(Q)(`Ban`)),9,Yh)):J(``,!0)])]))),128))])):(H(),U(`p`,Vh,k(P(Q)(`Nothing here yet.`)),1)),e.pagination.pages>1?(H(),U(`nav`,Xh,[e.pagination.page>1?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:m[4]||=t=>a({page:e.pagination.page-1})},k(P(Q)(`Previous`)),1)):J(``,!0),G(`span`,Zh,k(e.pagination.page)+` / `+k(e.pagination.pages),1),e.pagination.pagea({page:e.pagination.page+1})},k(P(Q)(`Next`)),1)):J(``,!0)])):J(``,!0),G(`h2`,Qh,k(P(Q)(`Bans`)),1),e.can_manage?(H(),U(`form`,{key:3,class:`m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4`,onSubmit:m[10]||=Tu(e=>s(),[`prevent`])},[G(`div`,null,[m[20]||=G(`label`,{class:`m-label`,for:`b-ip`},`IP`,-1),I(G(`input`,{id:`b-ip`,"onUpdate:modelValue":m[6]||=e=>P(o).values.ip=e,required:``,class:`m-input`},null,512),[[Y,P(o).values.ip]])]),G(`div`,null,[G(`label`,$h,k(P(Q)(`Minutes (0 = until lifted)`)),1),I(G(`input`,{id:`b-min`,"onUpdate:modelValue":m[7]||=e=>P(o).values.minutes=e,type:`number`,min:`0`,class:`m-input w-32`},null,512),[[Y,P(o).values.minutes,void 0,{number:!0}]])]),G(`div`,eg,[G(`label`,tg,k(P(Q)(`Reason`)),1),I(G(`input`,{id:`b-why`,"onUpdate:modelValue":m[8]||=e=>P(o).values.reason=e,maxlength:`200`,class:`m-input`},null,512),[[Y,P(o).values.reason]])]),e.whole_site_bans?(H(),U(`label`,ng,[I(G(`input`,{"onUpdate:modelValue":m[9]||=e=>P(o).values.whole_site=e,type:`checkbox`},null,512),[[du,P(o).values.whole_site]]),q(` `+k(P(Q)(`Whole site`)),1)])):J(``,!0),G(`button`,rg,k(P(Q)(`Ban`)),1),P(o).errors.ip?(H(),U(`p`,ig,k(P(o).errors.ip),1)):J(``,!0)],32)):J(``,!0),e.bans.length?(H(),U(`ul`,og,[(H(!0),U(B,null,R(e.bans,t=>(H(),U(`li`,{key:t.id,class:O([`flex flex-wrap items-center justify-between gap-3 p-4 text-sm`,t.active?``:`opacity-50`])},[G(`div`,null,[G(`p`,sg,[q(k(t.ip)+` `,1),t.automatic?(H(),U(`span`,cg,k(P(Q)(`automatic`)),1)):J(``,!0),m[21]||=q(),t.whole_site?(H(),U(`span`,lg,k(P(Q)(`whole site`)),1)):J(``,!0)]),G(`p`,ug,k(t.reason)+` · `+k(p(t))+` · `+k(t.hits)+` `+k(P(Q)(`hits`)),1)]),e.can_manage&&t.active?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:e=>c(t)},k(P(Q)(`Lift`)),9,dg)):J(``,!0)],2))),128))])):(H(),U(`p`,ag,k(P(Q)(`No bans.`)),1)),e.can_manage?(H(),U(B,{key:6},[G(`h2`,fg,k(P(Q)(`Rules`)),1),G(`form`,{class:`m-card grid max-w-3xl gap-4 p-5 sm:grid-cols-2`,onSubmit:Tu(u,[`prevent`])},[G(`label`,pg,[I(G(`input`,{"onUpdate:modelValue":m[11]||=e=>P(l).values.auto_ban=e,type:`checkbox`},null,512),[[du,P(l).values.auto_ban]]),q(` `+k(P(Q)(`Ban an address by itself after too many failed logins`)),1)]),G(`div`,null,[G(`label`,mg,k(P(Q)(`Failed logins`)),1),I(G(`input`,{id:`r-max`,"onUpdate:modelValue":m[12]||=e=>P(l).values.max_failures=e,type:`number`,min:`3`,max:`100`,class:`m-input`},null,512),[[Y,P(l).values.max_failures,void 0,{number:!0}]])]),G(`div`,null,[G(`label`,hg,k(P(Q)(`Within minutes`)),1),I(G(`input`,{id:`r-win`,"onUpdate:modelValue":m[13]||=e=>P(l).values.window_minutes=e,type:`number`,min:`1`,max:`1440`,class:`m-input`},null,512),[[Y,P(l).values.window_minutes,void 0,{number:!0}]])]),G(`div`,null,[G(`label`,gg,k(P(Q)(`Ban for minutes (0 = until lifted)`)),1),I(G(`input`,{id:`r-ban`,"onUpdate:modelValue":m[14]||=e=>P(l).values.ban_minutes=e,type:`number`,min:`0`,class:`m-input`},null,512),[[Y,P(l).values.ban_minutes,void 0,{number:!0}]])]),G(`div`,null,[G(`label`,_g,k(P(Q)(`Keep the log (days)`)),1),I(G(`input`,{id:`r-keep`,"onUpdate:modelValue":m[15]||=e=>P(l).values.keep_days=e,type:`number`,min:`7`,max:e.max_keep_days,class:`m-input`},null,8,vg),[[Y,P(l).values.keep_days,void 0,{number:!0}]]),G(`p`,yg,`≤ `+k(e.max_keep_days),1)]),G(`div`,bg,[G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(l).busy},k(P(Q)(`Save`)),9,xg)]),(H(!0),U(B,null,R(P(l).errors,(e,t)=>(H(),U(`p`,{key:t,class:`m-error sm:col-span-2`},k(e),1))),128))],32),G(`h2`,Sg,k(P(Q)(`Notes about addresses`)),1),G(`form`,{class:`m-card mb-4 flex max-w-3xl flex-wrap items-end gap-3 p-4`,onSubmit:Tu(f,[`prevent`])},[G(`div`,null,[m[22]||=G(`label`,{class:`m-label`,for:`n-ip`},`IP`,-1),I(G(`input`,{id:`n-ip`,"onUpdate:modelValue":m[16]||=e=>P(d).values.ip=e,required:``,class:`m-input`},null,512),[[Y,P(d).values.ip]])]),G(`div`,null,[G(`label`,Cg,k(P(Q)(`Group`)),1),I(G(`input`,{id:`n-group`,"onUpdate:modelValue":m[17]||=e=>P(d).values.group=e,maxlength:`60`,class:`m-input`},null,512),[[Y,P(d).values.group]])]),G(`div`,wg,[G(`label`,Tg,k(P(Q)(`Note`)),1),I(G(`input`,{id:`n-note`,"onUpdate:modelValue":m[18]||=e=>P(d).values.note=e,maxlength:`2000`,class:`m-input`},null,512),[[Y,P(d).values.note]])]),G(`button`,Eg,k(P(Q)(`Save`)),1),P(d).errors.ip?(H(),U(`p`,Dg,k(P(d).errors.ip),1)):J(``,!0)],32),e.notes.length?(H(),U(`ul`,Og,[(H(!0),U(B,null,R(e.notes,e=>(H(),U(`li`,{key:e.ip,class:`p-3`},[G(`b`,null,k(e.ip),1),m[23]||=q(),e.group?(H(),U(`span`,kg,k(e.group),1)):J(``,!0),q(` `+k(e.note),1)]))),128))])):J(``,!0)],64)):J(``,!0)],64))}}),jg={class:`mb-6 flex flex-wrap items-center justify-between gap-3`},Mg={class:`font-display text-2xl font-bold`},Ng={class:`text-sm text-muted`},Pg={key:0},Fg={class:`mb-6 flex flex-wrap gap-2`},Ig={class:`mb-6 grid grid-cols-2 gap-3 md:grid-cols-5`},Lg={class:`text-2xl font-bold`},Rg={class:`m-help`},zg={class:`m-card mb-6 p-4`},Bg={class:`mb-3 font-semibold`},Vg=[`aria-label`],Hg=[`title`],Ug={class:`mb-6 grid gap-6 md:grid-cols-2`},Wg={class:`m-card p-4`},Gg={class:`mb-3 font-semibold`},Kg={key:0,class:`text-sm text-muted`},qg={class:`divide-y divide-line text-sm`},Jg={class:`truncate`},Yg={class:`text-muted`},Xg={class:`m-card p-4`},Zg={class:`mb-3 font-semibold`},Qg={key:0,class:`text-sm text-muted`},$g={class:`divide-y divide-line text-sm`},e_={class:`truncate`},t_={class:`text-muted`},n_={class:`mb-3 font-semibold`},r_={key:0,class:`text-sm text-muted`},i_={class:`divide-y divide-line text-sm`},a_={class:`truncate`},o_={class:`text-muted`},s_={class:`m-card mb-6 overflow-x-auto p-4`},c_={class:`mb-3 font-semibold`},l_={class:`space-y-0.5 text-xs`},u_={class:`w-9 shrink-0 text-muted`},d_=[`title`],f_={class:`m-card mb-6 p-4`},p_={class:`mb-3 font-semibold`},m_={class:`text-sm font-normal text-muted`},h_={key:0,class:`text-sm text-muted`},g_={class:`divide-y divide-line text-sm`},__={class:`text-xs text-muted`},v_={class:`text-muted`},y_={class:`flex flex-wrap items-center gap-2 text-sm`},b_={class:`text-muted`},x_=[`href`],S_=L({__name:`StatisticsReport`,props:{range:{},ranges:{},exports:{},totals:{},previous:{},series:{},pages:{},posts:{},channels:{},sources:{},countries:{},devices:{},browsers:{},systems:{},heatmap:{},bots:{}},setup(e){let t=e,n=dc(()=>[[`Visitors`,`visitors`],[`Visits`,`visits`],[`Page views`,`page_views`],[`Average time`,`average_seconds`],[`Bounce rate`,`bounce_rate`]]),r=(e,t)=>e===`average_seconds`?`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`:e===`bounce_rate`?`${t}%`:t.toLocaleString(),i=e=>{let n=t.previous?.[e];return n?Math.round((t.totals[e]-n)/n*100):null},a=dc(()=>Math.max(1,...t.series.map(e=>e.visits))),o=dc(()=>Math.max(1,...t.heatmap.flatMap(e=>e.hours))),s=dc(()=>[[`Channels`,t.channels],[`Sources`,t.sources],[`Countries`,t.countries],[`Devices`,t.devices],[`Browsers`,t.browsers],[`Systems`,t.systems]]),c=e=>`${X.base}/statistics?range=${e}`,l=e=>`${X.base}/statistics/export?sheet=${e}&range=${new URLSearchParams($.path.split(`?`)[1]??``).get(`range`)??t.range.key}`;return(t,u)=>(H(),U(B,null,[G(`div`,jg,[G(`h1`,Mg,k(P(Q)(`Statistics`)),1),G(`p`,Ng,[q(k(e.range.from)+` → `+k(e.range.to),1),e.range.compared_to?(H(),U(`span`,Pg,` · `+k(P(Q)(`compared with`))+` `+k(e.range.compared_to),1)):J(``,!0)])]),G(`nav`,Fg,[(H(!0),U(B,null,R(e.ranges,t=>(H(),W(ed,{key:t.key,href:c(t.key),class:O([`m-btn`,e.range.key===t.key?`m-btn-primary`:`m-btn-secondary`])},{default:F(()=>[q(k(t.label),1)]),_:2},1032,[`href`,`class`]))),128))]),G(`div`,Ig,[(H(!0),U(B,null,R(n.value,([t,n])=>(H(),U(`div`,{key:n,class:`m-card p-4`},[G(`p`,Lg,k(r(n,e.totals[n])),1),G(`p`,Rg,[q(k(P(Q)(t)),1),i(n)===null?J(``,!0):(H(),U(`span`,{key:0,class:O((i(n)??0)>=0?`text-emerald-500`:`text-red-500`)},k((i(n)??0)>0?`+`:``)+k(i(n))+`%`,3))])]))),128))]),G(`section`,zg,[G(`h2`,Bg,k(P(Q)(`Visits`)),1),G(`div`,{class:`flex h-40 items-end gap-px`,role:`img`,"aria-label":P(Q)(`Visits`)},[(H(!0),U(B,null,R(e.series,e=>(H(),U(`div`,{key:e.key,class:`min-w-px flex-1 rounded-t bg-brand`,style:_e({height:Math.max(2,e.visits/a.value*100)+`%`}),title:`${e.label}: ${e.visits}`},null,12,Hg))),128))],8,Vg)]),G(`div`,Ug,[G(`section`,Wg,[G(`h2`,Gg,k(P(Q)(`Pages`)),1),e.pages.length?J(``,!0):(H(),U(`p`,Kg,k(P(Q)(`Nothing here yet.`)),1)),G(`ul`,qg,[(H(!0),U(B,null,R(e.pages,e=>(H(),U(`li`,{key:e.path,class:`flex justify-between gap-3 py-1.5`},[G(`span`,Jg,k(e.title??e.path),1),G(`span`,Yg,k(e.views),1)]))),128))])]),G(`section`,Xg,[G(`h2`,Zg,k(P(Q)(`Posts`)),1),e.posts.length?J(``,!0):(H(),U(`p`,Qg,k(P(Q)(`Nothing here yet.`)),1)),G(`ul`,$g,[(H(!0),U(B,null,R(e.posts,e=>(H(),U(`li`,{key:e.slug,class:`flex justify-between gap-3 py-1.5`},[G(`span`,e_,k(e.title),1),G(`span`,t_,k(e.views),1)]))),128))])]),(H(!0),U(B,null,R(s.value,([e,t])=>(H(),U(`section`,{key:e,class:`m-card p-4`},[G(`h2`,n_,k(P(Q)(e)),1),t.length?J(``,!0):(H(),U(`p`,r_,k(P(Q)(`Nothing here yet.`)),1)),G(`ul`,i_,[(H(!0),U(B,null,R(t,e=>(H(),U(`li`,{key:e.name+(e.channel??``),class:`flex justify-between gap-3 py-1.5`},[G(`span`,a_,k(e.name||P(Q)(`Direct`)),1),G(`span`,o_,k(e.visits),1)]))),128))])]))),128))]),G(`section`,s_,[G(`h2`,c_,k(P(Q)(`When people visit`)),1),G(`div`,l_,[(H(!0),U(B,null,R(e.heatmap,e=>(H(),U(`div`,{key:e.day,class:`flex items-center gap-0.5`},[G(`span`,u_,k(e.day),1),(H(!0),U(B,null,R(e.hours,(t,n)=>(H(),U(`span`,{key:n,class:`block h-5 min-w-3 flex-1 rounded-sm border border-line`,title:`${e.day} ${n}:00 · ${t}`,style:_e({background:`color-mix(in srgb, var(--m-brand) ${Math.round(t/o.value*100)}%, var(--m-panel-2))`})},null,12,d_))),128))]))),128))])]),G(`section`,f_,[G(`h2`,p_,[q(k(P(Q)(`Programs`))+` `,1),G(`span`,m_,`· `+k(e.bots.total),1)]),e.bots.names.length?J(``,!0):(H(),U(`p`,h_,k(P(Q)(`Nothing here yet.`)),1)),G(`ul`,g_,[(H(!0),U(B,null,R(e.bots.names,e=>(H(),U(`li`,{key:e.name,class:`flex justify-between gap-3 py-1.5`},[G(`span`,null,[q(k(e.name)+` `,1),G(`span`,__,k(e.kind),1)]),G(`span`,v_,k(e.hits),1)]))),128))])]),G(`p`,y_,[G(`span`,b_,k(P(Q)(`Download`))+`:`,1),(H(!0),U(B,null,R(e.exports,(e,t)=>(H(),U(`a`,{key:t,href:l(String(t)),class:`m-btn m-btn-secondary`},k(e)+` (CSV)`,9,x_))),128))])],64))}}),C_={class:`font-display mb-6 text-2xl font-bold`},w_={key:0,class:`m-card p-5 text-sm text-muted`},T_={key:1,class:`m-card divide-y divide-line`},E_={class:`min-w-0`},D_={class:`truncate font-semibold`},O_={class:`truncate text-xs text-muted`},k_={class:`m-badge`},A_={key:2,class:`mt-4 flex gap-2`},j_=L({__name:`ListPage`,props:{data:{},current_page:{},last_page:{},path:{}},setup(e){let t=e,n=dc(()=>$.path.includes(`/reviews`)?`reviews`:`pages`),r=dc(()=>n.value===`reviews`?`Reviews`:`Pages`),i=e=>n.value===`reviews`?e.author:e.title,a=e=>n.value===`reviews`?e.rating?`★`.repeat(e.rating):``:e.slug,o=e=>n.value===`reviews`?e.is_visible:e.is_published,s=e=>`${$.path.split(`?`)[0]}?page=${e}`;return(e,n)=>(H(),U(B,null,[G(`h1`,C_,k(P(Q)(r.value)),1),t.data.length?(H(),U(`ul`,T_,[(H(!0),U(B,null,R(t.data,e=>(H(),U(`li`,{key:e.id,class:`flex items-center justify-between gap-3 p-4`},[G(`div`,E_,[G(`p`,D_,k(i(e)),1),G(`p`,O_,k(a(e)),1)]),G(`span`,k_,k(o(e)?P(Q)(`Published`):P(Q)(`Draft`)),1)]))),128))])):(H(),U(`p`,w_,k(P(Q)(`Nothing here yet.`)),1)),t.last_page>1?(H(),U(`nav`,A_,[t.current_page>1?(H(),W(ed,{key:0,href:s(t.current_page-1),class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Previous`)),1)]),_:1},8,[`href`])):J(``,!0),t.current_page[q(k(P(Q)(`Next`)),1)]),_:1},8,[`href`])):J(``,!0)])):J(``,!0)],64))}}),M_={class:`space-y-5`},N_={key:0,class:`flex items-center gap-2 text-sm`},P_=[`onUpdate:modelValue`],F_=[`for`],I_={key:0,class:`text-muted`},L_=[`id`,`onUpdate:modelValue`],R_={key:0,value:``},z_=[`value`],B_=[`id`,`onUpdate:modelValue`,`rows`,`maxlength`,`required`],V_={key:3,class:`flex gap-2`},H_=[`id`,`onUpdate:modelValue`],U_=[`onClick`],W_=[`id`,`onUpdate:modelValue`,`type`,`maxlength`,`required`],G_=[`src`],K_={key:2,class:`mt-1 text-xs text-muted`},q_={key:3,class:`m-help`},J_={key:4,class:`m-error`},Y_=L({__name:`FormFields`,props:{fields:{},values:{},errors:{},prefix:{}},setup(e){let t=e,n=dc(()=>t.fields.filter(e=>!(e.advanced&&X.view===`simple`))),r=N(null),i=X.permissions.includes(`media.view`);return(t,a)=>(H(),U(`div`,M_,[(H(!0),U(B,null,R(n.value,t=>(H(),U(`div`,{key:t.key},[t.type===`toggle`?(H(),U(`label`,N_,[I(G(`input`,{"onUpdate:modelValue":n=>e.values[t.key]=n,type:`checkbox`},null,8,P_),[[du,e.values[t.key]]]),q(` `+k(P(Q)(t.label)),1)])):(H(),U(B,{key:1},[G(`label`,{for:`f-`+t.key,class:`m-label`},[q(k(P(Q)(t.label)),1),t.required?(H(),U(`span`,I_,` *`)):J(``,!0)],8,F_),t.type===`select`?I((H(),U(`select`,{key:0,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,class:`m-input`},[t.required?J(``,!0):(H(),U(`option`,R_)),(H(!0),U(B,null,R(t.options,(e,t)=>(H(),U(`option`,{key:t,value:t},k(e),9,z_))),128))],8,L_)),[[mu,e.values[t.key]]]):t.type===`markdown`?(H(),W(nf,{key:1,id:`f-`+t.key,modelValue:e.values[t.key],"onUpdate:modelValue":n=>e.values[t.key]=n,required:t.required,maxlength:t.max??void 0},null,8,[`id`,`modelValue`,`onUpdate:modelValue`,`required`,`maxlength`])):t.type===`textarea`||t.type===`lines`?I((H(),U(`textarea`,{key:2,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,rows:t.type===`lines`?5:4,maxlength:t.max??void 0,required:t.required,class:`m-input`},null,8,B_)),[[Y,e.values[t.key]]]):t.type===`media`?(H(),U(`div`,V_,[I(G(`input`,{id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,maxlength:`2048`,class:`m-input`},null,8,H_),[[Y,e.values[t.key]]]),P(i)?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary shrink-0`,onClick:e=>r.value=t.key},k(P(Q)(`Choose`)),9,U_)):J(``,!0)])):I((H(),U(`input`,{key:4,id:`f-`+t.key,"onUpdate:modelValue":n=>e.values[t.key]=n,type:t.type===`number`?`number`:t.type===`date`?`date`:`text`,maxlength:t.max??void 0,required:t.required,class:`m-input`},null,8,W_)),[[yu,e.values[t.key]]]),t.type===`media`&&e.values[t.key]?(H(),U(`img`,{key:5,src:e.values[t.key],alt:``,class:`mt-2 h-24 w-auto rounded-lg border border-line object-cover`},null,8,G_)):J(``,!0)],64)),t.type===`lines`?(H(),U(`p`,K_,k(P(Q)(`One per line.`)),1)):J(``,!0),t.help?(H(),U(`p`,q_,k(P(Q)(t.help)),1)):J(``,!0),e.errors?.[(e.prefix??``)+t.key]?(H(),U(`p`,J_,k(e.errors[(e.prefix??``)+t.key]),1)):J(``,!0)]))),128)),r.value?(H(),W(Hd,{key:0,onPick:a[0]||=t=>{e.values[r.value]=t,r.value=null},onClose:a[1]||=e=>r.value=null})):J(``,!0)]))}}),X_={class:`mb-6 flex items-center justify-between gap-3`},Z_={class:`font-display text-2xl font-bold`},Q_=[`disabled`],$_=L({__name:`RecordForm`,props:{resource:{},record:{}},setup(e){let t=e,n=`${X.base}/records/${t.resource.key}`,r=qu({...t.record.values});async function i(){(t.record.id===null?await r.send(`post`,n):await r.send(`put`,`${n}/${t.record.id}`))&&(B1(Q(`Saved.`)),U1(n))}return(t,a)=>(H(),U(B,null,[G(`div`,X_,[G(`h1`,Z_,k(e.record.id===null?P(Q)(`New`)+`: `+P(Q)(e.resource.singular):P(Q)(e.resource.singular)),1),K(ed,{href:n,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Back`)),1)]),_:1})]),G(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Tu(i,[`prevent`])},[K(Y_,{fields:e.resource.fields,values:P(r).values,errors:P(r).errors},null,8,[`fields`,`values`,`errors`]),G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(r).busy},k(P(r).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,Q_)],32)],64))}}),e1={class:`mb-6 flex items-center justify-between gap-3`},t1={class:`font-display text-2xl font-bold`},n1={key:0,class:`m-card p-5 text-sm text-muted`},r1={key:1,class:`m-card overflow-x-auto`},i1={class:`w-full text-left text-sm`},a1={class:`border-b border-line text-xs uppercase tracking-wide text-muted`},o1={key:0,class:`px-4 py-3`},s1={class:`divide-y divide-line`},c1={key:0,class:`flex justify-end gap-2 px-4 py-2`},l1=[`onClick`],u1={key:2,class:`mt-4 flex gap-2`},d1=L({__name:`RecordsIndex`,props:{resource:{},rows:{},current_page:{},last_page:{}},setup(e){let t=e,n=`${X.base}/records/${t.resource.key}`,r=e=>t.resource.fields.find(t=>t.key===e)?.label??e;function i(e,n){let r=e.values[n],i=t.resource.fields.find(e=>e.key===n);return i?.type===`toggle`?r?`✓`:``:i?.type===`select`?i.options[r]??r:String(r??``)}async function a(e){window.confirm(Q(`Are you sure?`))&&(await Z.delete(`${n}/${e.id}`),await W1())}return(t,o)=>(H(),U(B,null,[G(`div`,e1,[G(`h1`,t1,k(P(Q)(e.resource.label)),1),e.resource.can_manage?(H(),W(ed,{key:0,href:n+`/create`,class:`m-btn m-btn-primary`},{default:F(()=>[q(k(P(Q)(`Add`)),1)]),_:1},8,[`href`])):J(``,!0)]),e.rows.length?(H(),U(`div`,r1,[G(`table`,i1,[G(`thead`,a1,[G(`tr`,null,[(H(!0),U(B,null,R(e.resource.columns,e=>(H(),U(`th`,{key:e,class:`px-4 py-3 font-semibold`},k(P(Q)(r(e))),1))),128)),e.resource.can_manage?(H(),U(`th`,o1)):J(``,!0)])]),G(`tbody`,s1,[(H(!0),U(B,null,R(e.rows,t=>(H(),U(`tr`,{key:t.id},[(H(!0),U(B,null,R(e.resource.columns,e=>(H(),U(`td`,{key:e,class:`max-w-xs truncate px-4 py-3`},k(i(t,e)),1))),128)),e.resource.can_manage?(H(),U(`td`,c1,[K(ed,{href:`${n}/${t.id}/edit`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Edit`)),1)]),_:1},8,[`href`]),G(`button`,{type:`button`,class:`m-btn m-btn-danger`,onClick:e=>a(t)},k(P(Q)(`Delete`)),9,l1)])):J(``,!0)]))),128))])])])):(H(),U(`p`,n1,k(P(Q)(`Nothing here yet.`)),1)),e.last_page>1?(H(),U(`nav`,u1,[e.current_page>1?(H(),W(ed,{key:0,href:`${n}?page=${e.current_page-1}`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Previous`)),1)]),_:1},8,[`href`])):J(``,!0),e.current_page[q(k(P(Q)(`Next`)),1)]),_:1},8,[`href`])):J(``,!0)])):J(``,!0)],64))}}),f1={class:`mb-6 flex items-center justify-between gap-3`},p1={class:`font-display text-2xl font-bold`},m1={for:`title`,class:`m-label`},h1={key:0,class:`m-error`},g1={for:`meta`,class:`m-label`},_1={key:0,class:`m-error`},v1={for:`body`,class:`m-label`},y1={key:0,class:`m-error`},b1={class:`flex items-center gap-2 text-sm`},x1={class:`flex gap-3`},S1=[`disabled`],C1=L({__name:`PageForm`,props:{page:{}},setup(e){let t=e.page,n=qu({title:t.title,meta_description:t.meta_description??``,...t.defined?{content:{...t.content}}:{body:t.body??``,is_published:t.is_published??!1}});async function r(){await n.send(`put`,`${X.base}/pages/${t.slug}`)&&B1(Q(`Saved.`))}async function i(){window.confirm(Q(`Are you sure?`))&&(await Z.delete(`${X.base}/pages/${t.slug}`),U1(`${X.base}/pages`))}return(e,a)=>(H(),U(B,null,[G(`div`,f1,[G(`h1`,p1,k(P(t).title),1),K(ed,{href:P(X).base+`/pages`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Back`)),1)]),_:1},8,[`href`])]),G(`form`,{class:`m-card max-w-3xl space-y-5 p-5`,onSubmit:Tu(r,[`prevent`])},[G(`div`,null,[G(`label`,m1,k(P(Q)(`Title`)),1),I(G(`input`,{id:`title`,"onUpdate:modelValue":a[0]||=e=>P(n).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.title]]),P(n).errors.title?(H(),U(`p`,h1,k(P(n).errors.title),1)):J(``,!0)]),G(`div`,null,[G(`label`,g1,k(P(Q)(`Description for search engines`)),1),I(G(`input`,{id:`meta`,"onUpdate:modelValue":a[1]||=e=>P(n).values.meta_description=e,maxlength:`255`,class:`m-input`},null,512),[[Y,P(n).values.meta_description]]),P(n).errors.meta_description?(H(),U(`p`,_1,k(P(n).errors.meta_description),1)):J(``,!0)]),P(t).defined?(H(),W(Y_,{key:0,fields:P(t).fields,values:P(n).values.content,errors:P(n).errors,prefix:`content.`},null,8,[`fields`,`values`,`errors`])):(H(),U(B,{key:1},[G(`div`,null,[G(`label`,v1,k(P(Q)(`Text (Markdown)`)),1),K(nf,{id:`body`,modelValue:P(n).values.body,"onUpdate:modelValue":a[2]||=e=>P(n).values.body=e},null,8,[`modelValue`]),P(n).errors.body?(H(),U(`p`,y1,k(P(n).errors.body),1)):J(``,!0)]),G(`label`,b1,[I(G(`input`,{"onUpdate:modelValue":a[3]||=e=>P(n).values.is_published=e,type:`checkbox`},null,512),[[du,P(n).values.is_published]]),q(` `+k(P(Q)(`Publish`)),1)])],64)),G(`div`,x1,[G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(n).busy},k(P(n).busy?P(Q)(`Saving…`):P(Q)(`Save`)),9,S1),P(t).defined?J(``,!0):(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-danger`,onClick:i},k(P(Q)(`Delete`)),1))])],32),P(t).id&&P(X).permissions.includes(`revisions.view`)?(H(),W(yf,{key:0,type:`pages`,id:P(t).id},null,8,[`id`])):J(``,!0)],64))}}),w1={class:`font-display mb-6 text-2xl font-bold`},T1={class:`m-card divide-y divide-line`},E1={class:`min-w-0`},D1={class:`truncate font-semibold`},O1={class:`truncate text-xs text-muted`},k1={class:`flex items-center gap-2`},A1={key:0,class:`m-badge`},j1={key:0,class:`p-4 text-sm text-muted`},M1={for:`new-title`,class:`m-label`},N1={key:0,class:`m-error`},P1={for:`new-slug`,class:`m-label`},F1={key:0,class:`m-error`},I1=[`disabled`],L1=[{pattern:/^\/?$/,component:ud,data:!0},{pattern:/^\/login$/,component:Md,guest:!0},{pattern:/^\/profile$/,component:Bp,data:!0},{pattern:/^\/posts$/,component:ap,data:!0},{pattern:/^\/posts\/create$/,component:Kf,data:!0},{pattern:/^\/posts\/\d+\/edit$/,component:Kf,data:!0},{pattern:/^\/media$/,component:kh,data:!0,source:`/media/items`},{pattern:/^\/audit$/,component:Ag,data:!0},{pattern:/^\/statistics$/,component:S_,data:!0},{pattern:/^\/accounts$/,component:ym,data:!0},{pattern:/^\/groups$/,component:Rm,data:!0},{pattern:/^\/labels$/,component:Qm,data:!0},{pattern:/^\/pages$/,component:L({__name:`PagesIndex`,props:{pages:{}},setup(e){let t=qu({slug:``,title:``});async function n(){await t.send(`post`,`${X.base}/pages`)&&U1(`${X.base}/pages/${t.values.slug}`)}return(r,i)=>(H(),U(B,null,[G(`h1`,w1,k(P(Q)(`Pages`)),1),G(`ul`,T1,[(H(!0),U(B,null,R(e.pages,e=>(H(),U(`li`,{key:e.slug,class:`flex items-center justify-between gap-3 p-4`},[G(`div`,E1,[G(`p`,D1,k(e.title),1),G(`p`,O1,`/`+k(e.slug),1)]),G(`div`,k1,[e.defined?J(``,!0):(H(),U(`span`,A1,k(e.is_published?P(Q)(`Published`):P(Q)(`Draft`)),1)),K(ed,{href:`${P(X).base}/pages/${e.slug}`,class:`m-btn m-btn-secondary`},{default:F(()=>[q(k(P(Q)(`Edit`)),1)]),_:1},8,[`href`])])]))),128)),e.pages.length?J(``,!0):(H(),U(`li`,j1,k(P(Q)(`Nothing here yet.`)),1))]),G(`form`,{class:`m-card mt-6 grid max-w-3xl gap-4 p-5 sm:grid-cols-[1fr_1fr_auto] sm:items-end`,onSubmit:Tu(n,[`prevent`])},[G(`div`,null,[G(`label`,M1,k(P(Q)(`Title`)),1),I(G(`input`,{id:`new-title`,"onUpdate:modelValue":i[0]||=e=>P(t).values.title=e,required:``,maxlength:`255`,class:`m-input`},null,512),[[Y,P(t).values.title]]),P(t).errors.title?(H(),U(`p`,N1,k(P(t).errors.title),1)):J(``,!0)]),G(`div`,null,[G(`label`,P1,k(P(Q)(`Address (slug)`)),1),I(G(`input`,{id:`new-slug`,"onUpdate:modelValue":i[1]||=e=>P(t).values.slug=e,required:``,maxlength:`120`,class:`m-input`},null,512),[[Y,P(t).values.slug]]),P(t).errors.slug?(H(),U(`p`,F1,k(P(t).errors.slug),1)):J(``,!0)]),G(`button`,{type:`submit`,class:`m-btn m-btn-primary`,disabled:P(t).busy},k(P(Q)(`New page`)),9,I1)],32)],64))}}),data:!0},{pattern:/^\/pages\/[a-z0-9]+(?:-[a-z0-9]+)*$/,component:C1,data:!0},{pattern:/^\/records\/[a-z][a-z0-9_]*$/,component:d1,data:!0},{pattern:/^\/records\/[a-z][a-z0-9_]*\/(create|\d+\/edit)$/,component:$_,data:!0},{pattern:/^\/reviews$/,component:j_,data:!0}];function R1(e,t,n={}){L1.unshift({pattern:new RegExp(e),component:t,data:n.data,source:n.source})}var $=rn({path:``,component:null,props:{},loading:!0,forbidden:!1,tour:X.tutorial,toast:null}),z1;function B1(e,t=!1){$.toast={text:e,error:t},window.clearTimeout(z1),z1=window.setTimeout(()=>$.toast=null,4e3)}function V1(e){return e.split(`?`)[0].slice(X.base.length)||`/`}async function H1(e){let t=L1.find(t=>t.pattern.test(V1(e)));if(!X.user&&!t?.guest)window.location.assign(X.base+`/login`);else{if(X.user&&t?.guest)return U1(X.base,!0);$.loading=!0,$.forbidden=!1,$.path=e,$.component=t?.component??pd,$.props={};try{$.props=t?.data?await Z.get(t.source?X.base+t.source:e):{}}catch(e){e instanceof Uu&&e.status===401?window.location.assign(X.base+`/login`):e instanceof Uu&&e.status===403?$.forbidden=!0:B1(Q(`Something went wrong. Try again.`),!0)}finally{$.loading=!1}}}function U1(e,t=!1){return window.history[t?`replaceState`:`pushState`]({},``,e),window.scrollTo(0,0),H1(e)}function W1(){return H1($.path)}function G1(){window.addEventListener(`popstate`,()=>H1(window.location.pathname+window.location.search)),H1(window.location.pathname+window.location.search)}var K1=[`aria-label`],q1={key:0,class:`absolute inset-0 bg-black/60`},J1=[`aria-label`],Y1={class:`flex items-start gap-3`},X1={class:`m-bob m-glow -ml-1 shrink-0 rounded-full`},Z1={class:`min-w-0 pr-6`,"aria-live":`polite`},Q1={class:`font-display text-lg font-bold leading-snug`},$1={class:`mt-1.5 text-sm leading-relaxed text-muted`},e0={class:`mt-4 flex items-center justify-between gap-2`},t0={class:`flex gap-1`,"aria-hidden":`true`},n0={class:`text-xs text-muted`},r0={class:`mt-4 flex flex-wrap items-center gap-2`},i0=L({__name:`Tutorial`,setup(e){let t=(X.user?.name??``).split(` `)[0],n=e=>X.navigation.some(t=>t.href.endsWith(e)),r=()=>window.matchMedia(`(min-width: 768px)`).matches;function i(e){if(!(e instanceof HTMLElement))return null;let t=e.getBoundingClientRect();return t.width>0&&t.height>0&&t.left>=0&&t.right<=window.innerWidth&&t.top>=0&&t.bottom<=window.innerHeight?e:null}let a=e=>()=>i(document.querySelector(`nav[aria-label="Manager"] a[href$="${e}"]`));function o(){let e=[{id:`welcome`,image:`welcome`,title:Q(`Hi :name! Welcome!`,{name:t}),text:Q(`I will show you around in a few small steps. Looking around cannot break anything, and you can stop whenever you like: press the cross.`)},{id:`menu`,image:`point`,title:Q(`This is the menu`),text:Q(`Everything you can do lives here. Press a name and you are there.`),target:()=>i(r()?document.querySelector(`nav[aria-label="Manager"]`):document.querySelector(`header button`))},{id:`start`,image:`calm`,title:Q(`Your start page`),text:Q(`Lost? Press Dashboard, at the top of the menu, and you are back here. Nice and calm.`),target:a(`/manager`)}];n(`/posts`)&&e.push({id:`posts`,image:`write`,title:Q(`Write news`),text:Q(`Here you write articles and news for your website. Keep it as a draft until you are happy, then put it online.`),target:a(`/posts`)}),n(`/media`)&&e.push({id:`media`,image:`photos`,title:Q(`Your photos`),text:Q(`All photos and files live here. Upload them once and use them in posts and pages.`),target:a(`/media`)}),n(`/pages`)&&e.push({id:`pages`,image:`pages`,title:Q(`Your pages`),text:Q(`Change the texts and photos of the pages of your website here.`),target:a(`/pages`)});for(let[t,n]of(X.tutorial_steps??[]).entries())e.push({id:`module-`+t,image:n.image??`point`,title:Q(n.title),text:Q(n.text),target:n.href?a(n.href):void 0});return X.permissions.includes(`revisions.view`)&&(n(`/posts`)||n(`/pages`))&&e.push({id:`undo`,image:`undo`,title:Q(`Changed your mind?`),text:Q(`Every time you save a post or a page I keep the old version. You can always put an earlier one back.`)}),e.push({id:`oops`,image:`oops`,title:Q(`Something went wrong?`),text:Q(`A message tells you what. Read it, fix it and try again. Nothing is deleted without asking you first.`)}),e.push({id:`profile`,image:`profile`,title:Q(`Your own corner`),text:Q(`Here you choose your language and your colours, and change your password.`),target:()=>i(document.querySelector(`a[href="${X.base}/profile"]`))}),e.push({id:`party`,image:`party`,title:Q(`That is it!`),text:Q(`Want to see this again? Press Show the tour in the menu. Have fun!`)}),e}let s=o(),c=N(0),l=dc(()=>s[c.value]),u=dc(()=>c.value===s.length-1),d=N(null),f=N(null),p=N(null),m=N(null),h=N(!1);async function g(){await ir();let e=l.value.target?.()??null;if(!e){p.value=null,m.value=null,h.value=!1,f.value?.focus();return}let t=e.getBoundingClientRect(),n=d.value?.offsetHeight??320,i=d.value?.offsetWidth??380;if(p.value={top:t.top-6,left:t.left-6,width:t.width+12,height:t.height+12},!r()){m.value=null,h.value=!1,f.value?.focus();return}let a=t.right+28;m.value={left:a+ivoid 0)}function v(e){let t=c.value+e;if(t>=s.length)return _(!0);c.value=Math.max(0,t),g()}function y(e){e.key===`Escape`?_(!1):e.key===`ArrowRight`?v(1):e.key===`ArrowLeft`&&c.value>0&&v(-1)}return ia(()=>{window.addEventListener(`keydown`,y),window.addEventListener(`resize`,g),g()}),sa(()=>{window.removeEventListener(`keydown`,y),window.removeEventListener(`resize`,g)}),(e,t)=>(H(),U(`div`,{class:`fixed inset-0 z-50`,role:`dialog`,"aria-modal":`true`,"aria-label":P(Q)(`Tour`)},[p.value?(H(),U(`div`,{key:1,class:`m-spot pointer-events-none absolute rounded-xl`,style:_e({top:p.value.top+`px`,left:p.value.left+`px`,width:p.value.width+`px`,height:p.value.height+`px`})},null,4)):(H(),U(`div`,q1)),G(`div`,{ref_key:`card`,ref:d,class:O([`m-card absolute w-[min(24rem,calc(100vw-2rem))] p-5 shadow-2xl`,m.value?``:`bottom-4 left-1/2 -translate-x-1/2 md:bottom-auto md:top-1/2 md:-translate-y-1/2`]),style:_e(m.value?{top:m.value.top+`px`,left:m.value.left+`px`}:void 0)},[G(`button`,{type:`button`,class:`absolute right-3 top-3 rounded-lg p-1.5 text-muted hover:bg-text/10 hover:text-text`,"aria-label":P(Q)(`Stop the tour`),onClick:t[0]||=e=>_(!1)},[...t[4]||=[G(`svg`,{class:`h-5 w-5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`,"stroke-linecap":`round`,"aria-hidden":`true`},[G(`path`,{d:`M6 6l12 12M18 6L6 18`})],-1)]],8,J1),G(`div`,Y1,[G(`div`,X1,[(H(),W(sp,{key:l.value.image,name:l.value.image,flip:h.value,size:128},null,8,[`name`,`flip`]))]),G(`div`,Z1,[G(`h2`,Q1,k(l.value.title),1),G(`p`,$1,k(l.value.text),1)])]),G(`div`,e0,[G(`span`,t0,[(H(!0),U(B,null,R(P(s),(e,t)=>(H(),U(`span`,{key:t,class:O([`h-1.5 w-1.5 rounded-full`,t===c.value?`bg-brand`:`bg-line`])},null,2))),128))]),G(`span`,n0,k(c.value+1)+` / `+k(P(s).length),1)]),G(`div`,r0,[G(`button`,{type:`button`,class:`text-sm text-muted underline hover:text-text`,onClick:t[1]||=e=>_(!1)},k(P(Q)(`Stop the tour`)),1),t[5]||=G(`span`,{class:`flex-1`},null,-1),c.value>0?(H(),U(`button`,{key:0,type:`button`,class:`m-btn m-btn-secondary`,onClick:t[2]||=e=>v(-1)},k(P(Q)(`Back`)),1)):J(``,!0),G(`button`,{ref_key:`next`,ref:f,type:`button`,class:`m-btn m-btn-primary`,onClick:t[3]||=e=>v(1)},k(u.value?P(Q)(`Done`):P(Q)(`Next`)),513)])],6)],8,K1))}}),a0={class:`min-h-screen`},o0={class:`fixed inset-x-0 top-0 z-40 flex h-14 items-center justify-between border-b border-line bg-panel px-4 md:hidden`},s0={class:`font-display font-bold`},c0=[`aria-expanded`],l0={class:`hidden h-16 items-center gap-2 px-5 md:flex`},u0=[`src`],d0={class:`font-display text-lg font-bold`},f0={class:`flex-1 space-y-0.5 overflow-y-auto px-3 py-3`,"aria-label":`Manager`},p0={key:0,class:`my-3 border-line`},m0={key:1,class:`px-3 pb-1 pt-4 text-xs font-semibold uppercase tracking-wide text-muted`},h0=[`href`],g0={class:`border-t border-line p-4`},_0={class:`truncate text-sm font-semibold group-hover:text-brand`},v0={class:`truncate text-xs text-muted`},y0={class:`px-4 pb-16 pt-20 md:ml-60 md:px-8 md:pt-8`},b0={class:`mx-auto max-w-5xl`},x0=L({__name:`Layout`,setup(e){let t=N(!1),n=dc(()=>{let e=[];for(let t of[{label:`Dashboard`,href:X.base,icon:`home`},...X.navigation]){let n=t.section??``,r=e[e.length-1];r&&r.title===n?r.items.push(t):e.push({title:n,items:[t]})}return e}),r=N(X.view);async function i(){await Z.put(X.base+`/profile/view`,{view:r.value===`simple`?`full`:`simple`}),window.location.assign(X.base)}function a(e){let t=$.path.split(`?`)[0];return e===X.base?t===e:t===e||t.startsWith(e+`/`)}async function o(){let{redirect:e}=await Z.post(X.base+`/logout`);window.location.assign(e)}return Nr(()=>$.path,()=>t.value=!1),(e,s)=>(H(),U(`div`,a0,[G(`header`,o0,[G(`span`,s0,k(P(X).name),1),G(`button`,{type:`button`,class:`m-btn m-btn-secondary`,"aria-expanded":t.value,onClick:s[0]||=e=>t.value=!t.value},k(P(Q)(`Menu`)),9,c0)]),G(`aside`,{class:O([`fixed inset-y-0 left-0 z-30 flex w-60 flex-col border-r border-line bg-panel pt-14 transition-transform md:translate-x-0 md:pt-0`,t.value?`translate-x-0`:`-translate-x-full`])},[G(`div`,l0,[P(X).logo?(H(),U(`img`,{key:0,src:P(X).logo,alt:``,class:`h-7 w-auto`},null,8,u0)):J(``,!0),G(`span`,d0,k(P(X).name),1)]),G(`nav`,f0,[(H(!0),U(B,null,R(n.value,(e,t)=>(H(),U(B,{key:e.title+t},[!e.title&&t>0?(H(),U(`hr`,p0)):J(``,!0),e.title?(H(),U(`p`,m0,k(P(Q)(e.title)),1)):J(``,!0),(H(!0),U(B,null,R(e.items,e=>(H(),U(B,{key:e.href},[e.new_tab?(H(),U(`a`,{key:0,href:e.href,target:`_blank`,rel:`noopener`,class:`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-muted transition hover:bg-text/5 hover:text-text`},[K(Qu,{name:e.icon},null,8,[`name`]),q(k(P(Q)(e.label)),1)],8,h0)):(H(),W(ed,{key:1,href:e.href,class:O([`flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition`,a(e.href)?`bg-brand/15 text-text`:`text-muted hover:bg-text/5 hover:text-text`]),"aria-current":a(e.href)?`page`:void 0},{default:F(()=>[K(Qu,{name:e.icon},null,8,[`name`]),q(k(P(Q)(e.label)),1)]),_:2},1032,[`href`,`class`,`aria-current`]))],64))),128))],64))),128))]),G(`div`,g0,[K(ed,{href:P(X).base+`/profile`,class:`group block`},{default:F(()=>[G(`p`,_0,k(P(X).user?.name),1),G(`p`,v0,k(P(X).user?.email),1)]),_:1},8,[`href`]),P(X).tutorial_state?(H(),U(`button`,{key:0,type:`button`,class:`mt-2 block text-xs text-muted underline hover:text-text`,onClick:s[1]||=e=>P($).tour=!0},k(P(Q)(`Show the tour`)),1)):J(``,!0),P(X).can_switch?(H(),U(`button`,{key:1,type:`button`,class:`m-btn m-btn-secondary mt-3 w-full justify-center`,onClick:i},k(r.value===`simple`?P(Q)(`Show everything`):P(Q)(`Simple view`)),1)):J(``,!0),G(`button`,{type:`button`,class:`m-btn m-btn-secondary mt-3 w-full justify-center`,onClick:o},k(P(Q)(`Log out`)),1)])],2),t.value?(H(),U(`div`,{key:0,class:`fixed inset-0 z-20 bg-black/60 md:hidden`,onClick:s[2]||=e=>t.value=!1})):J(``,!0),P($).tour?(H(),W(i0,{key:1})):J(``,!0),G(`main`,y0,[G(`div`,b0,[Sa(e.$slots,`default`)])])]))}}),S0={key:0,class:`m-card p-5 text-sm`},C0={key:1,class:`text-sm text-muted`},w0=L({__name:`App`,setup(e){return(e,t)=>(H(),U(B,null,[P($).component&&!P(X).user?(H(),W(_a(P($).component),{key:0})):P($).component?(H(),W(x0,{key:1},{default:F(()=>[P($).forbidden?(H(),U(`p`,S0,k(P(Q)(`You may not open this page.`)),1)):P($).loading?(H(),U(`p`,C0,k(P(Q)(`Loading…`)),1)):(H(),W(_a(P($).component),Se(Ls({key:2},P($).props)),null,16))]),_:1})):J(``,!0),P($).toast?(H(),U(`div`,{key:2,role:`status`,class:O([`fixed bottom-5 right-5 z-50 rounded-lg border border-l-4 border-line bg-panel px-4 py-3 text-sm font-medium text-text shadow-xl`,P($).toast.error?`border-l-red-500`:`border-l-emerald-500`])},k(P($).toast.text),3)):J(``,!0)],64))}});Xu(X.locale),X.view===`simple`&&document.documentElement.classList.add(`is-simple`),window.IriksManager={Vue:Vu,boot:X,api:Z,t:Q,flash:B1,navigate:U1,register:R1,components:{Link:ed,FormFields:Y_,Icon:Qu,MediaPicker:Hd}};async function T0(){for(let e of X.extensions??[])try{await import(e)}catch(t){console.error(`Manager extension ${e} did not load`,t)}Fu(w0).mount(`#manager`),G1()}T0(); \ No newline at end of file diff --git a/resources/dist/vue.js b/resources/dist/vue.js new file mode 100644 index 0000000..826b71d --- /dev/null +++ b/resources/dist/vue.js @@ -0,0 +1,174 @@ +const Vue = window.IriksManager.Vue; +export const BaseTransition = Vue.BaseTransition; +export const BaseTransitionPropsValidators = Vue.BaseTransitionPropsValidators; +export const Comment = Vue.Comment; +export const DeprecationTypes = Vue.DeprecationTypes; +export const EffectScope = Vue.EffectScope; +export const ErrorCodes = Vue.ErrorCodes; +export const ErrorTypeStrings = Vue.ErrorTypeStrings; +export const Fragment = Vue.Fragment; +export const KeepAlive = Vue.KeepAlive; +export const ReactiveEffect = Vue.ReactiveEffect; +export const Static = Vue.Static; +export const Suspense = Vue.Suspense; +export const Teleport = Vue.Teleport; +export const Text = Vue.Text; +export const TrackOpTypes = Vue.TrackOpTypes; +export const Transition = Vue.Transition; +export const TransitionGroup = Vue.TransitionGroup; +export const TriggerOpTypes = Vue.TriggerOpTypes; +export const VueElement = Vue.VueElement; +export const __esModule = Vue.__esModule; +export const assertNumber = Vue.assertNumber; +export const callWithAsyncErrorHandling = Vue.callWithAsyncErrorHandling; +export const callWithErrorHandling = Vue.callWithErrorHandling; +export const camelize = Vue.camelize; +export const capitalize = Vue.capitalize; +export const cloneVNode = Vue.cloneVNode; +export const compatUtils = Vue.compatUtils; +export const compile = Vue.compile; +export const computed = Vue.computed; +export const createApp = Vue.createApp; +export const createBlock = Vue.createBlock; +export const createCommentVNode = Vue.createCommentVNode; +export const createElementBlock = Vue.createElementBlock; +export const createElementVNode = Vue.createElementVNode; +export const createHydrationRenderer = Vue.createHydrationRenderer; +export const createPropsRestProxy = Vue.createPropsRestProxy; +export const createRenderer = Vue.createRenderer; +export const createSSRApp = Vue.createSSRApp; +export const createSlots = Vue.createSlots; +export const createStaticVNode = Vue.createStaticVNode; +export const createTextVNode = Vue.createTextVNode; +export const createVNode = Vue.createVNode; +export const customRef = Vue.customRef; +export const defineAsyncComponent = Vue.defineAsyncComponent; +export const defineComponent = Vue.defineComponent; +export const defineCustomElement = Vue.defineCustomElement; +export const defineEmits = Vue.defineEmits; +export const defineExpose = Vue.defineExpose; +export const defineModel = Vue.defineModel; +export const defineOptions = Vue.defineOptions; +export const defineProps = Vue.defineProps; +export const defineSSRCustomElement = Vue.defineSSRCustomElement; +export const defineSlots = Vue.defineSlots; +export const devtools = Vue.devtools; +export const effect = Vue.effect; +export const effectScope = Vue.effectScope; +export const getCurrentInstance = Vue.getCurrentInstance; +export const getCurrentScope = Vue.getCurrentScope; +export const getCurrentWatcher = Vue.getCurrentWatcher; +export const getTransitionRawChildren = Vue.getTransitionRawChildren; +export const guardReactiveProps = Vue.guardReactiveProps; +export const h = Vue.h; +export const handleError = Vue.handleError; +export const hasInjectionContext = Vue.hasInjectionContext; +export const hydrate = Vue.hydrate; +export const hydrateOnIdle = Vue.hydrateOnIdle; +export const hydrateOnInteraction = Vue.hydrateOnInteraction; +export const hydrateOnMediaQuery = Vue.hydrateOnMediaQuery; +export const hydrateOnVisible = Vue.hydrateOnVisible; +export const initCustomFormatter = Vue.initCustomFormatter; +export const initDirectivesForSSR = Vue.initDirectivesForSSR; +export const inject = Vue.inject; +export const isMemoSame = Vue.isMemoSame; +export const isProxy = Vue.isProxy; +export const isReactive = Vue.isReactive; +export const isReadonly = Vue.isReadonly; +export const isRef = Vue.isRef; +export const isRuntimeOnly = Vue.isRuntimeOnly; +export const isShallow = Vue.isShallow; +export const isVNode = Vue.isVNode; +export const markRaw = Vue.markRaw; +export const mergeDefaults = Vue.mergeDefaults; +export const mergeModels = Vue.mergeModels; +export const mergeProps = Vue.mergeProps; +export const nextTick = Vue.nextTick; +export const nodeOps = Vue.nodeOps; +export const normalizeClass = Vue.normalizeClass; +export const normalizeProps = Vue.normalizeProps; +export const normalizeStyle = Vue.normalizeStyle; +export const onActivated = Vue.onActivated; +export const onBeforeMount = Vue.onBeforeMount; +export const onBeforeUnmount = Vue.onBeforeUnmount; +export const onBeforeUpdate = Vue.onBeforeUpdate; +export const onDeactivated = Vue.onDeactivated; +export const onErrorCaptured = Vue.onErrorCaptured; +export const onMounted = Vue.onMounted; +export const onRenderTracked = Vue.onRenderTracked; +export const onRenderTriggered = Vue.onRenderTriggered; +export const onScopeDispose = Vue.onScopeDispose; +export const onServerPrefetch = Vue.onServerPrefetch; +export const onUnmounted = Vue.onUnmounted; +export const onUpdated = Vue.onUpdated; +export const onWatcherCleanup = Vue.onWatcherCleanup; +export const openBlock = Vue.openBlock; +export const patchProp = Vue.patchProp; +export const popScopeId = Vue.popScopeId; +export const provide = Vue.provide; +export const proxyRefs = Vue.proxyRefs; +export const pushScopeId = Vue.pushScopeId; +export const queuePostFlushCb = Vue.queuePostFlushCb; +export const reactive = Vue.reactive; +export const readonly = Vue.readonly; +export const ref = Vue.ref; +export const registerRuntimeCompiler = Vue.registerRuntimeCompiler; +export const render = Vue.render; +export const renderList = Vue.renderList; +export const renderSlot = Vue.renderSlot; +export const resolveComponent = Vue.resolveComponent; +export const resolveDirective = Vue.resolveDirective; +export const resolveDynamicComponent = Vue.resolveDynamicComponent; +export const resolveFilter = Vue.resolveFilter; +export const resolveTransitionHooks = Vue.resolveTransitionHooks; +export const setBlockTracking = Vue.setBlockTracking; +export const setDevtoolsHook = Vue.setDevtoolsHook; +export const setTransitionHooks = Vue.setTransitionHooks; +export const shallowReactive = Vue.shallowReactive; +export const shallowReadonly = Vue.shallowReadonly; +export const shallowRef = Vue.shallowRef; +export const ssrContextKey = Vue.ssrContextKey; +export const ssrUtils = Vue.ssrUtils; +export const stop = Vue.stop; +export const toDisplayString = Vue.toDisplayString; +export const toHandlerKey = Vue.toHandlerKey; +export const toHandlers = Vue.toHandlers; +export const toRaw = Vue.toRaw; +export const toRef = Vue.toRef; +export const toRefs = Vue.toRefs; +export const toValue = Vue.toValue; +export const transformVNodeArgs = Vue.transformVNodeArgs; +export const triggerRef = Vue.triggerRef; +export const unref = Vue.unref; +export const useAttrs = Vue.useAttrs; +export const useCssModule = Vue.useCssModule; +export const useCssVars = Vue.useCssVars; +export const useHost = Vue.useHost; +export const useId = Vue.useId; +export const useModel = Vue.useModel; +export const useSSRContext = Vue.useSSRContext; +export const useShadowRoot = Vue.useShadowRoot; +export const useSlots = Vue.useSlots; +export const useTemplateRef = Vue.useTemplateRef; +export const useTransitionState = Vue.useTransitionState; +export const vModelCheckbox = Vue.vModelCheckbox; +export const vModelDynamic = Vue.vModelDynamic; +export const vModelRadio = Vue.vModelRadio; +export const vModelSelect = Vue.vModelSelect; +export const vModelText = Vue.vModelText; +export const vShow = Vue.vShow; +export const version = Vue.version; +export const warn = Vue.warn; +export const watch = Vue.watch; +export const watchEffect = Vue.watchEffect; +export const watchPostEffect = Vue.watchPostEffect; +export const watchSyncEffect = Vue.watchSyncEffect; +export const withAsyncContext = Vue.withAsyncContext; +export const withCtx = Vue.withCtx; +export const withDefaults = Vue.withDefaults; +export const withDirectives = Vue.withDirectives; +export const withKeys = Vue.withKeys; +export const withMemo = Vue.withMemo; +export const withModifiers = Vue.withModifiers; +export const withScopeId = Vue.withScopeId; +export default Vue; diff --git a/resources/js/pulse.js b/resources/js/pulse.js new file mode 100644 index 0000000..fcff87d --- /dev/null +++ b/resources/js/pulse.js @@ -0,0 +1,105 @@ +/* + * Reports a page view of the public site to the statistics of the manager, and how long the page was in view. + * No cookies, no storage, nothing about the visitor: the server decides what it keeps (see the README). A browser that + * asks not to be followed (Do Not Track, Global Privacy Control) is not counted, here and on the server. + * + * + * + * `data-spa` on the script tag: also report the pages a client-side router moves to (history.pushState). + */ +(function () { + 'use strict'; + + var script = document.currentScript; + var base = script && script.src ? script.src.replace(/\/pulse\.js(\?.*)?$/, '') : '/pulse'; + + if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl === true) { + return; + } + + var token = null; + var visible = 0; + var shownAt = document.visibilityState === 'visible' ? Date.now() : null; + var sent = false; + + function params() { + return new URLSearchParams(location.search); + } + + function other(referrer) { + try { + return new URL(referrer).host !== location.host ? referrer : ''; + } catch (e) { + return ''; + } + } + + function report(path, referrer) { + var query = params(); + + fetch(base + '/view', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + credentials: 'omit', + keepalive: true, + body: JSON.stringify({ + path: path, + referrer: referrer, + via: query.get('via') || query.get('utm_source') || '', + campaign: query.get('utm_campaign') || '', + }), + }) + .then(function (response) { return response.ok ? response.json() : null; }) + .then(function (data) { token = data && data.token ? data.token : null; }) + .catch(function () {}); + } + + function leave() { + if (shownAt !== null) { + visible += Date.now() - shownAt; + shownAt = null; + } + + if (token && !sent && visible > 0) { + sent = true; + var body = JSON.stringify({ token: token, seconds: Math.min(Math.round(visible / 1000), 7200) }); + + if (!(navigator.sendBeacon && navigator.sendBeacon(base + '/leave', new Blob([body], { type: 'application/json' })))) { + fetch(base + '/leave', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: body, keepalive: true, credentials: 'omit' }).catch(function () {}); + } + } + } + + function resume() { + shownAt = shownAt === null && document.visibilityState === 'visible' ? Date.now() : shownAt; + sent = false; + } + + document.addEventListener('visibilitychange', function () { + document.visibilityState === 'hidden' ? leave() : resume(); + }); + window.addEventListener('pagehide', leave); + + report(location.pathname, other(document.referrer)); + + if (script && script.hasAttribute('data-spa')) { + var previous = location.pathname; + var push = history.pushState; + + history.pushState = function () { + var result = push.apply(this, arguments); + + if (location.pathname !== previous) { + leave(); + visible = 0; + token = null; + shownAt = Date.now(); + sent = false; + report(location.pathname, location.origin + previous); + previous = location.pathname; + } + + return result; + }; + } +})(); diff --git a/resources/lang/nl.json b/resources/lang/nl.json new file mode 100644 index 0000000..69d4b45 --- /dev/null +++ b/resources/lang/nl.json @@ -0,0 +1,120 @@ +{ + "Audit log": "Auditlog", + "Banned an address": "Een adres geblokkeerd", + "Lifted the ban of an address": "De blokkade van een adres opgeheven", + "Banned the addresses of a group": "De adressen van een groep geblokkeerd", + "Lifted the bans of a group": "De blokkades van een groep opgeheven", + "Wrote or removed the note about an address": "Een notitie over een adres geschreven of verwijderd", + "Changed the rules of the audit log": "De regels van de auditlog gewijzigd", + "Opened the audit log": "De auditlog geopend", + "See the audit log: who logged in and what was done, with addresses and browsers": "De auditlog zien: wie er inlogde en wat er gedaan is, met adressen en browsers", + "Ban addresses and lift bans, write notes about addresses, and set the rules of the audit log": "Adressen blokkeren en weer vrijgeven, notities over adressen schrijven en de regels van de auditlog instellen", + "Media": "Media", + "Uploaded a file": "Een bestand geüpload", + "Changed a file": "Een bestand gewijzigd", + "Deleted a file": "Een bestand verwijderd", + "Opened the media library": "De mediabibliotheek geopend", + "See the media library and pick files from it": "De mediabibliotheek zien en er bestanden uit kiezen", + "Upload files": "Bestanden uploaden", + "Change the name, description and focus point of a file": "De naam, omschrijving en het scherpstelpunt van een bestand wijzigen", + "Delete files": "Bestanden verwijderen", + "Pages": "Pagina's", + "Opened the pages": "De pagina's geopend", + "Change the texts of the pages": "De teksten van de pagina's wijzigen", + "Site content": "Inhoud van de site", + "Posts": "Berichten", + "Categories and tags": "Categorieën en tags", + "Created a post": "Een bericht gemaakt", + "Changed a post": "Een bericht gewijzigd", + "Put a post on the site, or took it off": "Een bericht online gezet of offline gehaald", + "Deleted a post": "Een bericht verwijderd", + "Made a category or tag": "Een categorie of tag gemaakt", + "Renamed a category or tag": "Een categorie of tag hernoemd", + "Removed a category or tag": "Een categorie of tag verwijderd", + "Opened the posts": "De berichten geopend", + "Opened the form for a new post": "Het formulier voor een nieuw bericht geopend", + "Opened a post": "Een bericht geopend", + "Opened the preview of a post": "De voorvertoning van een bericht geopend", + "Opened the categories and tags": "De categorieën en tags geopend", + "See the posts, drafts included": "De berichten zien, concepten inbegrepen", + "Write posts: create drafts and change them": "Berichten schrijven: concepten maken en wijzigen", + "Publish, schedule and unpublish posts, and change posts that are live": "Berichten publiceren, plannen en offline halen, en berichten wijzigen die online staan", + "Delete posts (one that is live only together with publishing)": "Berichten verwijderen (een online bericht alleen samen met publiceren)", + "Manage the categories and tags: make them, and rename, merge and remove them on all posts": "De categorieën en tags beheren: maken, hernoemen, samenvoegen en verwijderen op alle berichten", + "Reviews": "Reviews", + "Opened the reviews": "De reviews geopend", + "Manage the reviews": "De reviews beheren", + "Statistics": "Statistieken", + "Exported the statistics": "De statistieken geëxporteerd", + "Opened the statistics": "De statistieken geopend", + "See the visitor statistics and download them": "De bezoekersstatistieken zien en downloaden", + "Accounts": "Accounts", + "Groups": "Groepen", + "Created an account": "Een account aangemaakt", + "Changed an account": "Een account gewijzigd", + "Deleted an account": "Een account verwijderd", + "Created a group": "Een groep aangemaakt", + "Changed a group": "Een groep gewijzigd", + "Deleted a group": "Een groep verwijderd", + "Opened the accounts": "De accounts geopend", + "Opened the groups": "De groepen geopend", + "Create, change and delete accounts, and put them in groups": "Accounts maken, wijzigen en verwijderen, en in groepen zetten", + "Users": "Gebruikers", + "Changed own account": "Eigen account gewijzigd", + "Logged in": "Ingelogd", + "Logged out": "Uitgelogd", + "Asked for :request": ":request opgevraagd", + "Was not allowed: :what": "Mocht dit niet: :what", + "The address was banned after too many failed logins": "Het adres is geblokkeerd na te veel mislukte inlogpogingen", + "Dark": "Donker", + "Light": "Licht", + "category": "categorie", + "tag": "tag", + "The :type \":name\" already exists.": "De :type \":name\" bestaat al.", + "You cannot delete your own account.": "Je kunt je eigen account niet verwijderen.", + "Another account already uses this email address.": "Een ander account gebruikt dit e-mailadres al.", + "You can only choose groups that allow nothing more than your own account.": "Je kunt alleen groepen kiezen die niet meer toestaan dan je eigen account.", + "The current password is not right.": "Het huidige wachtwoord klopt niet.", + "The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.": "De mediabibliotheek is vol: dit bestand past niet in de ruimte die over is. Verwijder bestanden die niet meer gebruikt worden, of verhoog manager.media.max_total_gb.", + "The file storage is not available right now. Try again in a moment.": "De bestandsopslag is nu niet beschikbaar. Probeer het zo opnieuw.", + ":ip is banned from the whole site.": ":ip is geblokkeerd voor de hele site.", + ":ip is banned from the manager.": ":ip is geblokkeerd voor de manager.", + "The ban of :ip is lifted.": "De blokkade van :ip is opgeheven.", + "The note about :ip is removed.": "De notitie over :ip is verwijderd.", + "The note about :ip is saved.": "De notitie over :ip is opgeslagen.", + "Rules saved.": "Regels opgeslagen.", + "That is the address you are on yourself.": "Dat is het adres waar je zelf op zit.", + "This address is on the list that is never banned.": "Dit adres staat op de lijst die nooit geblokkeerd wordt.", + "this site": "deze site", + "the manager": "de manager", + "This address is blocked from :where.": "Dit adres is geblokkeerd voor :where.", + "This address is blocked from :where until :when.": "Dit adres is geblokkeerd voor :where tot :when.", + "Switched between the simple and the whole manager": "Gewisseld tussen de simpele en de hele manager", + "See the whole manager, not only the simple screens": "De hele manager zien, niet alleen de simpele schermen", + "Switch between the simple and the whole manager": "Wisselen tussen de simpele en de hele manager", + "Manager": "Manager", + "Created a page": "Een pagina gemaakt", + "Changed a page": "Een pagina gewijzigd", + "Removed a page": "Een pagina verwijderd", + "Opened a page": "Een pagina geopend", + "A page with fields of its own cannot be removed.": "Een pagina met eigen velden kan niet verwijderd worden.", + "Resources": "Lijsten", + "Added a record": "Een item toegevoegd", + "Changed a record": "Een item gewijzigd", + "Removed a record": "Een item verwijderd", + "Opened a list": "Een lijst geopend", + "Opened the form for a new record": "Het formulier voor een nieuw item geopend", + "Opened a record": "Een item geopend", + "See :label": ":label bekijken", + "Add, change and delete :label": ":label toevoegen, wijzigen en verwijderen", + "History": "Geschiedenis", + "See the history of posts and pages": "De geschiedenis van berichten en pagina's zien", + "Put an earlier version of a post or page back": "Een eerdere versie van een bericht of pagina terugzetten", + "Put an earlier version back": "Een eerdere versie teruggezet", + "Opened the history of a text": "De geschiedenis van een tekst geopend", + "Prove you are not a program, then log in again.": "Laat zien dat je geen programma bent en log dan opnieuw in.", + "Finished or skipped the tour": "Rondleiding afgerond of overgeslagen", + "Write and put news on your website": "Schrijf nieuws en zet het op je website", + "Change the texts and photos of your pages": "Pas de teksten en foto's van je pagina's aan", + "Your photos and files": "Je foto's en bestanden" +} diff --git a/resources/mascot/calm.webp b/resources/mascot/calm.webp new file mode 100644 index 0000000..14438c5 Binary files /dev/null and b/resources/mascot/calm.webp differ diff --git a/resources/mascot/oops.webp b/resources/mascot/oops.webp new file mode 100644 index 0000000..45f6e44 Binary files /dev/null and b/resources/mascot/oops.webp differ diff --git a/resources/mascot/pages.webp b/resources/mascot/pages.webp new file mode 100644 index 0000000..47f1884 Binary files /dev/null and b/resources/mascot/pages.webp differ diff --git a/resources/mascot/party.webp b/resources/mascot/party.webp new file mode 100644 index 0000000..a92ecc4 Binary files /dev/null and b/resources/mascot/party.webp differ diff --git a/resources/mascot/peek.webp b/resources/mascot/peek.webp new file mode 100644 index 0000000..66b6294 Binary files /dev/null and b/resources/mascot/peek.webp differ diff --git a/resources/mascot/photos.webp b/resources/mascot/photos.webp new file mode 100644 index 0000000..4c391a0 Binary files /dev/null and b/resources/mascot/photos.webp differ diff --git a/resources/mascot/point.webp b/resources/mascot/point.webp new file mode 100644 index 0000000..5206c9e Binary files /dev/null and b/resources/mascot/point.webp differ diff --git a/resources/mascot/profile.webp b/resources/mascot/profile.webp new file mode 100644 index 0000000..39d1829 Binary files /dev/null and b/resources/mascot/profile.webp differ diff --git a/resources/mascot/undo.webp b/resources/mascot/undo.webp new file mode 100644 index 0000000..009f897 Binary files /dev/null and b/resources/mascot/undo.webp differ diff --git a/resources/mascot/welcome.webp b/resources/mascot/welcome.webp new file mode 100644 index 0000000..6f9e882 Binary files /dev/null and b/resources/mascot/welcome.webp differ diff --git a/resources/mascot/write.webp b/resources/mascot/write.webp new file mode 100644 index 0000000..fd5504d Binary files /dev/null and b/resources/mascot/write.webp differ diff --git a/resources/views/banned.blade.php b/resources/views/banned.blade.php new file mode 100644 index 0000000..16528f3 --- /dev/null +++ b/resources/views/banned.blade.php @@ -0,0 +1,13 @@ + + + + + + + {{ $status === 429 ? 'Too many attempts' : 'Blocked' }} + + +

{{ $status === 429 ? 'Too many attempts' : 'Blocked' }}

+

{{ $message }}

+ + diff --git a/resources/views/components/pulse.blade.php b/resources/views/components/pulse.blade.php new file mode 100644 index 0000000..94f40d9 --- /dev/null +++ b/resources/views/components/pulse.blade.php @@ -0,0 +1,5 @@ +{{-- Counts the page in the statistics of the manager (module `statistics`). Put it once in the layout of the public site. --}} +@props(['spa' => false]) +@if (\Illuminate\Support\Facades\Route::has(\IriksIT\Manager\Support\Names::route('pulse.script'))) + +@endif diff --git a/resources/views/dashboard.blade.php b/resources/views/dashboard.blade.php new file mode 100644 index 0000000..c9fa81f --- /dev/null +++ b/resources/views/dashboard.blade.php @@ -0,0 +1,16 @@ + + + + + + Manager + + +

Manager

+ + + diff --git a/resources/views/shell.blade.php b/resources/views/shell.blade.php new file mode 100644 index 0000000..ae2868e --- /dev/null +++ b/resources/views/shell.blade.php @@ -0,0 +1,21 @@ + + + + + + + {{ $title }} + {{-- The theme: values were checked by IriksIT\Manager\Support\Themes, nothing else goes in here. --}} + + + + + @if ($extensions !== []) + {{-- A bundle of the site imports `vue`: this makes it the Vue of the screens. Before any module script. --}} + + @endif +
+ + + + diff --git a/routes/guest.php b/routes/guest.php new file mode 100644 index 0000000..2179397 --- /dev/null +++ b/routes/guest.php @@ -0,0 +1,12 @@ +name('assets')->where('file', '[a-z.]+'); +Route::get('/_assets/mascot/{name}', MascotController::class)->name('mascot')->where('name', '[a-z]+'); +Route::get('/login', fn () => abort(404))->name('login'); // the shell answers browsers before this runs +Route::post('/login', [LoginController::class, 'store'])->name('login.store')->middleware('throttle:manager-login'); diff --git a/routes/manager.php b/routes/manager.php new file mode 100644 index 0000000..d7e82e8 --- /dev/null +++ b/routes/manager.php @@ -0,0 +1,19 @@ +name('dashboard'); +Route::get('/profile', [ProfileController::class, 'show'])->name('profile.show'); +Route::put('/profile', [ProfileController::class, 'update'])->name('profile.update'); +Route::put('/profile/view', [ProfileController::class, 'view'])->name('profile.view'); +Route::put('/profile/tutorial', [ProfileController::class, 'tutorial'])->name('profile.tutorial'); +Route::post('/markdown', MarkdownController::class)->name('markdown.preview')->middleware('throttle:120,1'); +Route::post('/logout', [LoginController::class, 'destroy'])->name('logout'); + +// A screen that exists only in the bundle of the site (`manager.extensions`) has no route of its own: a browser that +// asks for it gets the shell, which shows the screen. Anything else that asks for data gets a plain 404. +Route::fallback(fn () => abort(404)); diff --git a/src/Concerns/HasManagerAccess.php b/src/Concerns/HasManagerAccess.php new file mode 100644 index 0000000..2611f3c --- /dev/null +++ b/src/Concerns/HasManagerAccess.php @@ -0,0 +1,73 @@ + */ + public function managerGroups(): BelongsToMany + { + return $this->belongsToMany(Group::class, Names::table('group_user'), 'user_id', 'group_id'); + } + + public function isManagerSuperAdmin(): bool + { + return (bool) $this->getAttribute('is_super_admin'); + } + + /** + * Everything this account may do in the manager. + * + * @return list + */ + public function managerPermissions(): array + { + $registry = app(ModuleRegistry::class); + + if ($this->isManagerSuperAdmin()) { + return $registry->permissionValues(); + } + + $fromGroups = Sources::usesGroups() ? $this->managerGroups->flatMap(fn (Group $group) => $group->allowed())->all() : []; + + return $registry->complete([...$fromGroups, ...Sources::fromHost($this)]); + } + + public function hasManagerPermission(string $permission): bool + { + return in_array($permission, $this->managerPermissions(), true); + } + + /** + * Whether this account may do everything $other may. Someone who manages accounts only + * touches accounts that stay within their own rights; otherwise a new password for a + * mightier account would be a way up. + */ + public function managerOutranks(self $other): bool + { + if ($this->isManagerSuperAdmin()) { + return true; + } + + return ! $other->isManagerSuperAdmin() && array_diff($other->managerPermissions(), $this->managerPermissions()) === []; + } + + /** Whether this account may put someone in $group: only when the group gives nothing it lacks itself. */ + public function managerMayGive(Group $group): bool + { + return $this->isManagerSuperAdmin() || array_diff($group->allowed(), $this->managerPermissions()) === []; + } +} diff --git a/src/Console/DoctorCommand.php b/src/Console/DoctorCommand.php new file mode 100644 index 0000000..6bdb780 --- /dev/null +++ b/src/Console/DoctorCommand.php @@ -0,0 +1,190 @@ + */ + private array $checks = []; + + public function handle(ModuleRegistry $modules): int + { + $this->checkUserModel($modules); + $this->checkTables($modules); + $this->checkRoutes(); + $this->checkNames(); + $this->checkModules($modules); + + $failed = collect($this->checks)->contains('status', 'fail'); + + if ($this->option('json')) { + $this->line(json_encode(['ok' => ! $failed, 'checks' => $this->checks], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); + } else { + foreach ($this->checks as $check) { + $line = sprintf('[%s] %s: %s', strtoupper($check['status']), $check['check'], $check['message']); + $check['status'] === 'fail' ? $this->error($line) : ($check['status'] === 'warn' ? $this->warn($line) : $this->info($line)); + + if ($check['fix'] !== null && $check['status'] !== 'ok') { + $this->line(' fix: '.$check['fix']); + } + } + } + + return $failed ? self::FAILURE : self::SUCCESS; + } + + private function add(string $check, string $status, string $message, ?string $fix = null): void + { + $this->checks[] = ['check' => $check, 'status' => $status, 'message' => $message, 'fix' => $fix]; + } + + private function checkUserModel(ModuleRegistry $modules): void + { + $model = config('manager.user_model'); + + if (! is_string($model) || ! class_exists($model)) { + $this->add('user_model', 'fail', 'manager.user_model is not a class: '.var_export($model, true), 'Set MANAGER_USER_MODEL (or manager.user_model) to your User model, for example App\\Models\\User.'); + + return; + } + + $this->add('user_model', 'ok', "The user model is {$model}."); + + $guard = config('auth.defaults.guard'); + $loggedIn = config('auth.providers.'.config("auth.guards.{$guard}.provider").'.model'); + + if (is_string($loggedIn) && $loggedIn !== $model && ! is_subclass_of($loggedIn, $model) && ! is_subclass_of($model, $loggedIn)) { + $this->add('auth_model', 'fail', "People log in as {$loggedIn} (config/auth.php), but manager.user_model is {$model}: the manager would not know their rights.", 'Point manager.user_model (MANAGER_USER_MODEL) at the same model as the auth provider.'); + } + + if (! in_array(HasManagerAccess::class, class_uses_recursive($model), true)) { + $this->add('user_trait', 'fail', "{$model} does not use HasManagerAccess.", "Add `use \\IriksIT\\Manager\\Concerns\\HasManagerAccess;` inside the class {$model}."); + + return; + } + + $this->add('user_trait', 'ok', 'The user model uses HasManagerAccess.'); + + if (in_array('is_super_admin', (new $model)->getFillable(), true)) { + $this->add('super_admin_fillable', 'fail', 'is_super_admin is mass assignable: anyone who can fill the model could make themselves a super admin.', 'Remove is_super_admin from $fillable of the user model.'); + } + + if ($modules->enabled('users') && Schema::hasTable((new $model)->getTable()) && Schema::hasTable(Names::table('groups'))) { + $admins = $model::query()->where('is_super_admin', true)->count(); + $admins > 0 + ? $this->add('super_admin', 'ok', "{$admins} super admin(s) exist.") + : $this->add('super_admin', 'warn', 'There is no super admin yet: nobody can manage groups.', 'php artisan manager:create-user --name=... --email=... --password=...'); + } + } + + private function checkTables(ModuleRegistry $modules): void + { + $missing = []; + + foreach ($modules->active() as $module) { + foreach (method_exists($module, 'tables') ? $module->tables() : [] as $table) { + if (! Schema::hasTable(Names::table($table))) { + $missing[] = Names::table($table); + } + } + } + + $missing === [] + ? $this->add('tables', 'ok', 'The tables of every active module exist.') + : $this->add('tables', 'fail', 'Missing tables: '.implode(', ', $missing), 'php artisan migrate'); + } + + private function checkRoutes(): void + { + Route::has(Names::route('dashboard')) + ? $this->add('routes', 'ok', 'The manager routes are registered under /'.trim((string) config('manager.path'), '/').'.') + : $this->add('routes', 'fail', 'The manager routes are not registered.', 'Run `composer dump-autoload` and make sure the package service provider is discovered (not in dont-discover).'); + + if (Route::has('login')) { + $this->add('login', 'ok', 'The app has a login route.'); + } elseif (Route::has(Names::route('login'))) { + $this->add('login', 'ok', 'The app has no login of its own: visitors use the login of the manager.'); + } else { + $this->add('login', 'warn', 'There is no login: the auth middleware has nowhere to send visitors.', 'Set MANAGER_UI=package (the manager brings a login), or add a login to the app.'); + } + } + + /** Route names or addresses of the site that the package would share with its own. */ + private function checkNames(): void + { + $prefix = Names::routePrefix(); + $path = trim((string) config('manager.path'), '/'); + $names = []; + $foreign = []; + + foreach (Route::getRoutes()->getRoutes() as $route) { + $name = (string) $route->getName(); + $mine = $route->isFallback || ($route->getActionName() === 'Closure' && str_starts_with($name, $prefix)) || str_starts_with(ltrim($route->getActionName(), '\\'), 'IriksIT\\Manager\\'); + + if ($prefix !== '' && str_starts_with($name, $prefix) && $name !== $prefix) { + $names[$name] = ($names[$name] ?? 0) + 1; + } + + if (! $mine && ($route->uri() === $path || str_starts_with($route->uri(), $path.'/'))) { + $foreign[] = $route->uri(); + } + } + + $twice = array_keys(array_filter($names, fn (int $count) => $count > 1)); + + if ($twice !== []) { + $this->add('names', 'warn', 'Route names used twice: '.implode(', ', array_slice($twice, 0, 5)).'. The site and the manager share them, and one of the two stops working.', "Set 'route_name' in config/manager.php to something the site does not use, for example 'cms'."); + } elseif ($foreign !== []) { + $this->add('names', 'warn', 'The site has routes under the address of the manager: '.implode(', ', array_slice($foreign, 0, 5)).'.', "Move them, or set 'path' in config/manager.php (MANAGER_PATH) to another address."); + } else { + $this->add('names', 'ok', 'No route name or address is shared with the site.'); + } + } + + private function checkModules(ModuleRegistry $modules): void + { + $active = array_keys($modules->active()); + $this->add('modules', 'ok', 'Active modules: '.implode(', ', $active).'.'); + + if ($modules->enabled('media')) { + $disk = config('manager.media.disk'); + config("filesystems.disks.{$disk}") === null + ? $this->add('media_disk', 'fail', "The media disk \"{$disk}\" is not in config/filesystems.php.", 'Set MANAGER_MEDIA_DISK to a disk that exists.') + : $this->add('media_disk', 'ok', "The media disk is \"{$disk}\"."); + + if ($disk === 'public' && ! file_exists(public_path('storage'))) { + $this->add('storage_link', 'warn', 'public/storage does not exist: uploaded files cannot be served from the public disk.', 'php artisan storage:link'); + } + } + + if ($modules->enabled('audit')) { + $this->add('proxies', 'warn', 'The audit log stores the visitor address. Behind a proxy or load balancer, trusted proxies must be configured, or every visitor looks like one address and one bad actor can lock the manager out.', 'Configure trusted proxies (bootstrap/app.php: $middleware->trustProxies(...)) and set MANAGER_NEVER_BAN to your own address.'); + } + + if ($modules->enabled('statistics')) { + $pages = (array) config('manager.statistics.pages'); + $pages === ['/'] && ! config('manager.statistics.posts_path') + ? $this->add('statistics_pages', 'warn', 'Only the home page counts in the statistics.', 'Set manager.statistics.pages (and posts_path), or register a resolver with CountedPages::register().') + : $this->add('statistics_pages', 'ok', 'The statistics count '.count($pages).' page(s) and '.(config('manager.statistics.posts_path') ? 'the posts' : 'no posts').'.'); + } + } +} diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php new file mode 100644 index 0000000..5b4c54e --- /dev/null +++ b/src/Console/ImportCommand.php @@ -0,0 +1,70 @@ +` (`table`, `connection`, `map`). + */ +class ImportCommand extends Command +{ + protected $signature = 'manager:import {target : posts, pages or reviews} + {--table= : Table to read (default: config manager.import..table)} + {--connection= : Database connection of that table (default: the default one)} + {--map=* : package_column=source_column, repeat for each column that is named differently} + {--limit= : Only the first rows} + {--dry-run : Count what would happen and write nothing}'; + + protected $description = 'Copy the existing posts, pages or reviews of the site into the package tables'; + + public function handle(Importer $importer): int + { + $target = (string) $this->argument('target'); + $config = (array) config('manager.import.'.$target, []); + $table = $this->option('table') ?: ($config['table'] ?? null); + + if (! is_string($table) || $table === '') { + $this->error('Which table? Give --table=... or set manager.import.'.$target.'.table.'); + + return self::FAILURE; + } + + $map = (array) ($config['map'] ?? []); + + foreach ((array) $this->option('map') as $pair) { + if (! str_contains((string) $pair, '=')) { + $this->error("--map wants package_column=source_column, got {$pair}"); + + return self::FAILURE; + } + + [$to, $from] = explode('=', (string) $pair, 2); + $map[trim($to)] = trim($from); + } + + try { + $connection = DB::connection($this->option('connection') ?: ($config['connection'] ?? null)); + $result = $importer->run($target, $connection, $table, $map, (bool) $this->option('dry-run'), $this->option('limit') !== null ? (int) $this->option('limit') : null); + } catch (InvalidArgumentException $e) { + $this->error($e->getMessage()); + + return self::FAILURE; + } + + foreach ($result['problems'] as $problem) { + $this->warn($problem); + } + + $this->info(($this->option('dry-run') ? 'Dry run: ' : '')."{$result['created']} created, {$result['updated']} updated, {$result['skipped']} skipped."); + + return self::SUCCESS; + } +} diff --git a/src/Console/InstallCommand.php b/src/Console/InstallCommand.php new file mode 100644 index 0000000..82745e4 --- /dev/null +++ b/src/Console/InstallCommand.php @@ -0,0 +1,96 @@ +callSilently('vendor:publish', ['--tag' => 'manager-config']); + + $env = []; + + if ($list = $this->option('modules')) { + $wanted = array_filter(array_map('trim', explode(',', $list))); + $unknown = array_diff($wanted, array_keys($modules->all())); + + if ($unknown !== []) { + $this->error('Unknown module(s): '.implode(', ', $unknown).'. Known: '.implode(', ', array_keys($modules->all())).'.'); + + return self::FAILURE; + } + + foreach (array_keys($modules->all()) as $key) { + if (in_array($key, ['users', 'media'], true)) { + continue; // switched in config, on by default + } + + $env['MANAGER_'.strtoupper($key)] = in_array($key, $wanted, true) ? 'true' : 'false'; + } + } + + if ($model = $this->option('user-model')) { + $env['MANAGER_USER_MODEL'] = $model; + } + + if ($path = $this->option('path')) { + $env['MANAGER_PATH'] = trim($path, '/'); + } + + foreach ($env as $key => $value) { + $this->writeEnv($key, $value); + } + + if ($env !== []) { + $this->line('Wrote to .env: '.implode(', ', array_map(fn ($k, $v) => "{$k}={$v}", array_keys($env), $env)).'. Run `php artisan config:clear` if the config is cached.'); + } + + if ($this->option('migrate')) { + // The switches were just written: a fresh process sees them, this one still has the old config. + $this->line('Run `php artisan migrate` (a new process) so the migrations of the modules you switched on are loaded.'); + } + + if ($env !== []) { + // This process still has the old config: its check would report the old state. A new process is right. + $this->line('Next: add the HasManagerAccess trait to the user model, run `php artisan config:clear && php artisan migrate && php artisan storage:link`, then `php artisan manager:doctor --json`.'); + + return self::SUCCESS; + } + + return Artisan::call('manager:doctor', $this->option('json') ? ['--json' => true] : [], $this->output) === 0 ? self::SUCCESS : self::FAILURE; + } + + private function writeEnv(string $key, string $value): void + { + $file = base_path('.env'); + $contents = file_exists($file) ? file_get_contents($file) : ''; + $line = "{$key}={$value}"; + + $contents = preg_match("/^{$key}=.*$/m", $contents) + ? preg_replace("/^{$key}=.*$/m", $line, $contents) + : rtrim($contents, "\n")."\n{$line}\n"; + + file_put_contents($file, $contents); + } +} diff --git a/src/Console/MakeThemeCommand.php b/src/Console/MakeThemeCommand.php new file mode 100644 index 0000000..5bd6920 --- /dev/null +++ b/src/Console/MakeThemeCommand.php @@ -0,0 +1,95 @@ +argument('key'); + + if (! preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', $key)) { + $this->error('The key may only hold lowercase letters, numbers and dashes.'); + + return self::FAILURE; + } + + $raw = [ + 'label' => $this->option('label') ?: ucfirst($key), + 'scheme' => $this->option('light') ? 'light' : 'dark', + 'name' => $this->option('name'), + 'logo' => $this->option('logo'), + 'font' => $this->option('font'), + 'font_display' => $this->option('font-display'), + 'radius' => $this->option('radius'), + 'colors' => array_filter([ + 'brand' => $this->option('brand'), 'brand_alt' => $this->option('brand-alt'), 'ink' => $this->option('ink'), + 'panel' => $this->option('panel'), 'text' => $this->option('text'), + ]), + ]; + + // What the manager would accept: tell what was thrown away instead of silently writing a different theme. + $clean = $themes->sanitize($key, $raw); + $rejected = []; + + foreach ($raw['colors'] as $name => $value) { + ($clean['colors'][$name] ?? null) === $value || $rejected[] = $name.' ('.$value.')'; + } + + foreach (['radius', 'font', 'font_display', 'logo'] as $option) { + $raw[$option] !== null && ($clean[$option] ?? null) !== $raw[$option] && $rejected[] = $option.' ('.$raw[$option].')'; + } + + if ($rejected !== []) { + $this->error('Not accepted: '.implode(', ', $rejected).'. Colours are #rgb or #rrggbb; no quotes or semicolons in fonts.'); + + return self::FAILURE; + } + + $folder = $this->option('path') ?: (config('manager.themes_path') ?: resource_path('manager-themes')); + $file = rtrim($folder, '/')."/{$key}.json"; + + if (file_exists($file) && ! $this->option('force')) { + $this->error("{$file} exists. Use --force to overwrite it."); + + return self::FAILURE; + } + + is_dir($folder) || mkdir($folder, 0775, true); + $out = array_filter(['label' => $clean['label'], 'scheme' => $clean['scheme'], 'name' => $clean['name'], 'logo' => $clean['logo'], 'font' => $clean['font'], 'font_display' => $clean['font_display'], 'radius' => $clean['radius'], 'colors' => $clean['colors']], fn ($value) => $value !== null); + file_put_contents($file, json_encode($out, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n"); + + $this->info("Wrote {$file}. Everyone sees it with MANAGER_THEME={$key}; each account can pick it in its profile."); + + return self::SUCCESS; + } +} diff --git a/src/Contracts/LoginCheck.php b/src/Contracts/LoginCheck.php new file mode 100644 index 0000000..37cf31d --- /dev/null +++ b/src/Contracts/LoginCheck.php @@ -0,0 +1,30 @@ +> + */ + public function fields(): array; + + /** Runs first, before the password is looked at: a captcha belongs here. */ + public function before(Request $request): void; + + /** + * Runs when the email and password are right, before anyone is logged in: a second factor belongs here. When it refuses, the + * attempt counts as a failed login (the audit log and the bans see it). + */ + public function after(Request $request, Authenticatable $user): void; +} diff --git a/src/Contracts/Module.php b/src/Contracts/Module.php new file mode 100644 index 0000000..39f1707 --- /dev/null +++ b/src/Contracts/Module.php @@ -0,0 +1,73 @@ + keys of modules this one cannot work without */ + public function requires(): array; + + /** + * Permissions this module adds. Values are prefixed by the module key. + * + * @return list + */ + public function permissions(): array; + + /** @return list */ + public function navigation(): array; + + /** Absolute path of the routes file, or null. */ + public function routes(): ?string; + + /** Absolute path of a routes file outside the manager (no prefix, no manager middleware), or null. */ + public function publicRoutes(): ?string; + + /** Absolute path of the migrations folder, or null. */ + public function migrations(): ?string; + + /** @return list Artisan commands this module adds */ + public function commands(): array; + + /** + * What the audit log calls each thing that is done through this module's routes, by route + * name without the `manager.` prefix: `[label]` or `[label, [form fields that may be kept]]`. + * Never list a field a secret could be typed in. + * + * @return array}> + */ + public function actions(): array; + + /** + * What the audit log calls opening a page (a GET route), by route name without `manager.`. + * + * @return array + */ + public function views(): array; + + /** + * Middleware this module wants around every manager route: `before` runs ahead of the site's + * own manager middleware (session, login), `after` behind it. + * + * @return array{before?: list, after?: list} + */ + public function middleware(): array; + + /** Runs at boot, only when the module is on (register rate limiters, usage sources, ...). */ + public function boot(): void; +} diff --git a/src/Contracts/PermissionResolver.php b/src/Contracts/PermissionResolver.php new file mode 100644 index 0000000..17ccd59 --- /dev/null +++ b/src/Contracts/PermissionResolver.php @@ -0,0 +1,15 @@ + permission values such as `posts.write` */ + public function permissions(Authenticatable $user): array; +} diff --git a/src/Exceptions/MediaStorageException.php b/src/Exceptions/MediaStorageException.php new file mode 100644 index 0000000..800ca12 --- /dev/null +++ b/src/Exceptions/MediaStorageException.php @@ -0,0 +1,17 @@ + 'application/javascript', 'manager.css' => 'text/css', 'vue.js' => 'application/javascript']; + + public function __invoke(string $file): BinaryFileResponse + { + abort_unless(isset(self::FILES[$file]) && is_file($path = __DIR__.'/../../../resources/dist/'.$file), 404); + + return response()->file($path, [ + 'Content-Type' => self::FILES[$file], + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'X-Content-Type-Options' => 'nosniff', + ]); + } +} diff --git a/src/Http/Controllers/DashboardController.php b/src/Http/Controllers/DashboardController.php new file mode 100644 index 0000000..23a3f72 --- /dev/null +++ b/src/Http/Controllers/DashboardController.php @@ -0,0 +1,22 @@ +user(); + + // Only what this account may reach, in the face it looks at. + $navigation = $menu->for($user, array_values(array_filter($modules->permissionValues(), fn (string $permission) => $user?->can($permission)))); + + return $request->wantsJson() + ? response()->json(['navigation' => $navigation]) + : view('manager::dashboard', ['navigation' => $navigation]); + } +} diff --git a/src/Http/Controllers/LoginController.php b/src/Http/Controllers/LoginController.php new file mode 100644 index 0000000..ec787f4 --- /dev/null +++ b/src/Http/Controllers/LoginController.php @@ -0,0 +1,57 @@ +before($request); + + $credentials = $request->validate([ + 'email' => ['required', 'string', 'email', 'max:255'], + 'password' => ['required', 'string', 'max:200'], + ]); + + $refused = null; + + // `attemptWhen` runs the second checks after the password is right and before the login begins; a refusal is a failed login. + $loggedIn = Auth::attemptWhen($credentials, function ($user) use ($checks, $request, &$refused) { + try { + $checks->after($request, $user); + } catch (ValidationException $e) { + $refused = $e; + + return false; + } + + return true; + }, $request->boolean('remember')); + + if (! $loggedIn) { + throw $refused ?? ValidationException::withMessages(['email' => trans('auth.failed')]); + } + + $request->session()->regenerate(); + + return response()->json(['redirect' => '/'.trim((string) config('manager.path'), '/')]); + } + + public function destroy(Request $request): JsonResponse + { + Auth::guard()->logout(); + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return response()->json(['redirect' => Route::has(Names::route('login')) ? route(Names::route('login'), [], false) : '/']); + } +} diff --git a/src/Http/Controllers/MarkdownController.php b/src/Http/Controllers/MarkdownController.php new file mode 100644 index 0000000..c67d6d6 --- /dev/null +++ b/src/Http/Controllers/MarkdownController.php @@ -0,0 +1,18 @@ +validate(['text' => ['nullable', 'string', 'max:200000']]); + + return response()->json(['html' => Markdown::toHtml((string) ($data['text'] ?? ''))]); + } +} diff --git a/src/Http/Controllers/MascotController.php b/src/Http/Controllers/MascotController.php new file mode 100644 index 0000000..6f2e422 --- /dev/null +++ b/src/Http/Controllers/MascotController.php @@ -0,0 +1,43 @@ +.webp` or `.png` in `manager.mascot.path` (default: resources/mascot of + * the package); a site can give its own set by pointing the path at a folder of its own. A picture that is not there is + * answered with a small paw, so the tour works before the pictures do. + */ +class MascotController +{ + /** What the tour asks for. */ + public const NAMES = ['welcome', 'point', 'calm', 'write', 'photos', 'pages', 'undo', 'oops', 'party', 'profile', 'peek']; + + private const TYPES = ['webp' => 'image/webp', 'png' => 'image/png']; + + public function __invoke(string $name): BinaryFileResponse|Response + { + abort_unless(in_array($name, self::NAMES, true), 404); + + $folder = rtrim((string) (config('manager.mascot.path') ?: __DIR__.'/../../../resources/mascot'), '/'); + + foreach (self::TYPES as $extension => $type) { + if (is_file($path = "$folder/$name.$extension")) { + return response()->file($path, ['Content-Type' => $type, 'Cache-Control' => 'public, max-age=86400', 'X-Content-Type-Options' => 'nosniff']); + } + } + + return response(self::paw(), 200, ['Content-Type' => 'image/svg+xml', 'Cache-Control' => 'public, max-age=300', 'X-Content-Type-Options' => 'nosniff']); + } + + /** A paw: the stand-in for every picture that is not there yet. */ + private static function paw(): string + { + return '' + .'' + .'' + .''; + } +} diff --git a/src/Http/Controllers/ProfileController.php b/src/Http/Controllers/ProfileController.php new file mode 100644 index 0000000..2e894b5 --- /dev/null +++ b/src/Http/Controllers/ProfileController.php @@ -0,0 +1,87 @@ +user(); + + return response()->json(['profile' => [ + 'name' => (string) $user->name, + 'email' => (string) $user->email, + 'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(), + 'groups' => method_exists($user, 'managerGroups') ? $user->managerGroups()->pluck('name')->values() : [], + 'theme' => $themes->keyFor($user), + 'locale' => UserSetting::value($user, 'locale') ?? app()->getLocale(), + 'locales' => UserSetting::LOCALES, + 'tutorial' => UserSetting::value($user, 'tutorial'), + 'themes' => config('manager.user_themes') + ? collect($themes->all())->map(fn (array $theme, string $key) => ['key' => $key, 'label' => __($theme['label']), 'colors' => $theme['colors']])->values() + : [], + ]]); + } + + /** The face of the manager (`full` or `simple`) an account that may switch looks at. */ + public function view(Request $request, Menu $menu): JsonResponse + { + abort_unless($menu->maySwitch($request->user()), 403); + + $data = $request->validate(['view' => ['required', Rule::in([Menu::FULL, Menu::SIMPLE])]]); + UserSetting::put($request->user(), ['view' => $data['view']]); + + return response()->json(['view' => $data['view']]); + } + + /** Where the account stands with the tour: finished, skipped, or (to look at it again) pending. Any account may, for itself. */ + public function tutorial(Request $request): JsonResponse + { + $data = $request->validate(['state' => ['required', Rule::in(UserSetting::TUTORIAL)]]); + UserSetting::put($request->user(), ['tutorial' => $data['state']]); + + return response()->json(['tutorial' => $data['state']]); + } + + public function update(Request $request, Themes $themes): JsonResponse + { + $user = $request->user(); + app(AuditTrail::class)->about($user); + + $data = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'current_password' => ['nullable', 'string', 'max:200'], + 'password' => ['nullable', 'string', 'min:12', 'max:200', 'confirmed'], + 'theme' => ['nullable', 'string', Rule::in(array_keys($themes->all()))], + 'locale' => ['nullable', 'string', Rule::in(UserSetting::LOCALES)], + ]); + + if (($data['password'] ?? '') !== '' && ! Hash::check((string) ($data['current_password'] ?? ''), $user->getAuthPassword())) { + return response()->json(['message' => $wrong = __('The current password is not right.'), 'errors' => ['current_password' => [$wrong]]], 422); + } + + $user->name = $data['name']; + ($data['password'] ?? '') !== '' && $user->password = Hash::make($data['password']); + $user->save(); + + if (config('manager.user_themes') && $request->has('theme')) { + UserSetting::put($user, ['theme' => $data['theme'] ?: null]); + } + + if ($request->has('locale')) { + UserSetting::put($user, ['locale' => $data['locale'] ?: null]); + } + + return response()->json(['saved' => true]); + } +} diff --git a/src/Http/Middleware/Authenticate.php b/src/Http/Middleware/Authenticate.php new file mode 100644 index 0000000..ae86f6e --- /dev/null +++ b/src/Http/Middleware/Authenticate.php @@ -0,0 +1,21 @@ +expectsJson()) { + return null; + } + + return Route::has('login') ? route('login') : (Route::has(Names::route('login')) ? route(Names::route('login')) : null); + } +} diff --git a/src/Http/Middleware/ServeShell.php b/src/Http/Middleware/ServeShell.php new file mode 100644 index 0000000..ccf60ac --- /dev/null +++ b/src/Http/Middleware/ServeShell.php @@ -0,0 +1,32 @@ +isMethodSafe() || $request->wantsJson() || $request->ajax()) { + return $next($request); + } + + $name = (string) $request->route()?->getName(); + + if (in_array($name, [Names::route('assets'), Names::route('mascot')], true) || str_ends_with($name, '.export')) { + return $next($request); + } + + return response()->view('manager::shell', app(Shell::class)->data($request)); + } +} diff --git a/src/Http/Middleware/SetLocale.php b/src/Http/Middleware/SetLocale.php new file mode 100644 index 0000000..e5b10ad --- /dev/null +++ b/src/Http/Middleware/SetLocale.php @@ -0,0 +1,26 @@ +user(), 'locale'); + + if (in_array($chosen, UserSetting::LOCALES, true)) { + app()->setLocale($chosen); + } + + return $next($request); + } +} diff --git a/src/ManagerServiceProvider.php b/src/ManagerServiceProvider.php new file mode 100644 index 0000000..37c46ea --- /dev/null +++ b/src/ManagerServiceProvider.php @@ -0,0 +1,113 @@ +mergeConfigFrom(__DIR__.'/../config/manager.php', 'manager'); + + $this->app->singleton(Support\MediaUsage::class); + $this->app->singleton(Support\AuditTrail::class); + $this->app->singleton(Modules\Posts\PostLabels::class); + + $this->app->singleton(ModuleRegistry::class, fn ($app) => new ModuleRegistry( + // A config that was published before resources existed does not list their module. + array_values(array_unique([...$app['config']->get('manager.available', []), Modules\Resources\ResourcesModule::class, Modules\Revisions\RevisionsModule::class])), + $app['config']->get('manager.modules', []), + )); + } + + public function boot(ModuleRegistry $modules): void + { + $modules->validate(); + + $this->publishes([__DIR__.'/../config/manager.php' => config_path('manager.php')], 'manager-config'); + $this->loadJsonTranslationsFrom(__DIR__.'/../resources/lang'); + $this->loadViewsFrom(__DIR__.'/../resources/views', 'manager'); + $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); + + $this->app['router']->aliasMiddleware('manager.auth', Http\Middleware\Authenticate::class); + $this->app['router']->aliasMiddleware('manager.shell', Http\Middleware\ServeShell::class); + $this->app['router']->aliasMiddleware('manager.locale', Http\Middleware\SetLocale::class); + RateLimiter::for('manager-login', fn (Request $request) => Limit::perMinute(5)->by(strtolower((string) $request->input('email')).'|'.$request->ip())); + + foreach ($modules->active() as $module) { + if ($module->migrations() !== null) { + $this->loadMigrationsFrom($module->migrations()); + } + + if ($this->app->runningInConsole() && $module->commands() !== []) { + $this->commands($module->commands()); + } + + $module->boot(); + } + + if ($this->app->runningInConsole()) { + $this->commands([Console\InstallCommand::class, Console\DoctorCommand::class, Console\MakeThemeCommand::class, Console\ImportCommand::class]); + } + + $this->registerGates($modules); + $this->registerRoutes($modules); + } + + /** + * One gate per permission, and no Gate::before: a package must never answer for abilities + * of the host app. A super admin passes inside hasManagerPermission, for these gates only. + */ + private function registerGates(ModuleRegistry $modules): void + { + foreach ($modules->permissionValues() as $permission) { + Gate::define($permission, fn ($user) => method_exists($user, 'hasManagerPermission') && $user->hasManagerPermission($permission)); + } + + Gate::define(self::MANAGE_GROUPS, fn ($user) => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()); + } + + private function registerRoutes(ModuleRegistry $modules): void + { + $screens = config('manager.ui') === 'package'; + + if ($screens) { + // Outside `auth`, but behind the bans of the modules. + Route::middleware(['web', ...$modules->middleware('before'), 'manager.shell']) + ->prefix(config('manager.path')) + ->name(Names::routePrefix()) + ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/guest.php')); + } + + Route::middleware([...$modules->middleware('before'), ...config('manager.middleware'), 'manager.locale', ...($screens ? ['manager.shell'] : []), ...$modules->middleware('after')]) + ->prefix(config('manager.path')) + ->name(Names::routePrefix()) + ->group(function () use ($modules) { + $this->loadRoutesFrom(__DIR__.'/../routes/manager.php'); + + foreach ($modules->active() as $module) { + if ($module->routes() !== null) { + $this->loadRoutesFrom($module->routes()); + } + } + }); + + // Files for visitors: outside the manager, no prefix and none of its middleware. + foreach ($modules->active() as $module) { + if ($module->publicRoutes() !== null) { + $this->loadRoutesFrom($module->publicRoutes()); + } + } + } +} diff --git a/src/Models/AuditLog.php b/src/Models/AuditLog.php new file mode 100644 index 0000000..107e807 --- /dev/null +++ b/src/Models/AuditLog.php @@ -0,0 +1,39 @@ +|null $details + * @property Carbon $created_at + */ +class AuditLog extends Model +{ + public const LOGIN = 'login'; + + public const LOGIN_FAILED = 'login_failed'; + + public const LOGOUT = 'logout'; + + /** Something that was done in the manager. */ + public const ACTION = 'action'; + + /** A page of the manager that was opened. */ + public const VIEWED = 'viewed'; + + /** Something the account was not allowed to do. */ + public const REFUSED = 'refused'; + + public const BAN = 'ban'; + + public $timestamps = false; + + protected function casts(): array + { + return ['details' => 'array', 'created_at' => 'datetime']; + } +} diff --git a/src/Models/AuditSetting.php b/src/Models/AuditSetting.php new file mode 100644 index 0000000..fda4cb0 --- /dev/null +++ b/src/Models/AuditSetting.php @@ -0,0 +1,60 @@ + */ + protected $attributes = [ + 'auto_ban' => true, + // This many failed logins from one address ... + 'max_failures' => 10, + // ... within this many minutes ... + 'window_minutes' => 30, + // ... keep it out this long. 0: until someone lifts the ban. + 'ban_minutes' => 1440, + 'keep_days' => 90, + ]; + + protected function casts(): array + { + return [ + 'auto_ban' => 'boolean', + 'max_failures' => 'integer', + 'window_minutes' => 'integer', + 'ban_minutes' => 'integer', + 'keep_days' => 'integer', + ]; + } + + /** The longest the log may be kept (config `manager.audit.max_keep_days`): what a privacy policy promises. */ + public static function maxKeepDays(): int + { + return max(7, (int) config('manager.audit.max_keep_days', 90)); + } + + /** The rules as they are now: the saved row, or the defaults while nothing was saved. */ + public static function current(): self + { + return static::query()->find(1) ?? new self; + } + + /** + * @return array{auto_ban: bool, max_failures: int, window_minutes: int, ban_minutes: int, keep_days: int} + */ + public function rules(): array + { + return [ + 'auto_ban' => (bool) $this->auto_ban, + 'max_failures' => (int) $this->max_failures, + 'window_minutes' => (int) $this->window_minutes, + 'ban_minutes' => (int) $this->ban_minutes, + // Also for a row that was saved when more was allowed. + 'keep_days' => min(self::maxKeepDays(), (int) $this->keep_days), + ]; + } +} diff --git a/src/Models/Group.php b/src/Models/Group.php new file mode 100644 index 0000000..6c17d7f --- /dev/null +++ b/src/Models/Group.php @@ -0,0 +1,37 @@ +|null $permissions + */ +class Group extends Model +{ + protected function casts(): array + { + return ['permissions' => 'array']; + } + + public function users(): BelongsToMany + { + return $this->belongsToMany(config('manager.user_model'), Names::table('group_user'), 'group_id', 'user_id'); + } + + /** + * What the group allows, without anything that is no permission (any more), for instance + * of a module that was switched off. + * + * @return list + */ + public function allowed(): array + { + return app(ModuleRegistry::class)->complete($this->permissions ?? []); + } +} diff --git a/src/Models/IpBan.php b/src/Models/IpBan.php new file mode 100644 index 0000000..4aa51e9 --- /dev/null +++ b/src/Models/IpBan.php @@ -0,0 +1,45 @@ + 'boolean', 'whole_site' => 'boolean', 'hits' => 'integer', 'last_hit_at' => 'datetime', 'expires_at' => 'datetime', 'created_at' => 'datetime']; + } + + /** The list of bans for the whole site is kept in the cache (IpBans::wholeSite): any change makes it stale. */ + protected static function booted(): void + { + static::saved(fn () => IpBans::forgetWholeSite()); + static::deleted(fn () => IpBans::forgetWholeSite()); + } + + /** + * Bans that still keep their address out. + * + * @param Builder $query + */ + public function scopeActive(Builder $query): void + { + $query->where(fn (Builder $q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now())); + } + + public function isActive(): bool + { + return $this->expires_at === null || $this->expires_at->isFuture(); + } +} diff --git a/src/Models/IpNote.php b/src/Models/IpNote.php new file mode 100644 index 0000000..df69745 --- /dev/null +++ b/src/Models/IpNote.php @@ -0,0 +1,21 @@ + 'integer', 'width' => 'integer', 'height' => 'integer', 'focus_x' => 'float', 'focus_y' => 'float']; + } + + public function uploader(): BelongsTo + { + return $this->belongsTo(config('manager.user_model'), 'uploaded_by'); + } + + public function isImage(): bool + { + return str_starts_with($this->mime_type, 'image/'); + } + + /** + * The start of this file's address. It holds the id, so it stays the same when the file is + * renamed, and is what content is searched for to see where a file is used. + */ + public function urlPrefix(): string + { + return '/media-files/'.$this->id.'/'; + } + + /** + * The address visitors load the file from. It ends in /view on purpose: web servers tend to + * answer anything that ends in .jpg themselves, as a file on disk, and never ask the app. + */ + public function url(): string + { + return $this->urlPrefix().rawurlencode($this->filename).'/view'; + } + + /** + * The focus point of the image behind an address from the library, as a CSS `object-position` + * value ("30% 65%"). Null for any other address, or when no focus point was set. + */ + public static function focusFor(?string $url): ?string + { + if ($url === null || preg_match('#^/media-files/(\d+)/#', $url, $match) !== 1) { + return null; + } + + $media = static::query()->whereKey((int) $match[1])->whereNotNull('focus_x')->whereNotNull('focus_y')->first(['id', 'focus_x', 'focus_y']); + + return $media instanceof self + ? round((float) $media->focus_x * 100, 2).'% '.round((float) $media->focus_y * 100, 2).'%' + : null; + } + + /** What the manager shows. Never includes where the file is stored. */ + public function toLibraryItem(int $usageCount = 0): array + { + return [ + 'id' => $this->id, + 'name' => $this->name, + 'filename' => $this->filename, + 'url' => $this->url(), + 'mime_type' => $this->mime_type, + 'is_image' => $this->isImage(), + 'size' => $this->size, + 'width' => $this->width, + 'height' => $this->height, + 'alt' => $this->alt, + 'focus_x' => $this->focus_x, + 'focus_y' => $this->focus_y, + 'uploaded_by' => $this->uploader?->name, + 'created_at' => $this->created_at?->toIso8601String(), + 'usage_count' => $usageCount, + ]; + } +} diff --git a/src/Models/Model.php b/src/Models/Model.php new file mode 100644 index 0000000..617ed86 --- /dev/null +++ b/src/Models/Model.php @@ -0,0 +1,17 @@ +table ?? Names::table(parent::getTable()); + } +} diff --git a/src/Models/Page.php b/src/Models/Page.php new file mode 100644 index 0000000..a9ee06c --- /dev/null +++ b/src/Models/Page.php @@ -0,0 +1,51 @@ + 'array', 'is_published' => 'boolean']; + } + + /** + * The definitions of the pages: slug => ['title' => ..., 'fields' => normalized fields]. + * + * @return array>}> + */ + public static function definitions(): array + { + $out = []; + + foreach ((array) config('manager.pages.definitions', []) as $slug => $definition) { + if (is_string($slug) && preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $slug) && is_array($definition)) { + $out[$slug] = ['title' => (string) ($definition['title'] ?? ucfirst(str_replace('-', ' ', $slug))), 'fields' => Fields::normalize((array) ($definition['fields'] ?? []))]; + } + } + + return $out; + } + + /** + * What the public site shows on a page: every defined key, stored or default. + * + * @return array + */ + public static function contentFor(string $slug): array + { + $fields = self::definitions()[$slug]['fields'] ?? []; + $page = self::query()->where('slug', $slug)->first(); + + return Fields::values($fields, is_array($page?->content) ? $page->content : []); + } +} diff --git a/src/Models/PageView.php b/src/Models/PageView.php new file mode 100644 index 0000000..8c485c4 --- /dev/null +++ b/src/Models/PageView.php @@ -0,0 +1,26 @@ + 'datetime', 'hour' => 'integer', 'seconds' => 'integer']; + } + + /** @return BelongsTo */ + public function visit(): BelongsTo + { + return $this->belongsTo(Visit::class); + } +} diff --git a/src/Models/Post.php b/src/Models/Post.php new file mode 100644 index 0000000..239fdf4 --- /dev/null +++ b/src/Models/Post.php @@ -0,0 +1,84 @@ + 'array', + 'is_featured' => 'boolean', + 'published_at' => 'datetime', + ]; + } + + /** + * Posts that are visible on the public site: published and not scheduled for later. + * + * @param Builder $query + */ + public function scopePublished(Builder $query): void + { + $query->whereNotNull('published_at')->where('published_at', '<=', now()); + } + + public function isPublished(): bool + { + return $this->published_at !== null && $this->published_at->lte(now()); + } + + /** `draft`, `scheduled` or `published`. */ + public function status(): string + { + return match (true) { + $this->published_at === null => 'draft', + $this->published_at->isFuture() => 'scheduled', + default => 'published', + }; + } + + /** A slug for $title that no other post uses yet. */ + public static function uniqueSlug(string $title, ?int $ignoreId = null): string + { + $base = Str::slug($title) ?: 'post'; + $slug = $base; + $suffix = 2; + + while (static::query()->where('slug', $slug)->when($ignoreId, fn (Builder $q) => $q->whereKeyNot($ignoreId))->exists()) { + $slug = $base.'-'.$suffix++; + } + + return $slug; + } + + public function readingMinutes(): int + { + return max(1, (int) ceil(str_word_count(strip_tags($this->body)) / 220)); + } + + /** + * The fields a post card or listing needs, for the host's public pages. + * + * @return array + */ + public function toCard(): array + { + return [ + 'title' => $this->title, + 'slug' => $this->slug, + 'excerpt' => $this->excerpt ?? Str::limit(Markdown::toPlainText($this->body), 160), + 'cover_image' => $this->cover_image, + 'cover_focus' => Media::focusFor($this->cover_image), + 'category' => $this->category, + 'tags' => $this->tags ?? [], + 'is_featured' => $this->is_featured, + 'published_at' => $this->published_at?->toIso8601String(), + 'reading_minutes' => $this->readingMinutes(), + ]; + } +} diff --git a/src/Models/Record.php b/src/Models/Record.php new file mode 100644 index 0000000..a322098 --- /dev/null +++ b/src/Models/Record.php @@ -0,0 +1,12 @@ + 'array']; + } +} diff --git a/src/Models/Review.php b/src/Models/Review.php new file mode 100644 index 0000000..1a930fd --- /dev/null +++ b/src/Models/Review.php @@ -0,0 +1,5 @@ + 'array', 'changed' => 'array']; + } +} diff --git a/src/Models/UserSetting.php b/src/Models/UserSetting.php new file mode 100644 index 0000000..32dd5bd --- /dev/null +++ b/src/Models/UserSetting.php @@ -0,0 +1,35 @@ +updateOrCreate(['user_id' => $user->getKey()], $values); + } + + /** One value of what this account chose, or null. */ + public static function value(?object $user, string $column): ?string + { + return $user === null || $user->getKey() === null ? null : static::query()->where('user_id', $user->getKey())->value($column); + } + + public function getTable(): string + { + return Names::table('user_settings'); + } +} diff --git a/src/Models/Visit.php b/src/Models/Visit.php new file mode 100644 index 0000000..bdde6d7 --- /dev/null +++ b/src/Models/Visit.php @@ -0,0 +1,34 @@ + 'datetime', + 'last_seen_at' => 'datetime', + 'hour' => 'integer', + 'weekday' => 'integer', + 'page_views' => 'integer', + 'seconds' => 'integer', + ]; + } + + /** @return HasMany */ + public function pageViews(): HasMany + { + return $this->hasMany(PageView::class); + } +} diff --git a/src/Models/VisitorSalt.php b/src/Models/VisitorSalt.php new file mode 100644 index 0000000..de340f4 --- /dev/null +++ b/src/Models/VisitorSalt.php @@ -0,0 +1,52 @@ +toDateString(); + $salt = static::query()->where('day', $today)->value('salt'); + + if (is_string($salt)) { + return $salt; + } + + static::forgetOld(); + + try { + return static::query()->create(['day' => $today, 'salt' => Str::random(64)])->salt; + } catch (UniqueConstraintViolationException) { + // Another visitor arrived in the same instant and made today's key. + return static::query()->where('day', $today)->sole()->salt; + } + } + + /** Deletes every key that is not today's. Returns how many. */ + public static function forgetOld(): int + { + $deleted = static::query()->where('day', '<', now()->toDateString())->delete(); + + return is_int($deleted) ? $deleted : 0; + } +} diff --git a/src/Modules/Audit/AuditController.php b/src/Modules/Audit/AuditController.php new file mode 100644 index 0000000..a0712bd --- /dev/null +++ b/src/Modules/Audit/AuditController.php @@ -0,0 +1,336 @@ +string('show')->toString(); + + $filters = [ + 'show' => in_array($show, self::SHOW, true) ? $show : 'all', + 'user' => $request->integer('user') ?: null, + 'ip' => $request->string('ip')->trim()->toString(), + 'q' => $request->string('q')->trim()->toString(), + ]; + + $query = AuditLog::query(); + + match ($filters['show']) { + 'logins' => $query->whereIn('event', [AuditLog::LOGIN, AuditLog::LOGOUT]), + 'failed' => $query->where('event', AuditLog::LOGIN_FAILED), + 'actions' => $query->where('event', AuditLog::ACTION), + 'viewed' => $query->where('event', AuditLog::VIEWED), + 'refused' => $query->where('event', AuditLog::REFUSED), + 'bans' => $query->where(fn (Builder $q) => $q->where('event', AuditLog::BAN)->orWhere('subject_type', 'ip_ban')), + default => $query, + }; + + if ($filters['user'] !== null) { + $query->where('user_id', $filters['user']); + } + + if ($filters['ip'] !== '') { + $query->where('ip', $filters['ip']); + } + + if ($filters['q'] !== '') { + $like = '%'.addcslashes($filters['q'], '%_\\').'%'; + $query->where(fn (Builder $q) => $q->where('summary', 'like', $like)->orWhere('subject_label', 'like', $like) + ->orWhere('user_name', 'like', $like)->orWhere('email', 'like', $like)); + } + + $total = (clone $query)->count(); + $pages = max(1, (int) ceil($total / self::PER_PAGE)); + $page = min($pages, max(1, $request->integer('page', 1))); + $rows = $query->orderByDesc('id')->forPage($page, self::PER_PAGE)->get(); + + $banned = array_values(array_filter(IpBan::query()->active()->pluck('ip')->all(), fn (mixed $ip) => is_string($ip) && ! IpBans::isNeverBanned($ip))); + $posts = $this->existingPosts($rows->where('subject_type', 'post')->pluck('subject_id')->filter()->all()); + $day = now()->subDay(); + + return response()->json([ + 'entries' => $rows->map(fn (AuditLog $entry) => [ + 'id' => $entry->id, + 'at' => $entry->created_at->toIso8601String(), + 'event' => $entry->event, + 'summary' => $entry->summary, + 'subject' => $entry->subject_label === null ? null : [ + 'type' => str_replace('_', ' ', (string) $entry->subject_type), + 'label' => $entry->subject_label, + 'url' => $entry->subject_type === 'post' && in_array($entry->subject_id, $posts, true) + ? route(Names::route('posts.edit'), $entry->subject_id, false) + : null, + ], + 'details' => $entry->details ?? [], + 'user_id' => $entry->user_id, + 'who' => $entry->user_name, + 'email' => $entry->email, + 'ip' => $entry->ip, + 'browser' => $entry->user_agent === null ? null : self::browser($entry->user_agent), + 'user_agent' => $entry->user_agent, + 'banned' => $entry->ip !== null && in_array($entry->ip, $banned, true), + 'never_banned' => $entry->ip !== null && IpBans::isNeverBanned($entry->ip), + ])->values(), + 'pagination' => ['page' => $page, 'pages' => $pages, 'total' => $total], + 'filters' => $filters, + 'accounts' => $this->accounts(), + 'summary' => [ + 'logins' => AuditLog::query()->where('event', AuditLog::LOGIN)->where('created_at', '>=', $day)->count(), + 'failed' => AuditLog::query()->where('event', AuditLog::LOGIN_FAILED)->where('created_at', '>=', $day)->count(), + 'refused' => AuditLog::query()->where('event', AuditLog::REFUSED)->where('created_at', '>=', $day)->count(), + 'banned' => count($banned), + ], + 'bans' => IpBan::query()->orderByDesc('created_at')->get()->map(fn (IpBan $ban) => [ + 'id' => $ban->id, + 'ip' => $ban->ip, + 'reason' => $ban->reason, + 'automatic' => $ban->automatic, + 'whole_site' => $ban->whole_site, + 'by' => $ban->user_name, + 'hits' => $ban->hits, + 'last_hit_at' => $ban->last_hit_at?->toIso8601String(), + 'expires_at' => $ban->expires_at?->toIso8601String(), + 'created_at' => $ban->created_at->toIso8601String(), + 'active' => $ban->isActive() && ! IpBans::isNeverBanned($ban->ip), + ])->sortByDesc('active')->values(), + // What was written down about addresses, by address. Kept until removed, also after the log is gone. + 'notes' => IpNote::query()->orderByDesc('updated_at')->get()->map(fn (IpNote $note) => [ + 'ip' => $note->ip, + 'group' => $note->group_name, + 'note' => $note->note, + 'by' => $note->user_name, + 'updated_at' => $note->updated_at?->toIso8601String(), + ])->values(), + 'settings' => AuditSetting::current()->rules(), + 'max_keep_days' => AuditSetting::maxKeepDays(), + 'can_manage' => Gate::allows('audit.manage'), + 'my_ip' => $request->ip(), + // The addresses that are never banned (config manager.audit.never_ban): no button for those. + 'never_banned' => IpBans::neverBanned(), + 'whole_site_bans' => (bool) config('manager.audit.whole_site_bans'), + ]); + } + + public function ban(Request $request): JsonResponse + { + $request->validate([ + 'ip' => ['required', 'ip'], + 'reason' => ['nullable', 'string', 'max:200'], + // 0: until someone lifts it. At most a year. + 'minutes' => ['required', 'integer', 'min:0', 'max:525600'], + // Off the whole site, not only out of the manager. + 'whole_site' => ['boolean'], + ]); + + $ip = $request->string('ip')->trim()->toString(); + + // Nobody bans the address they are on: the next click would be refused. + if ($ip === $request->ip()) { + return $this->refuse('ip', 'That is the address you are on yourself.'); + } + + if (IpBans::isNeverBanned($ip)) { + return $this->refuse('ip', 'This address is on the list that is never banned.'); + } + + $wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans'); + $reason = $request->string('reason')->trim()->toString(); + $ban = $this->bans->ban($ip, $reason !== '' ? $reason : null, $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite); + + // Also when the address was banned before: the line of the log is filed under it either way. + if ($ban !== null) { + $this->trail->about($ban); + } + + return response()->json(['message' => $wholeSite ? __(':ip is banned from the whole site.', ['ip' => $ip]) : __(':ip is banned from the manager.', ['ip' => $ip])], 201); + } + + public function unban(int $ban): JsonResponse + { + $ipBan = IpBan::query()->findOrFail($ban); + $this->trail->about($ipBan); + $this->bans->lift($ipBan); + + return response()->json(['message' => __('The ban of :ip is lifted.', ['ip' => $ipBan->ip])]); + } + + /** Bans every address of a group at once, with the same time, reason and reach. */ + public function banGroup(Request $request): JsonResponse + { + $request->validate([ + 'group' => ['required', 'string', 'max:60'], + 'reason' => ['nullable', 'string', 'max:200'], + 'minutes' => ['required', 'integer', 'min:0', 'max:525600'], + 'whole_site' => ['boolean'], + ]); + + $group = $request->string('group')->trim()->toString(); + $reason = $request->string('reason')->trim()->toString(); + $wholeSite = $request->boolean('whole_site') && config('manager.audit.whole_site_bans'); + $banned = 0; + $skipped = 0; + + // The line of the log is about the group, not about the first address of it. + $this->trail->about(null); + + foreach ($this->addressesOf($group) as $ip) { + // The address one is on and the ones that are never banned stay in, as with a ban of one address. + $ban = $ip === $request->ip() ? null : $this->bans->ban($ip, $reason !== '' ? $reason : "Group: {$group}", $request->integer('minutes'), Auth::user(), wholeSite: $wholeSite); + $ban === null ? $skipped++ : $banned++; + } + + if ($banned === 0) { + return $this->refuse('group', $skipped === 0 + ? "The group \"{$group}\" has no addresses." + : "None of the addresses of \"{$group}\" can be banned: your own and the ones that are never banned stay in."); + } + + return response()->json(['message' => sprintf( + '%d %s of "%s" banned from %s%s.', + $banned, + $banned === 1 ? 'address' : 'addresses', + $group, + $wholeSite ? 'the whole site' : 'the manager', + $skipped > 0 ? " ({$skipped} left alone: your own or never banned)" : '', + ), 'banned' => $banned, 'skipped' => $skipped], 201); + } + + /** Lets every address of a group back in. */ + public function unbanGroup(Request $request): JsonResponse + { + $request->validate(['group' => ['required', 'string', 'max:60']]); + + $group = $request->string('group')->trim()->toString(); + $bans = IpBan::query()->whereIn('ip', $this->addressesOf($group))->get(); + $this->trail->about(null); + $bans->each(fn (IpBan $ban) => $this->bans->lift($ban)); + + return response()->json(['message' => sprintf('%d %s of "%s" lifted.', $bans->count(), $bans->count() === 1 ? 'ban' : 'bans', $group), 'lifted' => $bans->count()]); + } + + /** Writes the note about an address and the group it is in, or removes both when they are left empty. */ + public function note(Request $request): JsonResponse + { + $request->validate([ + 'ip' => ['required', 'ip'], + 'note' => ['nullable', 'string', 'max:2000'], + // Addresses with the same group are banned and let back in together. + 'group' => ['nullable', 'string', 'max:60'], + ]); + + $ip = IpNote::spell($request->string('ip')->toString()); + $text = $request->string('note')->trim()->toString(); + $group = $request->string('group')->trim()->toString(); + $note = IpNote::query()->where('ip', $ip)->first(); + + if ($text === '' && $group === '') { + if ($note !== null) { + $this->trail->about($note); + $note->delete(); + } + + return response()->json(['message' => __('The note about :ip is removed.', ['ip' => $ip])]); + } + + $note ??= new IpNote(['ip' => $ip]); + $user = Auth::user(); + $name = data_get($user, 'name'); + $note->fill(['note' => $text, 'group_name' => $group !== '' ? $group : null, 'user_id' => $user?->getAuthIdentifier(), 'user_name' => is_string($name) ? $name : null])->save(); + $this->trail->about($note); + + return response()->json(['message' => __('The note about :ip is saved.', ['ip' => $ip])]); + } + + public function settings(Request $request): JsonResponse + { + /** @var array $rules */ + $rules = $request->validate([ + 'auto_ban' => ['required', 'boolean'], + 'max_failures' => ['required', 'integer', 'min:3', 'max:100'], + 'window_minutes' => ['required', 'integer', 'min:1', 'max:1440'], + 'ban_minutes' => ['required', 'integer', 'min:0', 'max:525600'], + // What the site promises about how long the log is kept (config manager.audit.max_keep_days). + 'keep_days' => ['required', 'integer', 'min:7', 'max:'.AuditSetting::maxKeepDays()], + ]); + + AuditSetting::current()->forceFill(['id' => 1, ...$rules])->save(); + + return response()->json(['message' => __('Rules saved.'), 'settings' => AuditSetting::current()->rules()]); + } + + private function refuse(string $field, string $message): JsonResponse + { + return response()->json(['message' => $message = __($message), 'errors' => [$field => [$message]]], 422); + } + + /** + * @return list + */ + private function addressesOf(string $group): array + { + return array_values(array_filter(IpNote::query()->where('group_name', $group)->orderBy('id')->pluck('ip')->all(), is_string(...))); + } + + /** + * @param list $ids + * @return list + */ + private function existingPosts(array $ids): array + { + if ($ids === [] || ! Route::has(Names::route('posts.edit'))) { + return []; + } + + return Post::query()->whereIn('id', $ids)->pluck('id')->map(fn ($id) => (int) $id)->all(); + } + + /** @return list */ + private function accounts(): array + { + /** @var class-string $model */ + $model = config('manager.user_model'); + + return $model::query()->orderBy('name')->get()->map(fn ($user) => ['id' => $user->getKey(), 'name' => $user->name])->values()->all(); + } + + /** "Firefox on Linux": enough to recognise a browser; the whole line is there to hover. */ + private static function browser(string $line): string + { + $agent = new UserAgent($line); + + if ($agent->isBot()) { + return $agent->bot()['name'] ?? 'A program'; + } + + return $agent->browser().' on '.$agent->os(); + } +} diff --git a/src/Modules/Audit/AuditModule.php b/src/Modules/Audit/AuditModule.php new file mode 100644 index 0000000..636421e --- /dev/null +++ b/src/Modules/Audit/AuditModule.php @@ -0,0 +1,142 @@ + 'Audit log', 'route' => Names::route('audit.index'), 'permission' => 'audit.view']]; + } + + public function commands(): array + { + return [PruneAuditLog::class, LiftBan::class]; + } + + public function actions(): array + { + return [ + 'audit.bans.store' => ['Banned an address', ['reason', 'whole_site']], + 'audit.bans.destroy' => ['Lifted the ban of an address'], + 'audit.groups.ban' => ['Banned the addresses of a group', ['group', 'reason', 'whole_site']], + 'audit.groups.unban' => ['Lifted the bans of a group', ['group']], + 'audit.notes.update' => ['Wrote or removed the note about an address', ['ip', 'group']], + 'audit.settings' => ['Changed the rules of the audit log'], + ]; + } + + public function views(): array + { + return ['audit.index' => 'Opened the audit log']; + } + + /** A banned address is refused before the session starts; every request of a manager account is written down. */ + public function middleware(): array + { + return ['before' => [RefuseBannedAddress::class], 'after' => [RecordActions::class]]; + } + + public function boot(): void + { + app()->singleton(IpBans::class); + + app('router')->aliasMiddleware('manager.not-banned', RefuseBannedAddress::class); + + // The first thing a request makes is what the line of the log is about. + Event::listen('eloquent.created: *', function (string $event, array $data) { + if (($data[0] ?? null) instanceof Model) { + app(AuditTrail::class)->made($data[0]); + } + }); + + $this->listenForLogins(); + + if (config('manager.audit.whole_site_bans') && ($kernel = app(Kernel::class)) && method_exists($kernel, 'pushMiddleware')) { + $kernel->pushMiddleware(RefuseBannedFromTheSite::class); + } + + // Only the console runs the schedule; a web request never needs to resolve it. + if (app()->runningInConsole()) { + app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(PruneAuditLog::class)->dailyAt('03:40')); + } + } + + /** The host owns the login: Laravel's own events say what happened, whatever the login looks like. */ + private function listenForLogins(): void + { + $model = config('manager.user_model'); + + Event::listen(Login::class, function (Login $event) use ($model) { + if ($event->user instanceof $model) { + app(AuditTrail::class)->record(AuditLog::LOGIN, __('Logged in'), $event->user); + } + }); + + Event::listen(Logout::class, function (Logout $event) use ($model) { + if ($event->user instanceof $model) { + app(AuditTrail::class)->record(AuditLog::LOGOUT, __('Logged out'), $event->user); + } + }); + + Event::listen(Failed::class, function (Failed $event) { + $email = $event->credentials['email'] ?? null; + $email = is_string($email) ? $email : null; + + app(AuditTrail::class)->record( + AuditLog::LOGIN_FAILED, + $event->user === null ? 'Failed login: no such account' : 'Failed login: wrong password', + $event->user, + email: $email, + ); + + app(IpBans::class)->afterFailedLogin(request()->ip()); + }); + } +} diff --git a/src/Modules/Audit/IpBans.php b/src/Modules/Audit/IpBans.php new file mode 100644 index 0000000..95e4b7d --- /dev/null +++ b/src/Modules/Audit/IpBans.php @@ -0,0 +1,189 @@ + */ + public static function neverBanned(): array + { + $addresses = config('manager.audit.never_ban'); + + return is_array($addresses) ? array_values(array_filter($addresses, is_string(...))) : []; + } + + /** Compared in packed form: an IPv6 address has more than one spelling. */ + public static function isNeverBanned(string $ip): bool + { + $packed = @inet_pton($ip); + + foreach (self::neverBanned() as $address) { + if ($address === $ip || ($packed !== false && @inet_pton($address) === $packed)) { + return true; + } + } + + return false; + } + + /** The ban that keeps this address out of the manager now, if any. */ + public function for(?string $ip): ?IpBan + { + return $ip === null || self::isNeverBanned($ip) ? null : IpBan::query()->active()->where('ip', $ip)->first(); + } + + /** + * The ban that keeps this address off the whole site now, if any. Asked at every request of + * every visitor, so the list (address => id) comes from the cache; it is thrown away whenever + * a ban is saved or deleted (see IpBan). + */ + public function wholeSite(?string $ip): ?IpBan + { + if ($ip === null || self::isNeverBanned($ip)) { + return null; + } + + $banned = Cache::get(self::WHOLE_SITE); + + if (! is_array($banned)) { + // Not kept while the table is not there yet: the answer would outlive the migration. + if (! self::ready()) { + return null; + } + + $banned = IpBan::query()->where('whole_site', true)->pluck('id', 'ip')->all(); + Cache::forever(self::WHOLE_SITE, $banned); + } + + if (! isset($banned[$ip])) { + return null; + } + + // Only now the database: whether it still counts (a ban ends by itself). + return IpBan::query()->active()->where('whole_site', true)->where('ip', $ip)->first(); + } + + public static function forgetWholeSite(): void + { + Cache::forget(self::WHOLE_SITE); + } + + private static function ready(): bool + { + try { + return Schema::hasTable((new IpBan)->getTable()); + } catch (Throwable) { + return false; + } + } + + /** + * $minutes 0: until someone lifts it. Null for an address that is never banned. + */ + public function ban(string $ip, ?string $reason, int $minutes, ?Authenticatable $by, bool $automatic = false, bool $wholeSite = false): ?IpBan + { + if (self::isNeverBanned($ip)) { + return null; + } + + $name = $by === null ? null : data_get($by, 'name'); + + return IpBan::query()->updateOrCreate(['ip' => $ip], [ + 'reason' => $reason, + 'automatic' => $automatic, + 'whole_site' => $wholeSite, + 'user_id' => $by?->getAuthIdentifier(), + 'user_name' => is_string($name) ? $name : null, + 'hits' => 0, + 'last_hit_at' => null, + 'expires_at' => $minutes > 0 ? now()->addMinutes($minutes) : null, + 'created_at' => now(), + ]); + } + + public function lift(IpBan $ban): void + { + $ban->delete(); + } + + /** A banned address knocked: only counted, so a flood does not fill the log. */ + public function knocked(IpBan $ban): void + { + IpBan::query()->whereKey($ban->id)->update(['hits' => $ban->hits + 1, 'last_hit_at' => now()]); + } + + /** + * After a failed login: bans the address when it failed too often. What counts are the + * failures since the address last logged in or was last banned or let back in, so a ban that + * was lifted does not come back at the next typo. + */ + public function afterFailedLogin(?string $ip): ?IpBan + { + $rules = AuditSetting::current()->rules(); + + if ($ip === null || ! $rules['auto_ban'] || self::isNeverBanned($ip) || $this->for($ip) !== null) { + return null; + } + + // By id and not by time: a login in the same second as the failure before it still comes after it. + $reset = AuditLog::query() + ->where(fn (Builder $query) => $query + ->where(fn (Builder $q) => $q->where('event', AuditLog::LOGIN)->where('ip', $ip)) + ->orWhere(fn (Builder $q) => $q->where('subject_type', 'ip_ban')->where('subject_label', $ip))) + ->max('id'); + + $failures = AuditLog::query() + ->where('event', AuditLog::LOGIN_FAILED) + ->where('ip', $ip) + ->where('id', '>', is_numeric($reset) ? (int) $reset : 0) + ->where('created_at', '>=', now()->subMinutes($rules['window_minutes'])) + ->count(); + + if ($failures < $rules['max_failures']) { + return null; + } + + $ban = $this->ban($ip, sprintf('%d failed logins within %d minutes', $failures, $rules['window_minutes']), $rules['ban_minutes'], null, automatic: true); + + if ($ban === null) { + return null; + } + + $this->trail->record(AuditLog::BAN, __('The address was banned after too many failed logins'), subject: $ban, details: ['failures' => $failures]); + + return $ban; + } + + /** Bans that ended before $before are deleted; returns how many. */ + public function forgetExpiredBefore(Carbon $before): int + { + $ended = IpBan::query()->whereNotNull('expires_at')->where('expires_at', '<', $before); + $count = $ended->count(); + $ended->delete(); + + return $count; + } +} diff --git a/src/Modules/Audit/LiftBan.php b/src/Modules/Audit/LiftBan.php new file mode 100644 index 0000000..01d5e2e --- /dev/null +++ b/src/Modules/Audit/LiftBan.php @@ -0,0 +1,51 @@ +argument('ip'); + + if ($this->option('all')) { + $lifted = IpBan::query()->get()->each(fn (IpBan $ban) => $bans->lift($ban))->count(); + $this->line("{$lifted} ban(s) lifted."); + + return self::SUCCESS; + } + + if (! is_string($ip)) { + $rows = IpBan::query()->orderBy('ip')->get()->map(fn (IpBan $ban) => [ + $ban->ip, + $ban->isActive() ? ($ban->expires_at?->format('Y-m-d H:i') ?? 'until lifted') : 'ended', + $ban->reason ?? '', + ])->all(); + + $rows === [] ? $this->line('No address is banned.') : $this->table(['Address', 'Until', 'Reason'], $rows); + + return self::SUCCESS; + } + + $ban = IpBan::query()->where('ip', $ip)->first(); + + if ($ban === null) { + $this->error("{$ip} is not banned."); + + return self::FAILURE; + } + + $bans->lift($ban); + $this->line("The ban of {$ip} is lifted."); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Audit/PruneAuditLog.php b/src/Modules/Audit/PruneAuditLog.php new file mode 100644 index 0000000..16b2c07 --- /dev/null +++ b/src/Modules/Audit/PruneAuditLog.php @@ -0,0 +1,27 @@ +subDays(AuditSetting::current()->rules()['keep_days']); + + $old = AuditLog::query()->where('created_at', '<', $before); + $lines = $old->count(); + $old->delete(); + + $this->line(sprintf('%d line(s) of the audit log and %d ended ban(s) deleted.', $lines, $bans->forgetExpiredBefore($before))); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Audit/RecordActions.php b/src/Modules/Audit/RecordActions.php new file mode 100644 index 0000000..1b75c6c --- /dev/null +++ b/src/Modules/Audit/RecordActions.php @@ -0,0 +1,150 @@ +trail->reset(); + + $response = $next($request); + + if ($user !== null) { + $this->write($request, $response, $user, $this->trail->firstMade()); + } + + return $response; + } + + private function write(Request $request, Response $response, Authenticatable $user, ?Model $subject): void + { + $route = Str::after((string) $request->route()?->getName(), Names::routePrefix()); + $actions = $this->modules->actions(); + $views = $this->modules->views(); + $thrown = property_exists($response, 'exception') && $response->exception instanceof Throwable ? $response->exception : null; + $details = $this->details($request, $actions[$route][1] ?? []); + $name = $actions[$route][0] ?? ($views[$route] ?? ''); + $name = $name !== '' ? __($name) : __('Asked for :request', ['request' => $request->method().' /'.ltrim($request->path(), '/')]); + + if (in_array($route, self::SILENT, true)) { + return; + } + + if ($thrown !== null) { + // Only a refusal is worth a line; a form with a mistake or a page that is not there is not. + if ($thrown instanceof AuthorizationException || ($thrown instanceof HttpExceptionInterface && $thrown->getStatusCode() === 403)) { + $this->trail->record(AuditLog::REFUSED, __('Was not allowed: :what', ['what' => Str::lcfirst($name)]), $user, $subject, $details, $route); + } + + return; + } + + if ($response->getStatusCode() >= 400) { + return; + } + + $changes = ! in_array($request->method(), ['GET', 'HEAD', 'OPTIONS'], true); + + if (! $changes && ! isset($actions[$route])) { + $this->viewed($user, $route, __($views[$route] ?? ''), $subject, $details); + + return; + } + + $this->trail->record(AuditLog::ACTION, $name, $user, $subject, $details, $route); + } + + /** + * A page that was opened. Not twice in a row: filtering a list or loading a page again within + * a few minutes is the same look. A route with an empty name stays silent (what a page asks + * for in the background). + * + * @param array $details + */ + private function viewed(Authenticatable $user, string $route, string $summary, ?Model $subject, array $details): void + { + if ($summary === '') { + return; + } + + $last = AuditLog::query()->where('user_id', $user->getAuthIdentifier())->orderByDesc('id')->first(); + $about = $subject === null ? null : AuditTrail::describe($subject); + + if ($last !== null && $last->event === AuditLog::VIEWED && $last->action === $route + && $last->subject_id === ($about['id'] ?? null) && ($last->details ?? []) === $details + && $last->created_at->gt(now()->subMinutes(self::SAME_LOOK_MINUTES))) { + return; + } + + $this->trail->record(AuditLog::VIEWED, $summary, $user, $subject, $details, $route); + } + + /** + * What the address names (`/posts/5`) and the fields of the form a module said may be kept. + * + * @param list $kept + * @return array + */ + private function details(Request $request, array $kept): array + { + $input = []; + + foreach ($request->route()?->parameters() ?? [] as $name => $parameter) { + $value = $parameter instanceof BackedEnum ? $parameter->value : $parameter; + + if (is_scalar($value) && ! is_bool($value) && $name !== 'type') { + $input[$name] = Str::limit((string) $value, 100, '…'); + } + } + + foreach ($kept as $field) { + $value = $request->input($field); + + if (is_bool($value)) { + $value = $value ? 'yes' : 'no'; + } + + if (is_string($value) && $value !== '') { + $input[$field] = Str::limit($value, 100, '…'); + } + } + + return $input === [] ? [] : ['input' => $input]; + } +} diff --git a/src/Modules/Audit/RefuseBannedAddress.php b/src/Modules/Audit/RefuseBannedAddress.php new file mode 100644 index 0000000..0418a4c --- /dev/null +++ b/src/Modules/Audit/RefuseBannedAddress.php @@ -0,0 +1,56 @@ +bans->for($request->ip()); + + if ($ban === null) { + return $next($request); + } + + $this->bans->knocked($ban); + + return self::answer($request, $ban); + } + + /** The page (or JSON) a banned address gets, also for a ban on the whole site. */ + public static function answer(Request $request, IpBan $ban): Response + { + $where = $ban->whole_site ? __('this site') : __('the manager'); + $message = $ban->expires_at === null + ? __('This address is blocked from :where.', ['where' => $where]) + : __('This address is blocked from :where until :when.', ['where' => $where, 'when' => $ban->expires_at->format('j F Y, H:i')]); + + // A ban that followed too many attempts is "429 Too Many Requests" and says when to come + // back; one that was given by hand is a plain "403 Forbidden". + $status = $ban->automatic ? 429 : 403; + $headers = ['Cache-Control' => 'no-store']; + + if ($ban->automatic && $ban->expires_at !== null) { + $headers['Retry-After'] = (string) max(1, (int) now()->diffInSeconds($ban->expires_at, false)); + } + + return $request->expectsJson() + ? response()->json(['message' => $message], $status, $headers) + : response()->view('manager::banned', ['message' => $message, 'status' => $status], $status, $headers); + } +} diff --git a/src/Modules/Audit/RefuseBannedFromTheSite.php b/src/Modules/Audit/RefuseBannedFromTheSite.php new file mode 100644 index 0000000..a3306bd --- /dev/null +++ b/src/Modules/Audit/RefuseBannedFromTheSite.php @@ -0,0 +1,33 @@ +bans->wholeSite($request->ip()); + + if ($ban === null) { + return $next($request); + } + + $this->bans->knocked($ban); + + return RefuseBannedAddress::answer($request, $ban); + } +} diff --git a/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php b/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php new file mode 100644 index 0000000..49b2c0b --- /dev/null +++ b/src/Modules/Audit/migrations/2026_12_04_000003_create_manager_audit_tables.php @@ -0,0 +1,81 @@ +id(); + $table->string('event', 40)->index(); + // The route that was called, for an action in the manager. + $table->string('action', 100)->nullable(); + $table->string('summary'); + $table->string('subject_type', 40)->nullable(); + $table->unsignedBigInteger('subject_id')->nullable(); + $table->string('subject_label')->nullable(); + $table->json('details')->nullable(); + $table->unsignedBigInteger('user_id')->nullable()->index(); + $table->string('user_name')->nullable(); + // The address that was typed at a login that failed. + $table->string('email')->nullable(); + $table->string('ip', 45)->nullable()->index(); + $table->string('user_agent', 500)->nullable(); + $table->dateTime('created_at')->index(); + }); + + // Addresses that are kept out of the manager, or off the whole site. + Schema::create(Names::table('ip_bans'), function (Blueprint $table) { + $table->id(); + $table->string('ip', 45)->unique(); + $table->string('reason')->nullable(); + $table->boolean('automatic')->default(false); + $table->boolean('whole_site')->default(false); + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + // How often the address knocked while it was banned. + $table->unsignedInteger('hits')->default(0); + $table->timestamp('last_hit_at')->nullable(); + // Null: until someone lifts it. + $table->timestamp('expires_at')->nullable(); + $table->dateTime('created_at'); + }); + + // One row (id 1) with the rules; without it the defaults of the model count. + Schema::create(Names::table('audit_settings'), function (Blueprint $table) { + $table->id(); + $table->boolean('auto_ban')->default(true); + $table->unsignedSmallInteger('max_failures')->default(10); + $table->unsignedSmallInteger('window_minutes')->default(30); + $table->unsignedInteger('ban_minutes')->default(1440); + $table->unsignedSmallInteger('keep_days')->default(90); + $table->timestamps(); + }); + + Schema::create(Names::table('ip_notes'), function (Blueprint $table) { + $table->id(); + $table->string('ip', 45)->unique(); + // Addresses that belong together carry the same name here; null: no group. + $table->string('group_name', 60)->nullable()->index(); + $table->text('note'); + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + + foreach (['ip_notes', 'audit_settings', 'ip_bans', 'audit_logs'] as $table) { + Schema::dropIfExists(Names::table($table)); + } + } +}; diff --git a/src/Modules/Audit/routes.php b/src/Modules/Audit/routes.php new file mode 100644 index 0000000..1968f67 --- /dev/null +++ b/src/Modules/Audit/routes.php @@ -0,0 +1,15 @@ +name('audit.index')->middleware('can:audit.view'); + +Route::middleware('can:audit.manage')->group(function () { + Route::post('/audit/bans', [AuditController::class, 'ban'])->name('audit.bans.store'); + Route::delete('/audit/bans/{ban}', [AuditController::class, 'unban'])->name('audit.bans.destroy')->whereNumber('ban'); + Route::post('/audit/groups/ban', [AuditController::class, 'banGroup'])->name('audit.groups.ban'); + Route::post('/audit/groups/unban', [AuditController::class, 'unbanGroup'])->name('audit.groups.unban'); + Route::put('/audit/notes', [AuditController::class, 'note'])->name('audit.notes.update'); + Route::put('/audit/settings', [AuditController::class, 'settings'])->name('audit.settings'); +}); diff --git a/src/Modules/BaseModule.php b/src/Modules/BaseModule.php new file mode 100644 index 0000000..2228c74 --- /dev/null +++ b/src/Modules/BaseModule.php @@ -0,0 +1,98 @@ +path('routes.php'); + } + + public function publicRoutes(): ?string + { + return $this->path('public-routes.php'); + } + + public function commands(): array + { + return []; + } + + /** + * Tables (without the prefix) this module needs; `manager:doctor` checks that they exist. + * + * @return list + */ + public function tables(): array + { + return []; + } + + /** + * Steps this module adds to the tour. Each: `title` and `text` (English, translated through `__()`), an optional `image` (one of + * the pictures of the tour, `MascotController::NAMES`), `menu` (the short route name of a menu item to point at, like `reviews.index`) + * and `permission` (the step is left out for an account without it). The contract `Module` does not know this: a module without it adds none. + * + * @return list + */ + public function tutorial(): array + { + return []; + } + + public function actions(): array + { + return []; + } + + public function views(): array + { + return []; + } + + public function middleware(): array + { + return []; + } + + public function boot(): void {} + + public function migrations(): ?string + { + return $this->path('migrations'); + } + + private function path(string $name): ?string + { + $path = dirname((new \ReflectionClass($this))->getFileName()).'/'.$name; + + return file_exists($path) ? $path : null; + } +} diff --git a/src/Modules/Media/MediaController.php b/src/Modules/Media/MediaController.php new file mode 100644 index 0000000..2e00a43 --- /dev/null +++ b/src/Modules/Media/MediaController.php @@ -0,0 +1,152 @@ +json($this->limits()); + } + + public function items(): JsonResponse + { + $media = Media::query()->with('uploader')->latest()->latest('id')->get(); + $usage = $this->library->usageCounts($media); + + return response()->json([ + 'items' => $media->map(fn (Media $item) => $item->toLibraryItem($usage[$item->id] ?? 0))->values(), + ...$this->limits(), + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate([ + 'file' => ['required', 'file', 'mimes:'.implode(',', $this->extensions()), 'max:'.($this->maxMegabytes() * 1024)], + ...$this->focusRules(), + ]); + + $file = $request->file('file'); + abort_unless($file instanceof UploadedFile, 422); + + $room = $this->library->room(); + + if ($file->getSize() > $room['left']) { + $message = __('The media library is full: this file does not fit in the room that is left. Remove files that are no longer used, or raise manager.media.max_total_gb.'); + + return response()->json(['message' => $message, 'errors' => ['file' => [$message]], 'storage' => $room], 422); + } + + try { + $media = $this->library->store($file, $request->user()); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + if ($media->isImage()) { + $media->update($this->focus($request)); + } + + return response()->json(['item' => $media->load('uploader')->toLibraryItem(), 'storage' => $this->library->room()], 201); + } + + public function update(Request $request, string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + app(AuditTrail::class)->about($media); + + $request->validate([ + 'name' => ['required', 'string', 'max:250'], + 'alt' => ['nullable', 'string', 'max:500'], + ...$this->focusRules(), + ]); + + $alt = $request->string('alt')->trim()->toString(); + + $media->update([ + 'name' => $request->string('name')->trim()->toString(), + 'alt' => $alt !== '' ? $alt : null, + // Only when the request says something about it; renaming keeps the focus point. + ...($media->isImage() && $request->has('focus_x') ? $this->focus($request) : []), + ]); + + $usage = $this->library->usageCounts([$media]); + + return response()->json(['item' => $media->load('uploader')->toLibraryItem($usage[$media->id] ?? 0)]); + } + + public function destroy(string $media): JsonResponse + { + $media = Media::query()->findOrFail($media); + app(AuditTrail::class)->about($media); + + try { + $this->library->delete($media); + } catch (MediaStorageException $e) { + return $this->unavailable($e); + } + + return response()->json(['deleted' => true, 'storage' => $this->library->room()]); + } + + /** @return array> */ + private function focusRules(): array + { + return [ + 'focus_x' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_y'], + 'focus_y' => ['nullable', 'numeric', 'between:0,1', 'required_with:focus_x'], + ]; + } + + /** @return array{focus_x: float|null, focus_y: float|null} both null when none was sent */ + private function focus(Request $request): array + { + $x = $request->input('focus_x'); + $y = $request->input('focus_y'); + $set = is_numeric($x) && is_numeric($y); + + return ['focus_x' => $set ? round((float) $x, 4) : null, 'focus_y' => $set ? round((float) $y, 4) : null]; + } + + /** The reason goes to the log; the browser only hears that it did not work. */ + private function unavailable(MediaStorageException $e): JsonResponse + { + Log::warning('Media storage failed.', ['error' => $e->getMessage(), 'status' => $e->status]); + + return response()->json(['message' => __(self::UNAVAILABLE)], 502); + } + + /** @return array{max_file_mb: int, extensions: list, storage: array{used: int, limit: int, left: int}} */ + private function limits(): array + { + return ['max_file_mb' => $this->maxMegabytes(), 'extensions' => $this->extensions(), 'storage' => $this->library->room()]; + } + + private function maxMegabytes(): int + { + return max(1, config()->integer('manager.media.max_file_mb')); + } + + /** @return list */ + private function extensions(): array + { + return array_values(array_filter(config()->array('manager.media.extensions'), 'is_string')); + } +} diff --git a/src/Modules/Media/MediaFileController.php b/src/Modules/Media/MediaFileController.php new file mode 100644 index 0000000..1311fcd --- /dev/null +++ b/src/Modules/Media/MediaFileController.php @@ -0,0 +1,156 @@ +findOrFail((int) $media); + + $headers = $this->headers($media); + + // A media id never gets other content, so what the browser has is still right. + if (in_array($headers['ETag'], $request->getETags(), true)) { + return response('', 304, $headers); + } + + $range = $this->range($request, $media->size); + + if ($range === null) { + return response('', 416, ['Content-Range' => "bytes */{$media->size}"] + $headers); + } + + [$start, $end, $partial] = $range; + $length = $end - $start + 1; + + $headers['Content-Length'] = (string) $length; + + if ($partial) { + $headers['Content-Range'] = "bytes {$start}-{$end}/{$media->size}"; + } + + if ($request->isMethod('HEAD')) { + return response('', $partial ? 206 : 200, $headers); + } + + try { + $stream = $library->open($media); + } catch (MediaStorageException $e) { + if ($e->status === 404) { + abort(404); + } + + return response('This file is temporarily unavailable.', 503, ['Retry-After' => (string) ($e->retryAfter ?? 30), 'Cache-Control' => 'no-store']); + } + + return response()->stream(fn () => $this->send($stream, $start, $length), $partial ? 206 : 200, $headers); + } + + /** @return array */ + private function headers(Media $media): array + { + $inline = in_array($media->mime_type, self::INLINE_TYPES, true); + $name = str_replace(['"', '\\', "\r", "\n"], '', $media->filename); + + return [ + 'Content-Type' => $inline ? $media->mime_type : 'application/octet-stream', + 'Content-Disposition' => ($inline ? 'inline' : 'attachment').'; filename="'.$name.'"', + 'X-Content-Type-Options' => 'nosniff', + 'Accept-Ranges' => 'bytes', + 'Cache-Control' => 'public, max-age=31536000, immutable', + 'ETag' => '"'.($media->checksum ?? 'media-'.$media->id).'"', + ]; + } + + /** + * The part of the file the browser asks for: [first byte, last byte, is it a part]. + * Null when the request asks for bytes the file does not have. + * + * @return array{int, int, bool}|null + */ + private function range(Request $request, int $size): ?array + { + $header = $request->headers->get('Range'); + $whole = [0, max($size - 1, 0), false]; + + // No range, an empty file, or something other than one plain byte range: send it all. + if ($header === null || $size === 0 || preg_match('/^bytes=(\d*)-(\d*)$/', trim($header), $match) !== 1) { + return $whole; + } + + [, $first, $last] = $match; + + if ($first === '' && $last === '') { + return $whole; + } + + if ($first === '') { + // "bytes=-500": the last 500 bytes. + $start = max($size - (int) $last, 0); + $end = $size - 1; + } else { + $start = (int) $first; + $end = $last === '' ? $size - 1 : min((int) $last, $size - 1); + } + + if ($start >= $size || $start > $end) { + return null; + } + + return [$start, $end, true]; + } + + /** @param resource $stream */ + private function send($stream, int $start, int $length): void + { + try { + if ($start > 0 && stream_get_meta_data($stream)['seekable']) { + fseek($stream, $start); + } else { + $skip = $start; + + while ($skip > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $skip)); + + if ($chunk === false || $chunk === '') { + break; + } + + $skip -= strlen($chunk); + } + } + + while ($length > 0 && ! feof($stream)) { + $chunk = fread($stream, min(65536, $length)); + + if ($chunk === false || $chunk === '') { + break; + } + + echo $chunk; + flush(); + + $length -= strlen($chunk); + } + } finally { + fclose($stream); + } + } +} diff --git a/src/Modules/Media/MediaLibrary.php b/src/Modules/Media/MediaLibrary.php new file mode 100644 index 0000000..069028d --- /dev/null +++ b/src/Modules/Media/MediaLibrary.php @@ -0,0 +1,122 @@ +getClientOriginalExtension()); + $baseName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME); + $filename = (Str::slug($baseName) ?: 'file').($extension !== '' ? '.'.$extension : ''); + $path = $file->getRealPath(); + + if ($path === false) { + throw new MediaStorageException('The uploaded file could not be read.'); + } + + $mimeType = $file->getMimeType() ?? 'application/octet-stream'; + $dimensions = str_starts_with($mimeType, 'image/') ? @getimagesize($path) : false; + $disk ??= config('manager.media.disk'); + + $location = $file->store('media/'.now()->format('Y/m'), $disk); + + if ($location === false) { + throw new MediaStorageException('The file could not be stored.'); + } + + return Media::create([ + 'disk' => $disk, + 'location' => $location, + 'name' => Str::limit(trim($baseName) !== '' ? trim($baseName) : 'File', 250, ''), + 'filename' => $filename, + 'mime_type' => $mimeType, + 'size' => (int) $file->getSize(), + 'checksum' => hash_file('sha256', $path) ?: null, + 'width' => $dimensions !== false ? $dimensions[0] : null, + 'height' => $dimensions !== false ? $dimensions[1] : null, + 'uploaded_by' => $uploader?->getAuthIdentifier(), + ]); + } + + /** + * How full the library is: what all files together take, how much it may hold + * (`manager.media.max_total_gb`) and what is left. In bytes. + * + * @return array{used: int, limit: int, left: int} + */ + public function room(): array + { + $configured = config('manager.media.max_total_gb'); + $limit = (int) round((is_numeric($configured) ? max(0.0, (float) $configured) : 15.0) * 1_000_000_000); + $used = (int) Media::query()->sum('size'); + + return ['used' => $used, 'limit' => $limit, 'left' => max(0, $limit - $used)]; + } + + /** + * Open a file's content as a stream. Read it and close it. + * + * @return resource + * + * @throws MediaStorageException with status 404 when the file is gone + */ + public function open(Media $media) + { + $stream = Storage::disk($media->disk)->readStream($media->location); + + if (! is_resource($stream)) { + throw new MediaStorageException('The file is no longer there.', 404); + } + + return $stream; + } + + /** Delete the file and then its row. When the storage refuses, the row stays. */ + public function delete(Media $media): void + { + $disk = Storage::disk($media->disk); + + if ($disk->exists($media->location) && ! $disk->delete($media->location)) { + throw new MediaStorageException('The file could not be deleted.'); + } + + $media->delete(); + } + + /** + * How often each media file is used, keyed by media id: how many of the registered sources + * (MediaUsage) hold its address. Nothing registered means 0. + * + * @param iterable $items + * @return array + */ + public function usageCounts(iterable $items): array + { + $haystacks = $this->usage->haystacks(); + $counts = []; + + foreach ($items as $media) { + $prefix = $media->urlPrefix(); + $counts[$media->id] = count(array_filter($haystacks, fn (string $text) => str_contains($text, $prefix))); + } + + return $counts; + } +} diff --git a/src/Modules/Media/MediaModule.php b/src/Modules/Media/MediaModule.php new file mode 100644 index 0000000..58e867f --- /dev/null +++ b/src/Modules/Media/MediaModule.php @@ -0,0 +1,69 @@ + 'Media', 'route' => Names::route('media.index'), 'permission' => 'media.view', 'simple' => true, 'hint' => 'Your photos and files'], + ]; + } + + public function actions(): array + { + return [ + 'media.store' => ['Uploaded a file'], + 'media.update' => ['Changed a file'], + 'media.destroy' => ['Deleted a file'], + ]; + } + + public function views(): array + { + return ['media.index' => 'Opened the media library', 'media.items' => '']; + } + + public function boot(): void + { + RateLimiter::for('media-files', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.media.per_minute', 600)))->by((string) $request->ip())); + } +} diff --git a/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php new file mode 100644 index 0000000..01a4123 --- /dev/null +++ b/src/Modules/Media/migrations/2026_12_04_000002_create_manager_media.php @@ -0,0 +1,40 @@ +getTable(); + + // The file itself is elsewhere: `disk` says where, `location` is its path there. + Schema::create(Names::table('media'), function (Blueprint $table) use ($users) { + $table->id(); + $table->string('disk', 40); + $table->string('location'); + $table->string('name'); + $table->string('filename'); + $table->string('mime_type', 100); + $table->unsignedBigInteger('size'); + $table->string('checksum', 64)->nullable(); + $table->unsignedInteger('width')->nullable(); + $table->unsignedInteger('height')->nullable(); + $table->string('alt', 500)->nullable(); + // The part of an image that must stay in view when it is cropped to fit: + // 0-1 from the left and from the top. + $table->decimal('focus_x', 5, 4)->nullable(); + $table->decimal('focus_y', 5, 4)->nullable(); + $table->foreignId('uploaded_by')->nullable()->constrained($users)->nullOnDelete(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('media')); + } +}; diff --git a/src/Modules/Media/public-routes.php b/src/Modules/Media/public-routes.php new file mode 100644 index 0000000..aa1433a --- /dev/null +++ b/src/Modules/Media/public-routes.php @@ -0,0 +1,13 @@ +whereNumber('media') + ->middleware('throttle:media-files') + ->name(Names::route('media.file')); diff --git a/src/Modules/Media/routes.php b/src/Modules/Media/routes.php new file mode 100644 index 0000000..2b81661 --- /dev/null +++ b/src/Modules/Media/routes.php @@ -0,0 +1,10 @@ +name('media.index')->middleware('can:media.view'); +Route::get('/media/items', [MediaController::class, 'items'])->name('media.items')->middleware('can:media.view'); +Route::post('/media', [MediaController::class, 'store'])->name('media.store')->middleware('can:media.upload'); +Route::put('/media/{media}', [MediaController::class, 'update'])->name('media.update')->middleware('can:media.edit')->whereNumber('media'); +Route::delete('/media/{media}', [MediaController::class, 'destroy'])->name('media.destroy')->middleware('can:media.delete')->whereNumber('media'); diff --git a/src/Modules/Pages/PagesController.php b/src/Modules/Pages/PagesController.php new file mode 100644 index 0000000..a2687b4 --- /dev/null +++ b/src/Modules/Pages/PagesController.php @@ -0,0 +1,122 @@ +orderBy('title')->get()->keyBy('slug'); + $pages = []; + + foreach ($definitions as $slug => $definition) { + $pages[] = ['slug' => $slug, 'title' => $definition['title'], 'defined' => true, 'saved' => $stored->has($slug), 'updated_at' => $stored[$slug]->updated_at ?? null]; + } + + foreach ($stored as $slug => $page) { + if (! isset($definitions[$slug])) { + $pages[] = ['slug' => $slug, 'title' => $page->title, 'defined' => false, 'saved' => true, 'is_published' => $page->is_published, 'updated_at' => $page->updated_at]; + } + } + + return response()->json(['pages' => $pages]); + } + + public function show(string $slug): JsonResponse + { + return response()->json(['page' => $this->payload($slug)]); + } + + /** Makes a free page. A defined page is made by saving it. */ + public function store(Request $request): JsonResponse + { + $data = $request->validate([ + 'slug' => ['required', 'string', 'max:120', 'regex:/^'.self::SLUG.'$/', Rule::unique(Page::query()->getModel()->getTable(), 'slug'), Rule::notIn(array_keys(Page::definitions()))], + 'title' => ['required', 'string', 'max:255'], + ]); + + $page = Page::query()->create($data + ['is_published' => false]); + app(AuditTrail::class)->about($page); + + return response()->json(['page' => $this->payload($page->slug)], 201); + } + + public function update(Request $request, string $slug): JsonResponse + { + $definition = Page::definitions()[$slug] ?? null; + $page = Page::query()->where('slug', $slug)->first(); + abort_if($definition === null && $page === null, 404); + + $rules = [ + 'title' => ['required', 'string', 'max:255'], + 'meta_description' => ['nullable', 'string', 'max:255'], + ]; + + if ($definition !== null) { + $rules = [...$rules, 'content' => ['nullable', 'array'], ...Fields::rules($definition['fields'], 'content.')]; + } else { + $rules = [...$rules, 'body' => ['nullable', 'string', 'max:200000'], 'is_published' => ['boolean']]; + } + + $data = $request->validate($rules); + $values = ['title' => $data['title'], 'meta_description' => ($data['meta_description'] ?? '') ?: null]; + + if ($definition !== null) { + $values['content'] = Fields::clean($definition['fields'], (array) ($data['content'] ?? [])); + } else { + $values += ['body' => $data['body'] ?? null, 'is_published' => (bool) ($data['is_published'] ?? false)]; + } + + $page = $page ?? new Page(['slug' => $slug]); + $page->fill($values)->save(); + app(AuditTrail::class)->about($page); + + return response()->json(['page' => $this->payload($slug)]); + } + + /** Removes a free page; a defined page stays (its values go back to the defaults when it is emptied by saving). */ + public function destroy(string $slug): JsonResponse + { + abort_if(isset(Page::definitions()[$slug]), 422, __('A page with fields of its own cannot be removed.')); + + $page = Page::query()->where('slug', $slug)->firstOrFail(); + app(AuditTrail::class)->about($page); + $page->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array */ + private function payload(string $slug): array + { + $definition = Page::definitions()[$slug] ?? null; + $page = Page::query()->where('slug', $slug)->first(); + abort_if($definition === null && $page === null, 404); + + return [ + 'id' => $page?->id, + 'slug' => $slug, + 'title' => $page->title ?? $definition['title'], + 'meta_description' => $page->meta_description ?? '', + 'defined' => $definition !== null, + 'fields' => array_values($definition['fields'] ?? []), + 'content' => $definition !== null ? Fields::values($definition['fields'], is_array($page?->content) ? $page->content : []) : null, + 'body' => $definition === null ? (string) $page->body : null, + 'is_published' => $definition === null ? (bool) $page->is_published : null, + ]; + } +} diff --git a/src/Modules/Pages/PagesModule.php b/src/Modules/Pages/PagesModule.php new file mode 100644 index 0000000..5d4b826 --- /dev/null +++ b/src/Modules/Pages/PagesModule.php @@ -0,0 +1,66 @@ + 'Pages', 'route' => Names::route('pages.index'), 'permission' => 'pages.edit', 'simple' => true, 'hint' => 'Change the texts and photos of your pages'], + ]; + } + + /** Where the media library looks for the use of a file: the texts of the pages. */ + public function views(): array + { + return ['pages.index' => 'Opened the pages', 'pages.show' => 'Opened a page']; + } + + public function actions(): array + { + return [ + 'pages.store' => ['Created a page'], + 'pages.update' => ['Changed a page'], + 'pages.destroy' => ['Removed a page'], + ]; + } + + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Page::query()->get(['body', 'content'])->flatMap(fn (Page $row) => [$row->body, ...array_values(array_filter((array) $row->content, 'is_string'))])); + } +} diff --git a/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php new file mode 100644 index 0000000..beb594a --- /dev/null +++ b/src/Modules/Pages/migrations/2026_12_04_000002_create_manager_pages.php @@ -0,0 +1,26 @@ +id(); + $table->string('slug')->unique(); + $table->string('title'); + $table->longText('body')->nullable(); + $table->boolean('is_published')->default(false); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('pages')); + } +}; diff --git a/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php b/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php new file mode 100644 index 0000000..fd57e9f --- /dev/null +++ b/src/Modules/Pages/migrations/2026_12_06_000001_add_content_to_manager_pages.php @@ -0,0 +1,25 @@ +string('meta_description', 255)->nullable()->after('title'); + $table->json('content')->nullable()->after('body'); + }); + } + + public function down(): void + { + Schema::table(Names::table('pages'), function (Blueprint $table) { + $table->dropColumn(['meta_description', 'content']); + }); + } +}; diff --git a/src/Modules/Pages/routes.php b/src/Modules/Pages/routes.php new file mode 100644 index 0000000..f226379 --- /dev/null +++ b/src/Modules/Pages/routes.php @@ -0,0 +1,12 @@ +group(function () { + Route::get('/pages', [PagesController::class, 'index'])->name('pages.index'); + Route::post('/pages', [PagesController::class, 'store'])->name('pages.store'); + Route::get('/pages/{slug}', [PagesController::class, 'show'])->name('pages.show')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); + Route::put('/pages/{slug}', [PagesController::class, 'update'])->name('pages.update')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); + Route::delete('/pages/{slug}', [PagesController::class, 'destroy'])->name('pages.destroy')->where('slug', '[a-z0-9]+(?:-[a-z0-9]+)*'); +}); diff --git a/src/Modules/Posts/LabelController.php b/src/Modules/Posts/LabelController.php new file mode 100644 index 0000000..c91db84 --- /dev/null +++ b/src/Modules/Posts/LabelController.php @@ -0,0 +1,80 @@ +json($this->labels->overview()); + } + + /** A category or tag that no post uses yet; the post form offers it from then on. */ + public function store(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => $this->nameRules($type)], $this->messages()); + + $name = $request->string('name')->trim()->toString(); + + if (! $this->labels->create($type, $name)) { + return response()->json(['message' => $already = __('The :type ":name" already exists.', ['type' => __($type), 'name' => $name]), 'errors' => ['name' => [$already]]], 422); + } + + return response()->json(['created' => $name], 201); + } + + public function update(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string'], 'new_name' => $this->nameRules($type)], $this->messages()); + + $from = $request->string('name')->toString(); + $to = $request->string('new_name')->trim()->toString(); + + return response()->json(['posts' => $this->labels->rename($type, $from, $to)]); + } + + public function destroy(Request $request): JsonResponse + { + $type = $this->type($request); + $request->validate(['name' => ['required', 'string']]); + + return response()->json(['posts' => $this->labels->remove($type, $request->string('name')->toString())]); + } + + /** + * The same limits as the post form. + * + * @return list + */ + private function nameRules(string $type): array + { + return ['required', 'string', 'max:'.($type === PostLabels::CATEGORY ? 60 : 40), ...($type === PostLabels::TAG ? ['not_regex:/,/'] : [])]; + } + + /** @return array */ + private function messages(): array + { + $comma = 'A tag cannot hold a comma: the post form separates tags with it.'; + + return ['name.not_regex' => $comma, 'new_name.not_regex' => $comma]; + } + + private function type(Request $request): string + { + $request->validate(['type' => ['required', Rule::in([PostLabels::CATEGORY, PostLabels::TAG])]]); + + return $request->string('type')->toString(); + } +} diff --git a/src/Modules/Posts/PostController.php b/src/Modules/Posts/PostController.php new file mode 100644 index 0000000..1746c97 --- /dev/null +++ b/src/Modules/Posts/PostController.php @@ -0,0 +1,194 @@ +orderByRaw('published_at is null desc') + ->latest('published_at') + ->latest('id') + ->get() + ->map(fn (Post $post) => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'category' => $post->category, + 'is_featured' => $post->is_featured, + 'status' => $post->status(), + 'published_at' => $post->published_at?->toIso8601String(), + 'can_change' => Gate::allows('posts.write') && $this->mayTouch($post), + 'can_delete' => Gate::allows('posts.delete') && $this->mayTouch($post), + ]) + ->values(); + + return response()->json(['posts' => $posts]); + } + + public function create(): JsonResponse + { + return response()->json([ + 'post' => null, + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + public function store(Request $request): JsonResponse + { + $post = Post::create($this->validated($request)); + + return response()->json(['id' => $post->id], 201); + } + + public function edit(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + + return response()->json([ + 'post' => [ + 'id' => $post->id, + 'title' => $post->title, + 'slug' => $post->slug, + 'excerpt' => $post->excerpt, + 'body' => $post->body, + 'cover_image' => $post->cover_image, + 'category' => $post->category, + 'tags' => $post->tags ?? [], + 'is_featured' => $post->is_featured, + 'is_published' => $post->published_at !== null, + // datetime-local value, in the app timezone + 'published_at' => $post->published_at?->format('Y-m-d\TH:i'), + 'status' => $post->status(), + ], + 'categories' => $this->labels->categories(), + 'known_tags' => $this->labels->names(PostLabels::TAG), + ]); + } + + /** The post as a visitor will see it, also for drafts and scheduled posts. */ + public function preview(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + + return response()->json(['post' => [...$post->toCard(), 'body_html' => Markdown::toHtml($post->body)], 'preview' => true]); + } + + public function update(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + app(AuditTrail::class)->about($post); + + $post->update($this->validated($request, $post)); + + return response()->json(['saved' => true]); + } + + /** Puts a post on the site, or takes it off again (a draft) without opening it. */ + public function online(Request $request, string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + $request->validate(['online' => ['required', 'boolean']]); + app(AuditTrail::class)->about($post); + + $post->update(['published_at' => $request->boolean('online') ? ($post->published_at ?? now()) : null]); + + return response()->json(['status' => $post->status()]); + } + + public function destroy(string $post): JsonResponse + { + $post = Post::query()->findOrFail($post); + abort_unless($this->mayTouch($post), 403); + app(AuditTrail::class)->about($post); + + $post->delete(); + + return response()->json(['deleted' => true]); + } + + /** + * Validates the post form and turns it into model attributes. + * + * @return array + */ + private function validated(Request $request, ?Post $post = null): array + { + $request->validate([ + 'title' => ['required', 'string', 'max:255'], + 'slug' => ['nullable', 'string', 'max:255', 'regex:/^[a-z0-9]+(?:-[a-z0-9]+)*$/', Rule::unique(Names::table('posts'), 'slug')->ignore($post?->id)], + 'excerpt' => ['nullable', 'string', 'max:500'], + 'body' => ['required', 'string'], + 'cover_image' => ['nullable', 'string', 'max:2048'], + 'category' => ['nullable', 'string', 'max:60'], + 'tags' => ['array', 'max:20'], + 'tags.*' => ['nullable', 'string', 'max:40'], + 'is_featured' => ['boolean'], + 'is_published' => ['boolean'], + 'published_at' => ['nullable', 'date'], + ], [ + 'slug.regex' => 'Use only lowercase letters, numbers and dashes.', + ]); + + $title = $request->string('title')->trim()->toString(); + $slug = $request->string('slug')->trim()->toString(); + + // Publishing without a date means "now"; a date in the future schedules the post. + // Who may not publish only gets a draft, and a post that was live is not touched + // (mayTouch refused that before we got here). + $publishedAt = null; + if ($request->boolean('is_published') && Gate::allows('posts.publish')) { + $date = $request->string('published_at')->toString(); + $publishedAt = $date !== '' ? Carbon::parse($date) : ($post?->published_at ?? now()); + } + + return [ + 'title' => $title, + 'slug' => $slug !== '' ? $slug : Post::uniqueSlug($title, $post?->id), + 'excerpt' => $this->nullableString($request, 'excerpt'), + 'body' => $request->string('body')->toString(), + 'cover_image' => $this->nullableString($request, 'cover_image'), + 'category' => $this->nullableString($request, 'category'), + 'tags' => array_values(array_filter(array_map( + fn (mixed $tag) => is_string($tag) ? trim($tag) : '', + $request->array('tags'), + ))), + 'is_featured' => $request->boolean('is_featured'), + 'published_at' => $publishedAt, + ]; + } + + private function mayTouch(Post $post): bool + { + return $post->published_at === null || Gate::allows('posts.publish'); + } + + private function nullableString(Request $request, string $key): ?string + { + $value = $request->string($key)->trim()->toString(); + + return $value !== '' ? $value : null; + } +} diff --git a/src/Modules/Posts/PostLabels.php b/src/Modules/Posts/PostLabels.php new file mode 100644 index 0000000..bcd0f4a --- /dev/null +++ b/src/Modules/Posts/PostLabels.php @@ -0,0 +1,192 @@ +> */ + private array $suggestions = []; + + /** A site offers more categories in the post form, for instance the titles of its services. */ + public function suggestCategories(Closure $source): void + { + $this->suggestions[] = $source; + } + + /** + * What the post form offers as category: the suggestions of the site, the configured ones, + * and whatever is in use or was made by hand. + * + * @return list + */ + public function categories(): array + { + $suggested = []; + + foreach ($this->suggestions as $source) { + array_push($suggested, ...array_values([...$source()])); + } + + return array_values(array_unique([...$suggested, ...array_values((array) config('manager.posts.categories', [])), ...$this->names(self::CATEGORY)])); + } + + private function table(): string + { + return Names::table('post_labels'); + } + + /** + * Every category and tag, the ones made by hand included, with the number of posts (drafts + * included) that use it. + * + * @return array{categories: list, tags: list} + */ + public function overview(): array + { + $categories = []; + $tags = []; + + foreach (Post::query()->get(['id', 'category', 'tags']) as $post) { + if ($post->category !== null && $post->category !== '') { + $categories[$post->category] = ($categories[$post->category] ?? 0) + 1; + } + + foreach (array_unique($this->tagsOf($post)) as $tag) { + $tags[$tag] = ($tags[$tag] ?? 0) + 1; + } + } + + foreach (DB::table($this->table())->get(['type', 'name']) as $row) { + if (! is_string($row->name)) { + continue; + } + + if ($row->type === self::CATEGORY) { + $categories[$row->name] ??= 0; + } else { + $tags[$row->name] ??= 0; + } + } + + return ['categories' => $this->listed($categories), 'tags' => $this->listed($tags)]; + } + + /** + * The names of all categories or tags, to offer in the post form. + * + * @return list + */ + public function names(string $type): array + { + return array_column($this->overview()[$type === self::CATEGORY ? 'categories' : 'tags'], 'name'); + } + + /** Makes a category or tag that no post uses yet. False when the name is already there. */ + public function create(string $type, string $name): bool + { + if (in_array($name, $this->names($type), true)) { + return false; + } + + DB::table($this->table())->insert(['type' => $type, 'name' => $name, 'created_at' => now(), 'updated_at' => now()]); + + return true; + } + + /** Gives every post with the label the new name. Returns how many posts changed. */ + public function rename(string $type, string $from, string $to): int + { + if ($from === $to) { + return 0; + } + + // The name that was made by hand moves along, unless the new name is there already. + $made = DB::table($this->table())->where('type', $type); + if ((clone $made)->where('name', $to)->exists()) { + (clone $made)->where('name', $from)->delete(); + } else { + (clone $made)->where('name', $from)->update(['name' => $to, 'updated_at' => now()]); + } + + return $type === self::CATEGORY + ? Post::query()->where('category', $from)->update(['category' => $to]) + : $this->changeTags($from, $to); + } + + /** Takes the label off every post; the posts stay. Returns how many posts changed. */ + public function remove(string $type, string $name): int + { + DB::table($this->table())->where('type', $type)->where('name', $name)->delete(); + + return $type === self::CATEGORY + ? Post::query()->where('category', $name)->update(['category' => null]) + : $this->changeTags($name, null); + } + + /** Replaces a tag in every post that has it, or takes it out when $to is null. */ + private function changeTags(string $from, ?string $to): int + { + return DB::transaction(function () use ($from, $to) { + $changed = 0; + + foreach (Post::query()->whereNotNull('tags')->get() as $post) { + $tags = $this->tagsOf($post); + + if (! in_array($from, $tags, true)) { + continue; + } + + $new = []; + foreach ($tags as $tag) { + $tag = $tag === $from ? $to : $tag; + + // A post that had both names keeps the tag once. + if ($tag !== null && ! in_array($tag, $new, true)) { + $new[] = $tag; + } + } + + $post->update(['tags' => $new]); + $changed++; + } + + return $changed; + }); + } + + /** @return list */ + private function tagsOf(Post $post): array + { + return array_values(array_filter(is_array($post->tags) ? $post->tags : [], fn (mixed $tag) => is_string($tag) && $tag !== '')); + } + + /** + * @param array $counts + * @return list + */ + private function listed(array $counts): array + { + $names = array_map(fn (int|string $name) => (string) $name, array_keys($counts)); + natcasesort($names); + + return array_values(array_map(fn (string $name) => ['name' => $name, 'posts' => $counts[$name]], $names)); + } +} diff --git a/src/Modules/Posts/PostsModule.php b/src/Modules/Posts/PostsModule.php new file mode 100644 index 0000000..291b0f2 --- /dev/null +++ b/src/Modules/Posts/PostsModule.php @@ -0,0 +1,81 @@ + 'Posts', 'route' => Names::route('posts.index'), 'permission' => 'posts.view', 'simple' => true, 'hint' => 'Write and put news on your website'], + ['label' => 'Categories and tags', 'route' => Names::route('labels.index'), 'permission' => 'posts.labels'], + ]; + } + + public function actions(): array + { + return [ + 'posts.store' => ['Created a post'], + 'posts.update' => ['Changed a post'], + 'posts.online' => ['Put a post on the site, or took it off', ['online']], + 'posts.destroy' => ['Deleted a post'], + 'labels.store' => ['Made a category or tag', ['type', 'name']], + 'labels.update' => ['Renamed a category or tag', ['type', 'name', 'new_name']], + 'labels.destroy' => ['Removed a category or tag', ['type', 'name']], + ]; + } + + public function views(): array + { + return [ + 'posts.index' => 'Opened the posts', + 'posts.create' => 'Opened the form for a new post', + 'posts.edit' => 'Opened a post', + 'posts.preview' => 'Opened the preview of a post', + 'labels.index' => 'Opened the categories and tags', + ]; + } + + /** Where the media library looks for the use of a file: the texts of the posts. */ + public function boot(): void + { + app(MediaUsage::class)->register(fn () => Post::query()->get(['body', 'excerpt', 'cover_image'])->flatMap(fn (Post $row) => array_values($row->only(['body', 'excerpt', 'cover_image'])))); + } +} diff --git a/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php new file mode 100644 index 0000000..0c81595 --- /dev/null +++ b/src/Modules/Posts/migrations/2026_12_04_000002_create_manager_posts.php @@ -0,0 +1,46 @@ +id(); + $table->string('title'); + $table->string('slug')->unique(); + $table->string('excerpt', 500)->nullable(); + $table->longText('body'); + $table->string('cover_image', 2048)->nullable(); + $table->string('category', 60)->nullable(); + $table->json('tags')->nullable(); + $table->boolean('is_featured')->default(false); + // null = draft; a future date = scheduled + $table->timestamp('published_at')->nullable()->index(); + $table->timestamps(); + }); + + // Categories and tags that were made by hand, so one can exist before a post uses it. + // The ones a post uses are in the post itself; this only remembers names to offer. + Schema::create(Names::table('post_labels'), function (Blueprint $table) { + $table->id(); + $table->string('type', 10); + $table->string('name', 60); + $table->timestamps(); + + $table->unique(['type', 'name']); + }); + } + + public function down(): void + { + + Schema::dropIfExists(Names::table('post_labels')); + Schema::dropIfExists(Names::table('posts')); + } +}; diff --git a/src/Modules/Posts/routes.php b/src/Modules/Posts/routes.php new file mode 100644 index 0000000..623d3f6 --- /dev/null +++ b/src/Modules/Posts/routes.php @@ -0,0 +1,22 @@ +name('posts.index')->middleware('can:posts.view'); +Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create')->middleware('can:posts.write'); +Route::post('/posts', [PostController::class, 'store'])->name('posts.store')->middleware('can:posts.write'); +Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit')->middleware('can:posts.write')->whereNumber('post'); +Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('posts.preview')->middleware('can:posts.view')->whereNumber('post'); +Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update')->middleware('can:posts.write')->whereNumber('post'); +Route::put('/posts/{post}/online', [PostController::class, 'online'])->name('posts.online')->middleware('can:posts.publish')->whereNumber('post'); +Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy')->middleware('can:posts.delete')->whereNumber('post'); + +// The name of a label travels in the body, not the address: it can hold anything. +Route::middleware('can:posts.labels')->group(function () { + Route::get('/labels', [LabelController::class, 'index'])->name('labels.index'); + Route::post('/labels', [LabelController::class, 'store'])->name('labels.store'); + Route::put('/labels', [LabelController::class, 'update'])->name('labels.update'); + Route::delete('/labels', [LabelController::class, 'destroy'])->name('labels.destroy'); +}); diff --git a/src/Modules/Resources/ResourceController.php b/src/Modules/Resources/ResourceController.php new file mode 100644 index 0000000..19170c0 --- /dev/null +++ b/src/Modules/Resources/ResourceController.php @@ -0,0 +1,108 @@ +resource($resource, 'view'); + $page = Resources::query($def)->paginate($def['per_page']); + + return response()->json([ + 'resource' => $this->describe($def), + 'rows' => $page->getCollection()->map(fn (Model $model) => Resources::row($def, $model))->values(), + 'current_page' => $page->currentPage(), + 'last_page' => $page->lastPage(), + ]); + } + + public function create(string $resource): JsonResponse + { + $def = $this->resource($resource, 'manage'); + + return response()->json(['resource' => $this->describe($def), 'record' => ['id' => null, 'values' => Fields::values($def['fields'], [])]]); + } + + public function edit(string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + + return response()->json(['resource' => $this->describe($def), 'record' => Resources::row($def, $this->record($def, $id))]); + } + + public function store(Request $request, string $resource): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = Resources::save($def, null, $this->values($request, $def)); + app(AuditTrail::class)->about($model); + + return response()->json(['record' => Resources::row($def, $model)], 201); + } + + public function update(Request $request, string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = Resources::save($def, $this->record($def, $id), $this->values($request, $def)); + app(AuditTrail::class)->about($model); + + return response()->json(['record' => Resources::row($def, $model)]); + } + + public function destroy(string $resource, string $id): JsonResponse + { + $def = $this->resource($resource, 'manage'); + $model = $this->record($def, $id); + app(AuditTrail::class)->about($model); + $model->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array */ + private function resource(string $key, string $ability): array + { + $def = Resources::find($key); + abort_if($def === null, 404); + Gate::authorize($key.'.'.$ability); + + return $def; + } + + /** @param array $def */ + private function record(array $def, string $id): Model + { + return Resources::record($def, $id) ?? abort(404); + } + + /** + * @param array $def + * @return array + */ + private function values(Request $request, array $def): array + { + $data = $request->validate(Fields::rules($def['fields'])); + + return Fields::clean($def['fields'], $data); + } + + /** + * @param array $def + * @return array + */ + private function describe(array $def): array + { + return [ + 'key' => $def['key'], 'label' => $def['label'], 'singular' => $def['singular'], 'columns' => $def['columns'], + 'fields' => array_values($def['fields']), 'can_manage' => Gate::allows($def['key'].'.manage'), + ]; + } +} diff --git a/src/Modules/Resources/ResourcesModule.php b/src/Modules/Resources/ResourcesModule.php new file mode 100644 index 0000000..fa74d48 --- /dev/null +++ b/src/Modules/Resources/ResourcesModule.php @@ -0,0 +1,69 @@ + $resource) { + $permissions[] = new Permission($key.'.view', __('See :label', ['label' => $resource['label']]), $resource['label']); + $permissions[] = new Permission($key.'.manage', __('Add, change and delete :label', ['label' => $resource['label']]), $resource['label'], needs: [$key.'.view']); + } + + return $permissions; + } + + public function navigation(): array + { + return array_values(array_map( + fn (array $resource) => ['id' => 'records.'.$resource['key'], 'label' => $resource['label'], 'route' => Names::route('records.index'), 'params' => ['resource' => $resource['key']], 'permission' => $resource['key'].'.view', 'simple' => true, 'hint' => $resource['hint']], + Resources::all(), + )); + } + + public function actions(): array + { + return [ + 'records.store' => ['Added a record'], + 'records.update' => ['Changed a record'], + 'records.destroy' => ['Removed a record'], + ]; + } + + public function views(): array + { + return ['records.index' => 'Opened a list', 'records.create' => 'Opened the form for a new record', 'records.edit' => 'Opened a record']; + } +} diff --git a/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php b/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php new file mode 100644 index 0000000..987f0d9 --- /dev/null +++ b/src/Modules/Resources/migrations/2026_12_06_000001_create_manager_records.php @@ -0,0 +1,24 @@ +id(); + $table->string('resource', 40)->index(); + $table->json('data')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('records')); + } +}; diff --git a/src/Modules/Resources/routes.php b/src/Modules/Resources/routes.php new file mode 100644 index 0000000..3069e52 --- /dev/null +++ b/src/Modules/Resources/routes.php @@ -0,0 +1,14 @@ +.view` and `.manage`. +Route::prefix('/records/{resource}')->where(['resource' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+'])->group(function () { + Route::get('/', [ResourceController::class, 'index'])->name('records.index'); + Route::get('/create', [ResourceController::class, 'create'])->name('records.create'); + Route::post('/', [ResourceController::class, 'store'])->name('records.store'); + Route::get('/{id}/edit', [ResourceController::class, 'edit'])->name('records.edit'); + Route::put('/{id}', [ResourceController::class, 'update'])->name('records.update'); + Route::delete('/{id}', [ResourceController::class, 'destroy'])->name('records.destroy'); +}); diff --git a/src/Modules/Reviews/ReviewsController.php b/src/Modules/Reviews/ReviewsController.php new file mode 100644 index 0000000..d74ed8f --- /dev/null +++ b/src/Modules/Reviews/ReviewsController.php @@ -0,0 +1,14 @@ +json(Review::query()->latest()->paginate(25)); + } +} diff --git a/src/Modules/Reviews/ReviewsModule.php b/src/Modules/Reviews/ReviewsModule.php new file mode 100644 index 0000000..0bc86e4 --- /dev/null +++ b/src/Modules/Reviews/ReviewsModule.php @@ -0,0 +1,49 @@ + 'Reviews', 'route' => Names::route('reviews.index'), 'permission' => 'reviews.manage'], + ]; + } + + public function views(): array + { + return ['reviews.index' => 'Opened the reviews']; + } +} diff --git a/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php new file mode 100644 index 0000000..a261d2a --- /dev/null +++ b/src/Modules/Reviews/migrations/2026_12_04_000002_create_manager_reviews.php @@ -0,0 +1,27 @@ +id(); + $table->string('author'); + $table->string('place')->nullable(); + $table->unsignedTinyInteger('rating')->nullable(); + $table->text('body'); + $table->boolean('is_visible')->default(true); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('reviews')); + } +}; diff --git a/src/Modules/Reviews/routes.php b/src/Modules/Reviews/routes.php new file mode 100644 index 0000000..bbbd424 --- /dev/null +++ b/src/Modules/Reviews/routes.php @@ -0,0 +1,6 @@ +name('reviews.index')->middleware('can:reviews.manage'); diff --git a/src/Modules/Revisions/RevisionController.php b/src/Modules/Revisions/RevisionController.php new file mode 100644 index 0000000..7727f39 --- /dev/null +++ b/src/Modules/Revisions/RevisionController.php @@ -0,0 +1,65 @@ +find($type, $id, 'view'); + + $revisions = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->orderByDesc('id')->limit(100)->get(); + + return response()->json([ + 'revisions' => $revisions->map(fn (Revision $revision, int $position) => [ + 'id' => $revision->id, + 'created_at' => $revision->created_at, + 'user' => $revision->user_name, + 'changed' => $revision->changed ?? [], + 'current' => $position === 0, + // What the changed attributes were then, shortened: enough to see what an old version said. + 'values' => collect($revision->changed ?? [])->mapWithKeys(fn (string $key) => [$key => $this->shorten($revision->data[$key] ?? null)])->all(), + ])->values(), + 'can_restore' => Gate::allows('revisions.restore') && Gate::allows($config['restore']), + ]); + } + + public function restore(string $type, string $id, string $revision): JsonResponse + { + [$config, $model] = $this->find($type, $id, 'restore'); + $revision = Revision::query()->where('type', $type)->where('subject_id', $model->getKey())->whereKey($revision)->firstOrFail(); + + // A post that is on the site is only changed by someone who may publish. + abort_if($model instanceof Post && $model->isPublished() && Gate::denies('posts.publish'), 403); + + app(AuditTrail::class)->about($model); + Revisions::restore($model, $revision, $config); + + return response()->json(['restored' => true]); + } + + /** @return array{0: array{model: class-string, view: string, restore: string, except: list}, 1: Model} */ + private function find(string $type, string $id, string $ability): array + { + $config = Revisions::types()[$type] ?? null; + abort_if($config === null, 404); + Gate::authorize($config[$ability]); + + return [$config, $config['model']::query()->findOrFail($id)]; + } + + private function shorten(mixed $value): mixed + { + $text = is_scalar($value) || $value === null ? (string) $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + return mb_strlen($text) > 300 ? mb_substr($text, 0, 300).'…' : $text; + } +} diff --git a/src/Modules/Revisions/RevisionsModule.php b/src/Modules/Revisions/RevisionsModule.php new file mode 100644 index 0000000..ef5820b --- /dev/null +++ b/src/Modules/Revisions/RevisionsModule.php @@ -0,0 +1,54 @@ + ['Put an earlier version back']]; + } + + public function views(): array + { + return ['revisions.index' => 'Opened the history of a text']; + } + + public function boot(): void + { + Revisions::listen(); + } +} diff --git a/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php b/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php new file mode 100644 index 0000000..028a0a0 --- /dev/null +++ b/src/Modules/Revisions/migrations/2026_12_06_000001_create_manager_revisions.php @@ -0,0 +1,31 @@ +id(); + $table->string('type', 40); + $table->unsignedBigInteger('subject_id'); + // Who saved it: no foreign key, so the history stays when an account is removed. + $table->unsignedBigInteger('user_id')->nullable(); + $table->string('user_name')->nullable(); + $table->json('data'); + $table->json('changed')->nullable(); + $table->dateTime('created_at'); + + $table->index(['type', 'subject_id', 'id']); + }); + } + + public function down(): void + { + Schema::dropIfExists(Names::table('revisions')); + } +}; diff --git a/src/Modules/Revisions/routes.php b/src/Modules/Revisions/routes.php new file mode 100644 index 0000000..d141f2f --- /dev/null +++ b/src/Modules/Revisions/routes.php @@ -0,0 +1,10 @@ +prefix('/revisions/{type}/{id}')->where(['type' => '[a-z][a-z0-9_]*', 'id' => '[0-9]+', 'revision' => '[0-9]+'])->group(function () { + Route::get('/', [RevisionController::class, 'index'])->name('revisions.index'); + Route::post('/{revision}/restore', [RevisionController::class, 'restore'])->name('revisions.restore')->middleware('can:revisions.restore'); +}); diff --git a/src/Modules/Statistics/BotRecorder.php b/src/Modules/Statistics/BotRecorder.php new file mode 100644 index 0000000..b1bb119 --- /dev/null +++ b/src/Modules/Statistics/BotRecorder.php @@ -0,0 +1,66 @@ +bot(); + + if ($bot === null) { + return; + } + + $day = now()->toDateString(); + $name = $bot['name'] ?? self::OTHER; + + if ($bot['kind'] === 'other' && $name !== self::OTHER && $this->isOneTooMany($table, $day, $name)) { + $name = self::OTHER; + } + + // One statement, so two requests at the same moment both count. + DB::table($table)->upsert( + [['day' => $day, 'bot' => $name, 'kind' => $bot['kind'], 'path' => Str::limit('/'.trim(Str::before($path, '?'), '/'), 255, ''), 'hits' => 1]], + ['day', 'bot', 'path'], + ['hits' => DB::raw($table.'.hits + 1')], + ); + } + + private function isOneTooMany(string $table, string $day, string $name): bool + { + $unknown = DB::table($table)->where('day', $day)->where('kind', 'other'); + + if ((clone $unknown)->where('bot', $name)->exists()) { + return false; + } + + return $unknown->distinct()->count('bot') >= self::UNKNOWN_NAMES_A_DAY; + } +} diff --git a/src/Modules/Statistics/CountBots.php b/src/Modules/Statistics/CountBots.php new file mode 100644 index 0000000..ae251fd --- /dev/null +++ b/src/Modules/Statistics/CountBots.php @@ -0,0 +1,51 @@ +counts($request, $response)) { + try { + $this->recorder->hit((string) $request->userAgent(), $request->getPathInfo()); + } catch (Throwable $e) { + // Counting must never be the reason a page is not served. + report($e); + } + } + + return $response; + } + + private function counts(Request $request, Response $response): bool + { + $name = $request->route()?->getName(); + + return $request->isMethod('GET') + && $response->getStatusCode() === 200 + && is_string($name) + && ! str_starts_with($name, Names::routePrefix()) + // The same promise as for visitors: who asks not to be followed is not counted at all. + && $request->header('Sec-GPC') !== '1' + && $request->header('DNT') !== '1'; + } +} diff --git a/src/Modules/Statistics/CountedPages.php b/src/Modules/Statistics/CountedPages.php new file mode 100644 index 0000000..c546a50 --- /dev/null +++ b/src/Modules/Statistics/CountedPages.php @@ -0,0 +1,59 @@ + */ + private array $resolvers = []; + + /** + * @param Closure(string): (array{path: string, post_id: int|null}|null) $resolver gets a path like `/about`, returns the page or null + */ + public function register(Closure $resolver): void + { + $this->resolvers[] = $resolver; + } + + /** @return array{path: string, post_id: int|null}|null */ + public function resolve(string $path): ?array + { + $pages = array_map(fn (string $page) => '/'.trim($page, '/'), (array) config('manager.statistics.pages', ['/'])); + + if (in_array($path, $pages, true)) { + return ['path' => $path, 'post_id' => null]; + } + + $postsPath = config('manager.statistics.posts_path'); + + if (is_string($postsPath) && $postsPath !== '' && Manager::enabled('posts')) { + $prefix = '/'.trim($postsPath, '/').'/'; + + if (str_starts_with($path, $prefix)) { + $post = Post::query()->published()->where('slug', substr($path, strlen($prefix)))->first(); + + return $post instanceof Post ? ['path' => $path, 'post_id' => $post->id] : null; + } + } + + foreach ($this->resolvers as $resolver) { + $page = $resolver($path); + + if ($page !== null) { + return $page; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/ForgetVisitorKeys.php b/src/Modules/Statistics/ForgetVisitorKeys.php new file mode 100644 index 0000000..a68a275 --- /dev/null +++ b/src/Modules/Statistics/ForgetVisitorKeys.php @@ -0,0 +1,20 @@ +line(sprintf('%d key(s) of past days deleted.', VisitorSalt::forgetOld())); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Statistics/PulseController.php b/src/Modules/Statistics/PulseController.php new file mode 100644 index 0000000..d92ea17 --- /dev/null +++ b/src/Modules/Statistics/PulseController.php @@ -0,0 +1,58 @@ +` puts it in the page). */ + public function script(): BinaryFileResponse + { + return response()->file(__DIR__.'/../../../resources/js/pulse.js', [ + 'Content-Type' => 'application/javascript', + 'Cache-Control' => 'public, max-age=3600', + 'X-Content-Type-Options' => 'nosniff', + ]); + } + + public function view(Request $request, VisitRecorder $recorder): JsonResponse + { + // A browser that says its user does not want to be followed is not counted at all. + if ($request->header('Sec-GPC') === '1' || $request->header('DNT') === '1') { + return response()->json(['token' => null])->header('Cache-Control', 'no-store'); + } + + $countryHeader = config('manager.statistics.country_header'); + + $token = $recorder->view( + (string) $request->ip(), + (string) $request->userAgent(), + $request->string('path')->limit(300, '')->toString(), + [ + 'via' => $request->string('via')->limit(40, '')->toString(), + 'campaign' => $request->string('campaign')->limit(80, '')->toString(), + 'referrer' => $request->string('referrer')->limit(2000, '')->toString(), + // Only the country code is kept, and only when the site names the header that has it (Cloudflare: CF-IPCountry). + 'country' => is_string($countryHeader) && $countryHeader !== '' ? (string) $request->header($countryHeader, '') : '', + 'host' => $request->getHost(), + ], + ); + + return response()->json(['token' => $token])->header('Cache-Control', 'no-store'); + } + + public function leave(Request $request, VisitRecorder $recorder): Response + { + $recorder->leave($request->string('token')->limit(40, '')->toString(), $request->integer('seconds')); + + return response()->noContent()->header('Cache-Control', 'no-store'); + } +} diff --git a/src/Modules/Statistics/Source.php b/src/Modules/Statistics/Source.php new file mode 100644 index 0000000..b860bb7 --- /dev/null +++ b/src/Modules/Statistics/Source.php @@ -0,0 +1,122 @@ +, which + * is what tells a click on my own post apart from someone else's link. + */ +final class Source +{ + /** The platforms the site shares posts to; the values of ?via=. */ + public const PLATFORMS = ['linkedin', 'x', 'facebook', 'instagram']; + + /** Host (or the end of one) => platform. */ + private const SOCIAL = [ + 'linkedin.com' => 'linkedin', 'lnkd.in' => 'linkedin', 'com.linkedin.android' => 'linkedin', + 't.co' => 'x', 'x.com' => 'x', 'twitter.com' => 'x', 'com.twitter.android' => 'x', + 'facebook.com' => 'facebook', 'fb.com' => 'facebook', 'fb.me' => 'facebook', 'com.facebook.katana' => 'facebook', + 'instagram.com' => 'instagram', 'com.instagram.android' => 'instagram', + 'threads.net' => 'threads', 'threads.com' => 'threads', 'bsky.app' => 'bluesky', 'reddit.com' => 'reddit', + 'youtube.com' => 'youtube', 'youtu.be' => 'youtube', 'news.ycombinator.com' => 'hackernews', + 'tweakers.net' => 'tweakers', + ]; + + /** Host (or the end of one) => search engine. */ + private const SEARCH = [ + 'bing.com' => 'bing', 'duckduckgo.com' => 'duckduckgo', 'ecosia.org' => 'ecosia', + 'startpage.com' => 'startpage', 'search.brave.com' => 'brave', 'yandex.com' => 'yandex', 'yandex.ru' => 'yandex', + 'baidu.com' => 'baidu', 'kagi.com' => 'kagi', 'qwant.com' => 'qwant', 'search.yahoo.com' => 'yahoo', + 'com.google.android.googlequicksearchbox' => 'google', + ]; + + private function __construct( + public readonly string $channel, + public readonly ?string $source, + public readonly ?string $referrerHost, + ) {} + + /** + * @param string $via the ?via= of the address the visitor arrived on + * @param string $campaign its ?utm_source= + * @param string $referrer the address of the page that linked here + * @param string $ownHost this site's own host: a link from the site itself is no source + */ + public static function of(string $via, string $campaign, string $referrer, string $ownHost): self + { + $host = self::host($referrer); + if ($host === self::bare($ownHost)) { + $host = null; + } + + $via = strtolower(trim($via)); + if (in_array($via, self::PLATFORMS, true)) { + return new self('share', $via, $host); + } + + $campaign = strtolower(trim($campaign)); + if ($campaign !== '' && preg_match('/^[a-z0-9._-]{1,80}$/', $campaign) === 1) { + $platform = self::SOCIAL[$campaign.'.com'] ?? ($campaign === 'twitter' ? 'x' : null); + + return $platform !== null ? new self('social', $platform, $host) : new self('campaign', $campaign, $host); + } + + if ($host === null) { + return new self('direct', null, null); + } + + if (($platform = self::match($host, self::SOCIAL)) !== null) { + return new self('social', $platform, $host); + } + + // google.com, google.nl, google.co.uk ... + if (preg_match('/(^|\.)google\.[a-z.]{2,6}$/', $host) === 1) { + return new self('search', 'google', $host); + } + + if (($engine = self::match($host, self::SEARCH)) !== null) { + return new self('search', $engine, $host); + } + + return new self('referral', $host, $host); + } + + /** The host of an address, lower case and without "www."; null when there is none. */ + private static function host(string $address): ?string + { + $address = trim($address); + if ($address === '') { + return null; + } + + $host = parse_url($address, PHP_URL_HOST); + if (! is_string($host) || $host === '' || strlen($host) > 255) { + return null; + } + + return self::bare($host); + } + + private static function bare(string $host): string + { + $host = strtolower($host); + + return str_starts_with($host, 'www.') ? substr($host, 4) : $host; + } + + /** @param array $known */ + private static function match(string $host, array $known): ?string + { + foreach ($known as $end => $name) { + if ($host === $end || str_ends_with($host, '.'.$end)) { + return $name; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/Statistics.php b/src/Modules/Statistics/Statistics.php new file mode 100644 index 0000000..9ce0f16 --- /dev/null +++ b/src/Modules/Statistics/Statistics.php @@ -0,0 +1,746 @@ + 'Today', 'week' => 'This week', '7d' => 'Last 7 days', 'month' => 'This month', '30d' => 'Last 30 days', + '12m' => 'Last 12 months', 'all' => 'All time', + ]; + + /** A period between two dates of one's own choosing (`from` and `to`). */ + public const CUSTOM = 'custom'; + + /** What a period can be put next to: the one before it, the same days a year earlier, days of one's own choosing, or nothing. */ + public const COMPARISONS = ['previous' => 'The period before', 'year' => 'A year earlier', 'custom' => 'Another period', 'none' => 'Nothing']; + + /** What can be downloaded as a CSV file. */ + public const EXPORTS = ['days' => 'Per day', 'pages' => 'Pages', 'sources' => 'Sources', 'bots' => 'Bots']; + + public const DEFAULT_RANGE = '30d'; + + private const WEEKDAYS = [1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', 7 => 'Sun']; + + /** + * Everything the statistics page shows for one period. + * + * @param array $choice `from` and `to` for a period of one's own, `compare` (see COMPARISONS) and `compare_from` + * @return array + */ + public function report(string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $compares = $period['previous_from'] !== null && $period['previous_to'] !== null; + + return [ + 'range' => [ + 'key' => $period['key'], + 'label' => $period['label'], + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'compare' => $period['compare'], + 'compared_to' => $period['compared_to'], + 'previous_from' => $period['previous_from'], + 'previous_to' => $period['previous_to'], + ], + 'ranges' => $this->ranges(), + 'comparisons' => self::COMPARISONS, + 'exports' => self::EXPORTS, + 'totals' => $this->totals($from, $to), + 'previous' => $compares ? $this->totals((string) $period['previous_from'], (string) $period['previous_to'], $period['previous_until_hour']) : null, + 'series' => $this->series($from, $to, $period['bucket']), + // The other period, step by step: the first step of it next to the first step of this one. + 'previous_series' => $compares ? $this->series((string) $period['previous_from'], (string) $period['previous_to'], $period['bucket']) : null, + 'pages' => $this->pages($from, $to), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 10), + 'platforms' => $this->platforms($from, $to), + 'sources' => $this->sources($from, $to), + 'heatmap' => $this->heatmap($from, $to), + 'countries' => $this->grouped($from, $to, 'country', 8), + 'devices' => $this->grouped($from, $to, 'device', 5), + 'browsers' => $this->grouped($from, $to, 'browser', 6), + 'systems' => $this->grouped($from, $to, 'os', 6), + // Programs have no hour, so "today until now" has nothing fair to stand next to. + 'bots' => $this->bots($from, $to, $compares && $period['previous_until_hour'] === null ? [(string) $period['previous_from'], (string) $period['previous_to']] : null), + ]; + } + + /** + * The few numbers of a period that the screen of the owner shows (`OwnerNumbers`): the + * totals next to the period before, the visitors step by step, and the pages, articles + * and ways in that were used most. + * + * @return array{from: string, to: string, bucket: string, totals: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}, previous: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}|null, series: list, pages: list, posts: list, channels: list} + */ + public function brief(string $range): array + { + $period = $this->period($range); + $from = $period['from']; + $to = $period['to']; + + return [ + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'totals' => $this->totals($from, $to), + 'previous' => $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null, + 'series' => $this->series($from, $to, $period['bucket']), + 'pages' => $this->pages($from, $to, 6), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 6), + ]; + } + + /** + * One list of the period as rows for a CSV file. An unknown list gives the days. + * + * @param array $choice + * @return array{filename: string, header: list, rows: list>} + */ + public function export(string $sheet, string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $sheet = array_key_exists($sheet, self::EXPORTS) ? $sheet : 'days'; + + [$header, $rows] = match ($sheet) { + 'pages' => [['Page', 'Title', 'Views', 'Average seconds on the page'], array_map( + fn (array $page) => [$page['path'], $page['title'] ?? '', $page['views'], $page['average_seconds']], + $this->pages($from, $to, null), + )], + 'sources' => [['Source', 'Channel', 'Visits'], array_map( + fn (array $source) => [$source['name'], $source['channel'], $source['visits']], + $this->sources($from, $to, null), + )], + 'bots' => [['Program', 'Kind', 'Page', 'Requests'], $this->botRows($from, $to)], + default => [['Day', 'Visitors', 'Visits', 'Page views', 'Requests by programs'], array_map( + fn (array $day) => [$day['key'], $day['visitors'], $day['visits'], $day['page_views'], $day['bot_hits']], + $this->series($from, $to, 'day'), + )], + }; + + return ['filename' => "statistics-{$sheet}-{$from}-to-{$to}.csv", 'header' => $header, 'rows' => $rows]; + } + + /** + * The short version for the dashboard: today, the last 7 and the last 30 days, + * each next to the period before it, and the visitors per day of the last 30 days. + * + * @return array{periods: list, days: list} + */ + public function summary(): array + { + $periods = []; + + foreach (['today', '7d', '30d'] as $range) { + $period = $this->period($range); + $now = $this->totals($period['from'], $period['to']); + $before = $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null; + + $periods[] = [ + 'key' => $range, + 'label' => $period['label'], + 'visitors' => $now['visitors'], + 'page_views' => $now['page_views'], + 'previous_visitors' => $before['visitors'] ?? 0, + ]; + } + + $month = $this->period('30d'); + + return ['periods' => $periods, 'days' => $this->series($month['from'], $month['to'], 'day')]; + } + + /** + * A period as dates, with the period it is compared with. An unknown key + * gives the default period. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compare: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function period(string $range, array $choice = []): array + { + $period = $this->dates($range, $choice); + $compare = $choice['compare'] ?? 'previous'; + $nothing = ['compare' => 'none', 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, 'previous_until_hour' => null]; + + // All time has nothing before it. + if ($period['previous_from'] === null || $compare === 'none') { + return $nothing + $period; + } + + $from = CarbonImmutable::parse($period['from']); + $to = CarbonImmutable::parse($period['to']); + + if ($compare === 'year') { + return [ + 'compare' => 'year', 'compared_to' => 'the same days a year earlier', + 'previous_from' => $from->subYearNoOverflow()->toDateString(), 'previous_to' => $to->subYearNoOverflow()->toDateString(), + ] + $period; + } + + $start = $compare === 'custom' ? self::date($choice['compare_from'] ?? '') : null; + + if ($start !== null) { + // As many days as the period itself, from the chosen day on. + $end = $start->addDays((int) $from->diffInDays($to)); + + return [ + 'compare' => 'custom', 'compared_to' => self::span($start, $end), + 'previous_from' => $start->toDateString(), 'previous_to' => $end->toDateString(), + ] + $period; + } + + return ['compare' => 'previous'] + $period; + } + + /** + * The dates of a period, and of the period before it. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function dates(string $range, array $choice): array + { + $today = CarbonImmutable::now()->startOfDay(); + $day = fn (CarbonImmutable $date): string => $date->toDateString(); + + if (preg_match('/^\d{4}$/', $range) === 1 && in_array((int) $range, $this->years(), true)) { + $start = $today->setDate((int) $range, 1, 1); + + return [ + 'key' => $range, 'label' => $range, 'from' => $day($start), 'to' => $day($start->endOfYear()), 'bucket' => 'month', + 'compared_to' => (string) ((int) $range - 1), + 'previous_from' => $day($start->subYear()), 'previous_to' => $day($start->subDay()), 'previous_until_hour' => null, + ]; + } + + $from = self::date($choice['from'] ?? ''); + $to = self::date($choice['to'] ?? ''); + + if ($range === self::CUSTOM && $from !== null && $to !== null) { + // The wrong way round, or into the future: still a period. + [$from, $to] = $from <= $to ? [$from, $to] : [$to, $from]; + $to = $to->min($today); + $from = $from->min($to); + $days = (int) $from->diffInDays($to) + 1; + + return [ + 'key' => self::CUSTOM, 'label' => self::span($from, $to), 'from' => $day($from), 'to' => $day($to), + 'bucket' => match (true) { + $days === 1 => 'hour', + $days <= 92 => 'day', + $days <= 1100 => 'month', + default => 'year', + }, + 'compared_to' => $days === 1 ? 'the day before' : "the {$days} days before", + 'previous_from' => $day($from->subDays($days)), 'previous_to' => $day($from->subDay()), 'previous_until_hour' => null, + ]; + } + + if (! array_key_exists($range, self::RANGES)) { + $range = self::DEFAULT_RANGE; + } + + $period = ['key' => $range, 'label' => self::RANGES[$range], 'to' => $day($today), 'previous_until_hour' => null]; + $monday = $today->startOfWeek(CarbonImmutable::MONDAY); + $lastMonth = $today->startOfMonth()->subMonthNoOverflow(); + + return match ($range) { + // Today so far, next to yesterday up to the same hour: a fair comparison at any time of day. + 'today' => ['previous_until_hour' => CarbonImmutable::now()->hour] + $period + [ + 'from' => $day($today), 'bucket' => 'hour', 'compared_to' => 'yesterday at this time', + 'previous_from' => $day($today->subDay()), 'previous_to' => $day($today->subDay()), + ], + // A week and a month that are still running stand next to as many days of the one before. + 'week' => $period + [ + 'from' => $day($monday), 'bucket' => 'day', 'compared_to' => 'last week up to the same day', + 'previous_from' => $day($monday->subWeek()), 'previous_to' => $day($today->subWeek()), + ], + 'month' => $period + [ + 'from' => $day($today->startOfMonth()), 'bucket' => 'day', 'compared_to' => 'last month up to the same day', + 'previous_from' => $day($lastMonth), 'previous_to' => $day($lastMonth->setDay(min($today->day, $lastMonth->daysInMonth))), + ], + '7d' => $period + [ + 'from' => $day($today->subDays(6)), 'bucket' => 'day', 'compared_to' => 'the 7 days before', + 'previous_from' => $day($today->subDays(13)), 'previous_to' => $day($today->subDays(7)), + ], + '12m' => $period + [ + 'from' => $day($today->startOfMonth()->subMonthsNoOverflow(11)), 'bucket' => 'month', 'compared_to' => 'the 12 months before', + 'previous_from' => $day($today->startOfMonth()->subMonthsNoOverflow(23)), + 'previous_to' => $day($today->startOfMonth()->subMonthsNoOverflow(11)->subDay()), + ], + 'all' => $period + [ + 'from' => $this->firstDay() ?? $day($today), + // Months while that still fits on the screen, years after that. + 'bucket' => CarbonImmutable::parse($this->firstDay() ?? $day($today))->diffInMonths($today) > 24 ? 'year' : 'month', + 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, + ], + default => $period + [ + 'from' => $day($today->subDays(29)), 'bucket' => 'day', 'compared_to' => 'the 30 days before', + 'previous_from' => $day($today->subDays(59)), 'previous_to' => $day($today->subDays(30)), + ], + }; + } + + /** A date as 'Y-m-d' from the address bar, or null when it is not one. */ + private static function date(string $value): ?CarbonImmutable + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $value); + + // "2026-02-31" is read as the 3rd of March: not what was typed, so not a date. + return $date instanceof CarbonImmutable && $date->toDateString() === $value && $date->year >= 2000 ? $date : null; + } + + /** "1 Oct – 31 Oct 2026" */ + private static function span(CarbonImmutable $from, CarbonImmutable $to): string + { + if ($from->equalTo($to)) { + return $from->format('j M Y'); + } + + return $from->format($from->year === $to->year ? 'j M' : 'j M Y').' – '.$to->format('j M Y'); + } + + /** + * The periods to choose from: the fixed ones and every year there are visits of. + * + * @return list + */ + private function ranges(): array + { + $ranges = []; + foreach (self::RANGES as $key => $label) { + $ranges[] = ['key' => $key, 'label' => $label]; + } + foreach (array_reverse($this->years()) as $year) { + $ranges[] = ['key' => (string) $year, 'label' => (string) $year]; + } + + return $ranges; + } + + /** @return list every year from the first visit until now */ + private function years(): array + { + $first = $this->firstDay(); + + return $first === null ? [] : range((int) substr($first, 0, 4), CarbonImmutable::now()->year); + } + + private function firstDay(): ?string + { + $first = DB::table($this->table('visits'))->min('day'); + + return is_string($first) ? substr($first, 0, 10) : null; + } + + /** + * @param int|null $untilHour only count visits that started in or before this hour of the day + * @return array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int} + */ + private function totals(string $from, string $to, ?int $untilHour = null): array + { + $row = $this->visits($from, $to) + ->when($untilHour !== null, fn (Builder $query) => $query->where('hour', '<=', $untilHour)) + ->selectRaw('count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views') + ->selectRaw('sum(seconds) as seconds, sum(case when page_views <= 1 then 1 else 0 end) as bounces') + ->first(); + + $visits = self::number($row->visits ?? 0); + + return [ + 'visitors' => self::number($row->visitors ?? 0), + 'visits' => $visits, + 'page_views' => self::number($row->page_views ?? 0), + 'average_seconds' => $visits > 0 ? (int) round(self::number($row->seconds ?? 0) / $visits) : 0, + // Visits that ended after a single page, as a percentage. + 'bounce_rate' => $visits > 0 ? (int) round(100 * self::number($row->bounces ?? 0) / $visits) : 0, + ]; + } + + /** + * Visitors, visits and page views through time, one entry per hour, day, month + * or year. Every step of the period is there, also the ones without visits. + * + * `bot_hits` are the requests by programs; those have no hour, so per hour it stays 0. + * + * @return list + */ + private function series(string $from, string $to, string $bucket): array + { + $column = $bucket === 'hour' ? 'hour' : 'day'; + $rows = $this->visits($from, $to) + ->selectRaw("{$column} as step, count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views") + ->groupBy($column) + ->get(); + + $steps = []; + $start = CarbonImmutable::parse($from); + $end = CarbonImmutable::parse($to); + + if ($bucket === 'hour') { + foreach (range(0, 23) as $hour) { + $steps[(string) $hour] = sprintf('%02d:00', $hour); + } + } elseif ($bucket === 'day') { + for ($date = $start; $date <= $end; $date = $date->addDay()) { + $steps[$date->toDateString()] = $date->format('j M'); + } + } elseif ($bucket === 'month') { + for ($date = $start->startOfMonth(); $date <= $end; $date = $date->addMonth()) { + $steps[$date->format('Y-m')] = $date->format('M Y'); + } + } else { + foreach (range($start->year, $end->year) as $year) { + $steps[(string) $year] = (string) $year; + } + } + + $series = []; + foreach ($steps as $key => $label) { + $series[(string) $key] = ['key' => (string) $key, 'label' => $label, 'visitors' => 0, 'visits' => 0, 'page_views' => 0, 'bot_hits' => 0]; + } + + $keyOf = fn (mixed $step): string => match ($bucket) { + 'hour' => (string) (int) (is_scalar($step) ? $step : 0), + 'day' => substr(is_scalar($step) ? (string) $step : '', 0, 10), + 'month' => substr(is_scalar($step) ? (string) $step : '', 0, 7), + default => substr(is_scalar($step) ? (string) $step : '', 0, 4), + }; + + foreach ($rows as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['visitors'] += self::number($row->visitors); + $series[$key]['visits'] += self::number($row->visits); + $series[$key]['page_views'] += self::number($row->page_views); + } + } + + if ($bucket !== 'hour') { + foreach ($this->botHits($from, $to)->selectRaw('day as step, sum(hits) as hits')->groupBy('day')->get() as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['bot_hits'] += self::number($row->hits); + } + } + } + + return array_values($series); + } + + /** + * The pages that were looked at most, with the average time on the page. + * + * @return list + */ + private function pages(string $from, string $to, ?int $limit = 10): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to]) + ->selectRaw('path, max(post_id) as post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('path')->orderByDesc('views')->orderBy('path') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $titles = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->filter()->all())->pluck('title', 'id') : collect(); + + $pages = []; + foreach ($rows as $row) { + $views = self::number($row->views); + $title = $titles->get(self::number($row->post_id)); + + $pages[] = [ + 'path' => is_string($row->path) ? $row->path : '', + 'title' => is_string($title) ? $title : null, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + + return $pages; + } + + /** + * The posts that were read most. + * + * @return list + */ + private function posts(string $from, string $to): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to])->whereNotNull('post_id') + ->selectRaw('post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('post_id')->orderByDesc('views')->limit(10)->get(); + + $found = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->all())->get()->keyBy('id') : collect(); + + $posts = []; + foreach ($rows as $row) { + $post = $found->get(self::number($row->post_id)); + $views = self::number($row->views); + + if ($post instanceof Post) { + $posts[] = [ + 'title' => $post->title, + 'slug' => $post->slug, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + } + + return $posts; + } + + /** + * Visits counted by one column of `visits`, most first. + * + * @return list + */ + private function grouped(string $from, string $to, string $column, int $limit): array + { + $rows = $this->visits($from, $to)->whereNotNull($column) + ->select("{$column} as name")->selectRaw('count(*) as visits') + ->groupBy($column)->orderByDesc('visits')->orderBy($column)->limit($limit)->get(); + + $result = []; + foreach ($rows as $row) { + $result[] = ['name' => is_scalar($row->name) ? (string) $row->name : '', 'visits' => self::number($row->visits)]; + } + + return $result; + } + + /** + * The four platforms the site shares posts to: how many visits came from each, + * and how many of those through a link the site posted itself. + * + * @return list + */ + private function platforms(string $from, string $to): array + { + $rows = $this->visits($from, $to)->whereIn('source', Source::PLATFORMS)->whereIn('channel', ['share', 'social']) + ->selectRaw('source, channel, count(*) as visits')->groupBy('source', 'channel')->get(); + + $platforms = []; + foreach (Source::PLATFORMS as $platform) { + $platforms[$platform] = ['name' => $platform, 'visits' => 0, 'shared' => 0]; + } + + foreach ($rows as $row) { + $name = is_string($row->source) ? $row->source : ''; + if (isset($platforms[$name])) { + $platforms[$name]['visits'] += self::number($row->visits); + $platforms[$name]['shared'] += $row->channel === 'share' ? self::number($row->visits) : 0; + } + } + + return array_values($platforms); + } + + /** + * The sites, search engines and platforms that sent visitors, most first. + * + * @return list + */ + private function sources(string $from, string $to, ?int $limit = 12): array + { + $rows = $this->visits($from, $to)->whereNotNull('source') + ->selectRaw('source, channel, count(*) as visits') + ->groupBy('source', 'channel')->orderByDesc('visits')->orderBy('source') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $sources = []; + foreach ($rows as $row) { + $sources[] = [ + 'name' => is_string($row->source) ? $row->source : '', + 'channel' => is_string($row->channel) ? $row->channel : '', + 'visits' => self::number($row->visits), + ]; + } + + return $sources; + } + + /** + * The busy moments: visits per weekday and hour of the day. + * + * @return list}> + */ + private function heatmap(string $from, string $to): array + { + $rows = $this->visits($from, $to)->selectRaw('weekday, hour, count(*) as visits')->groupBy('weekday', 'hour')->get(); + + $grid = []; + foreach (self::WEEKDAYS as $number => $name) { + $grid[$number] = ['day' => $name, 'hours' => array_fill(0, 24, 0)]; + } + + foreach ($rows as $row) { + $weekday = self::number($row->weekday); + $hour = self::number($row->hour); + if (isset($grid[$weekday]) && $hour >= 0 && $hour <= 23) { + $grid[$weekday]['hours'][$hour] = self::number($row->visits); + } + } + + return array_values($grid); + } + + /** + * The programs that fetched pages (search engines, AI crawlers, link previews, + * scripts ...): how often in all, which ones, what kind, and which pages. + * They are counted on the server (BotRecorder) and are never part of the + * visitors above. + * + * @param array{0: string, 1: string}|null $before the period to compare the total with + * @return array{total: int, previous: int|null, names: list, kinds: list, pages: list} + */ + private function bots(string $from, string $to, ?array $before): array + { + $names = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, sum(hits) as hits') + ->groupBy('bot', 'kind')->orderByDesc('hits')->orderBy('bot')->limit(15)->get() as $row) { + $names[] = ['name' => is_string($row->bot) ? $row->bot : '', 'kind' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $kinds = []; + foreach ($this->botHits($from, $to)->selectRaw('kind, sum(hits) as hits') + ->groupBy('kind')->orderByDesc('hits')->orderBy('kind')->get() as $row) { + $kinds[] = ['name' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $pages = []; + foreach ($this->botHits($from, $to)->selectRaw('path, sum(hits) as hits') + ->groupBy('path')->orderByDesc('hits')->orderBy('path')->limit(10)->get() as $row) { + $pages[] = ['path' => is_string($row->path) ? $row->path : '', 'hits' => self::number($row->hits)]; + } + + return [ + 'total' => self::number($this->botHits($from, $to)->sum('hits')), + 'previous' => $before === null ? null : self::number($this->botHits($before[0], $before[1])->sum('hits')), + 'names' => $names, + 'kinds' => $kinds, + 'pages' => $pages, + ]; + } + + /** + * Every program and page of the period, for the export. + * + * @return list> + */ + private function botRows(string $from, string $to): array + { + $rows = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, path, sum(hits) as hits') + ->groupBy('bot', 'kind', 'path')->orderByDesc('hits')->orderBy('bot')->orderBy('path')->get() as $row) { + $rows[] = [is_string($row->bot) ? $row->bot : '', is_string($row->kind) ? $row->kind : '', is_string($row->path) ? $row->path : '', self::number($row->hits)]; + } + + return $rows; + } + + /** + * How often each post was opened, since the beginning, and how those readers + * got to it. Someone who landed on the post is counted under the way they + * arrived (a shared post on LinkedIn, Google, direct ...); someone who was on + * another page of the site first and clicked through is counted as "internal". + * + * @param int|null $postId only this post + * @return array}> by post id + */ + public function readers(?int $postId = null): array + { + $views = $this->table('page_views'); + $visits = $this->table('visits'); + $rows = DB::table($views) + ->join($visits, "{$visits}.id", '=', "{$views}.visit_id") + ->whereNotNull("{$views}.post_id") + ->when($postId !== null, fn (Builder $query) => $query->where("{$views}.post_id", $postId)) + ->selectRaw("{$views}.post_id as post, case when {$visits}.entry_path = {$views}.path then {$visits}.channel else 'internal' end as arrived_by") + ->selectRaw("case when {$visits}.entry_path = {$views}.path then {$visits}.source else null end as arrived_from") + ->selectRaw("count(*) as views, sum({$views}.seconds) as seconds") + ->groupBy('post', 'arrived_by', 'arrived_from') + ->orderByDesc('views')->orderBy('arrived_by')->orderBy('arrived_from') + ->get(); + + $posts = []; + $seconds = []; + + foreach ($rows as $row) { + $id = self::number($row->post); + $views = self::number($row->views); + + $posts[$id] ??= ['views' => 0, 'average_seconds' => 0, 'sources' => []]; + $posts[$id]['views'] += $views; + $posts[$id]['sources'][] = [ + 'channel' => is_string($row->arrived_by) ? $row->arrived_by : '', + 'name' => is_string($row->arrived_from) ? $row->arrived_from : null, + 'views' => $views, + ]; + $seconds[$id] = ($seconds[$id] ?? 0) + self::number($row->seconds); + } + + foreach ($posts as $id => $post) { + $posts[$id]['average_seconds'] = $post['views'] > 0 ? (int) round(($seconds[$id] ?? 0) / $post['views']) : 0; + } + + return $posts; + } + + private function visits(string $from, string $to): Builder + { + return DB::table($this->table('visits'))->whereBetween('day', [$from, $to]); + } + + private function botHits(string $from, string $to): Builder + { + return DB::table($this->table('bot_hits'))->whereBetween('day', [$from, $to]); + } + + /** A count or sum as the database gives it (int, numeric string or null). */ + private function table(string $name): string + { + return Names::table($name); + } + + private static function number(mixed $value): int + { + return is_numeric($value) ? (int) $value : 0; + } +} diff --git a/src/Modules/Statistics/StatisticsController.php b/src/Modules/Statistics/StatisticsController.php new file mode 100644 index 0000000..c5dbdb1 --- /dev/null +++ b/src/Modules/Statistics/StatisticsController.php @@ -0,0 +1,71 @@ +json($statistics->report($this->range($request), $this->choice($request))); + } + + /** One list of the period that is on the screen, as a CSV file. */ + public function export(Request $request, Statistics $statistics): StreamedResponse + { + $export = $statistics->export($request->string('sheet')->toString(), $this->range($request), $this->choice($request)); + + return response()->streamDownload(function () use ($export) { + $out = fopen('php://output', 'w'); + + if ($out === false) { + return; + } + + // The mark that tells a spreadsheet the file is UTF-8. + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, $export['header'], ',', '"', ''); + + foreach ($export['rows'] as $row) { + fputcsv($out, array_map(self::cell(...), $row), ',', '"', ''); + } + + fclose($out); + }, $export['filename'], ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store']); + } + + /** + * A page address, a referring site and the name of a program come from visitors. A spreadsheet + * runs a cell that starts like a formula, so such a cell gets a quote in front and is shown as + * the text it is. + */ + private static function cell(string|int $value): string|int + { + return is_string($value) && preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value; + } + + private function range(Request $request): string + { + return $request->string('range', Statistics::DEFAULT_RANGE)->toString(); + } + + /** @return array */ + private function choice(Request $request): array + { + $choice = []; + + foreach (['from', 'to', 'compare', 'compare_from'] as $key) { + $choice[$key] = $request->string($key)->limit(20, '')->toString(); + } + + // Nothing chosen is the period before, not "nothing". + if ($choice['compare'] === '') { + unset($choice['compare']); + } + + return $choice; + } +} diff --git a/src/Modules/Statistics/StatisticsModule.php b/src/Modules/Statistics/StatisticsModule.php new file mode 100644 index 0000000..cb610d4 --- /dev/null +++ b/src/Modules/Statistics/StatisticsModule.php @@ -0,0 +1,85 @@ + 'Statistics', 'route' => Names::route('statistics.index'), 'permission' => 'statistics.view']]; + } + + public function commands(): array + { + return [ForgetVisitorKeys::class]; + } + + public function actions(): array + { + return ['statistics.export' => ['Exported the statistics', ['sheet']]]; + } + + public function views(): array + { + return ['statistics.index' => 'Opened the statistics']; + } + + public function boot(): void + { + app()->singleton(CountedPages::class); + + // A person opens a few pages a minute; this only stops someone from flooding the statistics. + RateLimiter::for('manager-pulse', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.statistics.per_minute', 120)))->by((string) $request->ip())); + + // Programs never run the script that reports a view, so the server counts the pages it serves them. + // Through the kernel: it copies its own groups to the router when a request starts. + if (config('manager.statistics.count_bots') && method_exists($kernel = app(Kernel::class), 'appendMiddlewareToGroup')) { + $kernel->appendMiddlewareToGroup('web', CountBots::class); + } + + // Without yesterday's key, yesterday's visitor codes can no longer be traced back. + if (app()->runningInConsole()) { + app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(ForgetVisitorKeys::class)->dailyAt('00:05')); + } + } +} diff --git a/src/Modules/Statistics/VisitRecorder.php b/src/Modules/Statistics/VisitRecorder.php new file mode 100644 index 0000000..1017a5e --- /dev/null +++ b/src/Modules/Statistics/VisitRecorder.php @@ -0,0 +1,168 @@ +page($path); + + if ($agent->isBot() || $page === null) { + return null; + } + + $now = now(); + $hash = hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent); + + $visit = Visit::query() + ->where('visitor_hash', $hash) + ->where('last_seen_at', '>=', $now->copy()->subMinutes(self::VISIT_GAP_MINUTES)) + ->latest('id') + ->first(); + + if (! $visit instanceof Visit) { + $source = Source::of($arrival['via'] ?? '', $arrival['campaign'] ?? '', $arrival['referrer'] ?? '', $arrival['host'] ?? ''); + $country = strtoupper(trim($arrival['country'] ?? '')); + + $visit = Visit::query()->create([ + 'visitor_hash' => $hash, + 'started_at' => $now, + 'last_seen_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + 'weekday' => $now->dayOfWeekIso, + 'entry_path' => $page['path'], + 'exit_path' => $page['path'], + 'channel' => $source->channel, + 'source' => $source->source, + 'referrer_host' => $source->referrerHost, + // Cloudflare says XX for unknown and T1 for Tor: neither is a country. + 'country' => preg_match('/^[A-Z]{2}$/', $country) === 1 && ! in_array($country, ['XX', 'T1'], true) ? $country : null, + 'device' => $agent->device(), + 'browser' => $agent->browser(), + 'os' => $agent->os(), + ]); + } + + $token = Str::random(40); + + PageView::query()->create([ + 'token' => $token, + 'visit_id' => $visit->id, + 'path' => $page['path'], + 'post_id' => $page['post_id'], + 'viewed_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + ]); + + $visit->update([ + 'last_seen_at' => $now, + 'exit_path' => $page['path'], + 'page_views' => $visit->page_views + 1, + ]); + + return $token; + } + + /** + * Where the visit of this visitor came from (channel and source), for a request + * that is sent during it. Empty when the visit was not counted. + * + * @return array{channel?: string|null, source?: string|null} + */ + public function sourceOf(string $ip, string $userAgent): array + { + $visit = Visit::query() + ->where('visitor_hash', hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent)) + ->latest('id') + ->first(); + + return $visit instanceof Visit ? ['channel' => $visit->channel, 'source' => $visit->source] : []; + } + + /** + * The time a visitor had a page in view, reported when they leave it. The + * browser may report more than once (a tab that is hidden and shown again), + * each time with the total so far. + */ + public function leave(string $token, int $seconds): void + { + $view = PageView::query()->where('token', $token)->first(); + + if (! $view instanceof PageView || $seconds < 1) { + return; + } + + // Never longer than the time that really passed since the page was opened. + $passed = (int) abs(now()->diffInSeconds($view->viewed_at)) + 5; + $seconds = min($seconds, $passed, self::MAX_SECONDS_ON_A_PAGE); + + if ($seconds <= $view->seconds) { + return; + } + + $view->update(['seconds' => $seconds]); + + Visit::query()->whereKey($view->visit_id)->update([ + 'seconds' => (int) PageView::query()->where('visit_id', $view->visit_id)->sum('seconds'), + 'last_seen_at' => now(), + ]); + } + + /** The address as the statistics know it, or null when it is no public page of this site. */ + public function pathOf(string $path): ?string + { + return $this->page($path)['path'] ?? null; + } + + /** + * The page behind an address, or null when the address is not a public page + * of this site: that keeps made-up addresses out of the statistics. + * + * @return array{path: string, post_id: int|null}|null + */ + private function page(string $path): ?array + { + if (! str_starts_with($path, '/')) { + return null; + } + + $path = '/'.trim(Str::before($path, '?'), '/'); + + if (strlen($path) > 255) { + return null; + } + + return app(CountedPages::class)->resolve($path); + } +} diff --git a/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php new file mode 100644 index 0000000..78020c9 --- /dev/null +++ b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php @@ -0,0 +1,96 @@ +date('day')->primary(); + $table->string('salt', 64); + }); + + // One visit: the pages someone looks at with less than half an hour between them. + Schema::create(Names::table('visits'), function (Blueprint $table) { + $table->id(); + $table->string('visitor_hash', 64); + $table->dateTime('started_at'); + $table->dateTime('last_seen_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + // 1 = Monday ... 7 = Sunday. + $table->unsignedTinyInteger('weekday'); + $table->string('entry_path'); + $table->string('exit_path'); + // direct, search, social, referral, share or campaign. + $table->string('channel', 20); + // The platform or site behind the channel: "linkedin", "google", "example.com". + $table->string('source', 80)->nullable(); + $table->string('referrer_host')->nullable(); + $table->string('country', 2)->nullable(); + $table->string('device', 10); + $table->string('browser', 30); + $table->string('os', 20); + $table->unsignedInteger('page_views')->default(0); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index(['visitor_hash', 'last_seen_at']); + }); + + Schema::create(Names::table('page_views'), function (Blueprint $table) { + $table->id(); + // What the browser sends back when the visitor leaves the page, to report the time spent. + $table->string('token', 40)->unique(); + $table->foreignId('visit_id')->constrained(Names::table('visits'))->cascadeOnDelete(); + $table->string('path'); + // The post behind the page, when the posts module is on. No foreign key: posts may be off. + $table->unsignedBigInteger('post_id')->nullable(); + $table->dateTime('viewed_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index('path'); + }); + + // How often each program (search engine, AI crawler, link preview, ...) fetched each page, per + // day. A counter, not a log: no address, no browser line. + Schema::create(Names::table('bot_hits'), function (Blueprint $table) { + $table->id(); + $table->date('day'); + $table->string('bot', 60); + // search, ai, seo, social, monitor, feed, archive, scanner, script or other. + $table->string('kind', 20); + $table->string('path'); + $table->unsignedInteger('hits')->default(0); + + $table->unique(['day', 'bot', 'path']); + }); + } + + public function down(): void + { + + foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) { + Schema::dropIfExists(Names::table($table)); + } + } +}; diff --git a/src/Modules/Statistics/public-routes.php b/src/Modules/Statistics/public-routes.php new file mode 100644 index 0000000..da80677 --- /dev/null +++ b/src/Modules/Statistics/public-routes.php @@ -0,0 +1,14 @@ +. +Route::get(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/').'/pulse.js', [PulseController::class, 'script'])->name(Names::route('pulse.script')); + +Route::prefix(trim((string) config('manager.statistics.pulse_path', 'pulse'), '/'))->middleware('throttle:manager-pulse')->group(function () { + Route::post('/view', [PulseController::class, 'view'])->name(Names::route('pulse.view')); + Route::post('/leave', [PulseController::class, 'leave'])->name(Names::route('pulse.leave')); +}); diff --git a/src/Modules/Statistics/routes.php b/src/Modules/Statistics/routes.php new file mode 100644 index 0000000..6086467 --- /dev/null +++ b/src/Modules/Statistics/routes.php @@ -0,0 +1,7 @@ +name('statistics.index')->middleware('can:statistics.view'); +Route::get('/statistics/export', [StatisticsController::class, 'export'])->name('statistics.export')->middleware('can:statistics.view'); diff --git a/src/Modules/Users/AccountController.php b/src/Modules/Users/AccountController.php new file mode 100644 index 0000000..9292192 --- /dev/null +++ b/src/Modules/Users/AccountController.php @@ -0,0 +1,202 @@ +user(); + $model = $this->model(); + + return response()->json([ + 'accounts' => $model::query()->with('managerGroups')->orderBy('name')->orderBy('id')->get() + ->map(fn ($user) => [ + 'id' => $user->getKey(), + 'name' => $user->name, + 'email' => $user->email, + 'is_super_admin' => $user->isManagerSuperAdmin(), + 'is_you' => $user->is($me), + 'view' => UserSetting::value($user, 'view'), + 'tutorial' => UserSetting::value($user, 'tutorial'), + 'groups' => $user->managerGroups->sortBy('name')->map(fn (Group $group) => ['id' => $group->id, 'name' => $group->name])->values(), + 'can_change' => $me->managerOutranks($user), + 'can_delete' => $me->managerOutranks($user) && ! $user->is($me), + ])->values(), + 'groups' => Group::query()->orderBy('name')->get() + ->map(fn (Group $group) => [ + 'id' => $group->id, + 'name' => $group->name, + 'description' => $group->description, + 'can_give' => $me->managerMayGive($group), + ])->values(), + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate([...$this->rules(), 'password' => ['required', 'string', 'min:12', 'max:200']]); + + // Everything is checked before anything is stored: a refused group leaves no account behind. + $details = $this->details($request, null); + $groups = $this->groups($request); + + $model = $this->model(); + $user = new $model; + $user->forceFill([...$details, 'password' => Hash::make($request->string('password')->toString())])->save(); + $user->managerGroups()->sync($groups); + $this->settings($request, $user); + + return response()->json(['id' => $user->getKey()], 201); + } + + public function update(Request $request, string $account): JsonResponse + { + $me = $request->user(); + $user = $this->find($account); + abort_unless($me->managerOutranks($user), 403); + app(AuditTrail::class)->about($user); + + $request->validate([...$this->rules(), 'password' => ['nullable', 'string', 'min:12', 'max:200']]); + $details = $this->details($request, $user); + + // Groups mean nothing for a super admin, and nobody changes their own. + $groups = $user->isManagerSuperAdmin() || $user->is($me) ? null : $this->groups($request); + + $user->forceFill($details); + + // Empty: the password stays as it is. + if ($request->filled('password')) { + $user->forceFill(['password' => Hash::make($request->string('password')->toString())]); + } + + $user->save(); + + if ($groups !== null) { + $user->managerGroups()->sync($groups); + } + + $this->settings($request, $user); + + return response()->json(['saved' => true]); + } + + public function destroy(Request $request, string $account): JsonResponse + { + $me = $request->user(); + $user = $this->find($account); + abort_unless($me->managerOutranks($user), 403); + app(AuditTrail::class)->about($user); + + if ($user->is($me)) { + return response()->json(['message' => __('You cannot delete your own account.')], 422); + } + + $user->managerGroups()->detach(); + $user->delete(); + + return response()->json(['deleted' => true]); + } + + /** + * Which face of the manager the account looks at (`full`, `simple`, or empty for what its rights give) and whether + * it gets the tour at its next load. Only what the form sent is changed. + */ + private function settings(Request $request, $user): void + { + $values = []; + + if ($request->exists('view')) { + $values['view'] = $request->input('view') ?: null; + } + + if ($request->exists('tutorial')) { + $values['tutorial'] = $request->boolean('tutorial') ? 'pending' : (UserSetting::value($user, 'tutorial') === 'pending' ? 'skipped' : UserSetting::value($user, 'tutorial')); + } + + if ($values !== []) { + UserSetting::put($user, $values); + } + } + + /** @return class-string */ + private function model(): string + { + return config('manager.user_model'); + } + + private function find(string $id) + { + return $this->model()::query()->findOrFail($id); + } + + /** @return array> */ + private function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'email', 'max:255'], + 'groups' => ['array'], + 'groups.*' => ['integer'], + 'view' => ['nullable', Rule::in([Menu::FULL, Menu::SIMPLE])], + 'tutorial' => ['nullable', 'boolean'], + ]; + } + + /** + * Name and email address, the address in lower case and not in use by another account. + * + * @return array{name: string, email: string} + */ + private function details(Request $request, $user): array + { + $email = $request->string('email')->trim()->lower()->toString(); + + if ($this->model()::query()->where('email', $email)->when($user !== null, fn ($query) => $query->whereKeyNot($user->getKey()))->exists()) { + throw ValidationException::withMessages(['email' => __('Another account already uses this email address.')]); + } + + return ['name' => $request->string('name')->trim()->toString(), 'email' => $email]; + } + + /** + * The ids of the groups that were ticked. One that does not exist, or that gives more than + * the account that is logged in has, is refused. + * + * @return list + */ + private function groups(Request $request): array + { + $me = $request->user(); + $ids = array_values(array_unique(array_map(fn (mixed $id) => is_numeric($id) ? (int) $id : 0, $request->array('groups')))); + $groups = Group::query()->whereKey($ids)->get(); + + if ($groups->count() !== count($ids) || $groups->contains(fn (Group $group) => ! $me->managerMayGive($group))) { + throw ValidationException::withMessages(['groups' => __('You can only choose groups that allow nothing more than your own account.')]); + } + + return $ids; + } +} diff --git a/src/Modules/Users/CreateManagerUser.php b/src/Modules/Users/CreateManagerUser.php new file mode 100644 index 0000000..89163eb --- /dev/null +++ b/src/Modules/Users/CreateManagerUser.php @@ -0,0 +1,78 @@ +value('name', 'Name'); + $email = strtolower($this->value('email', 'Email')); + $password = $this->value('password', 'Password (min 12 characters)', secret: true); + $model = config('manager.user_model'); + + if ($name === '' || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { + $this->error('A name and a valid email address are required.'); + + return self::FAILURE; + } + + if ($model::query()->where('email', $email)->exists()) { + $this->error("A user with email {$email} already exists."); + + return self::FAILURE; + } + + if (mb_strlen($password) < 12) { + $this->error('Password must be at least 12 characters.'); + + return self::FAILURE; + } + + // Direct assignment: a super admin is never mass-assignable. + $user = new $model; + $user->forceFill(['name' => $name, 'email' => $email, 'password' => Hash::make($password)]); + $user->is_super_admin = true; + $user->save(); + + $this->info("Super admin account for {$name} <{$email}> created."); + + return self::SUCCESS; + } + + /** The option when it was given, otherwise the answer to a question. */ + private function value(string $option, string $question, bool $secret = false): string + { + $given = $this->option($option); + + if (is_string($given) && trim($given) !== '') { + return $secret ? $given : trim($given); + } + + $answer = $secret ? $this->secret($question) : $this->ask($question); + + if (! is_string($answer)) { + return ''; + } + + return $secret ? $answer : trim($answer); + } +} diff --git a/src/Modules/Users/GroupController.php b/src/Modules/Users/GroupController.php new file mode 100644 index 0000000..004f74f --- /dev/null +++ b/src/Modules/Users/GroupController.php @@ -0,0 +1,80 @@ +json([ + 'groups' => Group::query()->withCount('users')->orderBy('name')->get() + ->map(fn (Group $group) => [ + 'id' => $group->id, + 'name' => $group->name, + 'description' => $group->description, + 'permissions' => $group->allowed(), + 'accounts' => $group->users_count, + ])->values(), + 'catalogue' => $this->modules->catalogue(), + ]); + } + + public function store(Request $request): JsonResponse + { + $group = Group::create($this->validated($request)); + + return response()->json(['id' => $group->id], 201); + } + + public function update(Request $request, string $group): JsonResponse + { + $group = Group::query()->findOrFail($group); + app(AuditTrail::class)->about($group); + $group->update($this->validated($request, $group)); + + return response()->json(['saved' => true]); + } + + /** The accounts in it stay; they lose what only this group allowed. */ + public function destroy(string $group): JsonResponse + { + $group = Group::query()->findOrFail($group); + app(AuditTrail::class)->about($group); + $group->users()->detach(); + $group->delete(); + + return response()->json(['deleted' => true]); + } + + /** @return array{name: string, description: string|null, permissions: list} */ + private function validated(Request $request, ?Group $group = null): array + { + $table = Names::table('groups'); + + $request->validate([ + 'name' => ['required', 'string', 'max:60', Rule::unique($table, 'name')->ignore($group?->id)], + 'description' => ['nullable', 'string', 'max:500'], + 'permissions' => ['array'], + 'permissions.*' => ['string', Rule::in($this->modules->permissionValues())], + ]); + + $description = $request->string('description')->trim()->toString(); + + return [ + 'name' => $request->string('name')->trim()->toString(), + 'description' => $description !== '' ? $description : null, + 'permissions' => $this->modules->complete($request->array('permissions')), + ]; + } +} diff --git a/src/Modules/Users/UsersModule.php b/src/Modules/Users/UsersModule.php new file mode 100644 index 0000000..2f62b8f --- /dev/null +++ b/src/Modules/Users/UsersModule.php @@ -0,0 +1,67 @@ + 'Accounts', 'route' => Names::route('accounts.index'), 'permission' => 'accounts.manage'], + ['label' => 'Groups', 'route' => Names::route('groups.index'), 'permission' => 'groups.manage'], + ]; + } + + public function actions(): array + { + return [ + 'accounts.store' => ['Created an account'], + 'accounts.update' => ['Changed an account'], + 'accounts.destroy' => ['Deleted an account'], + 'groups.store' => ['Created a group'], + 'groups.update' => ['Changed a group'], + 'groups.destroy' => ['Deleted a group'], + ]; + } + + public function views(): array + { + return ['accounts.index' => 'Opened the accounts', 'groups.index' => 'Opened the groups']; + } + + public function commands(): array + { + return [CreateManagerUser::class]; + } +} diff --git a/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php new file mode 100644 index 0000000..e0b7386 --- /dev/null +++ b/src/Modules/Users/migrations/2026_12_04_000001_create_manager_groups.php @@ -0,0 +1,43 @@ +getTable(); + + // New accounts are never super admins; an existing one is not promoted here. + // `manager:create-user` is the way to make a super admin. + if (! Schema::hasColumn($users, 'is_super_admin')) { + Schema::table($users, fn (Blueprint $table) => $table->boolean('is_super_admin')->default(false)); + } + + Schema::create(Names::table('groups'), function (Blueprint $table) { + $table->id(); + $table->string('name')->unique(); + $table->string('description', 500)->nullable(); + $table->json('permissions')->nullable(); + $table->timestamps(); + }); + + Schema::create(Names::table('group_user'), function (Blueprint $table) use ($users) { + $table->foreignId('group_id')->constrained(Names::table('groups'))->cascadeOnDelete(); + $table->foreignId('user_id')->constrained($users)->cascadeOnDelete(); + $table->primary(['group_id', 'user_id']); + }); + } + + public function down(): void + { + $users = (new (config('manager.user_model')))->getTable(); + + Schema::dropIfExists(Names::table('group_user')); + Schema::dropIfExists(Names::table('groups')); + Schema::table($users, fn (Blueprint $table) => $table->dropColumn('is_super_admin')); + } +}; diff --git a/src/Modules/Users/routes.php b/src/Modules/Users/routes.php new file mode 100644 index 0000000..c87db22 --- /dev/null +++ b/src/Modules/Users/routes.php @@ -0,0 +1,21 @@ +group(function () { + Route::get('/accounts', [AccountController::class, 'index'])->name('accounts.index'); + Route::post('/accounts', [AccountController::class, 'store'])->name('accounts.store'); + Route::put('/accounts/{account}', [AccountController::class, 'update'])->name('accounts.update')->whereNumber('account'); + Route::delete('/accounts/{account}', [AccountController::class, 'destroy'])->name('accounts.destroy')->whereNumber('account'); +}); + +Route::middleware('can:groups.manage')->group(function () { + Route::get('/groups', [GroupController::class, 'index'])->name('groups.index'); + Route::post('/groups', [GroupController::class, 'store'])->name('groups.store'); + Route::put('/groups/{group}', [GroupController::class, 'update'])->name('groups.update')->whereNumber('group'); + Route::delete('/groups/{group}', [GroupController::class, 'destroy'])->name('groups.destroy')->whereNumber('group'); +}); diff --git a/src/Support/AuditTrail.php b/src/Support/AuditTrail.php new file mode 100644 index 0000000..5e3cb55 --- /dev/null +++ b/src/Support/AuditTrail.php @@ -0,0 +1,112 @@ +made = null; + $this->settled = false; + } + + public function made(Model $model): void + { + if (! $this->settled && $this->made === null && ! $model instanceof AuditLog) { + $this->made = $model; + } + } + + /** + * For a controller whose request is about something it did not make (an address that was + * banned before, an account that was changed), or about no single thing (null). + */ + public function about(?Model $model): void + { + $this->made = $model; + $this->settled = true; + } + + public function firstMade(): ?Model + { + return $this->made; + } + + /** + * @param array $details + */ + public function record( + string $event, + string $summary, + ?Authenticatable $user = null, + ?Model $subject = null, + array $details = [], + ?string $action = null, + ?string $email = null, + ): AuditLog { + // A command has no visitor: no address and no browser. + $request = app()->runningInConsole() && ! app()->runningUnitTests() ? null : request(); + $about = $subject === null ? null : self::describe($subject); + $agent = $request?->userAgent(); + $name = $user === null ? null : data_get($user, 'name'); + + return AuditLog::query()->create([ + 'event' => $event, + 'action' => $action, + 'summary' => Str::limit($summary, 250, '…'), + 'subject_type' => $about['type'] ?? null, + 'subject_id' => $about['id'] ?? null, + 'subject_label' => $about['label'] ?? null, + 'details' => $details === [] ? null : $details, + 'user_id' => $user?->getAuthIdentifier(), + 'user_name' => is_string($name) ? $name : null, + 'email' => $email === null ? null : Str::limit($email, 250, '…'), + 'ip' => $request?->ip(), + 'user_agent' => is_string($agent) ? Str::limit($agent, 490, '…') : null, + 'created_at' => now(), + ]); + } + + /** + * What a model is called in the log: its kind ('post', 'ip_ban'), its id and a name. + * + * @return array{type: string, id: int|null, label: string} + */ + public static function describe(Model $model): array + { + $id = $model->getKey(); + $id = is_int($id) ? $id : null; + $label = '#'.($id ?? '?'); + + foreach (['title', 'name', 'label', 'ip', 'slug'] as $attribute) { + $value = $model->getAttribute($attribute); + + if (is_string($value) && trim($value) !== '') { + $label = Str::limit(trim($value), 200, '…'); + break; + } + } + + return ['type' => Str::snake(class_basename($model)), 'id' => $id, 'label' => $label]; + } +} diff --git a/src/Support/Fields.php b/src/Support/Fields.php new file mode 100644 index 0000000..d63e6c9 --- /dev/null +++ b/src/Support/Fields.php @@ -0,0 +1,152 @@ + ['label' => 'Title on the photo', 'type' => 'text', 'help' => 'One line.', 'max' => 120] + * + * Types: `text` (one line), `textarea` (paragraphs), `markdown` (a long text in Markdown), `lines` (one item + * per line), `media` (a picture from the media library; the value is its address), `url`, `number`, `date`, + * `toggle` (a switch) and `select` (needs `options`: a list of values, or value => label). `required`, `default` and + * `rules` (extra Laravel rules) are optional on every type. `help` is a line of explanation under the field; `advanced` + * hides the field in the simple face of the manager (it keeps its value). + */ +final class Fields +{ + public const TYPES = ['text', 'textarea', 'markdown', 'lines', 'media', 'url', 'number', 'date', 'toggle', 'select']; + + private const LENGTHS = ['text' => 255, 'textarea' => 20000, 'markdown' => 100000, 'lines' => 10000, 'media' => 2048, 'url' => 2048, 'date' => 40, 'select' => 255]; + + /** + * The definitions in one shape, with a key, a label and a known type; what is wrong is dropped. + * + * @param array $fields key => definition + * @return array, max: ?int, rules: list}> + */ + public static function normalize(array $fields): array + { + $out = []; + + foreach ($fields as $key => $field) { + if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,59}$/', $key) || ! is_array($field)) { + continue; + } + + $type = in_array($field['type'] ?? 'text', self::TYPES, true) ? ($field['type'] ?? 'text') : 'text'; + $options = []; + + $given = (array) ($field['options'] ?? []); + + foreach ($given as $value => $label) { + $options[(string) (array_is_list($given) ? $label : $value)] = (string) $label; + } + + if ($type === 'select' && $options === []) { + continue; + } + + $out[$key] = [ + 'key' => $key, + 'label' => (string) ($field['label'] ?? ucfirst(str_replace('_', ' ', $key))), + 'type' => $type, + 'help' => isset($field['help']) ? (string) $field['help'] : null, + 'advanced' => (bool) ($field['advanced'] ?? false), + 'required' => (bool) ($field['required'] ?? false), + 'default' => $field['default'] ?? self::empty($type), + 'options' => $options, + 'max' => isset($field['max']) ? max(1, (int) $field['max']) : null, + 'rules' => array_values((array) ($field['rules'] ?? [])), + ]; + } + + return $out; + } + + /** + * The Laravel rules for the values, keyed ``. + * + * @param array> $fields normalized + * @return array> + */ + public static function rules(array $fields, string $prefix = ''): array + { + $rules = []; + + foreach ($fields as $key => $field) { + $type = $field['type']; + $max = $field['max'] ?? self::LENGTHS[$type] ?? null; + $presence = $field['required'] ? 'required' : 'nullable'; + + $rules[$prefix.$key] = [$presence, ...match ($type) { + 'toggle' => ['boolean'], + 'number' => ['numeric'], + 'date' => ['date'], + 'select' => ['string', Rule::in(array_keys($field['options']))], + 'media', 'url' => ['string', 'max:'.$max, 'regex:'.self::ADDRESS], + default => ['string', 'max:'.$max], + }, ...$field['rules']]; + } + + return $rules; + } + + /** A web address or a path of the site. Never `javascript:` and its kin. */ + public const ADDRESS = '#^(/(?!/)|https?://)[^\s<>"\']*$#i'; + + /** + * What is stored: only the known keys, in the type of the field, the default where nothing is given. + * + * @param array> $fields normalized + * @param array $input + * @return array + */ + public static function clean(array $fields, array $input): array + { + $out = []; + + foreach ($fields as $key => $field) { + $value = array_key_exists($key, $input) ? $input[$key] : $field['default']; + + $out[$key] = match ($field['type']) { + 'toggle' => filter_var($value, FILTER_VALIDATE_BOOLEAN), + 'number' => $value === null || $value === '' ? null : $value + 0, + default => $value === null ? '' : (is_scalar($value) ? trim((string) $value) : ''), + }; + } + + return $out; + } + + /** + * The stored values over the defaults, for the screens and for the public site. + * + * @param array> $fields normalized + * @param array $stored + * @return array + */ + public static function values(array $fields, array $stored): array + { + $out = []; + + foreach ($fields as $key => $field) { + $out[$key] = array_key_exists($key, $stored) ? $stored[$key] : $field['default']; + } + + return $out; + } + + private static function empty(string $type): mixed + { + return match ($type) { + 'toggle' => false, + 'number' => null, + default => '', + }; + } +} diff --git a/src/Support/Importer.php b/src/Support/Importer.php new file mode 100644 index 0000000..8b0b6d9 --- /dev/null +++ b/src/Support/Importer.php @@ -0,0 +1,125 @@ +, columns: list, required: list, key: list}> + */ + public const TARGETS = [ + 'posts' => [ + 'model' => Post::class, + 'columns' => ['title', 'slug', 'excerpt', 'body', 'cover_image', 'category', 'tags', 'is_featured', 'published_at'], + 'required' => ['title', 'body'], + 'key' => ['slug'], + ], + 'pages' => [ + 'model' => Page::class, + 'columns' => ['slug', 'title', 'body', 'is_published'], + 'required' => ['slug', 'title'], + 'key' => ['slug'], + ], + 'reviews' => [ + 'model' => Review::class, + 'columns' => ['author', 'place', 'rating', 'body', 'is_visible'], + 'required' => ['author', 'body'], + 'key' => ['author', 'body'], + ], + ]; + + /** + * @param array $map package column => column of the source table; same name when left out + * @return array{created: int, updated: int, skipped: int, problems: list} + */ + public function run(string $target, ConnectionInterface $source, string $table, array $map = [], bool $dry = false, ?int $limit = null): array + { + $spec = self::TARGETS[$target] ?? throw new InvalidArgumentException("Unknown target {$target}; use one of: ".implode(', ', array_keys(self::TARGETS))); + + foreach (array_keys($map) as $column) { + if (! in_array($column, $spec['columns'], true)) { + throw new InvalidArgumentException("{$target} has no column {$column}; known: ".implode(', ', $spec['columns'])); + } + } + + $result = ['created' => 0, 'updated' => 0, 'skipped' => 0, 'problems' => []]; + $query = $source->table($table); + $limit !== null && $query->limit($limit); + + foreach ($query->get() as $number => $row) { + $row = (array) $row; + $values = []; + + foreach ($spec['columns'] as $column) { + $from = $map[$column] ?? $column; + + if (array_key_exists($from, $row)) { + $values[$column] = $this->convert($column, $row[$from]); + } + } + + if ($target === 'posts' || $target === 'pages') { + $values['slug'] = ($values['slug'] ?? '') !== '' ? Str::slug((string) $values['slug']) : Str::slug((string) ($values['title'] ?? '')); + } + + foreach ($spec['required'] as $column) { + if (! isset($values[$column]) || $values[$column] === '') { + $result['skipped']++; + $result['problems'][] = 'row '.($number + 1).": no value for {$column}"; + + continue 2; + } + } + + $key = Arr::only($values, $spec['key']); + $model = $spec['model']; + $existing = $model::query()->where($key)->first(); + $existing ? $result['updated']++ : $result['created']++; + + if (! $dry) { + $existing ? $existing->update($values) : $model::query()->create($values); + } + } + + return $result; + } + + private function convert(string $column, mixed $value): mixed + { + return match ($column) { + 'tags' => $this->tags($value), + 'is_featured', 'is_published', 'is_visible' => filter_var($value, FILTER_VALIDATE_BOOLEAN), + 'rating' => $value === null || $value === '' ? null : max(1, min(5, (int) $value)), + 'published_at' => $value === null || $value === '' ? null : $value, + default => is_string($value) ? trim($value) : $value, + }; + } + + /** @return list */ + private function tags(mixed $value): array + { + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : array_map('trim', explode(',', $value)); + } + + return array_values(array_filter(array_map(fn ($tag) => is_string($tag) ? trim($tag) : '', (array) $value), fn ($tag) => $tag !== '')); + } +} diff --git a/src/Support/Login/BaseLoginCheck.php b/src/Support/Login/BaseLoginCheck.php new file mode 100644 index 0000000..f4130d2 --- /dev/null +++ b/src/Support/Login/BaseLoginCheck.php @@ -0,0 +1,20 @@ + 'turnstile', 'type' => 'turnstile', 'site_key' => (string) config('manager.login.turnstile.site_key')]]; + } + + public function before(Request $request): void + { + $token = $request->string('turnstile')->limit(2048, '')->toString(); + + if ($token === '' || ! $this->valid($token, (string) $request->ip())) { + throw ValidationException::withMessages(['turnstile' => __('Prove you are not a program, then log in again.')]); + } + } + + private function valid(string $token, string $ip): bool + { + try { + $answer = Http::asForm()->timeout(5)->post(self::VERIFY, ['secret' => config('manager.login.turnstile.secret'), 'response' => $token, 'remoteip' => $ip]); + + return $answer->ok() && $answer->json('success') === true; + } catch (Throwable) { + return false; + } + } +} diff --git a/src/Support/LoginChecks.php b/src/Support/LoginChecks.php new file mode 100644 index 0000000..1f1f0fe --- /dev/null +++ b/src/Support/LoginChecks.php @@ -0,0 +1,47 @@ + */ + public function all(): array + { + $classes = array_values(array_unique([...(array) config('manager.login.checks', []), ...(Turnstile::configured() ? [Turnstile::class] : [])])); + $checks = []; + + foreach ($classes as $class) { + if (is_string($class) && is_subclass_of($class, LoginCheck::class)) { + $checks[] = app($class); + } + } + + return $checks; + } + + /** @return list> */ + public function fields(): array + { + return array_merge(...array_map(fn (LoginCheck $check) => $check->fields(), $this->all()) ?: [[]]); + } + + public function before(Request $request): void + { + foreach ($this->all() as $check) { + $check->before($request); + } + } + + public function after(Request $request, Authenticatable $user): void + { + foreach ($this->all() as $check) { + $check->after($request, $user); + } + } +} diff --git a/src/Support/Markdown.php b/src/Support/Markdown.php new file mode 100644 index 0000000..83373e4 --- /dev/null +++ b/src/Support/Markdown.php @@ -0,0 +1,37 @@ + 'escape', + 'allow_unsafe_links' => false, + 'external_link' => [ + 'internal_hosts' => array_values(array_filter([$host, ...(array) config('manager.markdown.internal_hosts', [])])), + 'open_in_new_window' => true, + 'noopener' => 'external', + 'noreferrer' => 'external', + ], + ], [new ExternalLinkExtension]); + } + + public static function toPlainText(string $markdown): string + { + $text = strip_tags(self::toHtml($markdown)); + + return trim((string) preg_replace('/\s+/', ' ', html_entity_decode($text, ENT_QUOTES | ENT_HTML5))); + } +} diff --git a/src/Support/MediaUsage.php b/src/Support/MediaUsage.php new file mode 100644 index 0000000..cef3f56 --- /dev/null +++ b/src/Support/MediaUsage.php @@ -0,0 +1,36 @@ +> */ + private array $sources = []; + + /** @param Closure(): iterable $source */ + public function register(Closure $source): void + { + $this->sources[] = $source; + } + + /** @return list */ + public function haystacks(): array + { + $texts = []; + + foreach ($this->sources as $source) { + foreach ($source() as $text) { + $texts[] = is_string($text) ? $text : ''; + } + } + + return $texts; + } +} diff --git a/src/Support/Menu.php b/src/Support/Menu.php new file mode 100644 index 0000000..65db2bb --- /dev/null +++ b/src/Support/Menu.php @@ -0,0 +1,83 @@ +hasFull($user) ? self::FULL : self::SIMPLE; + } + + public function maySwitch(?object $user): bool + { + return $user !== null && config('manager.simple_view') && ($this->hasFull($user) || Gate::forUser($user)->allows('manager.switch')); + } + + /** + * @param list $allowed the permissions this account has + * @return list + */ + public function for(?object $user, array $allowed): array + { + if ($user === null) { + return []; + } + + $simple = $this->view($user) === self::SIMPLE; + $items = []; + + foreach ($this->modules->navigation() as $item) { + if (($item['permission'] ?? null) !== null && ! in_array($item['permission'], $allowed, true)) { + continue; + } + + if ($simple && ! $item['simple']) { + continue; + } + + $items[] = array_filter([ + 'label' => $item['label'], + 'href' => isset($item['route']) ? route($item['route'], $item['params'] ?? [], false) : (string) $item['url'], + 'section' => $item['section'] ?? null, + 'hint' => $item['hint'] ?? null, + 'icon' => $item['icon'] ?? null, + 'new_tab' => ($item['new_tab'] ?? false) ?: null, + ], fn ($value) => $value !== null); + } + + return $items; + } + + private function hasFull(object $user): bool + { + return (method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin()) || Gate::forUser($user)->allows('manager.full'); + } +} diff --git a/src/Support/ModuleRegistry.php b/src/Support/ModuleRegistry.php new file mode 100644 index 0000000..d77d20a --- /dev/null +++ b/src/Support/ModuleRegistry.php @@ -0,0 +1,254 @@ + */ + private array $all = []; + + /** + * @param list> $available + * @param array $switches + */ + public function __construct(array $available, private readonly array $switches) + { + foreach ($available as $class) { + $module = new $class; + $this->all[$module->key()] = $module; + } + } + + /** @return array every known module */ + public function all(): array + { + return $this->all; + } + + public function has(string $key): bool + { + return isset($this->all[$key]); + } + + public function enabled(string $key): bool + { + if (! $this->has($key)) { + return false; + } + + return (bool) ($this->switches[$key] ?? $this->all[$key]->enabledByDefault()); + } + + /** @return array the modules that are on */ + public function active(): array + { + return array_filter($this->all, fn (Module $module) => $this->enabled($module->key())); + } + + /** + * A module that is on while one it needs is off is a configuration mistake: fail loudly at boot. + */ + public function validate(): void + { + foreach ($this->active() as $module) { + foreach ($module->requires() as $needed) { + if (! $this->enabled($needed)) { + throw new ModuleException("Manager module '{$module->key()}' needs module '{$needed}', which is off."); + } + } + } + } + + /** @return array permission value => permission, of the active modules only */ + public function permissions(): array + { + $permissions = []; + + foreach ($this->active() as $module) { + foreach ($module->permissions() as $permission) { + $permissions[$permission->value] = $permission; + } + } + + if (config('manager.simple_view')) { + $permissions['manager.full'] = new Permission('manager.full', 'See the whole manager, not only the simple screens', 'Manager'); + $permissions['manager.switch'] = new Permission('manager.switch', 'Switch between the simple and the whole manager', 'Manager'); + } + + return $permissions; + } + + /** @return list */ + public function permissionValues(): array + { + return array_keys($this->permissions()); + } + + /** + * The given values without what is no permission (any more), completed with what they + * need, in the order of the permissions. + * + * @param array $values + * @return list + */ + public function complete(array $values): array + { + $known = $this->permissions(); + $wanted = []; + + foreach ($values as $value) { + if (is_string($value) && isset($known[$value])) { + $wanted[$value] = true; + + foreach ($known[$value]->needs as $needed) { + $wanted[$needed] = true; + } + } + } + + return array_values(array_filter(array_keys($known), fn (string $value) => isset($wanted[$value]))); + } + + /** + * The list for the group form, per section. + * + * @return list}>}> + */ + public function catalogue(): array + { + $sections = []; + + foreach ($this->permissions() as $permission) { + $sections[__($permission->section)][] = ['value' => $permission->value, 'label' => __($permission->label), 'needs' => $permission->needs]; + } + + $catalogue = []; + foreach ($sections as $section => $permissions) { + $catalogue[] = ['section' => $section, 'permissions' => $permissions]; + } + + return $catalogue; + } + + /** + * The menu: what the modules give, changed by config `manager.menu`, in order. An item has `label`, + * `route` (or `url` for a link of the site's own) and `permission`, and may add `section` (a heading), + * `icon`, `order` (lower comes first; default 100), `simple` (shown in the simple view) and `new_tab`. + * + * @return list + */ + public function navigation(): array + { + $changes = (array) config('manager.menu.items', []); + $items = []; + + foreach ($this->active() as $module) { + foreach ($module->navigation() as $item) { + $short = $item['id'] ?? (isset($item['route']) ? Str::after($item['route'], Names::routePrefix()) : ''); + $item = [...$item, ...(array) ($changes[$short] ?? [])]; + + if (($item['hidden'] ?? false) === true) { + continue; + } + + $items[] = $item; + } + } + + foreach ((array) config('manager.menu.links', []) as $link) { + if (is_array($link) && isset($link['label'], $link['url'])) { + $items[] = $link + ['permission' => null]; + } + } + + $items = array_map(fn (array $item) => [ + ...$item, + 'label' => __($item['label']), + ...(isset($item['section']) ? ['section' => __($item['section'])] : []), + ...(isset($item['hint']) && $item['hint'] !== null ? ['hint' => __($item['hint'])] : []), + 'order' => (int) ($item['order'] ?? 100), + 'simple' => (bool) ($item['simple'] ?? false), + ], $items); + + // PHP's sort is stable: items with the same order keep the order of the modules. + usort($items, fn (array $a, array $b) => $a['order'] <=> $b['order']); + + return array_values($items); + } + + /** + * The steps the modules add to the tour, for an account with these permissions. + * + * @param list $allowed + * @return list + */ + public function tutorial(array $allowed): array + { + $steps = []; + + foreach ($this->active() as $module) { + foreach (method_exists($module, 'tutorial') ? $module->tutorial() : [] as $step) { + if (! isset($step['title'], $step['text']) || (isset($step['permission']) && ! in_array($step['permission'], $allowed, true))) { + continue; + } + + $steps[] = [ + 'title' => __($step['title']), + 'text' => __($step['text']), + 'image' => isset($step['image']) && in_array($step['image'], MascotController::NAMES, true) ? $step['image'] : null, + 'href' => isset($step['menu']) ? route(Names::route($step['menu']), [], false) : null, + ]; + } + } + + return $steps; + } + + /** + * Audit-log names of what is done: the modules' own plus the core's. + * + * @return array}> + */ + public function actions(): array + { + $actions = ['profile.update' => ['Changed own account'], 'profile.view' => ['Switched between the simple and the whole manager'], 'profile.tutorial' => ['Finished or skipped the tour']]; + + foreach ($this->active() as $module) { + $actions = [...$actions, ...$module->actions()]; + } + + return $actions; + } + + /** @return array */ + public function views(): array + { + $views = ['dashboard' => 'Opened the dashboard', 'profile.show' => 'Opened own account']; + + foreach ($this->active() as $module) { + $views = [...$views, ...$module->views()]; + } + + return $views; + } + + /** @return list middleware of the active modules for `before` or `after` the site's own */ + public function middleware(string $position): array + { + $middleware = []; + + foreach ($this->active() as $module) { + array_push($middleware, ...($module->middleware()[$position] ?? [])); + } + + return $middleware; + } +} diff --git a/src/Support/Names.php b/src/Support/Names.php new file mode 100644 index 0000000..42f4384 --- /dev/null +++ b/src/Support/Names.php @@ -0,0 +1,33 @@ +.`, also the name of the gate + * @param string $label what the group form says next to the tick box + * @param string $section the heading it is listed under + * @param list $needs values this one is useless without; a group that gets this gets those too + */ + public function __construct( + public string $value, + public string $label, + public string $section, + public array $needs = [], + ) {} +} diff --git a/src/Support/Permissions/RoleMap.php b/src/Support/Permissions/RoleMap.php new file mode 100644 index 0000000..6034bd1 --- /dev/null +++ b/src/Support/Permissions/RoleMap.php @@ -0,0 +1,33 @@ + ['posts.view', 'posts.write'], 'owner' => ['*']]` (`*` is everything). The attribute is + * `manager.permissions.role_attribute`. + */ +final class RoleMap implements PermissionResolver +{ + public function permissions(Authenticatable $user): array + { + $roles = $user->{(string) config('manager.permissions.role_attribute', 'role')} ?? []; + $roles = $roles instanceof Collection ? $roles->all() : (array) $roles; + $map = (array) config('manager.permissions.roles', []); + $out = []; + + foreach ($roles as $role) { + $name = is_object($role) ? (string) ($role->name ?? '') : (string) (is_scalar($role) ? $role : ''); + + foreach ((array) ($map[$name] ?? []) as $permission) { + $out[] = (string) $permission; + } + } + + return array_values(array_unique($out)); + } +} diff --git a/src/Support/Permissions/Sources.php b/src/Support/Permissions/Sources.php new file mode 100644 index 0000000..638f43c --- /dev/null +++ b/src/Support/Permissions/Sources.php @@ -0,0 +1,45 @@ + what the roles of the site allow (empty in `groups` mode) */ + public static function fromHost(Authenticatable $user): array + { + if (self::mode() === 'groups') { + return []; + } + + $class = config('manager.permissions.resolver'); + $resolver = is_string($class) && is_subclass_of($class, PermissionResolver::class) ? app($class) : (config('manager.permissions.roles') ? new RoleMap : null); + + if ($resolver === null) { + return []; + } + + $known = app(ModuleRegistry::class)->permissionValues(); + $given = $resolver->permissions($user); + + return in_array('*', $given, true) ? $known : array_values(array_filter($given, fn ($value) => is_string($value) && in_array($value, $known, true))); + } + + private static function mode(): string + { + return in_array(config('manager.permissions.mode'), ['groups', 'host', 'merge'], true) ? config('manager.permissions.mode') : 'groups'; + } +} diff --git a/src/Support/Resources.php b/src/Support/Resources.php new file mode 100644 index 0000000..683e7d8 --- /dev/null +++ b/src/Support/Resources.php @@ -0,0 +1,123 @@ + ['label' => 'Services', 'singular' => 'Service', 'model' => App\Models\Service::class, + * 'columns' => ['name', 'price'], 'order' => ['position', 'asc'], 'fields' => [...]] + */ +final class Resources +{ + /** Names the permissions of modules that exist already would clash with. */ + private const RESERVED = ['posts', 'pages', 'media', 'accounts', 'groups', 'audit', 'statistics', 'reviews', 'labels', 'profile', 'manager', 'records']; + + /** + * @return array>, columns: list, order: array{0: string, 1: string}, per_page: int}> + */ + public static function all(): array + { + $out = []; + + foreach ((array) config('manager.resources', []) as $key => $definition) { + if (! is_string($key) || ! preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) || in_array($key, self::RESERVED, true) || ! is_array($definition)) { + continue; + } + + $fields = Fields::normalize((array) ($definition['fields'] ?? [])); + $model = $definition['model'] ?? null; + $columns = array_values(array_filter((array) ($definition['columns'] ?? array_slice(array_keys($fields), 0, 3)), fn ($column) => isset($fields[$column]))); + $order = (array) ($definition['order'] ?? []); + + $out[$key] = [ + 'key' => $key, + 'label' => (string) ($definition['label'] ?? ucfirst(str_replace('_', ' ', $key))), + 'hint' => isset($definition['hint']) ? (string) $definition['hint'] : null, + 'singular' => (string) ($definition['singular'] ?? $definition['label'] ?? $key), + 'model' => is_string($model) && is_subclass_of($model, Eloquent::class) ? $model : null, + 'fields' => $fields, + 'columns' => $columns, + 'order' => [preg_match('/^[a-z_][a-z0-9_]*$/', (string) ($order[0] ?? '')) ? (string) $order[0] : 'id', ($order[1] ?? 'desc') === 'asc' ? 'asc' : 'desc'], + 'per_page' => max(5, min(200, (int) ($definition['per_page'] ?? 50))), + ]; + } + + return $out; + } + + /** @return ?array */ + public static function find(string $key): ?array + { + return self::all()[$key] ?? null; + } + + /** + * @param array $resource + * @return Builder + */ + public static function query(array $resource): Builder + { + [$column, $direction] = $resource['order']; + + if ($resource['model'] !== null) { + return $resource['model']::query()->orderBy($column, $direction)->orderBy('id', 'desc'); + } + + // The package's own table keeps the values in one JSON column. + $query = Record::query()->where('resource', $resource['key']); + + return $column !== 'id' && isset($resource['fields'][$column]) ? $query->orderBy('data->'.$column, $direction) : $query->orderBy('id', $column === 'id' ? $direction : 'desc'); + } + + /** + * @param array $resource + * @return array + */ + public static function row(array $resource, Eloquent $model): array + { + $stored = $resource['model'] === null ? (array) $model->getAttribute('data') : null; + $values = []; + + foreach ($resource['fields'] as $key => $field) { + $values[$key] = $stored !== null ? ($stored[$key] ?? $field['default']) : ($model->getAttribute($key) ?? $field['default']); + } + + return ['id' => $model->getKey(), 'values' => $values]; + } + + /** + * @param array $resource + * @param array $values cleaned by `Fields::clean` + */ + public static function save(array $resource, ?Eloquent $model, array $values): Eloquent + { + if ($resource['model'] === null) { + $model ??= new Record(['resource' => $resource['key']]); + $model->data = $values; + } else { + $model ??= new $resource['model']; + // Only the keys the site defined: the definition is the whitelist. + $model->forceFill($values); + } + + $model->save(); + + return $model; + } + + /** + * @param array $resource + */ + public static function record(array $resource, int|string $id): ?Eloquent + { + return self::query($resource)->reorder()->whereKey($id)->first(); + } +} diff --git a/src/Support/Revisions.php b/src/Support/Revisions.php new file mode 100644 index 0000000..5f78d8f --- /dev/null +++ b/src/Support/Revisions.php @@ -0,0 +1,118 @@ + ['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']] + */ +final class Revisions +{ + /** How many states are kept per record unless config `manager.revisions.keep` says otherwise. */ + private const KEEP = 50; + + /** + * What has a history: key => model, the permissions to see and to put back, the attributes that are not part of it (for a + * post that is whether it is on the site: going back in time must not publish or hide anything). + * + * @return array, view: string, restore: string, except: list}> + */ + public static function types(): array + { + $types = [ + 'posts' => ['model' => Post::class, 'view' => 'posts.view', 'restore' => 'posts.write', 'except' => ['published_at']], + 'pages' => ['model' => Page::class, 'view' => 'pages.edit', 'restore' => 'pages.edit', 'except' => ['is_published']], + ]; + + foreach ((array) config('manager.revisions.types', []) as $key => $type) { + if (is_string($key) && preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) && is_array($type) && is_subclass_of($type['model'] ?? '', Eloquent::class)) { + $types[$key] = ['model' => $type['model'], 'view' => (string) ($type['view'] ?? $key.'.view'), 'restore' => (string) ($type['restore'] ?? $key.'.manage'), 'except' => array_values((array) ($type['except'] ?? []))]; + } + } + + return array_filter($types, fn (array $type) => ! in_array($type['model'], (array) config('manager.revisions.skip', []), true)); + } + + /** Starts keeping the history of every type: a save of a record writes its state, a delete removes its history. */ + public static function listen(): void + { + foreach (self::types() as $key => $type) { + $type['model']::saved(fn (Eloquent $model) => self::record($key, $model)); + $type['model']::deleted(fn (Eloquent $model) => Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->delete()); + } + } + + public static function record(string $key, Eloquent $model): ?Revision + { + $type = self::types()[$key] ?? null; + + if ($type === null || ! $model->getKey()) { + return null; + } + + $data = self::snapshot($model, $type['except']); + $latest = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->first(); + + if ($latest !== null && $latest->data == $data) { + return null; + } + + $user = auth()->user(); + $revision = Revision::query()->create([ + 'type' => $key, + 'subject_id' => $model->getKey(), + 'user_id' => $user?->getAuthIdentifier(), + 'user_name' => $user === null ? null : mb_substr((string) ($user->name ?? ''), 0, 255), + 'data' => $data, + 'changed' => $latest === null ? array_keys($data) : self::changed((array) $latest->data, $data), + 'created_at' => now(), + ]); + + // Keep the newest ones only. + $old = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->skip(max(5, (int) config('manager.revisions.keep', self::KEEP)))->take(1000)->pluck('id'); + $old->isNotEmpty() && Revision::query()->whereKey($old)->delete(); + + return $revision; + } + + /** + * Puts a state back. It is a save like any other, so the history shows it and the state before it is not lost. + * + * @param array{except: list} $type + */ + public static function restore(Eloquent $model, Revision $revision, array $type): Eloquent + { + $keep = array_flip([...$type['except'], $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); + $model->forceFill(array_diff_key((array) $revision->data, $keep))->save(); + + return $model; + } + + /** + * @param list $except + * @return array + */ + private static function snapshot(Eloquent $model, array $except): array + { + $skip = array_flip([...$except, $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); + + return array_diff_key($model->attributesToArray(), $skip); + } + + /** + * @param array $before + * @param array $after + * @return list + */ + private static function changed(array $before, array $after): array + { + return array_values(array_filter(array_keys($after + $before), fn ($key) => ($before[$key] ?? null) != ($after[$key] ?? null))); + } +} diff --git a/src/Support/Shell.php b/src/Support/Shell.php new file mode 100644 index 0000000..fea08e7 --- /dev/null +++ b/src/Support/Shell.php @@ -0,0 +1,68 @@ +, css: string, scripts: string, styles: string} */ + public function data(Request $request): array + { + $user = $request->user(); + $key = $this->themes->keyFor($user); + $theme = $this->themes->all()[$key]; + $dist = __DIR__.'/../../resources/dist'; + + $allowed = $user === null ? [] : array_values(array_filter( + [...$this->modules->permissionValues(), ManagerServiceProvider::MANAGE_GROUPS], + fn (string $permission) => Gate::forUser($user)->allows($permission), + )); + + $navigation = $this->menu->for($user, $allowed); + + $extensions = array_values(array_filter( + (array) config('manager.extensions', []), + fn ($url) => is_string($url) && preg_match('#^(/(?!/)|https://)[^\s<>"\'\\\\]*$#', $url) === 1, + )); + + return [ + 'extensions' => $extensions, + 'css' => $this->themes->css($theme), + 'title' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'), + 'version' => is_file($dist.'/manager.js') ? substr(md5_file($dist.'/manager.js').md5_file($dist.'/manager.css'), 0, 10) : 'dev', + 'boot' => [ + 'base' => '/'.trim((string) config('manager.path'), '/'), + 'name' => $theme['name'] ?? config('manager.name') ?? config('app.name', 'Manager'), + 'logo' => $theme['logo'], + 'locale' => app()->getLocale(), + 'user' => $user === null ? null : [ + 'name' => (string) ($user->name ?? ''), + 'email' => (string) ($user->email ?? ''), + 'is_super_admin' => method_exists($user, 'isManagerSuperAdmin') && $user->isManagerSuperAdmin(), + ], + 'permissions' => $allowed, + 'navigation' => $navigation, + 'extensions' => $user === null ? [] : $extensions, + 'view' => $this->menu->view($user), + 'can_switch' => $this->menu->maySwitch($user), + 'simple_view' => (bool) config('manager.simple_view'), + 'tutorial' => UserSetting::value($user, 'tutorial') === 'pending', + 'tutorial_state' => UserSetting::value($user, 'tutorial'), + 'tutorial_steps' => $user === null ? [] : $this->modules->tutorial($allowed), + 'mascot' => '/'.trim((string) config('manager.path'), '/').'/_assets/mascot/', + 'locales' => UserSetting::LOCALES, + 'theme' => $key, + 'can_login' => Route::has(Names::route('login')), + 'login_fields' => $user === null ? $this->loginChecks->fields() : [], + ], + ]; + } +} diff --git a/src/Support/Themes.php b/src/Support/Themes.php new file mode 100644 index 0000000..fd665b1 --- /dev/null +++ b/src/Support/Themes.php @@ -0,0 +1,128 @@ + ['label' => 'Dark', 'scheme' => 'dark', 'colors' => [ + 'ink' => '#0a0a12', 'panel' => '#12121d', 'panel2' => '#191927', 'line' => '#26263a', + 'muted' => '#a3a3b8', 'text' => '#f4f4f8', 'brand' => '#f43676', 'brand_alt' => '#ff6b9d', + ]], + 'light' => ['label' => 'Light', 'scheme' => 'light', 'colors' => [ + 'ink' => '#f4f6f8', 'panel' => '#ffffff', 'panel2' => '#eceff3', 'line' => '#d9dee5', + 'muted' => '#5d6a73', 'text' => '#192c27', 'brand' => '#009ba3', 'brand_alt' => '#007c83', + ]], + ]; + + /** @return array> */ + public function all(): array + { + $themes = self::BUILT_IN; + + foreach ((array) config('manager.themes', []) as $key => $theme) { + $themes[(string) $key] = $theme; + } + + $path = config('manager.themes_path') ?: (function_exists('resource_path') ? resource_path('manager-themes') : null); + + foreach ($path && is_dir($path) ? glob($path.'/*.json') : [] as $file) { + $theme = json_decode((string) file_get_contents($file), true); + + if (is_array($theme)) { + $themes[basename($file, '.json')] = $theme; + } + } + + $clean = []; + + foreach ($themes as $key => $theme) { + if (preg_match('/^[a-z0-9][a-z0-9-]{0,40}$/', (string) $key) && ($safe = $this->sanitize($key, $theme))) { + $clean[$key] = $safe; + } + } + + return $clean; + } + + /** The key of the theme this account sees: its own choice when allowed, else the site's. */ + public function keyFor(?object $user): string + { + $all = $this->all(); + $default = array_key_exists(config('manager.theme'), $all) ? config('manager.theme') : 'dark'; + + if ($user !== null && config('manager.user_themes') && $user->getKey() !== null) { + $chosen = UserSetting::query()->where('user_id', $user->getKey())->value('theme'); + + if ($chosen !== null && isset($all[$chosen])) { + return $chosen; + } + } + + return $default; + } + + /** @return array|null */ + public function sanitize(string $key, mixed $theme): ?array + { + if (! is_array($theme)) { + return null; + } + + $base = self::BUILT_IN[($theme['scheme'] ?? 'dark') === 'light' ? 'light' : 'dark']; + $colors = $base['colors']; + + foreach (self::COLORS as $name) { + $value = $theme['colors'][$name] ?? null; + + if (is_string($value) && preg_match('/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $value)) { + $colors[$name] = $value; + } + } + + $radius = $theme['radius'] ?? '0.5rem'; + $font = $theme['font'] ?? null; + $display = $theme['font_display'] ?? null; + $logo = $theme['logo'] ?? null; + $name = $theme['name'] ?? null; + $label = $theme['label'] ?? ucfirst(str_replace('-', ' ', $key)); + + return [ + 'label' => is_string($label) ? mb_substr(strip_tags($label), 0, 60) : $key, + 'scheme' => $base['scheme'], + 'colors' => $colors, + 'radius' => is_string($radius) && preg_match('/^\d{1,2}(\.\d{1,2})?(px|rem)$/', $radius) ? $radius : '0.5rem', + 'font' => is_string($font) && preg_match('/^[\w ,\'"-]{1,120}$/', $font) ? $font : null, + 'font_display' => is_string($display) && preg_match('/^[\w ,\'"-]{1,120}$/', $display) ? $display : null, + 'logo' => is_string($logo) && preg_match('#^(/|https://)[\w\-./%~]{1,300}$#', $logo) ? $logo : null, + 'name' => is_string($name) ? mb_substr(strip_tags($name), 0, 80) : null, + ]; + } + + /** The CSS variables of one theme, ready for a style block (values are already checked). */ + public function css(array $theme): string + { + $vars = []; + + foreach ($theme['colors'] as $name => $value) { + $vars[] = '--m-'.str_replace('_', '-', $name).':'.$value; + } + + $vars[] = '--m-radius:'.$theme['radius']; + $theme['font'] && $vars[] = '--m-font:'.$theme['font']; + $theme['font_display'] && $vars[] = '--m-font-display:'.$theme['font_display']; + $vars[] = 'color-scheme:'.$theme['scheme']; + + return ':root{'.implode(';', $vars).'}'; + } +} diff --git a/src/Support/UserAgent.php b/src/Support/UserAgent.php new file mode 100644 index 0000000..eb7751b --- /dev/null +++ b/src/Support/UserAgent.php @@ -0,0 +1,215 @@ +line) === '' || preg_match(self::BOTS, $this->line) === 1; + } + + /** + * The programs the statistics know by name, as pattern => [name, kind]. The + * first one that fits wins, so a longer name stands before the one it holds + * ("Applebot-Extended" before "Applebot"). + * + * Kinds: search (search engine), ai (collects for or answers through an AI), + * seo (marketing tools), social (the preview of a shared link), monitor, feed, + * archive, scanner (looks for weak spots), script (a program or library). + */ + private const KNOWN_BOTS = [ + '/GPTBot/i' => ['GPTBot', 'ai'], + '/ChatGPT-User/i' => ['ChatGPT', 'ai'], + '/OAI-SearchBot/i' => ['OpenAI search', 'ai'], + '/Claude-SearchBot/i' => ['Claude search', 'ai'], + '/Claude-User/i' => ['Claude', 'ai'], + '/ClaudeBot|anthropic-ai|claude-web/i' => ['ClaudeBot', 'ai'], + '/Perplexity-User/i' => ['Perplexity', 'ai'], + '/PerplexityBot/i' => ['PerplexityBot', 'ai'], + '/Google-Extended|GoogleOther|Google-CloudVertexBot/i' => ['Google (AI and other)', 'ai'], + '/Applebot-Extended/i' => ['Applebot-Extended', 'ai'], + '/meta-externalagent|meta-externalfetcher/i' => ['Meta AI', 'ai'], + '/Bytespider/i' => ['Bytespider', 'ai'], + '/Amazonbot/i' => ['Amazonbot', 'ai'], + '/CCBot/i' => ['Common Crawl', 'ai'], + '/cohere-ai|cohere-training/i' => ['Cohere', 'ai'], + '/MistralAI/i' => ['Mistral', 'ai'], + '/DuckAssistBot/i' => ['DuckAssist', 'ai'], + '/YouBot/i' => ['YouBot', 'ai'], + '/Diffbot/i' => ['Diffbot', 'ai'], + '/ImagesiftBot/i' => ['ImagesiftBot', 'ai'], + '/Timpibot/i' => ['Timpibot', 'ai'], + + '/Googlebot|Google-InspectionTool|Storebot-Google|AdsBot-Google|Mediapartners-Google|APIs-Google/i' => ['Googlebot', 'search'], + '/bingbot|BingPreview|adidxbot|msnbot/i' => ['Bingbot', 'search'], + '/DuckDuckBot|DuckDuckGo/i' => ['DuckDuckBot', 'search'], + '/YandexBot|YandexImages|Yandex/i' => ['YandexBot', 'search'], + '/Baiduspider/i' => ['Baiduspider', 'search'], + '/Applebot/i' => ['Applebot', 'search'], + '/Slurp/i' => ['Yahoo', 'search'], + '/Qwantbot|Qwantify/i' => ['Qwant', 'search'], + '/SeznamBot/i' => ['SeznamBot', 'search'], + '/PetalBot/i' => ['PetalBot', 'search'], + '/Sogou/i' => ['Sogou', 'search'], + '/MojeekBot/i' => ['Mojeek', 'search'], + '/Bravebot/i' => ['Brave', 'search'], + '/Kagibot/i' => ['Kagi', 'search'], + + '/AhrefsBot|AhrefsSiteAudit/i' => ['AhrefsBot', 'seo'], + '/SemrushBot|SiteAuditBot|SplitSignalBot/i' => ['SemrushBot', 'seo'], + '/MJ12bot/i' => ['Majestic', 'seo'], + '/DotBot|rogerbot/i' => ['Moz', 'seo'], + '/DataForSeoBot/i' => ['DataForSEO', 'seo'], + '/BLEXBot/i' => ['BLEXBot', 'seo'], + '/SerpstatBot/i' => ['Serpstat', 'seo'], + '/Barkrowler/i' => ['Barkrowler', 'seo'], + '/Screaming Frog/i' => ['Screaming Frog', 'seo'], + '/SEOkicks|seobility|Sistrix|linkdexbot/i' => ['Other SEO tool', 'seo'], + + '/facebookexternalhit|Facebot|facebookcatalog/i' => ['Facebook', 'social'], + '/LinkedInBot/i' => ['LinkedIn', 'social'], + '/Twitterbot/i' => ['X', 'social'], + '/WhatsApp/i' => ['WhatsApp', 'social'], + '/TelegramBot/i' => ['Telegram', 'social'], + '/Slackbot|Slack-ImgProxy/i' => ['Slack', 'social'], + '/Discordbot/i' => ['Discord', 'social'], + '/Pinterestbot|Pinterest\\/0/i' => ['Pinterest', 'social'], + '/redditbot/i' => ['Reddit', 'social'], + '/Mastodon|Pleroma|Akkoma|Misskey/i' => ['Mastodon and the fediverse', 'social'], + '/Bluesky/i' => ['Bluesky', 'social'], + '/SkypeUriPreview|MicrosoftPreview/i' => ['Microsoft link preview', 'social'], + '/Embedly|Iframely/i' => ['Embed service', 'social'], + + '/UptimeRobot/i' => ['UptimeRobot', 'monitor'], + '/Uptime-Kuma/i' => ['Uptime Kuma', 'monitor'], + '/Pingdom/i' => ['Pingdom', 'monitor'], + '/StatusCake/i' => ['StatusCake', 'monitor'], + '/Better Uptime|BetterStack/i' => ['Better Stack', 'monitor'], + '/Site24x7/i' => ['Site24x7', 'monitor'], + '/Lighthouse|PageSpeed|GTmetrix/i' => ['Speed test', 'monitor'], + '/Cloudflare/i' => ['Cloudflare', 'monitor'], + '/Zabbix|Nagios|check_http|Datadog|NewRelic/i' => ['Other monitoring', 'monitor'], + + '/Feedly|Feedbin|Inoreader|NewsBlur|Miniflux|FreshRSS|Tiny Tiny RSS|FeedFetcher/i' => ['Feed reader', 'feed'], + '/archive\.org_bot|ia_archiver|Wayback/i' => ['Internet Archive', 'archive'], + + '/CensysInspect/i' => ['Censys', 'scanner'], + '/Shodan/i' => ['Shodan', 'scanner'], + '/Expanse|Palo Alto/i' => ['Palo Alto Expanse', 'scanner'], + '/InternetMeasurement/i' => ['InternetMeasurement', 'scanner'], + '/l9explore|l9tcpid|LeakIX/i' => ['LeakIX', 'scanner'], + '/zgrab|masscan|Nmap|Nuclei|Nikto|sqlmap|WPScan|dirbuster|gobuster/i' => ['Scanning tool', 'scanner'], + + '/HeadlessChrome|Puppeteer|Playwright|Selenium|PhantomJS/i' => ['Headless browser', 'script'], + '/curl/i' => ['curl', 'script'], + '/Wget/i' => ['Wget', 'script'], + '/python|aiohttp|httpx|scrapy/i' => ['Python', 'script'], + '/Go-http-client/i' => ['Go', 'script'], + '/okhttp|Java\/|Apache-HttpClient/i' => ['Java', 'script'], + '/axios|node-fetch|undici|node/i' => ['Node.js', 'script'], + '/Guzzle|PHP/i' => ['PHP', 'script'], + '/Ruby|Faraday/i' => ['Ruby', 'script'], + '/libwww-perl|Perl/i' => ['Perl', 'script'], + '/Postman|Insomnia/i' => ['API client', 'script'], + ]; + + /** For a program that is not in the list: the word in its line that names it. */ + private const BOT_WORD = '/[A-Za-z0-9][A-Za-z0-9._-]*(?:bot|crawler|crawl|spider|scan|fetch|monitor|preview|archive|validator)[A-Za-z0-9._-]*/i'; + + /** + * Which program this is, or null for a person. A program that is not known + * by name is called by the one word of its line that names it ("FooBot"), + * never by the line; without such a word it is `null` as a name, for the + * caller to file under "other". + * + * @return array{name: string|null, kind: string}|null + */ + public function bot(): ?array + { + if (! $this->isBot()) { + return null; + } + + foreach (self::KNOWN_BOTS as $pattern => [$name, $kind]) { + if (preg_match($pattern, $this->line) === 1) { + return ['name' => $name, 'kind' => $kind]; + } + } + + $word = preg_match(self::BOT_WORD, $this->line, $match) === 1 ? substr($match[0], 0, 40) : null; + + return ['name' => $word, 'kind' => 'other']; + } + + public function device(): string + { + if (preg_match('/iPad|Tablet|PlayBook|Silk/i', $this->line) === 1 + || (str_contains($this->line, 'Android') && ! str_contains($this->line, 'Mobile'))) { + return 'tablet'; + } + + return preg_match('/Mobi|iPhone|iPod|Android/i', $this->line) === 1 ? 'mobile' : 'desktop'; + } + + public function browser(): string + { + // Order matters: nearly every browser also says "Chrome" and "Safari". + $browsers = [ + 'Edge' => '/Edg(e|A|iOS)?\//', + 'Opera' => '/OPR\/|Opera/', + 'Samsung Internet' => '/SamsungBrowser\//', + 'Vivaldi' => '/Vivaldi\//', + 'Firefox' => '/Firefox\/|FxiOS\//', + 'Chrome' => '/Chrome\/|CriOS\//', + 'Safari' => '/Safari\//', + ]; + + foreach ($browsers as $name => $pattern) { + if (preg_match($pattern, $this->line) === 1) { + return $name; + } + } + + return 'Other'; + } + + public function os(): string + { + $systems = [ + 'iOS' => '/iPhone|iPad|iPod/', + 'Android' => '/Android/', + 'Windows' => '/Windows/', + 'macOS' => '/Mac OS X|Macintosh/', + 'ChromeOS' => '/CrOS/', + 'Linux' => '/Linux|X11/', + ]; + + foreach ($systems as $name => $pattern) { + if (preg_match($pattern, $this->line) === 1) { + return $name; + } + } + + return 'Other'; + } +}