diff --git a/docs/seltd.md b/docs/seltd.md new file mode 100644 index 0000000..c00a70d --- /dev/null +++ b/docs/seltd.md @@ -0,0 +1,675 @@ +# SE Local Trenddata + +SE Local Trenddata ist eine webbasierte Trend-, Dashboard- und Quellenverwaltung fuer lokale Anlagen- und WAGO-Daten. Das Projekt besteht aus einem React-Frontend, einer Node.js/Express-API, MariaDB, Redis und einem Collector-Service fuer Protokollquellen wie Modbus TCP, OPC UA, BACnet IP und KNX IP. + +Das Ziel ist, bestehende breite Trendtabellen wie `isp01`, `isp02` usw. weiter nutzen zu koennen und zusaetzlich neue Quellen sauber ueber eine Weboberflaeche anzulegen, zu scannen, zu loggen und im Dashboard oder in der Trendansicht auszuwerten. + +--- + +## Inhaltsverzeichnis + +- [Projektaufbau](#projektaufbau) +- [Architektur](#architektur) +- [Services und Ports](#services-und-ports) +- [Schnellstart mit Docker Compose](#schnellstart-mit-docker-compose) +- [Lokale Entwicklung](#lokale-entwicklung) +- [Konfiguration](#konfiguration) +- [Login, Benutzer und Rollen](#login-benutzer-und-rollen) +- [Frontend-Funktionen](#frontend-funktionen) +- [API-Funktionen](#api-funktionen) +- [Collector-Funktionen](#collector-funktionen) +- [Datenbank und Speicher](#datenbank-und-speicher) +- [WAGO- oder SD-Karten-Betrieb](#wago--oder-sd-karten-betrieb) +- [Backup und Restore](#backup-und-restore) +- [Deployment-Hinweise](#deployment-hinweise) +- [Troubleshooting](#troubleshooting) +- [Sicherheits-Checkliste](#sicherheits-checkliste) + +--- + +## Projektaufbau + +```text +SeLTD/ +├── .env.example +├── docker-compose.yml +├── docker-compose.wago.yml +├── docker/ +│ └── redis/ +│ └── redis.conf +├── api/ +│ ├── Dockerfile +│ ├── package.json +│ └── src/ +│ ├── index.js +│ ├── auth.js +│ ├── config.js +│ ├── db.js +│ ├── redis.js +│ └── lib/ +│ ├── isp.js +│ └── store.js +├── collector/ +│ ├── Dockerfile +│ ├── package.json +│ └── src/ +│ └── index.js +└── web/ + ├── Dockerfile + ├── package.json + ├── vite.config.js + ├── public/ + │ └── logo.png + └── src/ + ├── App.jsx + ├── api.js + ├── main.jsx + ├── styles.css + └── components/ + ├── Gauge.jsx + └── TrendChart.jsx +``` + +### Hauptbereiche + +| Bereich | Aufgabe | +| --- | --- | +| `web/` | React/Vite-Frontend fuer Login, Dashboard, Trends, Admin-Bereich, Quellen, Rollen und Benutzer | +| `api/` | Express-API fuer Auth, Rollen, Aliase, Trendabfragen, Dashboard, SQL-Import und Benutzerverwaltung | +| `collector/` | HTTP-Service fuer Protokollquellen, Datenpunkte, Scans, Imports und zyklisches Logging | +| `mariadb` | Persistente Trenddaten und Benutzer-Tabelle | +| `redis` | Metadaten, Aliase, Rollen, Einheiten, Dashboards, Auswahlen und User-Praeferenzen | +| `dockhand` | Docker-Verwaltung ueber Weboberflaeche | +| `cadvisor` | Container-Metriken fuer Monitoring | + +--- + +## Architektur + +```text +Browser + │ + │ http://localhost:5173 + ▼ +React/Vite Frontend (web) + │ + ├── API-Aufrufe: http://localhost:18080/api/... + │ ▼ + │ Express API (api, intern Port 8080) + │ ├── MariaDB: Benutzer, Trendtabellen, SQL-Daten + │ └── Redis: Rollen, Einheiten, Aliase, Dashboard, Auswahlen + │ + └── Collector-Aufrufe: http://localhost:18110/... + ▼ + Collector-Service + ├── sources.json unter /app/data + ├── Modbus TCP / OPC UA / BACnet / KNX + └── schreibt aktive Datenpunkte in MariaDB-Trendtabellen +``` + +Wichtig: Die API laeuft im Container intern auf Port `8080`, wird aber nach aussen auf `18080` gemappt. Das Frontend muss deshalb im Browser auf `http://localhost:18080/api` zugreifen. + +--- + +## Services und Ports + +| Service | Container | Interner Port | Host-Port | Zweck | +| --- | --- | ---: | ---: | --- | +| Web | `seltd-web` | 5173 | 5173 | React/Vite-Oberflaeche | +| API | `seltd-api` | 8080 | 18080 | REST-API | +| Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling | +| MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten | +| Redis | `seltd-redis` | 6379 | 6379 | Metadaten und App-State | +| Dockhand | `dockhand` | 3000 | 3000 | Docker-Webverwaltung | +| cAdvisor | `cadvisor_ltd` | 8080 | 9090 | Container-Metriken | + +--- + +## Schnellstart mit Docker Compose + +Du solltest WSL installiert haben. +Falls du das nicht hast: +```powershell + wsl --install Ubuntu +``` +Dann kannst du Docker Desktop installieren: + https://docs.docker.com/desktop/setup/install/windows-install/ +Die Installation einfach durchklicken und wenn du gefragt wirst ob du Hyper-V oder WSL verwenden möchtest, wähle WSL. + + +### 1. Repository vorbereiten + +Wenn du git auf deinem rechner installiert hast, dann öffne eine Powershell in dem Ordner, in dem du das LTD-System haben willst. +(rechtsklick im Windowsexplorer ins leere --> "In Terminal öffnen") +```powershell +git clone https://git.portal.se-cloud.de/Hannes/SE-LTD +cd ./SeLTD +``` +Powershell nicht schließen, brauchst du gleich noch. + + +### 2. Stack bauen und starten + +Falls du Powershell geschlossen hast: +(rechtsklick im Windowsexplorer ins leere --> "In Terminal öffnen") + +```powershell +docker compose build --no-cache web api collector +docker compose up -d --force-recreate +``` +Die lokalen Images werden jetzt gebaut und die Onlineimages werden heruntrergeladen. +Wenn das fertig ist müssen alle 7 Container gestartet sein. + +Im Nachgang kannst du dies in der Powershell mit... +```powershell +docker ps -a +``` +...überprüfen + +### 3. Aufrufen +Nun stehen dir mehrere Tools zur Verfügung: +| Frontend | `http://localhost:5173` | +--> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends. + +| API Healthcheck | `http://localhost:18080/api/health` | +--> hier kannst du schauen ob die API läuft + +| Collector Healthcheck | `http://localhost:18110/health` | +--> hier kannst du schauen ob der Collector läuft, was nur wichtig ist, wenn du Datenpunkte per OPC,KNX, Modbus oder Bacnet angebunden hast. + +| Dockhand | `http://localhost:3000` | +--> Dockhand ist Container verwaltungstool, dass es dir ermöglicht, auch grafisch den Zustand deiner Container und deines Stacks zu sehen. + Der Vorteil hier, im Gegensatz zur normalen Docker Desktopoberfläche: Du kannst es auf jedem beliebigen anderen Rechner, der auf dein Netzwerk zugriff hat, öffnen. + +| cAdvisor | `http://localhost:9090` | +--> Cadvisor stellt alle Containerdaten für Monitoring und Analyticprogramme bereit. + So kann bei einer größeren Anlage, das Dockersystem mitr Prometheus oder ähnlichem überwacht werden. + Cadvisor stellt di Daten per html bereit, kannst du dir gern anschauen, ist aber ziemlich unübersichtlich. +### 4. Standard-Login + +```text +Username: admin +Passwort: [individuell festlegen] +``` + +--- + + +## Konfiguration + +Die wichtigsten Variablen liegen in `.env`. + +| Variable | Beispiel | Beschreibung | +| --- | --- | --- | +| `JWT_SECRET` | `[individuell festlegen]` | Signatur fuer Login-Tokens. In Produktion unbedingt aendern. | +| `ADMIN_USERNAME` | `admin` | Initialer Admin-Username | +| `ADMIN_EMAIL` | `admin@example.com` | Initiale Admin-E-Mail | +| `ADMIN_PASSWORD` | `[individuell festlegen]` | Initiales Admin-Passwort | +| `ADMIN_NAME` | `System Admin` | Anzeigename des Admins | +| `MARIADB_ROOT_PASSWORD` | `[individuell festlegen]` | MariaDB-Root-Passwort | +| `DB_PASSWORD_FALLBACK` | `[individuell festlegen]` | Fallback fuer alte Entwicklungsvolumes | +| `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe | +| `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt | +| `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung | + + + + +## Login, Benutzer und Rollen + +Die API legt beim Start automatisch einen Admin-Benutzer an oder aktualisiert den vorhandenen Admin. + +### Systemrollen + +| Rolle | Rechte | +| --- | --- | +| `viewer` | Dashboard anzeigen, Trendansicht anzeigen | +| `technician` | Dashboard, Trends, Aliase, Quellen, Debug | +| `admin` | Alle Rechte inkl. Benutzer- und Rollenverwaltung | + +### Rechtekatalog + +| Recht | Bedeutung | +| --- | --- | +| `view_dashboard` | Dashboard anzeigen und speichern | +| `view_trends` | Trends anzeigen, Auswahlen nutzen | +| `edit_aliases` | Aliase und Einheiten bearbeiten | +| `manage_sources` | Quellen und Datenpunkte verwalten | +| `manage_users` | Benutzer anlegen und bearbeiten | +| `manage_roles` | Rollen und Rechte verwalten | +| `view_debug` | Collector-Debug sehen | + +Benutzer, Rollen und Passwoerter werden ueber den Admin-Bereich verwaltet. + +--- + +## Frontend-Funktionen + +### Login + +- Username-basierter Login +- JWT-Token wird im Browser gespeichert +- Passwortwechsel ueber Einstellungen +- Rollenbasierte Navigation + +### Dashboard + +- Widgets aus aktueller Auswahl oder gespeicherter Auswahl +- Widget-Typen: + - Graph + - Zahl + - Zeigermanometer +- Dashboard wird pro Benutzer gespeichert + +### Trendansicht + +- Datenpunkte aus mehreren Trendtabellen kombinierbar +- Auswahl speicherbar und optional fuer andere Benutzer freigebbar +- Zeitraeume als Presets von 5 Minuten bis 30 Tage +- Eigener Start-/Endzeitraum moeglich +- Aktuelle Werte werden separat angezeigt +- Fokusmodus fuer den Graphen + +### Trend-Export + +Der Trendgraph kann exportiert werden als: + +- CSV +- XLSX +- PNG +- JPG +- SVG +- PDF + +### Admin: Aliase + +- Anzeigename und Beschreibung pro Trendtabelle +- Alias, Einheit, Faktor, Typ, Min/Max und Farbe pro Wert +- CSV-Import und CSV-Export +- Encoding-/Grad-Celsius-Bereinigung + +### Admin: Einheiten + +- Systemeinheiten wie `°C`, `%`, `K`, `V`, `A`, `Pa` +- Eigene Einheiten wie `bar`, `m³/h`, `Hz` usw. +- Einheitenauswahl bei Aliasen und Datenpunkten + +### Admin: Quellen + +- Protokollquellen anlegen und bearbeiten +- Unterstuetzte Protokolle in der UI: + - Modbus TCP + - OPC UA + - BACnet IP + - KNX IP +- Poll-Intervall und Schreibmodus konfigurierbar +- Scan-Ergebnisse und importierte Punkte koennen ins Logging uebernommen werden +- Manuelle Datenpunkte koennen erstellt und bearbeitet werden + +--- + +## API-Funktionen + +Die API laeuft unter: + +```text +http://localhost:18080/api +``` + +### Authentifizierung + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `POST` | `/api/auth/login` | Login mit Username/Passwort | +| `GET` | `/api/auth/me` | Aktuellen Benutzer lesen | +| `POST` | `/api/auth/change-password` | Passwort aendern | + +### Trends und ISPs + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `GET` | `/api/isps` | Verfuegbare Trendtabellen lesen | +| `GET` | `/api/isps/:isp/aliases` | Alias-Metadaten lesen | +| `PUT` | `/api/isps/:isp/aliases` | Alias-Metadaten speichern | +| `POST` | `/api/trend-tables` | Neue Trendtabelle anlegen | +| `POST` | `/api/trends/query` | Trenddaten abfragen | +| `POST` | `/api/points/latest` | Letzte Werte lesen | + +### Einheiten + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `GET` | `/api/units` | Einheiten lesen | +| `POST` | `/api/units` | Einheit anlegen | +| `PATCH` | `/api/units/:symbol` | Einheit bearbeiten | + +### Benutzer und Rollen + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `GET` | `/api/users` | Benutzerliste | +| `POST` | `/api/users` | Benutzer anlegen | +| `PATCH` | `/api/users/:id` | Benutzer bearbeiten | +| `GET` | `/api/roles` | Rollenliste inkl. Rechtekatalog | +| `POST` | `/api/roles` | Rolle anlegen | +| `PATCH` | `/api/roles/:name` | Rolle bearbeiten | + +### Auswahlen und Dashboard + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `GET` | `/api/selections` | Gespeicherte Auswahlen lesen | +| `POST` | `/api/selections` | Auswahl speichern | +| `PUT` | `/api/selections/:selectionId` | Auswahl aktualisieren | +| `DELETE` | `/api/selections/:selectionId` | Auswahl loeschen | +| `GET` | `/api/dashboard` | Dashboard laden | +| `PUT` | `/api/dashboard` | Dashboard speichern | +| `POST` | `/api/dashboard/data` | Widget-Daten laden | +| `GET` | `/api/preferences` | Benutzerpraeferenzen laden | +| `PUT` | `/api/preferences` | Benutzerpraeferenzen speichern | + +--- + +## Collector-Funktionen + +Der Collector laeuft unter: + +```text +http://localhost:18110 +``` + +Er verwaltet Quellen und Datenpunkte in einer JSON-Datei (`/app/data/sources.json`) und schreibt aktive Punkte zyklisch in MariaDB. + +### Collector-Endpunkte + +| Methode | Pfad | Beschreibung | +| --- | --- | --- | +| `GET` | `/health` | Healthcheck | +| `GET` | `/capabilities` | Unterstuetzte Protokolle/Funktionen | +| `GET` | `/sources` | Quellen lesen | +| `POST` | `/sources` | Quelle anlegen | +| `PUT` | `/sources/:id` | Quelle bearbeiten | +| `DELETE` | `/sources/:id` | Quelle loeschen | +| `GET` | `/datapoints` | Datenpunkte lesen | +| `POST` | `/datapoints/manual` | Datenpunkt manuell anlegen | +| `PATCH` | `/datapoints/:id` | Datenpunkt bearbeiten, aktivieren, deaktivieren | +| `POST` | `/datapoints/:id/read` | Live-Wert lesen | +| `POST` | `/imports/modbus-csv` | Modbus-CSV importieren | +| `POST` | `/imports/knx-xml` | KNX-XML importieren | +| `POST` | `/scan/opcua` | OPC-UA-Scan starten | +| `POST` | `/scan/bacnet` | BACnet-Scan starten | +| `GET` | `/debug` | Debugdaten lesen | + +### Schreibmodus + +| Modus | Bedeutung | +| --- | --- | +| `interval` | Jeder Poll wird geschrieben | +| `cov` | Nur bei Wertaenderung wird geschrieben | + +### Aktive vs. inaktive Datenpunkte + +- Inaktive Datenpunkte sind gefunden/importiert, werden aber nicht geloggt. +- Aktive Datenpunkte werden vom Collector gepollt und in die zugehoerige Trendtabelle geschrieben. +- In der Weboberflaeche entspricht das der Trennung zwischen „Gefunden / importiert“ und „Wird geloggt“. + +--- + +## Datenbank und Speicher + +### MariaDB + +MariaDB speichert: + +- `app_users` +- bestehende `isp...` Tabellen +- neue `trend_...` Tabellen +- Registry-Tabellen fuer Quellen und Datenpunkte, falls vom Collector/API genutzt + +Die API kann bestehende breite Tabellen mit `Wert1`, `Wert2`, ... lesen. Neue lokale Trendtabellen koennen bis zu 2000 Werte unterstuetzen. + +### Redis + +Redis speichert: + +- Rollen +- Einheiten +- Aliase und Tabellen-Metadaten +- Auswahlen +- Dashboard-Konfiguration +- Benutzerpraeferenzen + +Redis sollte deshalb ebenfalls gebackupt werden, nicht nur MariaDB. + +--- + + + +### MariaDB Backup + +```powershell +docker exec seltd-mariadb mariadb-dump -uroot -p --all-databases > seltd-mariadb-backup.sql +``` + +Restore: + +```powershell +type .\seltd-mariadb-backup.sql | docker exec -i seltd-mariadb mariadb -uroot -p +``` + +### Redis Backup + +Redis nutzt ein Docker-Volume. Fuer ein einfaches Dateibackup: + +```powershell +docker run --rm -v seltd_redis_data:/data -v ${PWD}:/backup alpine tar czf /backup/seltd-redis-backup.tar.gz -C /data . +``` + +### Collector Backup + +```powershell +docker run --rm -v seltd_collector_data:/data -v ${PWD}:/backup alpine tar czf /backup/seltd-collector-backup.tar.gz -C /data . +``` + +--- + + +### Browsercache + +Bei alten JavaScript-Fehlern nach einem Fix: + +```text +Strg + F5 +``` + + +### Nginx Proxy Manager + +Wenn das Frontend hinter Nginx laeuft, muessen die API- und Collector-URLs sauber erreichbar sein. Entweder: + +- Frontend, API und Collector unter eigenen Subdomains veroeffentlichen, oder +- Nginx so konfigurieren, dass `/api` zur API und `/collector` zum Collector weitergeleitet wird. + +In diesem Fall kann `VITE_API_URL` statt `VITE_API_PORT` gesetzt werden: + +```env +VITE_API_URL=https://trend-api.example.local/api +VITE_COLLECTOR_URL=https://trend-collector.example.local +``` + +--- + +## Troubleshooting + +### Fehler: `NetworkError when attempting to fetch resource` + +Ursachen: + +- API-Container laeuft nicht +- falscher Port im Frontend +- CORS nicht korrekt +- Browser ruft alte Version auf + +Pruefen: + +```powershell +docker ps +curl http://localhost:18080/api/health +``` + +Wenn Frontend lokal auf `localhost:5173` laeuft: + +```env +CORS_ORIGIN=* +``` + +Danach API neu starten: + +```powershell +docker compose restart api +``` + +### Fehler: Browser zeigt alte React-Fehler nach Fix + +Sehr wahrscheinlich wurde das Docker-Image nicht neu gebaut. + +```powershell +docker compose down +docker compose build --no-cache web api collector +docker compose up -d +``` + +Danach im Browser `Strg + F5`. + +### MariaDB Login oder DB-Verbindung fehlgeschlagen + +Logs ansehen: + +```powershell +docker logs seltd-api --tail 100 +docker logs seltd-mariadb --tail 100 +``` + +Pruefen, ob MariaDB healthy ist: + +```powershell +docker ps +``` + +### Redis-Probleme + +```powershell +docker exec seltd-redis redis-cli ping +``` + +Erwartet: + +```text +PONG +``` + +--- + +## Nuetzliche Befehle + +### Alle Container anzeigen + +```powershell +docker compose ps +``` + +### Logs live verfolgen + +```powershell +docker compose logs -f +``` + +Nur API: + +```powershell +docker logs seltd-api -f +``` + +Nur Frontend: + +```powershell +docker logs seltd-web -f +``` + +Nur Collector: + +```powershell +docker logs seltd-collector -f +``` + +### Komplett neu starten + +```powershell +docker compose restart +``` + +### Komplett neu bauen + +```powershell +docker compose down +docker compose build --no-cache +docker compose up -d +``` + +### Volumes loeschen + +Achtung: Dadurch gehen Daten verloren. + +```powershell +docker compose down -v +``` + +--- + +## Sicherheits-Checkliste + +Vor produktiver Nutzung: + +- [ ] `JWT_SECRET` auf langen zufaelligen Wert setzen +- [ ] Admin-Passwort aendern +- [ ] MariaDB-Root-Passwort aendern +- [ ] MariaDB-Port `3306` nicht ungeschuetzt ins Internet veroeffentlichen +- [ ] Redis-Port `6379` nicht ungeschuetzt ins Internet veroeffentlichen +- [ ] Dockhand absichern oder nur intern bereitstellen +- [ ] Backups fuer MariaDB, Redis und Collector-Daten einrichten +- [ ] Reverse Proxy mit HTTPS verwenden + +--- + +## Bekannte Hinweise + +- Leere Trendtabellen erscheinen nicht in der Trendauswahl, aber im Admin-Bereich. +- Bestehende breite `isp...` Tabellen bleiben kompatibel. +- Neue lokale Tabellen koennen als `trend_...` Tabellen angelegt werden. +- Der Collector speichert seine Quellen/Datenpunkte aktuell dateibasiert in `sources.json`. +- Fuer vollstaendige Protokollintegration muessen je nach Feldbus noch Details wie Adressierung, Datentyp, Byteorder und Authentifizierung sauber projektspezifisch gepflegt werden. + +--- + +--- + +## Konfiguration und Sicherheit + +Vor dem ersten Start `.env.example` nach `.env` kopieren und mindestens `JWT_SECRET`, `ADMIN_PASSWORD` und `REDIS_PASSWORD` durch eigene lange Zufallswerte ersetzen. Die lokale `.env` wird nicht versioniert. + +Redis ist ausschließlich innerhalb des Docker-Netzwerks erreichbar und verlangt ein Passwort. Für Diagnosezwecke: + +```powershell +docker compose exec redis redis-cli -a $env:REDIS_PASSWORD ping +``` + +Alle Dienste können vor einem Deployment statisch geprüft werden: + +```powershell +npm --prefix api run check +npm --prefix collector run check +npm --prefix symcon-collector run check +npm --prefix bacnet-collector run check +npm --prefix runner run check +npm --prefix web run check +``` diff --git a/src/Gateway.Api/Domain/Mqtt.cs b/src/Gateway.Api/Domain/Mqtt.cs index bb098e8..f6afadc 100644 --- a/src/Gateway.Api/Domain/Mqtt.cs +++ b/src/Gateway.Api/Domain/Mqtt.cs @@ -46,7 +46,8 @@ public sealed record MqttMapping( string? TopicName, string? JsonTopic, string? JsonProperty, - DateTimeOffset CreatedAtUtc); + DateTimeOffset CreatedAtUtc, + string? TopicTemplate = null); public sealed record CreateMqttMappingRequest( Guid PointId, @@ -60,7 +61,8 @@ public sealed record CreateMqttMappingRequest( SeMonitoringCategory? SeCategory, string? TopicName, string? JsonTopic, - string? JsonProperty); + string? JsonProperty, + string? TopicTemplate = null); public sealed record UpdateMqttConfigurationRequest( MqttConfiguration Configuration, @@ -71,7 +73,11 @@ public sealed record MqttConfigurationView(MqttConfiguration Configuration, bool public sealed record MqttMonitoringSite(int? ProjectYear, string? ProjectNumber, string? IspNumber); public sealed record MqttPointDefaults(Guid PointId, SeMonitoringCategory? Category, string TopicName); -public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList Points); +public sealed record MqttMappingDefaults(MqttMonitoringSite Site, IReadOnlyList Points, MqttTopicTemplateView TopicTemplate); +public sealed record MqttTopicPlaceholder(string Token, string Description); +public sealed record MqttTopicTemplateView(string Template, string DefaultTemplate, IReadOnlyList Placeholders, + IReadOnlyDictionary PreviewValues); +public sealed record UpdateMqttTopicTemplateRequest(string Template); public sealed record MqttInboundMessage(string Topic, JsonElement Payload, DateTimeOffset ReceivedAtUtc); diff --git a/src/Gateway.Api/Gateway.Api.csproj b/src/Gateway.Api/Gateway.Api.csproj index 180a2ea..294cae9 100644 --- a/src/Gateway.Api/Gateway.Api.csproj +++ b/src/Gateway.Api/Gateway.Api.csproj @@ -8,4 +8,10 @@ + + + + diff --git a/src/Gateway.Api/Program.cs b/src/Gateway.Api/Program.cs index 6cf6074..bd9d244 100644 --- a/src/Gateway.Api/Program.cs +++ b/src/Gateway.Api/Program.cs @@ -25,6 +25,7 @@ builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -81,6 +82,14 @@ app.Use(async (context, next) => app.UseDefaultFiles(); app.UseStaticFiles(); +app.MapGet("/api/docs", (HttpRequest request, SessionService sessions, GatewayDocumentation docs) => + sessions.IsValid(request.Headers.Authorization) ? Results.Ok(docs.Entries) : Results.Unauthorized()); +app.MapGet("/api/docs/content", (string path, HttpRequest request, SessionService sessions, GatewayDocumentation docs) => +{ + if (!sessions.IsValid(request.Headers.Authorization)) return Results.Unauthorized(); + return docs.Find(path) is { } file ? Results.Ok(file) : Results.NotFound(); +}); + app.MapGet("/api/presentation", (HttpRequest request, GatewayStore store, SessionService sessions) => sessions.IsValid(request.Headers.Authorization) ? Results.Ok(new { units = store.ListDisplayUnits(), points = store.ListPointPresentations() }) : Results.Unauthorized()); @@ -474,6 +483,9 @@ app.MapGet("/api/mqtt/mappings", (HttpRequest request, GatewayStore store, Sessi app.MapGet("/api/mqtt/mapping-defaults", (HttpRequest request, GatewayStore store, SessionService sessions) => sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) ? Results.Ok(store.GetMqttMappingDefaults()) : Results.StatusCode(403)); +app.MapPut("/api/mqtt/topic-template", (UpdateMqttTopicTemplateRequest template, HttpRequest request, GatewayStore store, SessionService sessions) => + sessions.HasPermission(request.Headers.Authorization, GatewayPermissions.ManageIntegrations) + ? Results.Ok(store.UpdateMqttTopicTemplate(template.Template)) : Results.StatusCode(403)); app.MapPost("/api/mqtt/mappings", (CreateMqttMappingRequest mapping, HttpRequest request, GatewayStore store, SessionService sessions, MqttClientService mqttClient) => { diff --git a/src/Gateway.Api/Services/GatewayDatabase.cs b/src/Gateway.Api/Services/GatewayDatabase.cs index dcf09da..915d571 100644 --- a/src/Gateway.Api/Services/GatewayDatabase.cs +++ b/src/Gateway.Api/Services/GatewayDatabase.cs @@ -156,7 +156,8 @@ public sealed class GatewayDatabase topic_name TEXT NULL, json_topic TEXT NULL, json_property TEXT NULL, - created_at_utc TEXT NOT NULL + created_at_utc TEXT NOT NULL, + topic_template TEXT NULL ); CREATE UNIQUE INDEX IF NOT EXISTS idx_mqtt_mapping_point_topic ON mqtt_mappings(point_id, format, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property); @@ -230,6 +231,7 @@ public sealed class GatewayDatabase EnsureColumn(connection, "trend_logs", "public_access", "INTEGER NOT NULL DEFAULT 0"); EnsureColumn(connection, "bacnet_discovered_devices", "network", "INTEGER NOT NULL DEFAULT 0"); EnsureColumn(connection, "bacnet_discovered_devices", "mac", "TEXT NULL"); + EnsureColumn(connection, "mqtt_mappings", "topic_template", "TEXT NULL"); using var indexMigration = connection.BeginTransaction(); using var pointIndexes = connection.CreateCommand(); pointIndexes.Transaction = indexMigration; diff --git a/src/Gateway.Api/Services/GatewayDocumentation.cs b/src/Gateway.Api/Services/GatewayDocumentation.cs new file mode 100644 index 0000000..c4dc0d6 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayDocumentation.cs @@ -0,0 +1,37 @@ +namespace Gateway.Api.Services; + +public sealed record DocumentationEntry(string Path, string Title); +public sealed record DocumentationFile(string Path, string Markdown); + +public sealed class GatewayDocumentation +{ + private readonly Dictionary _files; + public IReadOnlyList Entries { get; } + + public GatewayDocumentation() + { + var directory = Path.Combine(AppContext.BaseDirectory, "Documentation"); + var paths = Directory.Exists(directory) ? Directory.GetFiles(directory, "*.md", SearchOption.AllDirectories) : []; + _files = paths.Select(path => new DocumentationFile(Path.GetRelativePath(directory, path).Replace('\\', '/'), + File.ReadAllText(path))) + .ToDictionary(file => file.Path, StringComparer.Ordinal); + Entries = _files.Values + .OrderBy(file => file.Path != "README.md") + .ThenBy(file => file.Path, StringComparer.Ordinal) + .Select(file => new DocumentationEntry(file.Path, ReadTitle(file))).ToArray(); + } + + public DocumentationFile? Find(string path) => _files.GetValueOrDefault(path); + + private static string ReadTitle(DocumentationFile file) + { + using var reader = new StringReader(file.Markdown); + while (reader.ReadLine() is { } line) + { + if (string.IsNullOrWhiteSpace(line)) continue; + if (line.StartsWith("# ", StringComparison.Ordinal)) return line[2..].Trim(); + break; + } + return Path.GetFileNameWithoutExtension(file.Path); + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs b/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs index 6e3fce0..cfb3342 100644 --- a/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs +++ b/src/Gateway.Api/Services/GatewayStore.BulkMappings.cs @@ -37,6 +37,7 @@ public sealed partial class GatewayStore var prefix = request.MqttTopicPrefix?.Trim().TrimEnd('/'); var mqttFormat = request.MqttFormat ?? (prefix is null ? MqttMappingFormat.SeMonitoring : MqttMappingFormat.Json); var site = request.MqttSite ?? DefaultMonitoringSite(configuration.Installation); + var topicTemplate = ReadMqttTopicTemplate(connection, transaction); var alarms = request.Target == BulkMappingTarget.Mqtt && mqttFormat == MqttMappingFormat.SeMonitoring ? ReadMqttAlarmPoints(connection, transaction) : []; if (request.Target == BulkMappingTarget.Mqtt && mqttFormat != MqttMappingFormat.SeMonitoring && @@ -74,7 +75,7 @@ public sealed partial class GatewayStore if (monitoring && pointDefaults.Category is null) throw new DomainValidationException($"'{source.DisplayName}' benötigt das MQTT-Format JSON."); var topicName = pointDefaults.TopicName; - var topic = monitoring ? BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName) : + var topic = monitoring ? BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName) : $"{prefix}/{(slug.Length == 0 ? "punkt" : slug)}-{source.Id:N}"; var occupied = mqtt.Where(mapping => GetMqttTopic(mapping) == topic).ToArray(); if (occupied.Any(mapping => mapping.PointId == source.Id && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)) @@ -85,7 +86,7 @@ public sealed partial class GatewayStore if (monitoring && occupied.Length > 0) { topicName = $"{topicName}-{source.Id:N}"; - topic = BuildMonitoringTopic(site, pointDefaults.Category!.Value, topicName); + topic = BuildMonitoringTopic(topicTemplate, site, pointDefaults.Category!.Value, topicName); if (mqtt.Any(mapping => mapping.PointId == source.Id && GetMqttTopic(mapping) == topic && mapping.Direction is MqttDirection.Publish or MqttDirection.Bidirectional)) { @@ -98,7 +99,8 @@ public sealed partial class GatewayStore var mqttMapping = SaveMqttMapping(connection, transaction, null, new CreateMqttMappingRequest(source.Id, mqttFormat, MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false, monitoring ? site.ProjectYear : null, monitoring ? site.ProjectNumber : null, monitoring ? site.IspNumber : null, - monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null))!; + monitoring ? pointDefaults.Category : null, monitoring ? topicName : null, monitoring ? null : topic, null, + monitoring ? topicTemplate : null))!; mqtt.Add(mqttMapping); mqttCreated.Add(mqttMapping.Id); saved.Add($"{source.DisplayName} → {topic}"); diff --git a/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs b/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs index 5671b4f..9ecea84 100644 --- a/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs +++ b/src/Gateway.Api/Services/GatewayStore.ConfigurationCsv.cs @@ -18,7 +18,7 @@ public sealed partial class GatewayStore private static readonly string[] MappingColumns = ["Id", "SourcePointId", "TargetPointId", "Direction", "Enabled", "BacnetPriority", "AcknowledgeMultipleExternalWriters", "Transform"]; private static readonly string[] MqttMappingColumns = - ["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty"]; + ["Id", "PointId", "Format", "Direction", "QualityOfService", "Retain", "ProjectYear", "ProjectNumber", "IspNumber", "SeCategory", "TopicName", "JsonTopic", "JsonProperty", "TopicTemplate"]; public string ExportConfigurationCsv(ConfigurationCsvKind kind) { @@ -32,7 +32,8 @@ public sealed partial class GatewayStore mapping.AcknowledgeMultipleExternalWriters, mapping.Transform.GetRawText() }), _ => ListMqttMappings().Select(mapping => new object?[] { mapping.Id, mapping.PointId, mapping.Format, mapping.Direction, mapping.QualityOfService, mapping.Retain, mapping.ProjectYear, mapping.ProjectNumber, - mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty }) + mapping.IspNumber, mapping.SeCategory, mapping.TopicName, mapping.JsonTopic, mapping.JsonProperty, + mapping.Format == MqttMappingFormat.SeMonitoring ? mapping.TopicTemplate ?? DefaultMqttTopicTemplate : null }) }; var output = new StringBuilder("\uFEFF"); output.AppendJoin(';', CsvColumns(kind)).Append("\r\n"); @@ -65,7 +66,10 @@ public sealed partial class GatewayStore var columns = CsvColumns(kind); try { - if (!(parser.ReadFields() ?? []).Select(value => value.Trim()).SequenceEqual(columns, StringComparer.OrdinalIgnoreCase)) + var importedColumns = (parser.ReadFields() ?? []).Select(value => value.Trim()).ToArray(); + if (kind == ConfigurationCsvKind.MqttMappings && importedColumns.Length == columns.Length - 1) + columns = columns[..^1]; + if (!importedColumns.SequenceEqual(columns, StringComparer.OrdinalIgnoreCase)) throw new DomainValidationException("Die CSV-Spalten stimmen mit der exportierten Vorlage nicht überein."); } catch (MalformedLineException) { throw new DomainValidationException("Ungültiger CSV-Kopf."); } @@ -136,7 +140,8 @@ public sealed partial class GatewayStore CsvEnum(fields[3], "Direction"), CsvEnum(fields[4], "QualityOfService"), CsvBool(fields[5], "Retain"), CsvInteger(fields[6], "ProjectYear"), CsvOptional(fields[7]), CsvOptional(fields[8]), CsvOptional(fields[9]) is { } category ? CsvEnum(category, "SeCategory") : null, - CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12])); + CsvOptional(fields[10]), CsvOptional(fields[11]), CsvOptional(fields[12]), + fields.Length > 13 ? CsvOptional(fields[13]) : DefaultMqttTopicTemplate); SaveMqttMapping(connection, transaction, update ? id : null, mqtt, update ? null : id); break; } diff --git a/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs b/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs index 929c7dc..6807ea9 100644 --- a/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs +++ b/src/Gateway.Api/Services/GatewayStore.MqttDefaults.cs @@ -11,7 +11,8 @@ public sealed partial class GatewayStore using var connection = _database.OpenConnection(); var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection).Installation); var alarms = ReadMqttAlarmPoints(connection); - return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray()); + return new(site, ReadPoints(connection).Select(point => GetMqttPointDefaults(point, alarms)).ToArray(), + TopicTemplateView(ReadMqttTopicTemplate(connection), site)); } internal GatewayPoint? GetMqttPoint(Guid id) @@ -49,6 +50,4 @@ public sealed partial class GatewayStore return new(point.Id, category, name.Length == 0 ? "Punkt" : name); } - private static string BuildMonitoringTopic(MqttMonitoringSite site, SeMonitoringCategory category, string name) => - $"Projekte{site.ProjectYear}/{site.ProjectNumber}/{site.IspNumber}/{GetCategorySegment(category)}/{name}_Wert"; } diff --git a/src/Gateway.Api/Services/GatewayStore.MqttTopicTemplate.cs b/src/Gateway.Api/Services/GatewayStore.MqttTopicTemplate.cs new file mode 100644 index 0000000..825c857 --- /dev/null +++ b/src/Gateway.Api/Services/GatewayStore.MqttTopicTemplate.cs @@ -0,0 +1,97 @@ +using System.Globalization; +using System.Text.RegularExpressions; +using Gateway.Api.Domain; +using Microsoft.Data.Sqlite; + +namespace Gateway.Api.Services; + +public sealed partial class GatewayStore +{ + private const string MqttTopicTemplateKey = "mqtt_topic_template"; + private const string DefaultMqttTopicTemplate = "Projekte{Jahr}/{Projekt}/{ISP}/{Kategorie}/{Datenpunkt}_Wert"; + private static readonly Regex MqttTemplateTokenPattern = new(@"\{([^{}]*)\}", RegexOptions.CultureInvariant); + private static readonly MqttTopicPlaceholder[] MqttTopicPlaceholders = + [ + new("{Jahr}", "Projektjahr"), + new("{Projekt}", "Projektnummer mit P"), + new("{ISP}", "ISP mit Präfix"), + new("{Kategorie}", "Analog, Notify, Alarms oder Setpoints"), + new("{Datenpunkt}", "Punktname aus dem Mapping"), + new("{Rechnername}", "Aus Projekt und ISP") + ]; + + public MqttTopicTemplateView UpdateMqttTopicTemplate(string template) + { + var normalized = template?.Trim() ?? ""; + ValidateMqttTopicTemplate(normalized); + using var connection = _database.OpenConnection(); + using var transaction = connection.BeginTransaction(); + var site = DefaultMonitoringSite(ReadGatewayConfiguration(connection, transaction).Installation); + SetSetting(connection, MqttTopicTemplateKey, normalized, transaction); + WriteAudit(connection, "mqtt", "Default MQTT topic template updated.", transaction); + transaction.Commit(); + return TopicTemplateView(normalized, site); + } + + private static string ReadMqttTopicTemplate(SqliteConnection connection, SqliteTransaction? transaction = null) => + GetSetting(connection, MqttTopicTemplateKey, transaction) ?? DefaultMqttTopicTemplate; + + private static MqttTopicTemplateView TopicTemplateView(string template, MqttMonitoringSite site) => + new(template, DefaultMqttTopicTemplate, MqttTopicPlaceholders, TopicTemplateValues( + new(site.ProjectYear ?? DateTimeOffset.UtcNow.Year, site.ProjectNumber ?? "P190726", site.IspNumber ?? "ISP1"), + SeMonitoringCategory.Analog, "Vorlauftemperatur")); + + private static Dictionary TopicTemplateValues(MqttMonitoringSite site, SeMonitoringCategory category, string name) + { + var isp = site.IspNumber ?? ""; + var project = site.ProjectNumber ?? ""; + return new(StringComparer.Ordinal) + { + ["{Jahr}"] = site.ProjectYear?.ToString(CultureInfo.InvariantCulture) ?? "", + ["{Projekt}"] = project, + ["{ISP}"] = isp, + ["{Kategorie}"] = GetCategorySegment(category), + ["{Datenpunkt}"] = name, + ["{Rechnername}"] = isp.StartsWith("ISP", StringComparison.Ordinal) && project.Length > 0 + ? $"SE-UGW-{project}-ISP{isp[3..].PadLeft(2, '0')}" : "" + }; + } + + private static void ValidateMqttTopicTemplate(string template) + { + if (template.Length is 0 or > 1024 || template.Any(char.IsControl)) + throw new DomainValidationException("Der MQTT-Standardpfad muss 1 bis 1024 Zeichen enthalten, ohne Steuerzeichen."); + if (!template.Contains("{Datenpunkt}", StringComparison.Ordinal)) + throw new DomainValidationException("Der MQTT-Standardpfad benötigt den Platzhalter {Datenpunkt}."); + var sample = BuildMonitoringTopic(template, new(2019, "P190726", "ISP1"), SeMonitoringCategory.Analog, "Vorlauftemperatur"); + if (!MqttExternalTopics.IsTopic(sample)) + throw new DomainValidationException("Der erzeugte MQTT-Pfad ist zu lang oder enthält Wildcards (+ oder #)."); + } + + private static void ValidateMqttTopicInputs(string template, CreateMqttMappingRequest mapping) + { + ValidateMqttTopicTemplate(template); + var needsHost = template.Contains("{Rechnername}", StringComparison.Ordinal); + if (template.Contains("{Jahr}", StringComparison.Ordinal) && mapping.ProjectYear is not (>= 2000 and <= 2100)) + throw new DomainValidationException("Für {Jahr} ein Projektjahr zwischen 2000 und 2100 eingeben."); + if (needsHost || template.Contains("{Projekt}", StringComparison.Ordinal)) + { + var project = mapping.ProjectNumber; + var valid = template == DefaultMqttTopicTemplate ? IsProjectNumber(project) + : project is not null && Regex.IsMatch(project, "^P[A-Z0-9_-]{1,32}$", RegexOptions.CultureInvariant); + if (!valid) throw new DomainValidationException("Für den MQTT-Pfad eine gültige Projektnummer mit Präfix P eingeben."); + } + if ((needsHost || template.Contains("{ISP}", StringComparison.Ordinal)) && !IsIspNumber(mapping.IspNumber)) + throw new DomainValidationException("Für den MQTT-Pfad eine gültige ISP-Nummer mit Präfix ISP eingeben."); + } + + private static string BuildMonitoringTopic(string template, MqttMonitoringSite site, SeMonitoringCategory category, string name) + { + var values = TopicTemplateValues(site, category, name); + var topic = MqttTemplateTokenPattern.Replace(template, match => values.TryGetValue(match.Value, out var value) ? value : + throw new DomainValidationException($"Unbekannter MQTT-Platzhalter '{match.Value}'.")); + if (topic.IndexOfAny(['{', '}']) >= 0) + throw new DomainValidationException("Ein MQTT-Platzhalter enthält eine unvollständige Klammer."); + return topic; + } +} diff --git a/src/Gateway.Api/Services/GatewayStore.cs b/src/Gateway.Api/Services/GatewayStore.cs index 2f3d019..6ef58f9 100644 --- a/src/Gateway.Api/Services/GatewayStore.cs +++ b/src/Gateway.Api/Services/GatewayStore.cs @@ -717,7 +717,7 @@ public sealed partial class GatewayStore using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = """ - SELECT id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc + SELECT id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc, topic_template FROM mqtt_mappings ORDER BY created_at_utc; """; @@ -753,7 +753,12 @@ public sealed partial class GatewayStore var point = FindActivePoint(connection, transaction, request.PointId) ?? throw new DomainValidationException("Der MQTT-Quellpunkt existiert nicht."); - ValidateMqttMappingRequest(request, point); + var template = request.Format == MqttMappingFormat.SeMonitoring + ? NormalizeNullable(request.TopicTemplate) ?? (existing?.Format == MqttMappingFormat.SeMonitoring + ? existing.TopicTemplate ?? DefaultMqttTopicTemplate + : ReadMqttTopicTemplate(connection, transaction)) + : null; + ValidateMqttMappingRequest(request, point, template); var mapping = new MqttMapping( existing?.Id ?? newId ?? Guid.NewGuid(), request.PointId, @@ -768,11 +773,15 @@ public sealed partial class GatewayStore NormalizeNullable(request.TopicName), NormalizeNullable(request.JsonTopic), NormalizeNullable(request.JsonProperty), - existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow); + existing?.CreatedAtUtc ?? DateTimeOffset.UtcNow, + template == DefaultMqttTopicTemplate ? null : template); var topic = GetMqttTopic(mapping); + if (mapping.Format == MqttMappingFormat.SeMonitoring && !MqttExternalTopics.IsTopic(topic)) + throw new DomainValidationException("Der aus der Vorlage erzeugte MQTT-Pfad ist ungültig oder zu lang."); if (mappings.Any(other => other.Id != mapping.Id && GetMqttTopic(other) == topic && (mapping.Format == MqttMappingFormat.SingleTopic || other.Format == MqttMappingFormat.SingleTopic || + mapping.TopicTemplate != null || other.TopicTemplate != null || other.PointId == mapping.PointId && other.Format == mapping.Format && (mapping.Format != MqttMappingFormat.Json || other.JsonProperty == mapping.JsonProperty)))) throw new DomainValidationException("Dieses MQTT-Topic ist bereits für eine kollidierende Zuordnung belegt."); @@ -782,13 +791,13 @@ public sealed partial class GatewayStore using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = existing is null ? """ - INSERT INTO mqtt_mappings(id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc) - VALUES($id, $pointId, $format, $direction, $qualityOfService, $retain, $projectYear, $projectNumber, $ispNumber, $category, $topicName, $jsonTopic, $jsonProperty, $createdAt); + INSERT INTO mqtt_mappings(id, point_id, format, direction, quality_of_service, retain, project_year, project_number, isp_number, se_category, topic_name, json_topic, json_property, created_at_utc, topic_template) + VALUES($id, $pointId, $format, $direction, $qualityOfService, $retain, $projectYear, $projectNumber, $ispNumber, $category, $topicName, $jsonTopic, $jsonProperty, $createdAt, $template); """ : """ UPDATE mqtt_mappings SET point_id=$pointId, format=$format, direction=$direction, quality_of_service=$qualityOfService, retain=$retain, project_year=$projectYear, project_number=$projectNumber, isp_number=$ispNumber, se_category=$category, - topic_name=$topicName, json_topic=$jsonTopic, json_property=$jsonProperty WHERE id=$id; + topic_name=$topicName, json_topic=$jsonTopic, json_property=$jsonProperty, topic_template=$template WHERE id=$id; """; command.Parameters.AddWithValue("$id", mapping.Id.ToString()); command.Parameters.AddWithValue("$pointId", mapping.PointId.ToString()); @@ -803,6 +812,7 @@ public sealed partial class GatewayStore command.Parameters.AddWithValue("$topicName", (object?)mapping.TopicName ?? DBNull.Value); command.Parameters.AddWithValue("$jsonTopic", (object?)mapping.JsonTopic ?? DBNull.Value); command.Parameters.AddWithValue("$jsonProperty", (object?)mapping.JsonProperty ?? DBNull.Value); + command.Parameters.AddWithValue("$template", (object?)mapping.TopicTemplate ?? DBNull.Value); if (existing is null) command.Parameters.AddWithValue("$createdAt", mapping.CreatedAtUtc.ToString("O")); command.ExecuteNonQuery(); WriteAudit(connection, "mqtt", $"MQTT mapping '{topic}' {(existing is null ? "created" : "updated")} for point '{point.DisplayName}'.", transaction); @@ -816,7 +826,8 @@ public sealed partial class GatewayStore public static string GetMqttTopic(MqttMapping mapping) => mapping.Format switch { - MqttMappingFormat.SeMonitoring => BuildMonitoringTopic(new MqttMonitoringSite(mapping.ProjectYear, mapping.ProjectNumber, mapping.IspNumber), mapping.SeCategory!.Value, mapping.TopicName!), + MqttMappingFormat.SeMonitoring => BuildMonitoringTopic(mapping.TopicTemplate ?? DefaultMqttTopicTemplate, + new MqttMonitoringSite(mapping.ProjectYear, mapping.ProjectNumber, mapping.IspNumber), mapping.SeCategory!.Value, mapping.TopicName!), MqttMappingFormat.Json or MqttMappingFormat.SingleTopic => mapping.JsonTopic ?? throw new InvalidOperationException("The MQTT topic is missing."), _ => throw new InvalidOperationException("Unknown MQTT mapping format.") }; @@ -1560,9 +1571,10 @@ public sealed partial class GatewayStore reader.IsDBNull(10) ? null : reader.GetString(10), reader.IsDBNull(11) ? null : reader.GetString(11), reader.IsDBNull(12) ? null : reader.GetString(12), - ParseTimestamp(reader.GetString(13))); + ParseTimestamp(reader.GetString(13)), + reader.IsDBNull(14) ? null : reader.GetString(14)); - private static void ValidateMqttMappingRequest(CreateMqttMappingRequest request, GatewayPoint point) + private static void ValidateMqttMappingRequest(CreateMqttMappingRequest request, GatewayPoint point, string? topicTemplate) { if (!Enum.IsDefined(request.Format) || !Enum.IsDefined(request.Direction) || !Enum.IsDefined(request.QualityOfService) || request.SeCategory is { } category && !Enum.IsDefined(category)) @@ -1588,11 +1600,11 @@ public sealed partial class GatewayStore return; } - if (request.ProjectYear is not (>= 2000 and <= 2100) || !IsProjectNumber(request.ProjectNumber) || !IsIspNumber(request.IspNumber) || - request.SeCategory is null || !IsValidTopicName(request.TopicName)) + if (request.SeCategory is null || !IsValidTopicName(request.TopicName)) { - throw new DomainValidationException("SE-Monitoring benötigt Jahr, Projektnummer P…, ISP-Nummer ISP…, Kategorie und einen gültigen Punktnamen."); + throw new DomainValidationException("SE-Monitoring benötigt eine Kategorie und einen gültigen Punktnamen."); } + ValidateMqttTopicInputs(topicTemplate!, request); if (classification == MqttPointClassification.Structured) { diff --git a/src/Gateway.Api/wwwroot/app.js b/src/Gateway.Api/wwwroot/app.js index 1eb9dfe..2e10495 100644 --- a/src/Gateway.Api/wwwroot/app.js +++ b/src/Gateway.Api/wwwroot/app.js @@ -134,6 +134,8 @@ function renderShell() { const nav = `${can('view_dashboard') ? '' : ''}${can('view_trends') ? '' : ''}${can('manage_sources') || can('manage_gateway') || can('manage_integrations') ? '' : ''}${can('manage_sources') ? '' : ''}${adminTabs().length ? '' : ''}`; const theme = state.preferences?.theme || 'system'; app.innerHTML = `
`; + document.querySelector('.sidebar-foot').insertAdjacentHTML('afterbegin', + ''); document.querySelector('#sidebar-logout').addEventListener('click', logout); document.querySelector('.shell').classList.toggle('unpinned', state.preferences?.sidebarPinned === false); document.querySelector('#sidebar-pin').addEventListener('click', async () => { try { state.preferences = await api('/api/auth/preferences', { method: 'PUT', body: JSON.stringify({ sidebarPinned: state.preferences?.sidebarPinned === false }) }); renderShell(); } catch (error) { window.alert(error.message); } }); @@ -145,7 +147,7 @@ function renderShell() { function renderView() { document.querySelectorAll('[data-view]').forEach(button => button.classList.toggle('active', button.dataset.view === state.view)); const content = document.querySelector('#content'); - const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem }; + const views = { overview: viewDashboard, points: viewDataPoints, mappings: viewMappings, mqtt: viewMqtt, trends: viewTrends, runner: viewRunner, protocols: viewProtocols, admin: viewAdmin, system: viewSystem, docs: viewDocumentation }; content.innerHTML = views[state.view](); bindView(state.view); } @@ -211,9 +213,9 @@ function viewPoints() {
-

Registrierte Punkte ${state.points.length}

${configurationCsvButtons('points')}
+

Registrierte Punkte ${state.points.length}

${configurationCsvButtons('points')}
- ${rows ? `
+ ${rows ? `
NameProtokollBereichWerttyp
${rows}
NameProtokollBereichWerttyp BACnet-ObjektZugriffIdentitätAktionen
` : '
Noch keine Datenpunkte.
'}
@@ -280,7 +282,7 @@ function viewMqtt() { const mapping = entry.mapping; return `${escapeHtml(pointNames[mapping.pointId] || mapping.pointId)}${escapeHtml(mqttMappingFormatLabel(mapping.format))}${escapeHtml(mapping.direction)}${escapeHtml(entry.topic)}${escapeHtml(mapping.qualityOfService)}${mapping.retain ? 'ja' : 'nein'}${mappingActions(mapping.id, 'mqtt-mapping')}`; }).join(''); - return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}

Broker-Verbindung

${status.connected ? 'online' : 'offline'}
Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.

SE-Monitoring-Schema

Projekte{Jahr}/P{Projektnummer}/ISP{Nummer}/Kategorie/{Punkt}_Wert

AnalogNur analoge Punkte (AI/AO/AV usw.)
NotifyNur digitale Zustände, keine Störungen
AlarmsDigitale Alarm-Punkte
SetpointsAnaloge oder digitale Sollwerte, immer senden und empfangen

Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.

${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}

${mqttMappingForm(editing)}

Konfigurierte MQTT-Mappings ${state.mqttMappings.length}

${configurationCsvButtons('mqtt')}
${state.mqttMappings.length ? `
${rows}
PunktFormatRichtungTopicQoSRetainAktionen
` : '
Noch keine MQTT-Mappings.
'}
`; + return `${header('MQTT / MQTTS', connection)}${viewMqttTopicBrowser()}

Broker-Verbindung

${status.connected ? 'online' : 'offline'}
Zertifikatsfehler nur für bekannte, kontrollierte Broker ignorieren. Die Option deaktiviert die Prüfung der Broker-Identität.

SE-Monitoring-Schema

${escapeHtml(mqttTopicTemplate() || '—')}

AnalogNur analoge Punkte (AI/AO/AV usw.)
NotifyNur digitale Zustände, keine Störungen
AlarmsDigitale Alarm-Punkte
SetpointsAnaloge oder digitale Sollwerte, immer senden und empfangen

Schedules und Kalender sind ausschließlich als JSON-Mapping möglich. JSON-TOPICs akzeptieren keine Wildcards; mehrere Punkte dürfen mit eigenen JSON-Eigenschaften dasselbe Topic verwenden.

${editing ? 'MQTT-Mapping bearbeiten' : 'MQTT-Mapping anlegen'}

${mqttMappingForm(editing)}

Konfigurierte MQTT-Mappings ${state.mqttMappings.length}

${configurationCsvButtons('mqtt')}
${state.mqttMappings.length ? `
${rows}
PunktFormatRichtungTopicQoSRetainAktionen
` : '
Noch keine MQTT-Mappings.
'}
`; } function viewTrends() { @@ -344,10 +346,11 @@ function viewSystem(section = 'settings') { if (section === 'users') return userPanel; if (section === 'roles') return rolePanel; if (section === 'debug') return auditPanel; - return `${header('Einstellungen')}

Passwort ändern

Darstellung

${can('manage_gateway') ? viewInstallationSettings() : ''}
${can('manage_gateway') ? '

Netzwerk · IPv4

Netzwerkstatus wird geladen …

' : ''}`; + return `${header('Einstellungen')}

Passwort ändern

Darstellung

${can('manage_gateway') ? viewInstallationSettings() : ''}${can('manage_integrations') ? viewMqttTopicTemplateSettings() : ''}
${can('manage_gateway') ? '

Netzwerk · IPv4

Netzwerkstatus wird geladen …

' : ''}`; } function bindView(view) { + if (view === 'docs') return bindDocumentation(); if (view === 'overview') return bindDashboard(); if (view === 'admin') return bindAdmin(); if (view === 'points') { @@ -403,6 +406,7 @@ function bindView(view) { if (view === 'system') { document.querySelector('#password-form')?.addEventListener('submit', submitPassword); bindInstallationSettings(); + bindMqttTopicTemplateSettings(); const networkPanel = document.querySelector('#host-network'); if (networkPanel) bindHostNetwork(networkPanel); document.querySelector('#content').querySelectorAll('[data-theme]').forEach(button => button.addEventListener('click', () => setTheme(button.dataset.theme))); diff --git a/src/Gateway.Api/wwwroot/documentation.js b/src/Gateway.Api/wwwroot/documentation.js new file mode 100644 index 0000000..072a91a --- /dev/null +++ b/src/Gateway.Api/wwwroot/documentation.js @@ -0,0 +1,140 @@ +function viewDocumentation() { + return `${header('Dokumentation')}
+ +
+

Dokumentation wird geladen …

+
+
`; +} + +function bindDocumentation() { + const root = document.querySelector('#documentation'); + const tabs = root.querySelector('[role=tablist]'); + const panel = root.querySelector('#documentation-panel'); + let documents = []; + let revision = 0; + + function setMessage(message) { + const text = document.createElement('p'); + text.className = 'note'; + text.role = 'status'; + text.textContent = message; + panel.replaceChildren(text); + } + + function scrollToHeading(fragment) { + if (!fragment) return; + [...panel.querySelectorAll('[id]')].find(heading => heading.id === fragment)?.scrollIntoView({ block:'start' }); + } + + async function openDocument(index, fragment) { + const selected = documents[index]; + if (!selected) return; + const current = ++revision; + state.documentationPath = selected.path; + [...tabs.children].forEach((tab, position) => { + const active = position === index; + tab.classList.toggle('active', active); + tab.setAttribute('aria-selected', String(active)); + tab.tabIndex = active ? 0 : -1; + }); + panel.setAttribute('aria-labelledby', `documentation-tab-${index}`); + setMessage('Dokument wird geladen …'); + try { + const file = await api(`/api/docs/content?path=${encodeURIComponent(selected.path)}`); + if (!root.isConnected || current !== revision) return; + panel.replaceChildren(renderDocumentationMarkdown(file, documents)); + scrollToHeading(fragment); + } catch (error) { + if (root.isConnected && current === revision) setMessage(error.message); + } + } + + tabs.addEventListener('click', event => { + const tab = event.target.closest('[data-document-tab]'); + if (tab) openDocument(Number(tab.dataset.documentTab)); + }); + tabs.addEventListener('keydown', event => { + const tab = event.target.closest('[data-document-tab]'); + if (!tab) return; + const index = Number(tab.dataset.documentTab); + const next = { ArrowLeft:(index + documents.length - 1) % documents.length, ArrowRight:(index + 1) % documents.length, + Home:0, End:documents.length - 1 }[event.key]; + if (next === undefined) return; + event.preventDefault(); + tabs.children[next].focus(); + openDocument(next); + }); + panel.addEventListener('click', event => { + const link = event.target.closest('[data-document-link]'); + if (!link) return; + const target = link.dataset.documentLink; + event.preventDefault(); + if (target === state.documentationPath) scrollToHeading(link.dataset.documentFragment); + else openDocument(documents.findIndex(document => document.path === target), link.dataset.documentFragment); + }); + + api('/api/docs').then(catalog => { + if (!root.isConnected) return; + documents = catalog; + if (!documents.length) { + setMessage('Keine Dokumente vorhanden.'); + return; + } + tabs.innerHTML = documents.map(({ title }, index) => ``).join(''); + tabs.hidden = false; + panel.role = 'tabpanel'; + panel.tabIndex = 0; + openDocument(Math.max(0, documents.findIndex(document => document.path === state.documentationPath))); + }).catch(error => { if (root.isConnected) setMessage(error.message); }); +} + +function renderDocumentationMarkdown(file, documents) { + const content = document.createElement('div'); + content.className = 'documentation-markdown'; + content.innerHTML = window.markdownit({ html:false }).render(file.markdown); + const slugs = new Set(); + for (const heading of content.querySelectorAll('h1, h2, h3, h4, h5, h6')) { + const base = heading.textContent.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').trim().replace(/\s+/g, '-') || 'abschnitt'; + let slug = base; + for (let suffix = 1; slugs.has(slug); suffix++) slug = `${base}-${suffix}`; + slugs.add(slug); + heading.id = slug; + } + for (const table of content.querySelectorAll('table')) { + const container = document.createElement('div'); + container.className = 'table-scroll'; + table.replaceWith(container); + container.append(table); + } + const paths = new Set(documents.map(document => document.path)); + const localOrigin = 'https://documentation.invalid'; + const base = new URL(file.path.split('/').map(encodeURIComponent).join('/'), localOrigin); + for (const link of content.querySelectorAll('a[href]')) { + let url; + try { url = new URL(link.getAttribute('href'), base); } + catch { + link.removeAttribute('href'); + continue; + } + if (url.origin === localOrigin) { + try { + const path = decodeURIComponent(url.pathname.slice(1)); + if (paths.has(path)) { + link.dataset.documentLink = path; + link.dataset.documentFragment = decodeURIComponent(url.hash.slice(1)); + link.href = url.hash || '#'; + continue; + } + } catch (error) { + if (!(error instanceof URIError)) throw error; + } + link.removeAttribute('href'); + } else if (url.protocol === 'https:' || url.protocol === 'http:') { + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + } else if (url.protocol !== 'mailto:') link.removeAttribute('href'); + } + return content; +} diff --git a/src/Gateway.Api/wwwroot/index.html b/src/Gateway.Api/wwwroot/index.html index db81d3d..2cee068 100644 --- a/src/Gateway.Api/wwwroot/index.html +++ b/src/Gateway.Api/wwwroot/index.html @@ -11,17 +11,19 @@ } catch { /* Dark is the default when browser storage is unavailable. */ } - +
- + - + - + + + diff --git a/src/Gateway.Api/wwwroot/ltd.css b/src/Gateway.Api/wwwroot/ltd.css index c4b18db..99ee9b5 100644 --- a/src/Gateway.Api/wwwroot/ltd.css +++ b/src/Gateway.Api/wwwroot/ltd.css @@ -16,6 +16,23 @@ body { min-width:360px; font-size:12px; } .sidebar-foot { position:static; margin-top:auto; padding:10px 0 0; border-top:1px solid var(--line); gap:8px; } .sidebar-foot .btn { justify-self:start; } .sidebar-foot small { font-size:9px; text-align:center; } +.documentation-card { padding:16px 20px; } +.documentation-markdown { max-width:112ch; font-size:13px; line-height:1.6; overflow-wrap:anywhere; } +.documentation-markdown :is(h1,h2,h3,h4,h5,h6) { margin:1.15em 0 .45em; scroll-margin-top:12px; } +.documentation-markdown h1 { font-size:23px; margin-top:0; } +.documentation-markdown h2 { font-size:17px; } +.documentation-markdown h3 { font-size:15px; } +.documentation-markdown p { margin:0 0 10px; } +.documentation-markdown :is(ul,ol) { margin:0 0 12px; padding-left:24px; } +.documentation-markdown li + li { margin-top:3px; } +.documentation-markdown a { color:var(--blue); text-decoration:underline; } +.documentation-markdown hr { border:0; border-top:1px solid var(--line); margin:18px 0; } +.documentation-markdown blockquote { border-left:3px solid var(--blue); margin:10px 0; padding:5px 12px; } +.documentation-markdown pre { overflow:auto; border:1px solid var(--line); border-radius:8px; background:var(--panel-2); padding:10px; } +.documentation-markdown :not(pre) > code { background:var(--panel-2); padding:1px 4px; border-radius:4px; } +.documentation-markdown table { margin:3px 0 10px; } +.documentation-markdown :is(td,th) { text-align:left; vertical-align:top; } +.documentation-markdown img { max-width:100%; } .theme-control { display:grid; gap:6px; } .theme-caption { color:var(--muted); font-size:10px; } .sidebar-foot .theme-toggle { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; } @@ -97,6 +114,8 @@ input[type="color"] { padding:4px; width:36px; flex:0 0 36px; } .connection-facts dd { margin:0; overflow-wrap:anywhere; } .connection-issues { max-height:35dvh; overflow:auto; overflow-wrap:anywhere; } [data-mqtt-preview] { overflow-wrap:anywhere; } +.mqtt-topic-placeholders { display:flex; flex-wrap:wrap; gap:5px; } +.mqtt-topic-placeholders .btn { display:flex; flex-wrap:wrap; gap:5px; border-radius:8px; } .mqtt-topic-browser { margin-bottom:10px; } .mqtt-browser-start { align-self:end; } .mqtt-browser-content { margin-top:12px; } @@ -137,6 +156,18 @@ input[type="color"] { padding:4px; width:36px; flex:0 0 36px; } .chart-legend i { display:inline-block; width:10px; height:3px; margin-right:5px; vertical-align:middle; } .widget-grid { margin-top:10px; } .table-scroll { overflow:auto; } +.point-inventory { + display:flex; + flex-direction:column; + max-height:max(16rem,calc(100dvh - 12rem)); +} +.point-inventory-scroll { + min-height:0; + overscroll-behavior:contain; + scrollbar-color:var(--line-strong) transparent; +} +.point-inventory-scroll thead th { position:sticky; top:0; z-index:1; background:var(--panel-2); } +.point-inventory-scroll:focus-visible { outline:2px solid var(--blue); outline-offset:-2px; } .empty { text-align:center; padding:28px 10px; } .runner-columns { min-height:230px; } details > summary { cursor:pointer; color:var(--muted); padding:7px 0; } @@ -144,6 +175,7 @@ button:focus-visible,a:focus-visible { outline:2px solid var(--blue); outline-of @media(min-width:1800px) { .alias-table .scroll { max-height:65vh; } } @media(max-width:1100px) { .grid.two,.grid.equal { grid-template-columns:1fr; } + .point-inventory { max-height:max(16rem,60dvh); } .status { max-width:45%; text-align:right; } .bacnet-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"settings" "search" "devices"; grid-template-rows:auto; } .bacnet-devices { position:static; max-height:60dvh; } diff --git a/src/Gateway.Api/wwwroot/mapping-batch.js b/src/Gateway.Api/wwwroot/mapping-batch.js index 645dce9..1053149 100644 --- a/src/Gateway.Api/wwwroot/mapping-batch.js +++ b/src/Gateway.Api/wwwroot/mapping-batch.js @@ -31,7 +31,10 @@ function viewMappingBatch() {
`; +} + +function bindMqttTopicTemplateSettings() { + const form = document.querySelector('#mqtt-topic-template-form'); + if (!form) return; + let settings = state.mqttMappingDefaults.topicTemplate; + const input = form.elements.template; + const preview = form.querySelector('[data-mqtt-preview]'); + const save = form.querySelector('[type=submit]'); + const updatePreview = () => { + preview.textContent = expandMqttTopicTemplate(input.value, settings.previewValues) || '—'; + }; + form.querySelectorAll('[data-template-insert]').forEach(button => button.addEventListener('click', () => { + const start = input.selectionStart; + const end = input.selectionEnd; + input.focus({ preventScroll: true }); + input.setRangeText(button.dataset.templateInsert, start, end, 'end'); + updatePreview(); + })); + form.querySelector('[data-template-default]').addEventListener('click', () => { + input.value = settings.defaultTemplate; + input.focus({ preventScroll: true }); + updatePreview(); + }); + input.addEventListener('input', updatePreview); + form.addEventListener('submit', async event => { + event.preventDefault(); + save.disabled = true; + const value = input.value; + try { + settings = await api('/api/mqtt/topic-template', { method:'PUT', body:JSON.stringify({ template:value }) }); + state.mqttMappingDefaults.topicTemplate = settings; + if (input.value === value) input.value = settings.template; + updatePreview(); + errorTarget('mqtt-template-message', 'MQTT-Standardpfad gespeichert.', true); + } catch (error) { errorTarget('mqtt-template-message', error.message); } + finally { save.disabled = false; } + }); + updatePreview(); +} diff --git a/src/Gateway.Api/wwwroot/vendor/markdown-it-15.0.3.min.js b/src/Gateway.Api/wwwroot/vendor/markdown-it-15.0.3.min.js new file mode 100644 index 0000000..eb0da63 --- /dev/null +++ b/src/Gateway.Api/wwwroot/vendor/markdown-it-15.0.3.min.js @@ -0,0 +1,14 @@ +(function(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.markdownit=t())})(this,function(){var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r},n={};function r(e){let t=n[e];if(t)return t;t=n[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);t.push(n)}for(let n=0;n=55296&&e<=57343?`���`:String.fromCharCode(e),r+=6;continue}}if((a&248)==240&&r+91114111?t+=`����`:(e-=65536,t+=String.fromCharCode(55296+(e>>10),56320+(e&1023))),r+=9;continue}}t+=`�`}}return t})}i.defaultChars=`;/?:@&=+$,#`,i.componentChars=``;var a={};function o(e){let t=a[e];if(t)return t;t=a[e]=[];for(let e=0;e<128;e++){let n=String.fromCharCode(e);/^[0-9a-z]$/i.test(n)?t.push(n):t.push(`%`+(`0`+e.toString(16).toUpperCase()).slice(-2))}for(let n=0;n=55296&&o<=57343){if(o>=55296&&o<=56319&&t+1=56320&&n<=57343){i+=encodeURIComponent(e[t]+e[t+1]),t++;continue}}i+=`%EF%BF%BD`}else i+=encodeURIComponent(e[t])}return i}s.defaultChars=`;/?:@&=+$,-_.!~*'()#`,s.componentChars=`-_.!~*'()`;function c(e){let t=``;return t+=e.protocol||``,t+=e.slashes?`//`:``,t+=e.auth?e.auth+`@`:``,e.hostname&&e.hostname.indexOf(`:`)!==-1?t+=`[`+e.hostname+`]`:t+=e.hostname||``,t+=e.port?`:`+e.port:``,t+=e.pathname||``,t+=e.search||``,t+=e.hash||``,t}function l(){this.protocol=null,this.slashes=null,this.auth=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null}var u=/^([a-z0-9.+-]+:)/i,d=/:[0-9]*$/,f=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,p=[`%`,`/`,`?`,`;`,`#`,`'`,`{`,`}`,`|`,`\\`,`^`,"`",`<`,`>`,`"`,"`",` `,`\r`,` +`,` `],m=[`/`,`?`,`#`],h=255,g=/^[+a-z0-9A-Z_-]{0,63}$/,_=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,v={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function b(e,t){if(e&&e instanceof l)return e;let n=new l;return n.parse(e,t),n}l.prototype.parse=function(e,t){let n,r,i,a=e;if(a=a.trim(),!t&&e.split(`#`).length===1){let e=f.exec(a);if(e)return this.pathname=e[1],e[2]&&(this.search=e[2]),this}let o=u.exec(a);if(o&&(o=o[0],n=o.toLowerCase(),this.protocol=o,a=a.substr(o.length)),(t||o||a.match(/^\/\/[^@\/]+@[^@\/]+/))&&(i=a.substr(0,2)===`//`,i&&!(o&&v[o])&&(a=a.substr(2),this.slashes=!0)),!v[o]&&(i||o&&!y[o])){let e=-1;for(let t=0;t127?r+=`x`:r+=n[e];if(!r.match(g)){let r=e.slice(0,t),i=e.slice(t+1),o=n.match(_);o&&(r.push(o[1]),i.unshift(o[2])),i.length&&(a=i.join(`.`)+a),this.hostname=r.join(`.`);break}}}}this.hostname.length>h&&(this.hostname=``),o&&(this.hostname=this.hostname.substr(1,this.hostname.length-2))}let s=a.indexOf(`#`);s!==-1&&(this.hash=a.substr(s),a=a.slice(0,s));let c=a.indexOf(`?`);return c!==-1&&(this.search=a.substr(c),a=a.slice(0,c)),a&&(this.pathname=a),y[n]&&this.hostname&&!this.pathname&&(this.pathname=``),this},l.prototype.parseHost=function(e){let t=d.exec(e);t&&(t=t[0],t!==`:`&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)};var x=t({decode:()=>i,encode:()=>s,format:()=>c,parse:()=>b}),S=t({Any:()=>C,Cc:()=>ee,Cf:()=>te,P:()=>ne,S:()=>re,Z:()=>ie}),C=/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,ee=/[\0-\x1F\x7F-\x9F]/,te=/[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/,ne=/[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B4E\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u2E52-\u2E5D\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDD6E\uDEAD\uDED0\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9\uDFD4\uDFD5\uDFD7\uDFD8]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2\uDF00-\uDF09\uDFE1]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDF43-\uDF4F\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDD6D-\uDD6F\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD839\uDDFF|\uD83A[\uDD5E\uDD5F]/,re=/[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C1\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2429\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E5\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBD2\uFD40-\uFD4F\uFD90\uFD91\uFDC8-\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD803[\uDD8E\uDD8F\uDED1-\uDED8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDC00-\uDCEF\uDCFA-\uDCFC\uDD00-\uDEB3\uDEBA-\uDED0\uDEE0-\uDEF0\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED8\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0-\uDCBB\uDCC0\uDCC1\uDCD0-\uDCD8\uDD00-\uDE57\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF-\uDEF8\uDF00-\uDF92\uDF94-\uDFEF\uDFFA]/,ie=/[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,ae=[8364,0,8218,402,8222,8230,8224,8225,710,8240,352,8249,338,0,381,0,0,8216,8217,8220,8221,8226,8211,8212,732,8482,353,8250,339,0,382,376];function oe(e){return e===0||e>=55296&&e<=57343||e>1114111}function se(e){return oe(e)?65533:e>=128&&e<=159&&ae[e-128]||e}function ce(e){return e-1>>>0<127||e-160>>>0<55136?String.fromCharCode(e):String.fromCodePoint(se(e))}var w=(()=>{let e=new Uint8Array(127),t=0;for(let n=33;n<=126;n++)n!==34&&n!==36&&n!==92&&(e[n]=t++);return e})();function le(e,t,n,r,i,a){let o=e.length,s=a*90,c=0,l=()=>{let t=w[e.charCodeAt(c++)];return t=a&&(t=t*91-s+w[e.charCodeAt(c++)]);let n=f[t];if(n<0){let e=p[t],n=e+m[t];for(;e%#%&}*%}(%}9%}/%})%}*%}*%}?&}&%}3%}&*#%})%#%#)}#&#-#+*%E%%'%'#%}#*V##&##I}#&&##%&%#&&Qf%%))w/0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function be(e){return(e|k)-O.LOWER_A>>>0<=25}function xe(e){return e===O.EQUALS||be(e)||ve(e)}var Se;(function(e){e[e.EntityStart=0]=`EntityStart`,e[e.NumericStart=1]=`NumericStart`,e[e.NumericDecimal=2]=`NumericDecimal`,e[e.NumericHex=3]=`NumericHex`,e[e.NamedEntity=4]=`NamedEntity`})(Se||(Se={}));var Ce;(function(e){e[e.Legacy=0]=`Legacy`,e[e.Strict=1]=`Strict`,e[e.Attribute=2]=`Attribute`})(Ce||(Ce={}));function we(e,t,n,r){let i=(t&T.BRANCH_LENGTH)>>7,a=t&T.JUMP_TABLE;if(a){if(i===0)return r===a?n:-1;let t=r-a;if(t>>>0>=i)return-1;let o=e[n+t];return o===0?-1:n+i+o-1&65535}if(i===0)return-1;let o=i+1>>1,s=n+o+i;for(let t=0;t>1)]>>((t&1)<<3)&255;if(i===r)return s+e[n+o+t]&65535;if(i>r)return-1}return-1}function Te(e,t,n){return n===1?String.fromCharCode(e[t]&T.VALUE_MASK):n===2?String.fromCharCode(e[t+1]):String.fromCharCode(e[t+1],e[t+2])}function Ee(e,t,n){let r=t+1,i=0,a=r;if(r>>0>9)break;i=i*10+t,r+=1}if(r===a)return 0;r1114111&&(i=1114112);let o=r-t;return o>=he&&(ge=o,o=he),o<>7;do{let c=i+1,d=e.charCodeAt(c),f,p;if(d===O.NUM){let n=Ee(e,c,a);f=_e(n),t&&f>0&&e.charCodeAt(c+f-1)!==O.SEMI&&(f=0),p=f===0?``:ce(n&me)}else if(be(d)){f=0,p=``;let n=d-l,i;if(n>>>0>7;if(n===0){if(e.charCodeAt(h)!==t)break trie;i+=1}else{let a=e.charCodeAt(h)-t;if(a>>>0>=n)break trie;let o=r[i+1+a];if(o===0)break trie;i=i+n+o&65535}if(m=r[i],h+=1,h>=a)break trie}if((m&(T.VALUE_LENGTH|T.FLAG13))===T.FLAG13){let t=(m&T.BRANCH_LENGTH)>>7;if(e.charCodeAt(h)!==(m&T.JUMP_TABLE))break;h+=1;let n=t-1,a=i+1,o=0;for(;o+1>8&255)))break trie;h+=1,a+=1}if(o>1),m=r[i];continue}let n=m>>>14,l=e.charCodeAt(h);if(n!==0){if(l===O.SEMI){f=h-c+1,p=n===1?String.fromCharCode(m&T.VALUE_MASK):Te(r,i,n);break}if(!t&&(m&T.FLAG13)===0&&(f=h-c,o=i,s=n),n===1)break}let u=we(r,m,i+(n||1),l);if(u<0)break;i=u,m=r[i],h+=1}if(p===``){let e=m>>>14;e!==0&&!t&&(m&T.FLAG13)===0&&(f=h-c,o=i,s=e),f>0&&(p=Te(r,o,s))}}else f=0,p=``;f===0||n&&d!==O.NUM&&e.charCodeAt(c+f-1)!==O.SEMI&&c+f=0);return s+e.slice(o)}function Oe(e){return De(e,!0,!1)}var ke=t({arrayReplaceAt:()=>je,asciiTrim:()=>R,callable:()=>Ae,escapeHtml:()=>M,escapeRE:()=>Ue,fromCodePoint:()=>A,isMdAsciiPunct:()=>I,isPunctChar:()=>We,isPunctCharCode:()=>F,isSpace:()=>N,isValidEntityCode:()=>Me,isWhiteSpace:()=>P,lib:()=>Ke,normalizeReference:()=>L,unescapeAll:()=>j,unescapeMd:()=>Le});function Ae(e){let t=function(...n){return Reflect.construct(e,n,new.target&&new.target!==t?new.target:e)};return Object.defineProperty(t,"name",{value:e.name}),Object.setPrototypeOf(t,e),t.prototype=e.prototype,t}function je(e,t,n){return[].concat(e.slice(0,t),n,e.slice(t+1))}function Me(e){return!(e>=55296&&e<=57343||e>=64976&&e<=65007||(e&65535)==65535||(e&65535)==65534||e>=0&&e<=8||e===11||e>=14&&e<=31||e>=127&&e<=159||e>1114111)}function A(e){if(e>65535){e-=65536;let t=55296+(e>>10),n=56320+(e&1023);return String.fromCharCode(t,n)}return String.fromCharCode(e)}var Ne=/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g,Pe=RegExp(`${Ne.source}|&([a-z#][a-z0-9]{1,31});`,`gi`),Fe=/^#((?:x[a-f0-9]{1,8}|[0-9]{1,8}))$/i;function Ie(e,t){if(t.charCodeAt(0)===35&&Fe.test(t)){let n=t[1].toLowerCase()===`x`?parseInt(t.slice(2),16):parseInt(t.slice(1),10);return Me(n)?A(n):e}let n=Oe(e);return n===e?e:n}function Le(e){return e.indexOf(`\\`)<0?e:e.replace(Ne,`$1`)}function j(e){return e.indexOf(`\\`)<0&&e.indexOf(`&`)<0?e:e.replace(Pe,function(e,t,n){return t||Ie(e,n)})}var Re=/[&<>"]/,ze=/[&<>"]/g,Be={"&":`&`,"<":`<`,">":`>`,'"':`"`};function Ve(e){return Be[e]}function M(e){return Re.test(e)?e.replace(ze,Ve):e}var He=/[.?*+^$[\]\\(){}|-]/g;function Ue(e){return e.replace(He,`\\$&`)}function N(e){switch(e){case 9:case 32:return!0}return!1}function P(e){if(e>=8192&&e<=8202)return!0;switch(e){case 9:case 10:case 11:case 12:case 13:case 32:case 160:case 5760:case 8239:case 8287:case 12288:return!0}return!1}function We(e){return ne.test(e)||re.test(e)}function F(e){return We(A(e))}function I(e){switch(e){case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:case 42:case 43:case 44:case 45:case 46:case 47:case 58:case 59:case 60:case 61:case 62:case 63:case 64:case 91:case 92:case 93:case 94:case 95:case 96:case 123:case 124:case 125:case 126:return!0;default:return!1}}function L(e){return e=e.trim().replace(/\s+/g,` `),e.toLowerCase().toUpperCase()}function Ge(e){return e===32||e===9||e===10||e===13}function R(e){let t=0;for(;t=t&&Ge(e.charCodeAt(n));n--);return e.slice(t,n+1)}var Ke={mdurl:x,ucmicro:S};function qe(e,t,n){let r,i,a,o,s=e.posMax,c=e.pos;for(e.pos=t+1,r=1;e.pos32))return a;if(r===41){if(o===0)break;o--}i++}return t===i||o!==0||(a.str=j(e.slice(t,i)),a.pos=i,a.ok=!0),a}function Ye(e,t,n,r){let i,a=t,o={ok:!1,can_continue:!1,pos:0,str:``,marker:0};if(r)o.str=r.str,o.marker=r.marker;else{if(a>=n)return o;let r=e.charCodeAt(a);if(r!==34&&r!==39&&r!==40)return o;t++,a++,r===40&&(r=41),o.marker=r}for(;aJe,parseLinkLabel:()=>qe,parseLinkTitle:()=>Ye}),z=class{constructor(e,t,n){D(this,`map`,null),D(this,`level`,0),D(this,`children`,null),D(this,`content`,``),D(this,`markup`,``),D(this,`info`,``),D(this,`block`,!1),D(this,`hidden`,!1),this.type=e,this.tag=t,this.attrs=null,this.nesting=n,this.meta=null}attrIndex(e){if(!this.attrs)return-1;let t=this.attrs;for(let n=0,r=t.length;n=0&&(n=this.attrs[t][1]),n}attrJoin(e,t){let n=this.attrIndex(e);n<0?this.attrPush([e,t]):this.attrs[n][1]=`${this.attrs[n][1]} ${t}`}},B=class{constructor(){D(this,`__rules__`,[]),D(this,`__cache__`,null)}__find__(e){for(let t=0;t{t.enabled&&t.alt.forEach(t=>{t&&e.add(t)})}),this.__cache__=Object.create(null),this.__cache__[``]=[],this.__rules__.forEach(e=>{e.enabled&&this.__cache__[``].push(e.fn)}),e.forEach(e=>{this.__cache__[e]=[],this.__rules__.forEach(t=>{t.enabled&&t.alt.indexOf(e)>=0&&this.__cache__[e].push(t.fn)})})}at(e,t,n={}){let r=this.__find__(e);if(r===-1)throw Error(`Parser rule not found: ${e}`);this.__rules__[r].fn=t,this.__rules__[r].alt=n.alt||[],this.__cache__=null}before(e,t,n,r={}){let i=this.__find__(e);if(i===-1)throw Error(`Parser rule not found: ${e}`);this.__rules__.splice(i,0,{name:t,enabled:!0,fn:n,alt:r.alt||[]}),this.__cache__=null}after(e,t,n,r={}){let i=this.__find__(e);if(i===-1)throw Error(`Parser rule not found: ${e}`);this.__rules__.splice(i+1,0,{name:t,enabled:!0,fn:n,alt:r.alt||[]}),this.__cache__=null}push(e,t,n={}){this.__rules__.push({name:e,enabled:!0,fn:t,alt:n.alt||[]}),this.__cache__=null}enable(e,t=!1){Array.isArray(e)||(e=[e]);let n=[];return e.forEach(e=>{let r=this.__find__(e);if(r<0){if(t)return;throw Error(`Rules manager: invalid rule name ${e}`)}this.__rules__[r].enabled=!0,n.push(e)}),this.__cache__=null,n}enableOnly(e,t=!1){Array.isArray(e)||(e=[e]),this.__rules__.forEach(e=>{e.enabled=!1}),this.enable(e,t)}disable(e,t=!1){Array.isArray(e)||(e=[e]);let n=[];return e.forEach(e=>{let r=this.__find__(e);if(r<0){if(t)return;throw Error(`Rules manager: invalid rule name ${e}`)}this.__rules__[r].enabled=!1,n.push(e)}),this.__cache__=null,n}getRules(e){return this.__cache__||this.__compile__(),this.__cache__[e]||[]}},V={};V.code_inline=function(e,t,n,r,i){let a=e[t];return`${M(a.content)}`},V.code_block=function(e,t,n,r,i){let a=e[t];return`${M(e[t].content)}\n`},V.fence=function(e,t,n,r,i){let a=e[t],o=a.info?j(a.info).trim():``,s=``,c=``;if(o){let e=o.split(/(\s+)/g);s=e[0],c=e.slice(2).join(``)}let l;if(l=n.highlight&&n.highlight(a.content,s,c)||M(a.content),l.indexOf(`${l}\n`}return`
${l}
\n`},V.image=function(e,t,n,r,i){let a=e[t];return a.attrs[a.attrIndex(`alt`)][1]=i.renderInlineAsText(a.children,n,r),i.renderToken(e,t,n)},V.hardbreak=function(e,t,n){return n.xhtmlOut?`
+`:`
+`},V.softbreak=function(e,t,n){return n.breaks?n.xhtmlOut?`
+`:`
+`:` +`},V.text=function(e,t){return M(e[t].content)},V.html_block=function(e,t){return e[t].content},V.html_inline=function(e,t){return e[t].content};var Ze=class{constructor(){D(this,`rules`,Object.assign({},V))}renderAttrs(e){let t,n,r;if(!e.attrs)return``;for(r=``,t=0,n=e.attrs.length;t=0&&e[a].hidden&&e[a].nesting===0;)a--;r.block&&r.nesting!==-1&&a>=0&&e[a].hidden&&e[a].nesting===-1&&(i+=` +`),i+=(r.nesting===-1?` +`:`>`,i}renderInline(e,t,n){let r=``,i=this.rules;for(let a=0,o=e.length;a\s]/i.test(e)}function ot(e){return/^<\/a\s*>/i.test(e)}function st(e){let t=e.tokens;if(e.md.options.linkify)for(let n=0,r=t.length;n=0;t--){let n=r[t];if(n.type===`link_close`)for(t--;r[t].level!==n.level&&r[t].type!==`link_open`;)t--;else if(n.type===`html_inline`&&(at(n.content)&&a>0&&a--,ot(n.content)&&a++),!(a>0)&&n.type===`text`&&e.md.linkify.test(n.content)){let a=n.content,o=e.md.linkify.match(a),s=[],c=n.level,l=0;o.length>0&&o[0].index===0&&t>0&&r[t-1].type===`text_special`&&(o=o.slice(1));for(let t=0;tl){let t=new e.Token(`text`,``,0);t.content=a.slice(l,u),t.level=c,s.push(t)}let d=new e.Token(`link_open`,`a`,1);d.attrs=[[`href`,r]],d.level=c++,d.markup=`linkify`,d.info=`auto`,s.push(d);let f=new e.Token(`text`,``,0);f.content=i,f.level=c,s.push(f);let p=new e.Token(`link_close`,`a`,-1);p.level=--c,p.markup=`linkify`,p.info=`auto`,s.push(p),l=o[t].lastIndex}if(l0){let e=r.length;for(let t of i)e+=t.nodes.length-1;let a=Array(e),o=0,s=0;i.reverse();for(let e=0;e=0;n--){let r=e[n];r.type===`text`&&!t&&(r.content=r.content.replace(ut,ft)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function mt(e){let t=0;for(let n=e.length-1;n>=0;n--){let r=e[n];r.type===`text`&&!t&&ct.test(r.content)&&(r.content=r.content.replace(/\+-/g,`±`).replace(/\.{2,}/g,`…`).replace(/([?!])…/g,`$1..`).replace(/([?!]){4,}/g,`$1$1$1`).replace(/,{2,}/g,`,`).replace(/(^|[^-])---(?=[^-]|$)/gm,`$1—`).replace(/(^|\s)--(?=\s|$)/gm,`$1–`).replace(/(^|[^-\s])--(?=[^-\s]|$)/gm,`$1–`)),r.type===`link_open`&&r.info===`auto`&&t--,r.type===`link_close`&&r.info===`auto`&&t++}}function ht(e){let t;if(e.md.options.typographer)for(t=e.tokens.length-1;t>=0;t--)e.tokens[t].type===`inline`&&(lt.test(e.tokens[t].content)&&pt(e.tokens[t].children),ct.test(e.tokens[t].content)&&mt(e.tokens[t].children))}var gt=/['"]/,_t=/['"]/g,vt=`’`,yt=1e3;function bt(e,t,n){for(;e.length>n;){let n=e.pop();n.isSingleQuote?t.single=n.prevSameQuoteIdx:t.double=n.prevSameQuoteIdx}}function H(e,t,n,r){e[t]||(e[t]=[]),e[t].push({pos:n,ch:r})}function xt(e,t){let n=``,r=0;t.sort((e,t)=>e.pos-t.pos);for(let i=0;i=0&&!(r[n].level<=c);n--);if(bt(r,i,n+1),s.type!==`text`)continue;let l=s.content,u=0,d=l.length;OUTER:for(;u=0)h=l.charCodeAt(s.index-1);else for(n=o-1;n>=0&&e[n].type!==`softbreak`&&e[n].type!==`hardbreak`;n--)if(e[n].content){h=e[n].content.charCodeAt(e[n].content.length-1);break}let g=32;if(u=48&&h<=57&&(p=f=!1),f&&p&&(f=_,p=v),!f&&!p)m&&H(a,o,s.index,vt);else{if(p&&(n=m?i.single:i.double,n>=0&&r[n].level===c)){let e=r[n],c,l;m?(c=t.md.options.quotes[2],l=t.md.options.quotes[3]):(c=t.md.options.quotes[0],l=t.md.options.quotes[1]),H(a,o,s.index,l),H(a,e.tokenIdx,e.contentPos,c),bt(r,i,n);continue OUTER}if(f){if(r.length>=yt)return;r.push({tokenIdx:o,contentPos:s.index,isSingleQuote:m,level:c,prevSameQuoteIdx:m?i.single:i.double}),m?i.single=r.length-1:i.double=r.length-1}else p&&m&&H(a,o,s.index,vt)}}}Object.keys(a).forEach(function(t){let n=Number(t);e[n].content=xt(e[n].content,a[t])})}function Ct(e){if(e.md.options.typographer)for(let t=e.tokens.length-1;t>=0;t--)e.tokens[t].type===`inline`&>.test(e.tokens[t].content)&&St(e.tokens[t].children,e)}function wt(e){let t,n,r=e.length;for(t=0;t0&&this.level++,this.tokens.push(r),r}isEmpty(e){return this.bMarks[e]+this.tShift[e]>=this.eMarks[e]}skipEmptyLines(e){for(let t=this.lineMax;et;)if(!N(this.src.charCodeAt(--e)))return e+1;return e}skipChars(e,t){for(let n=this.src.length;en;)if(t!==this.src.charCodeAt(--e))return e+1;return e}getLines(e,t,n,r){if(e>=t)return``;let i=Array(t-e);for(let a=0,o=e;on?i[a]=Array(e-n+1).join(` `)+this.src.slice(c,l):i[a]=this.src.slice(c,l)}return i.join(``)}},kt=65536;function At(e,t){let n=e.bMarks[t]+e.tShift[t],r=e.eMarks[t];return e.src.slice(n,r)}function jt(e){let t=[],n=e.length,r=0,i=e.charCodeAt(r),a=!1,o=0,s=``;for(;rn)return!1;let i=t+1;if(e.sCount[i]=4)return!1;let a=e.bMarks[i]+e.tShift[i];if(a>=e.eMarks[i])return!1;let o=e.src.charCodeAt(a++);if(o!==124&&o!==45&&o!==58||a>=e.eMarks[i])return!1;let s=e.src.charCodeAt(a++);if(s!==124&&s!==45&&s!==58&&!N(s)||o===45&&N(s))return!1;for(;a=4)return!1;l=jt(c),l.length&&l[0]===``&&l.shift(),l.length&&l[l.length-1]===``&&l.pop();let d=l.length;if(d===0||d!==u.length)return!1;if(r)return!0;let f=e.parentType;e.parentType=`table`;let p=e.md.block.ruler.getRules(`blockquote`),m=e.push(`table_open`,`table`,1),h=[t,0];m.map=h;let g=e.push(`thead_open`,`thead`,1);g.map=[t,t+1];let _=e.push(`tr_open`,`tr`,1);_.map=[t,t+1];for(let t=0;t=4||(l=jt(c),l.length&&l[0]===``&&l.shift(),l.length&&l[l.length-1]===``&&l.pop(),y+=d-l.length,y>kt))break;if(i===t+2){let n=e.push(`tbody_open`,`tbody`,1);n.map=v=[t+2,0]}let a=e.push(`tr_open`,`tr`,1);a.map=[i,i+1];for(let t=0;t=4)r++,i=r;else break;e.line=i;let a=e.push(`code_block`,`code`,0);return a.content=e.getLines(t,i,4+e.blkIndent,!1)+` +`,a.map=[t,e.line],!0}function Pt(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4||i+3>a)return!1;let o=e.src.charCodeAt(i);if(o!==126&&o!==96)return!1;let s=i;i=e.skipChars(i,o);let c=i-s;if(c<3)return!1;let l=e.src.slice(s,i),u=e.src.slice(i,a);if(o===96&&u.indexOf(String.fromCharCode(o))>=0)return!1;if(r)return!0;let d=t,f=!1;for(;d++,!(d>=n||(i=s=e.bMarks[d]+e.tShift[d],a=e.eMarks[d],i=4)&&(i=e.skipChars(i,o),!(i-s=4||e.src.charCodeAt(i)!==62)return!1;if(r)return!0;let s=[],c=[],l=[],u=[],d=e.md.block.ruler.getRules(`blockquote`),f=e.parentType;e.parentType=`blockquote`;let p=!1,m;for(m=t;m=a)break;if(e.src.charCodeAt(i++)===62&&!t){let t=e.sCount[m]+1,n,r;e.src.charCodeAt(i)===32?(i++,t++,r=!1,n=!0):e.src.charCodeAt(i)===9?(n=!0,(e.bsCount[m]+t)%4==3?(i++,t++,r=!1):r=!0):n=!1;let o=t;for(s.push(e.bMarks[m]),e.bMarks[m]=i;i=a,c.push(e.bsCount[m]),e.bsCount[m]=e.sCount[m]+1+ +!!n,l.push(e.sCount[m]),e.sCount[m]=o-t,u.push(e.tShift[m]),e.tShift[m]=i-e.bMarks[m];continue}if(p)break;let r=!1;for(let t=0,i=d.length;t`;let _=[t,0];g.map=_,e.md.block.tokenize(e,t,m);let v=e.push(`blockquote_close`,`blockquote`,-1);v.markup=`>`,e.lineMax=o,e.parentType=f,_[1]=e.line;for(let n=0;n=4)return!1;let a=e.bMarks[t]+e.tShift[t],o=e.src.charCodeAt(a++);if(o!==42&&o!==45&&o!==95)return!1;let s=1;for(;a=r)return-1;let a=e.src.charCodeAt(i++);if(a<48||a>57)return-1;for(;;){if(i>=r)return-1;if(a=e.src.charCodeAt(i++),a>=48&&a<=57){if(i-n>=10)return-1}else{if(a===41||a===46)break;return-1}}return i=4||e.listIndent>=0&&e.sCount[c]-e.listIndent>=4&&e.sCount[c]=e.blkIndent&&(u=!0);let d,f,p;if((p=Rt(e,c))>=0){if(d=!0,o=e.bMarks[c]+e.tShift[c],f=Number(e.src.slice(o,p-1)),u&&f!==1)return!1}else if((p=Lt(e,c))>=0)d=!1;else return!1;if(u&&e.skipSpaces(p)>=e.eMarks[c])return!1;if(r)return!0;let m=e.src.charCodeAt(p-1),h=e.tokens.length;d?(s=e.push(`ordered_list_open`,`ol`,1),f!==1&&(s.attrs=[[`start`,f]])):s=e.push(`bullet_list_open`,`ul`,1);let g=[c,0];s.map=g,s.markup=String.fromCharCode(m);let _=!1,v=e.md.block.ruler.getRules(`list`),y=e.parentType;for(e.parentType=`list`;c=i?1:r-t,f>4&&(f=1);let h=t+f;s=e.push(`list_item_open`,`li`,1),s.markup=String.fromCharCode(m);let g=[c,0];s.map=g,d&&(s.info=e.src.slice(o,p-1));let y=e.tight,b=e.tShift[c],x=e.sCount[c],S=e.listIndent;if(e.listIndent=e.blkIndent,e.blkIndent=h,e.tight=!0,e.tShift[c]=u-e.bMarks[c],e.sCount[c]=r,u>=i&&e.isEmpty(c+1)?e.line=Math.min(e.line+2,n):e.md.block.tokenize(e,c,n),(!e.tight||_)&&(l=!1),_=e.line-c>1&&e.isEmpty(e.line-1),e.blkIndent=e.listIndent,e.listIndent=S,e.tShift[c]=b,e.sCount[c]=x,e.tight=y,s=e.push(`list_item_close`,`li`,-1),s.markup=String.fromCharCode(m),c=e.line,g[1]=c,c>=n||e.sCount[c]=4)break;let C=!1;for(let t=0,r=v.length;t56319)continue;let i=e.charCodeAt(n+1);i>=56320&&i<=57343&&(t--,n++)}return t}function U(e,t){return Math.min(e.eMarks[t]+1,e.src.length)}function W(e,t){let n=e.lineMax;if(t>=n||e.isEmpty(t))return-1;let r=!1;if(e.sCount[t]-e.blkIndent>3&&(r=!0),e.sCount[t]<0&&(r=!0),!r){let r=e.md.block.ruler.getRules(`reference`),i=e.parentType;e.parentType=`reference`;let a=!1;for(let i=0,o=r.length;i=4||i.charCodeAt(a)!==91)return!1;let s=U(e,t),c=``,l=-1,u=++a;for(;aVt*2)return!1;let t=i.charCodeAt(a);if(t===91)return!1;if(t===93){l=a;break}if(t===92&&(t=i.charCodeAt(++a)),t===10&&aVt&&Ht(c)>Vt))return!1;for(a=l+2;a\`\\x00-\\x20]+|'[^']*'|"[^"]*"))?)*\\s*\\/?>`,Kt=`<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>`;RegExp(`^(?:${Gt}|${Kt}||<[?][\\s\\S]*?[?]>|]*>|)`);var qt=RegExp(`^(?:${Gt}|${Kt})`),G=[[/^<(script|pre|style|textarea)(?=(\s|>|$))/i,/<\/(script|pre|style|textarea)>/i,!0],[/^/,!0],[/^<\?/,/\?>/,!0],[/^/,!0],[/^/,!0],[RegExp(`^|$))`,`i`),/^$/,!0],[RegExp(`${qt.source}\\s*$`),/^$/,!1]];function Jt(e,t,n,r){let i=e.bMarks[t]+e.tShift[t],a=e.eMarks[t];if(e.sCount[t]-e.blkIndent>=4||!e.md.options.html||e.src.charCodeAt(i)!==60)return!1;let o=e.src.slice(i,a),s=0;for(;s=4)return!1;let o=e.src.charCodeAt(i);if(o!==35||i>=a)return!1;let s=1;for(o=e.src.charCodeAt(++i);o===35&&i6||ii&&N(e.src.charCodeAt(c-1))&&(a=c),e.line=t+1;let l=e.push(`heading_open`,`h${s}`,1);l.markup=`########`.slice(0,s),l.map=[t,e.line];let u=e.push(`inline`,``,0);u.content=R(e.src.slice(i,a)),u.map=[t,e.line],u.children=[];let d=e.push(`heading_close`,`h${s}`,-1);return d.markup=`########`.slice(0,s),!0}function Xt(e,t,n){let r=e.md.block.ruler.getRules(`paragraph`);if(e.sCount[t]-e.blkIndent>=4)return!1;let i=e.parentType;e.parentType=`paragraph`;let a=0,o,s=t+1;for(;s3)continue;if(e.sCount[s]>=e.blkIndent){let t=e.bMarks[s]+e.tShift[s],n=e.eMarks[s];if(t=n))){a=o===61?1:2;break}}if(e.sCount[s]<0)continue;let t=!1;for(let i=0,a=r.length;i3||e.sCount[a]<0)continue;let t=!1;for(let i=0,o=r.length;i=n||e.sCount[o]=a){e.line=n;break}let t=e.line,c=!1;for(let a=0;a=e.line)throw Error(`block rule didn't increment state.line`);break}if(!c)throw Error(`none of the block rules matched`);e.tight=!s,e.isEmpty(e.line-1)&&(s=!0),o=e.line,o0&&(this.level++,this._prev_delimiters.push(this.delimiters),this.delimiters=[],i={delimiters:this.delimiters}),this.pendingLevel=this.level,this.tokens.push(r),this.tokens_meta.push(i),r}scanDelims(e,t){let n=this.posMax,r=this.src.charCodeAt(e),i;if(e===0)i=32;else if(e===1)i=this.src.charCodeAt(0),(i&63488)==55296&&(i=65533);else if(i=this.src.charCodeAt(e-1),(i&64512)==56320){let t=this.src.charCodeAt(e-2);i=(t&64512)==55296?65536+(t-55296<<10)+(i-56320):65533}else(i&64512)==55296&&(i=65533);let a=e;for(;a=65&&e<=90||e>=97&&e<=122}function rn(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===45||e===46}function an(e,t){if(!e.md.options.linkify||e.linkLevel>0)return!1;let n=e.pos,r=e.posMax;if(n+3>r||e.src.charCodeAt(n)!==58||e.src.charCodeAt(n+1)!==47||e.src.charCodeAt(n+2)!==47)return!1;let i=n-Math.min(10,e.pending.length,n),a=n;for(;a>i&&rn(e.src.charCodeAt(a-1));)a--;if(a===n||!nn(e.src.charCodeAt(a)))return!1;let o=n-a,s=e.md.linkify.matchAtStart(e.src.slice(a));if(!s)return!1;let c=s.url;if(c.length<=o)return!1;let l=c.length;for(;l>0&&c.charCodeAt(l-1)===42;)l--;l!==c.length&&(c=c.slice(0,l));let u=e.md.normalizeLink(c);if(!e.md.validateLink(u))return!1;if(!t){e.pending=e.pending.slice(0,-o);let t=e.push(`link_open`,`a`,1);t.attrs=[[`href`,u]],t.markup=`linkify`,t.info=`auto`;let n=e.push(`text`,``,0);n.content=e.md.normalizeLinkText(c);let r=e.push(`link_close`,`a`,-1);r.markup=`linkify`,r.info=`auto`}return e.pos+=c.length-o,!0}function on(e,t){let n=e.pos;if(e.src.charCodeAt(n)!==10)return!1;let r=e.pending.length-1,i=e.posMax;if(!t){if(r>=0&&e.pending.charCodeAt(r)===32){if(r>=1&&e.pending.charCodeAt(r-1)===32){let t=r-1;for(;t>=1&&e.pending.charCodeAt(t-1)===32;)t--;e.pending=e.pending.slice(0,t),e.push(`hardbreak`,`br`,0)}else e.pending=e.pending.slice(0,-1),e.push(`softbreak`,`br`,0)}else e.push(`softbreak`,`br`,0)}for(n++;n?@[]^_\`{|}~-`.split(``).forEach(function(e){sn[e.charCodeAt(0)]=1});function cn(e,t){let n=e.pos,r=e.posMax;if(e.src.charCodeAt(n)!==92||(n++,n>=r))return!1;let i=e.src.charCodeAt(n);if(i===10){for(t||e.push(`hardbreak`,`br`,0),n++;n=55296&&i<=56319&&n+1=56320&&t<=57343&&(a+=e.src[n+1],n++)}let o=`\\`+a;if(!t){let t=e.push(`text_special`,``,0);t.content=i<256&&sn[i]!==0?a:o,t.markup=o,t.info=`escape`}return e.pos=n+1,!0}function ln(e){let t={},n=0;for(;(n=e.indexOf("`",n))!==-1;){let r=n;for(;e.charCodeAt(++n)===96;);t[n-r]=r}return t}function un(e,t){var n;let r=e.pos;if(e.src.charCodeAt(r)!==96)return!1;let i=e.posMax,a=r+1;for(;a=a){let n=a,r;for(;(r=e.src.indexOf("`",n))!==-1&&ri)break;if(n-r===s){if(!t){let t=e.push(`code_inline`,`code`,0);t.markup=o;let n=e.src.slice(a,r).replace(/\n/g,` `);n.startsWith(` `)&&n.endsWith(` `)&&/[^ ]/.test(n)&&(n=n.slice(1,-1)),t.content=n}return e.pos=n,!0}}}return t||(e.pending+=o),e.pos=a,!0}function dn(e,t){let n=e.pos,r=e.src.charCodeAt(n);if(t||r!==126)return!1;let i=e.scanDelims(e.pos,!0),a=i.length,o=String.fromCharCode(r);if(a<2)return!1;let s;a%2&&(s=e.push(`text`,``,0),s.content=o,a--);for(let t=0;t=0;r--){let n=t[r];if(n.marker!==95&&n.marker!==42||n.end===-1)continue;let i=t[n.end],a=r>0&&t[r-1].end===n.end+1&&t[r-1].marker===n.marker&&t[r-1].token===n.token-1&&t[n.end+1].token===i.token+1,o=String.fromCharCode(n.marker),s=e.tokens[n.token];s.type=a?`strong_open`:`em_open`,s.tag=a?`strong`:`em`,s.nesting=1,s.markup=a?o+o:o,s.content=``;let c=e.tokens[i.token];c.type=a?`strong_close`:`em_close`,c.tag=a?`strong`:`em`,c.nesting=-1,c.markup=a?o+o:o,c.content=``,a&&(e.tokens[t[r-1].token].content=``,e.tokens[t[n.end+1].token].content=``,r--)}}function _n(e){let t=e.tokens_meta,n=e.tokens_meta.length;gn(e,e.delimiters);for(let i=0;i=d)return!1;if(c=m,i=e.md.helpers.parseLinkDestination(e.src,m,e.posMax),i.ok){for(o=e.md.normalizeLink(i.str),e.md.validateLink(o)?m=i.pos:o=``,c=m;m=d||e.src.charCodeAt(m)!==41)&&(l=!0),m++}if(l){if(e.env.references===void 0)return!1;if(m=0?r=e.src.slice(c,m++):m=p+1):m=p+1,r||(r=e.src.slice(f,p)),r=L(r),a=e.env.references[r],!a)return e.pos=u,!1;o=a.href,s=a.title}if(!t){e.pos=f,e.posMax=p;let t=e.push(`link_open`,`a`,1),n=[[`href`,o]];if(t.attrs=n,s&&n.push([`title`,s]),r){let e=Object.create(null);e.label=r,t.meta=e}e.linkLevel++,e.md.inline.tokenize(e),e.linkLevel--,e.push(`link_close`,`a`,-1)}return e.pos=m,e.posMax=d,!0}function bn(e,t){let n,r,i,a,o,s,c,l,u=``,d=e.pos,f=e.posMax;if(e.src.charCodeAt(e.pos)!==33||e.src.charCodeAt(e.pos+1)!==91)return!1;let p=e.pos+2,m=e.md.helpers.parseLinkLabel(e,e.pos+1,!1);if(m<0)return!1;if(a=m+1,a=f)return!1;for(l=a,s=e.md.helpers.parseLinkDestination(e.src,a,e.posMax),s.ok&&(u=e.md.normalizeLink(s.str),e.md.validateLink(u)?a=s.pos:u=``),l=a;a=f||e.src.charCodeAt(a)!==41)return e.pos=d,!1;a++}else{if(e.env.references===void 0)return!1;if(a=0?i=e.src.slice(l,a++):a=m+1):a=m+1,i||(i=e.src.slice(p,m)),i=L(i),o=e.env.references[i],!o)return e.pos=d,!1;u=o.href,c=o.title}if(!t){r=e.src.slice(p,m);let t=[];e.md.inline.parse(r,e.md,e.env,t);let n=e.push(`image`,`img`,0),a=[[`src`,u],[`alt`,``]];if(n.attrs=a,n.children=t,n.content=r,c&&a.push([`title`,c]),i){let e=Object.create(null);e.label=i,n.meta=e}}return e.pos=a,e.posMax=f,!0}var xn=/^([a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/,Sn=/^([a-zA-Z][a-zA-Z0-9+.-]{1,31}):([^<>\x00-\x20]*)$/;function Cn(e,t){let n=e.pos;if(e.src.charCodeAt(n)!==60)return!1;let r=e.pos,i=e.posMax;for(;;){if(++n>=i)return!1;let t=e.src.charCodeAt(n);if(t===60)return!1;if(t===62)break}let a=e.src.slice(r+1,n);if(Sn.test(a)){let n=e.md.normalizeLink(a);if(!e.md.validateLink(n))return!1;if(!t){let t=e.push(`link_open`,`a`,1);t.attrs=[[`href`,n]],t.markup=`autolink`,t.info=`auto`;let r=e.push(`text`,``,0);r.content=e.md.normalizeLinkText(a);let i=e.push(`link_close`,`a`,-1);i.markup=`autolink`,i.info=`auto`}return e.pos+=a.length+2,!0}if(xn.test(a)){let n=e.md.normalizeLink(`mailto:${a}`);if(!e.md.validateLink(n))return!1;if(!t){let t=e.push(`link_open`,`a`,1);t.attrs=[[`href`,n]],t.markup=`autolink`,t.info=`auto`;let r=e.push(`text`,``,0);r.content=e.md.normalizeLinkText(a);let i=e.push(`link_close`,`a`,-1);i.markup=`autolink`,i.info=`auto`}return e.pos+=a.length+2,!0}return!1}function wn(e){return/^\s]/i.test(e)}function Tn(e){return/^<\/a\s*>/i.test(e)}function En(e){let t=e|32;return t>=97&&t<=122}function Dn(e,t){let n=e.src,r,i;if(n.startsWith(``}else if(n.startsWith(``;else if(n.charCodeAt(t+1)===63)r=t+2,i=`?>`;else if(En(n.charCodeAt(t+2)))r=t+3,i=`>`;else return-1;if(e.skipHtmlSpecial)return-1;let a=n.indexOf(i,r);return a<0?(e.skipHtmlSpecial=!0,-1):a+i.length}function On(e,t){if(!e.md.options.html)return!1;let n=e.posMax,r=e.pos;if(e.src.charCodeAt(r)!==60||r+2>=n)return!1;let i,a=e.src.charCodeAt(r+1);if(a===33||a===63)i=Dn(e,r);else if(a===47||En(a)){let t=e.src.slice(r).match(qt);i=t?r+t[0].length:-1}else return!1;if(i<0)return!1;if(!t){let t=e.push(`html_inline`,``,0);t.content=e.src.slice(r,i),wn(t.content)&&e.linkLevel++,Tn(t.content)&&e.linkLevel--}return e.pos=i,!0}var kn=/^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i,An=/^&([a-z][a-z0-9]{1,31});/i;function jn(e,t){let n=e.pos,r=e.posMax;if(e.src.charCodeAt(n)!==38||n+1>=r)return!1;if(e.src.charCodeAt(n+1)===35){let r=e.src.slice(n).match(kn);if(r){if(!t){let t=r[1][0].toLowerCase()===`x`?parseInt(r[1].slice(1),16):parseInt(r[1],10),n=e.push(`text_special`,``,0);n.content=Me(t)?A(t):A(65533),n.markup=r[0],n.info=`entity`}return e.pos+=r[0].length,!0}}else{let r=e.src.slice(n).match(An);if(r){let n=Oe(r[0]);if(n!==r[0]){if(!t){let t=e.push(`text_special`,``,0);t.content=n,t.markup=r[0],t.info=`entity`}return e.pos+=r[0].length,!0}}}return!1}function Mn(e){let t={},n=e.length;if(!n)return;let r=0,i=-2,a=[];for(let o=0;os;c-=a[c]+1){let t=e[c];if(t.marker===n.marker&&t.open&&t.end<0){let r=!1;if((t.close||n.open)&&(t.length+n.length)%3==0&&(t.length%3!=0||n.length%3!=0)&&(r=!0),!r){let r=c>0&&!e[c-1].open?a[c-1]+1:0;a[o]=o-c+r,a[c]=r,n.open=!1,t.end=o,t.close=!1,l=-1,i=-2;break}}}l!==-1&&(t[n.marker][(n.open?3:0)+(n.length||0)%3]=l)}}function Nn(e){let t=e.tokens_meta,n=e.tokens_meta.length;Mn(e.delimiters);for(let e=0;e0&&r++,i[t].type===`text`&&t+1=e.pos)throw Error(`inline rule didn't increment state.pos`);break}}else e.pos=e.posMax;o||e.pos++,a[t]=e.pos}tokenize(e){let t=this.ruler.getRules(``),n=t.length,r=e.posMax,i=e.md.options.maxNesting;for(;e.pos=e.pos)throw Error(`inline rule didn't increment state.pos`);break}}if(o){if(e.pos>=r)break}else e.pending+=e.src[e.pos++]}e.pending&&e.pushPending()}parse(e,t,n,r){let i=new this.State(e,t,n,r);this.tokenize(i);let a=this.ruler2.getRules(``),o=a.length;for(let e=0;e<\uff5c]/:t}get_pseudo_letter(){var e,t;return(t=(e=this.cache).src_pseudo_letter)==null?e.src_pseudo_letter=RegExp(`(?:(?!${this.get_text_separators().source}|${this.src_ZPCc})${this.src_Any})`):t}get_ipv4_addr(){var e,t;return(t=(e=this.cache).src_ip4)==null?e.src_ip4=RegExp(`(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])[.]){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])`):t}get_ipv6_addr(){var e,t;let n=`[0-9A-Fa-f]{1,4}`,r=`(?:(?:${n}:${n})|${this.get_ipv4_addr().source})`;return(t=(e=this.cache).src_ip6_addr)==null?e.src_ip6_addr=RegExp(`(?:(?:${n}:){6}${r}|::(?:${n}:){5}${r}|(?:${n})?::(?:${n}:){4}${r}|(?:(?:${n}:){0,1}${n})?::(?:${n}:){3}${r}|(?:(?:${n}:){0,2}${n})?::(?:${n}:){2}${r}|(?:(?:${n}:){0,3}${n})?::${n}:${r}|(?:(?:${n}:){0,4}${n})?::${r}|(?:(?:${n}:){0,5}${n})?::${n}|(?:(?:${n}:){0,6}${n})?::)`):t}get_ipv6_url_host(){var e,t;return(t=(e=this.cache).src_ip6_host)==null?e.src_ip6_host=RegExp(`\\[${this.get_ipv6_addr().source}\\]`):t}get_ipv6_mail_host(){var e,t;return(t=(e=this.cache).src_ipv6_mail_host)==null?e.src_ipv6_mail_host=RegExp(`\\[IPv6:${this.get_ipv6_addr().source}\\]`):t}get_auth(){var e,t;return(t=(e=this.cache).src_auth)==null?e.src_auth=RegExp(`(?:(?:(?!${this.src_ZCc}|[@/\\[\\]()]).){1,50}@)?`):t}get_port(){var e,t;return(t=(e=this.cache).src_port)==null?e.src_port=RegExp(`(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?`):t}get_host_terminator(){var e,t;return(t=(e=this.cache).src_host_terminator)==null?e.src_host_terminator=RegExp(`(?=$|${this.get_text_separators().source}|${this.src_ZPCc})(?!${this.opts[`---`]?`-(?!--)|`:`-|`}_|:\\d|\\.-|\\.(?!$|${this.src_ZPCc}))`):t}get_path_terminator(){var e,t;return(t=(e=this.cache).src_path_terminator)==null?e.src_path_terminator=RegExp(`${this.src_ZPCc}|${this.get_text_separators().source}`):t}get_path(){var e,t;return(t=(e=this.cache).src_path)==null?e.src_path=RegExp(`(?:[/?#](?:${this.nestedPairRE(`[`,`]`)}|${this.nestedPairRE(`(`,`)`)}|${this.nestedPairRE(`{`,`}`)}|\\"(?:(?!${this.src_ZCc}|["]).){1,100}\\"|\\'(?:(?!${this.src_ZCc}|[']).){1,100}\\'|\\'(?=${this.get_pseudo_letter().source}|[-])|\\.{2,20}[:]?[a-zA-Z0-9%/&]|\\.(?!${this.src_ZCc}|[.]|$)|`+(this.opts[`---`]?`\\-(?!--(?:[^-]|$))(?:-{0,19})|`:`\\-{1,20}|`)+`,(?!${this.src_ZCc}|$)|;(?!${this.src_ZCc}|$)|\\!{1,20}(?!${this.src_ZCc}|[!]|$)|\\?(?!${this.src_ZCc}|[?]|$)|`+this.get_path_extra().source+`[\\\\/:%@#&=_~*]|(?!${this.get_path_terminator().source}).){1,${this.opts.maxLength}}|\\/)?`):t}get_mail_name(){var e,t;return(t=(e=this.cache).src_mail_name)==null?e.src_mail_name=RegExp("[-!#$%&'*+/=?^_`{|}~a-zA-Z0-9](?:[-!#$%&'*+/=?^_`{|}~a-zA-Z0-9]|[.](?=[-!#$%&'*+/=?^_`{|}~a-zA-Z0-9])){0,63}"):t}get_xn(){var e,t;return(t=(e=this.cache).src_xn)==null?e.src_xn=RegExp(`xn--[a-z0-9\\-]{1,59}`):t}get_tld(){if(this.cache.tld)return this.cache.tld;let e=[...new Set(this.opts.tlds||[])].sort().reverse().join(`|`);return this.cache.tld=RegExp(`${e||`$#none#$`}|${this.get_xn().source}`),this.cache.tld}get_domain_root(){var e,t;return(t=(e=this.cache).src_domain_root)==null?e.src_domain_root=RegExp(`(?:`+this.get_xn().source+`|${this.get_pseudo_letter().source}{1,63})`):t}get_domain(){var e,t;return(t=(e=this.cache).src_domain)==null?e.src_domain=RegExp(`(?:`+this.get_xn().source+`|(?:${this.get_pseudo_letter().source})|(?:${this.get_pseudo_letter().source}(?:-|${this.get_pseudo_letter().source}){0,61}${this.get_pseudo_letter().source}))`):t}get_url_host_port(){var e,t;return(t=(e=this.cache).url_host_port)==null?e.url_host_port=RegExp(`(?:`+this.get_ipv6_url_host().source+`|(?:(?:(?:${this.get_domain().source})\\.){0,10}${this.get_domain().source}))`+this.get_port().source+this.get_host_terminator().source):t}get_fuzzy_url_host_port(){var e,t;return(t=(e=this.cache).fuzzy_url_host_port)==null?e.fuzzy_url_host_port=RegExp(`(?:`+(this.opts.fuzzyIP?this.get_ipv4_addr().source+`|`:``)+`(?:(?:(?:${this.get_domain().source})\\.){1,10}(?:${this.get_tld().source})))`+this.get_host_terminator().source):t}get_mail_host(){var e,t;return(t=(e=this.cache).src_mail_host)==null?e.src_mail_host=RegExp(`(?:`+this.get_ipv6_mail_host().source+`|(?:(?:(?:${this.get_domain().source})\\.){0,4}${this.get_domain().source}))`+this.get_host_terminator().source):t}get_fuzzy_mail_host(){var e,t;return(t=(e=this.cache).src_fuzzy_mail_host)==null?e.src_fuzzy_mail_host=RegExp(`(?:`+this.get_ipv6_mail_host().source+`|(?:(?:(?:${this.get_domain().source})[.]){1,4}${this.get_domain_root().source}))`+this.get_host_terminator().source):t}get_path_extra(){var e,t;return(t=(e=this.cache).src_path_extra)==null?e.src_path_extra=RegExp(``):t}get_fuzzy_mail_host_search(){var e,t;return(t=(e=this.cache).mail_fuzzy_host_search)==null?e.mail_fuzzy_host_search=RegExp(`@${this.get_fuzzy_mail_host().source}`,`ig`):t}get_fuzzy_link_search(){var e,t;return(t=(e=this.cache).link_fuzzy_search)==null?e.link_fuzzy_search=RegExp(`(^|(?![.:/\\-_@])(?:[$+<=>^\`|\uff5c]|${this.src_ZPCc}))(?:(?![$+<=>^\`|\uff5c])${this.get_fuzzy_url_host_port().source}${this.get_path().source})`,`ig`):t}get_http_validator(){var e,t;return(t=(e=this.cache).http_validator)==null?e.http_validator=RegExp(`\\/\\/`+(this.opts.urlAuth?this.get_auth().source:``)+this.get_url_host_port().source+this.get_path().source,`iy`):t}get_relative_proto_validator(){var e,t;return(t=(e=this.cache).relative_proto_validator)==null?e.relative_proto_validator=RegExp((this.opts.urlAuth?this.get_auth().source:``)+`(?:localhost|${this.get_ipv6_url_host().source}|(?:(?:${this.get_domain().source})[.]){1,10}${this.get_domain_root().source})`+this.get_port().source+this.get_host_terminator().source+this.get_path().source,`iy`):t}get_mail_name_validator(){var e,t;return(t=(e=this.cache).mail_name_validator)==null?e.mail_name_validator=RegExp(`(?:^|${this.get_text_separators().source}|"|\\(|${this.src_ZCc})(${this.get_mail_name().source})$`):t}get_mailto_validator(){var e,t;return(t=(e=this.cache).mailto_validator)==null?e.mailto_validator=RegExp(`${this.get_mail_name().source}@${this.get_mail_host().source}`,`iy`):t}get_schema_names(){var e,t;return(t=(e=this.cache).schema_names)==null?e.schema_names=new RegExp((this.opts.schema_names||[]).map(e=>this.escapeRE(e)).join(`|`)):t}get_schema_search(){var e,t;return(t=(e=this.cache).schema_search)==null?e.schema_search=RegExp(`(^|(?!_)(?:[><\uff5c]|${this.src_ZPCc}))(${this.get_schema_names().source})`,`ig`):t}get_schema_at_start(){var e,t;return(t=(e=this.cache).schema_at_start)==null?e.schema_at_start=RegExp(`^${this.get_schema_search().source}`,`i`):t}},Un={validate:(e,t,n)=>{let r=n.re.get_http_validator();r.lastIndex=t;let i=r.exec(e);return i?i[0].length:0},normalize:(e,t)=>t.normalize(e)},Wn={"http:":Un,"https:":Un,"ftp:":Un,"//":{validate:function(e,t,n){let r=n.re.get_relative_proto_validator();r.lastIndex=t;let i=r.exec(e);return i?t>=3&&e[t-3]===`:`||t>=3&&e[t-3]===`/`?0:i[0].length:0},normalize:(e,t)=>t.normalize(e)},"mailto:":{validate:function(e,t,n){let r=n.re.get_mailto_validator();r.lastIndex=t;let i=r.exec(e);return i?i[0].length:0},normalize:(e,t)=>t.normalize(e)}},Gn=`a:cdefgilmnoqrstuwxz|b:abdefghijmnorstvwyz|c:acdfghiklmnoruvwxyz|d:ejkmoz|e:cegrstu|f:ijkmor|g:abdefghilmnpqrstuwy|h:kmnrtu|i:delmnoqrst|j:emop|k:eghimnprwyz|l:abcikrstuvy|m:acdeghklmnopqrstuvwxyz|n:acefgilopruz|o:m|p:aefghklmnrstwy|q:a|r:eosuw|s:abcdeghijklmnortuvxyz|t:cdfghjklmnortvwz|u:agksyz|v:aceginu|w:fs|y:et|z:amw`,Kn=`biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф`;function qn(){let e=Kn.split(`|`);return Gn.split(`|`).forEach(t=>{let n=t.indexOf(`:`),r=t.slice(0,n);for(let i of t.slice(n+1))e.push(r+i)}),e}var Jn={fuzzyLink:!1,fuzzyEmail:!0,fuzzyIP:!1,"---":!1,tlds:qn(),urlAuth:!1,maxLength:1e4},Yn=class{constructor(e,t,n,r){D(this,`schema`,void 0),D(this,`index`,void 0),D(this,`lastIndex`,void 0),D(this,`raw`,void 0),D(this,`text`,void 0),D(this,`url`,void 0);let i=e.slice(n,r);this.schema=t.toLowerCase(),this.index=n,this.lastIndex=r,this.raw=i,this.text=i,this.url=i}},Xn=class{constructor(e={}){D(this,`__opts__`,void 0),D(this,`__schemas__`,void 0),D(this,`re`,void 0);let{rebuilder:t}=e,n=Bn(e,Vn);this.__opts__=q(q({},Jn),n),this.__schemas__=q({},Wn),this.re=t||new Hn,this.re.set(q(q({},this.__opts__),{},{schema_names:Object.keys(this.__schemas__)}))}add(e,t=null){if(!t)delete this.__schemas__[e];else{let n=q({normalize:(e,t)=>t.normalize(e)},t);this.__schemas__[e]=n}return this.re.set(q(q({},this.__opts__),{},{schema_names:Object.keys(this.__schemas__)})),this}set(e={}){return this.__opts__=q(q({},this.__opts__),e),this.re.set(q(q({},this.__opts__),{},{schema_names:Object.keys(this.__schemas__)})),this}test(e){if(!e.length)return!1;let t,n;for(n=this.re.get_schema_search(),n.lastIndex=0;(t=n.exec(e))!==null;)if(this.testSchemaAt(e,t[2],n.lastIndex))return!0;if(this.__opts__.fuzzyLink&&this.__schemas__[`http:`]&&(n=this.re.get_fuzzy_link_search(),n.lastIndex=0,n.exec(e)!==null))return!0;if(this.__opts__.fuzzyEmail&&this.__schemas__[`mailto:`]&&e.indexOf(`@`)>=0){let n=this.re.get_fuzzy_mail_host_search(),r=this.re.get_mail_name_validator();for(n.lastIndex=0;(t=n.exec(e))!==null;){let n=e.slice(Math.max(0,t.index-65),t.index);if(r.test(n))return!0}}return!1}testSchemaAt(e,t,n){return this.__schemas__[t.toLowerCase()]?this.__schemas__[t.toLowerCase()].validate(e.slice(0,n+this.__opts__.maxLength),n,this):0}match(e){let t=[],n=this.re.get_schema_search(),r,i,a,o,s,c,l=!1,u=!1,d=!1,f=0;if(!e.length)return null;for(n.lastIndex=0,this.__opts__.fuzzyLink&&this.__schemas__[`http:`]&&(r=this.re.get_fuzzy_link_search(),r.lastIndex=0),this.__opts__.fuzzyEmail&&this.__schemas__[`mailto:`]&&(i=this.re.get_fuzzy_mail_host_search(),i.lastIndex=0,a=this.re.get_mail_name_validator());;){let p=Math.max(f-1,0);if(i&&a&&!d&&(!s||s.index=f)break;i.lastIndex=f)break;r.lastIndexm.lastIndex))&&(m=o);let h;if(!l)for(;;){if(!c){n.lastIndexm.index)break;let t=c;c=void 0;let r=this.testSchemaAt(e,t.schema,t.lastIndex);if(r){h={schema:t.schema,index:t.index,lastIndex:t.lastIndex+r};break}}let g=h;if((!g||s&&(s.indexg.lastIndex))&&(g=s),(!g||o&&(o.indexg.lastIndex))&&(g=o),!g)break;g===s?s=void 0:g===o&&(o=void 0);let _=new Yn(e,g.schema,g.index,g.lastIndex);_.schema?this.__schemas__[_.schema].normalize(_,this):this.normalize(_),t.push(_),f=g.lastIndex}return t.length?t:null}matchAtStart(e){if(!e.length)return null;let t=this.re.get_schema_at_start().exec(e);if(!t)return null;let n=this.testSchemaAt(e,t[2],t[0].length);if(!n)return null;let r=new Yn(e,t[2],t.index+t[1].length,t.index+t[0].length+n);return this.__schemas__[r.schema].normalize(r,this),r}tlds(e,t=!1){return e=Array.isArray(e)?e:[e],t?this.__opts__.tlds=this.__opts__.tlds.concat(e):this.__opts__.tlds=e,this.re.set(q(q({},this.__opts__),{},{schema_names:Object.keys(this.__schemas__)})),this}normalize(e){e.schema||(e.url=`http://${e.url}`),e.schema===`mailto:`&&!/^mailto:/i.test(e.url)&&(e.url=`mailto:${e.url}`)}},J=2147483647,Y=36,Zn=1,X=26,Qn=38,$n=700,er=72,tr=128,nr=`-`,rr=/^xn--/,ir=/[^\0-\x7F]/,ar=/[\x2E\u3002\uFF0E\uFF61]/g,or={overflow:`Overflow: input needs wider integers to process`,"not-basic":`Illegal input >= 0x80 (not a basic code point)`,"invalid-input":`Invalid input`},sr=35,Z=Math.floor,cr=String.fromCharCode;function Q(e){throw RangeError(or[e])}function lr(e,t){let n=[],r=e.length;for(;r--;)n[r]=t(e[r]);return n}function ur(e,t){let n=e.split(`@`),r=``;n.length>1&&(r=n[0]+`@`,e=n[1]),e=e.replace(ar,`.`);let i=lr(e.split(`.`),t).join(`.`);return r+i}function dr(e){let t=[],n=0,r=e.length;for(;n=55296&&i<=56319&&nString.fromCodePoint(...e),pr=function(e){return e>=48&&e<58?26+(e-48):e>=65&&e<91?e-65:e>=97&&e<123?e-97:Y},mr=function(e,t){return e+22+75*(e<26)-((t!=0)<<5)},hr=function(e,t,n){let r=0;for(e=n?Z(e/$n):e>>1,e+=Z(e/t);e>455;r+=Y)e=Z(e/sr);return Z(r+36*e/(e+Qn))},gr=function(e){let t=[],n=e.length,r=0,i=tr,a=er,o=e.lastIndexOf(nr);o<0&&(o=0);for(let n=0;n=128&&Q(`not-basic`),t.push(e.charCodeAt(n));for(let s=o>0?o+1:0;s=n&&Q(`invalid-input`);let o=pr(e.charCodeAt(s++));o>=Y&&Q(`invalid-input`),o>Z((J-r)/t)&&Q(`overflow`),r+=o*t;let c=i<=a?Zn:i>=a+X?X:i-a;if(oZ(J/l)&&Q(`overflow`),t*=l}let c=t.length+1;a=hr(r-o,c,o==0),Z(r/c)>J-i&&Q(`overflow`),i+=Z(r/c),r%=c,t.splice(r++,0,i)}return String.fromCodePoint(...t)},_r=function(e){let t=[];e=dr(e);let n=e.length,r=tr,i=0,a=er;for(let n of e)n<128&&t.push(cr(n));let o=t.length,s=o;for(o&&t.push(nr);s=r&&tZ((J-i)/c)&&Q(`overflow`),i+=(n-r)*c,r=n;for(let n of e)if(nJ&&Q(`overflow`),n===r){let e=i;for(let n=Y;;n+=Y){let r=n<=a?Zn:n>=a+X?X:n-a;if(e=0))try{t.hostname=vr.toASCII(t.hostname)}catch(e){}return t.auth&&(t.auth=s(t.auth)),t.hostname&&(t.hostname=s(t.hostname)),t.pathname&&(t.pathname=s(t.pathname)),t.search&&(t.search=s(t.search)),t.hash&&(t.hash=s(t.hash)),c(t)}normalizeLinkText(e){let t=b(e,!0);if(t.hostname&&(!t.protocol||Sr.indexOf(t.protocol)>=0))try{t.hostname=vr.toUnicode(t.hostname)}catch(e){}return i(c(t),i.defaultChars+`%`)}constructor(...e){D(this,`inline`,new Ln),D(this,`block`,new Qt),D(this,`core`,new Dt),D(this,`renderer`,new Ze),D(this,`linkify`,new Xn),D(this,`utils`,ke),D(this,`helpers`,Object.assign({},Xe));let[t,n]=e;typeof t==`string`?(this.configure(t),n&&this.set(n)):(this.configure(`default`),this.set(t||{}))}set(e){return Object.assign(this.options,e),this}configure(e){let t;if(typeof e==`string`){let n=e;if(t=yr[n],!t)throw Error(`Wrong 'markdown-it' preset "${n}", check name`)}else t=e;if(!t)throw Error("Wrong `markdown-it` preset, can't be empty");t.options&&(this.options=q({},t.options));let n=t.components;if(n){var r;[`core`,`block`,`inline`].forEach(e=>{var t;let r=(t=n[e])==null?void 0:t.rules;r&&this[e].ruler.enableOnly(r)});let e=(r=n.inline)==null?void 0:r.rules2;e&&this.inline.ruler2.enableOnly(e)}return this}enable(e,t=!1){let n=[];Array.isArray(e)||(e=[e]),[`core`,`block`,`inline`].forEach(t=>{n=n.concat(this[t].ruler.enable(e,!0))}),n=n.concat(this.inline.ruler2.enable(e,!0));let r=e.filter(e=>n.indexOf(e)<0);if(r.length&&!t)throw Error(`MarkdownIt. Failed to enable unknown rule(s): ${r}`);return this}disable(e,t=!1){let n=[];Array.isArray(e)||(e=[e]),[`core`,`block`,`inline`].forEach(t=>{n=n.concat(this[t].ruler.disable(e,!0))}),n=n.concat(this.inline.ruler2.disable(e,!0));let r=e.filter(e=>n.indexOf(e)<0);if(r.length&&!t)throw Error(`MarkdownIt. Failed to disable unknown rule(s): ${r}`);return this}use(e,...t){return e.apply(e,[this,...t]),this}parse(e,t){if(typeof e!=`string`)throw Error(`Input data should be a String`);let n=new this.core.State(e,this,t);return this.core.process(n),n.tokens}render(e,t={}){return this.renderer.render(this.parse(e,t),this.options,t)}parseInline(e,t){let n=new this.core.State(e,this,t);return n.inlineMode=!0,this.core.process(n),n.tokens}renderInline(e,t={}){return this.renderer.render(this.parseInline(e,t),this.options,t)}};return D($,`Token`,z),D($,`Ruler`,B),D($,`Renderer`,Ze),D($,`ParserCore`,Dt),D($,`StateCore`,Qe),D($,`ParserBlock`,Qt),D($,`StateBlock`,Ot),D($,`ParserInline`,Ln),D($,`StateInline`,$t),Ae($)}); +//# sourceMappingURL=markdown-it.umd.min.js.map \ No newline at end of file diff --git a/src/Gateway.Api/wwwroot/vendor/markdown-it-LICENSE.txt b/src/Gateway.Api/wwwroot/vendor/markdown-it-LICENSE.txt new file mode 100644 index 0000000..7ffa058 --- /dev/null +++ b/src/Gateway.Api/wwwroot/vendor/markdown-it-LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin. + +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/tests/Gateway.SmokeTests/Program.cs b/tests/Gateway.SmokeTests/Program.cs index d5f541a..3fc1fe6 100644 --- a/tests/Gateway.SmokeTests/Program.cs +++ b/tests/Gateway.SmokeTests/Program.cs @@ -126,6 +126,36 @@ Assert(mqttDefaults.Site == new MqttMonitoringSite(2026, "P260123", "ISP3") && var monitoringBatch = store.CreateBulkMappings(new([csvSource.Id, statePoint.Id, alarmPoint.Id], BulkMappingTarget.Mqtt)); Assert(monitoringBatch.Created == 3 && monitoringBatch.Assignments.Any(item => item.Contains("/Alarms/", StringComparison.Ordinal)) && monitoringBatch.Assignments.Any(item => item.Contains("/Notify/", StringComparison.Ordinal)), "Bulk MQTT should use SE-Monitoring by default."); +var oldTopics = store.ListMqttMappings().ToDictionary(mapping => mapping.Id, GatewayStore.GetMqttTopic); +var templateView = store.UpdateMqttTopicTemplate("Anlagen/{Rechnername}/{Kategorie}/{Datenpunkt}"); +Assert(templateView.PreviewValues["{Rechnername}"] == "SE-UGW-P260123-ISP03", "The preview must show the configured installation identity."); +var templatedRequest = new CreateMqttMappingRequest(csvSource.Id, MqttMappingFormat.SeMonitoring, MqttDirection.Publish, + MqttQualityOfService.AtLeastOnce, false, null, "P260123", "ISP3", SeMonitoringCategory.Analog, "Vorlauf", null, null); +var customMapping = store.CreateMqttMapping(templatedRequest); +const string customTopic = "Anlagen/SE-UGW-P260123-ISP03/Analog/Vorlauf"; +Assert(GatewayStore.GetMqttTopic(customMapping) == customTopic && + store.ListMqttMappings().Where(mapping => oldTopics.ContainsKey(mapping.Id)).All(mapping => GatewayStore.GetMqttTopic(mapping) == oldTopics[mapping.Id]), + "A new template must affect new mappings and preserve every previously resolved topic."); +var bulkTemplate = store.UpdateMqttTopicTemplate("Messwerte/{Projekt}/{Datenpunkt}"); +var batchWithTemplate = store.CreateBulkMappings(new([statePoint.Id], BulkMappingTarget.Mqtt)); +Assert(batchWithTemplate.Created == 1 && batchWithTemplate.Assignments.Single().EndsWith("Messwerte/P260123/Pumpe_läuft", StringComparison.Ordinal) && + GatewayStore.GetMqttTopic(store.UpdateMqttMapping(customMapping.Id, templatedRequest with { Retain = true })!) == customTopic, + "Bulk mappings must use the active template while an existing mapping edit keeps its saved path."); +try +{ + store.UpdateMqttTopicTemplate("Messwerte/{Unbekannt}/{Datenpunkt}"); + throw new InvalidOperationException("An unknown MQTT placeholder must be rejected."); +} +catch (DomainValidationException) +{ + Assert(store.GetMqttMappingDefaults().TopicTemplate.Template == bulkTemplate.Template, "Rejected templates must not overwrite the saved template."); +} +var legacyMqttCsv = "Id;PointId;Format;Direction;QualityOfService;Retain;ProjectYear;ProjectNumber;IspNumber;SeCategory;TopicName;JsonTopic;JsonProperty\r\n" + + $";{csvSource.Id};SeMonitoring;Publish;AtLeastOnce;False;2026;P260123;ISP3;Analog;CsvLegacy;;\r\n"; +Assert(store.ImportConfigurationCsv(ConfigurationCsvKind.MqttMappings, legacyMqttCsv).Created == 1 && + store.ListMqttMappings().Any(mapping => GatewayStore.GetMqttTopic(mapping) == "Projekte2026/P260123/ISP3/Analog/CsvLegacy_Wert"), + "MQTT CSVs exported before the template field must continue to resolve legacy paths."); +store.UpdateMqttTopicTemplate(templateView.DefaultTemplate); var rawMqtt = store.CreateMqttMapping(new(csvSource.Id, MqttMappingFormat.SingleTopic, MqttDirection.Publish, MqttQualityOfService.AtLeastOnce, false, null, null, null, null, null, "plant/temperature", null)); Assert(GatewayStore.GetMqttTopic(rawMqtt) == "plant/temperature", "A numeric single-topic mapping must use the specified topic exactly.");