Plugins #14
@@ -52,7 +52,7 @@ jobs:
|
||||
uses: https://github.com/actions/cache@v4
|
||||
with:
|
||||
path: /root/.npm
|
||||
key: npm-linux-${{ hashFiles('package-lock.json', 'server/package-lock.json') }}
|
||||
key: npm-linux-${{ hashFiles('package-lock.json', 'server/package-lock.json', 'docs-site/package-lock.json') }}
|
||||
restore-keys: npm-linux-
|
||||
|
||||
- name: Restore Electron cache
|
||||
@@ -71,6 +71,7 @@ jobs:
|
||||
apt-get update && apt-get install -y --no-install-recommends zip
|
||||
npm ci
|
||||
cd server && npm ci
|
||||
cd ../docs-site && npm ci
|
||||
|
||||
- name: Set CI release version
|
||||
run: >
|
||||
@@ -83,6 +84,7 @@ jobs:
|
||||
cd toju-app
|
||||
npx ng build --configuration production --base-href='./'
|
||||
cd ..
|
||||
npm run build:docs
|
||||
npx --package typescript tsc -p tsconfig.electron.json
|
||||
cd server
|
||||
node ../tools/sync-server-build-version.js
|
||||
@@ -124,7 +126,7 @@ jobs:
|
||||
uses: https://github.com/actions/cache@v4
|
||||
with:
|
||||
path: ~/AppData/Local/npm-cache
|
||||
key: npm-windows-${{ hashFiles('package-lock.json', 'server/package-lock.json') }}
|
||||
key: npm-windows-${{ hashFiles('package-lock.json', 'server/package-lock.json', 'docs-site/package-lock.json') }}
|
||||
restore-keys: npm-windows-
|
||||
|
||||
- name: Restore Electron cache
|
||||
@@ -142,6 +144,7 @@ jobs:
|
||||
run: |
|
||||
npm ci
|
||||
npm ci --prefix server
|
||||
npm ci --prefix docs-site
|
||||
|
||||
- name: Set CI release version
|
||||
run: >
|
||||
@@ -154,6 +157,7 @@ jobs:
|
||||
Push-Location "toju-app"
|
||||
npx ng build --configuration production --base-href='./'
|
||||
Pop-Location
|
||||
npm run build:docs
|
||||
npx --package typescript tsc -p tsconfig.electron.json
|
||||
Push-Location server
|
||||
node ../tools/sync-server-build-version.js
|
||||
@@ -194,6 +198,7 @@ jobs:
|
||||
Copy-Item -Path (Join-Path $projectRoot 'package.json') -Destination (Join-Path $electronBuilderWorkspace 'package.json') -Force
|
||||
Copy-Item -Path (Join-Path $projectRoot 'package-lock.json') -Destination (Join-Path $electronBuilderWorkspace 'package-lock.json') -Force
|
||||
Invoke-RoboCopy (Join-Path $projectRoot 'dist') (Join-Path $electronBuilderWorkspace 'dist')
|
||||
Invoke-RoboCopy (Join-Path $projectRoot 'docs-site/build') (Join-Path $electronBuilderWorkspace 'docs-site/build')
|
||||
Invoke-RoboCopy (Join-Path $projectRoot 'images') (Join-Path $electronBuilderWorkspace 'images')
|
||||
Invoke-RoboCopy (Join-Path $projectRoot 'node_modules') (Join-Path $electronBuilderWorkspace 'node_modules')
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -16,6 +16,7 @@ yarn-error.log
|
||||
dist-electron
|
||||
node_modules/*
|
||||
*server/node_modules/*
|
||||
/docs-site/node_modules/
|
||||
.angular
|
||||
# IDEs and editors
|
||||
.idea/
|
||||
@@ -39,6 +40,8 @@ node_modules/*
|
||||
.sass-cache/
|
||||
/connect.lock
|
||||
/coverage
|
||||
/docs-site/.docusaurus/
|
||||
/docs-site/build/
|
||||
/libpeerconnection.log
|
||||
testem.log
|
||||
/typings
|
||||
|
||||
@@ -13,13 +13,15 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
|
||||
| `server/` | Signaling server, server-directory API, and websocket runtime | [server/README.md](server/README.md) |
|
||||
| `e2e/` | Playwright end-to-end coverage for the product client | [e2e/README.md](e2e/README.md) |
|
||||
| `website/` | Angular 19 marketing site served separately from the product client | [website/README.md](website/README.md) |
|
||||
| `docs-site/` | Docusaurus app and plugin documentation served by the Electron Local API | [docs-site/docs/intro.md](docs-site/docs/intro.md) |
|
||||
|
||||
## Install
|
||||
|
||||
1. Run `npm install` from the repository root.
|
||||
2. Run `cd server && npm install` for the server package.
|
||||
3. If you need to work on the marketing site, run `cd website && npm install`.
|
||||
4. Copy `.env.example` to `.env`.
|
||||
4. If you need to work on the Docusaurus docs, run `cd docs-site && npm install`.
|
||||
5. Copy `.env.example` to `.env`.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -36,8 +38,9 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
|
||||
- `npm run electron:dev` starts the Angular product client and Electron together.
|
||||
- `npm run server:dev` starts only the server with reload.
|
||||
- `npm run build` builds the Angular product client to `dist/client`.
|
||||
- `npm run build:docs` builds the Docusaurus documentation site to `docs-site/build`.
|
||||
- `npm run build:electron` builds the Electron code to `dist/electron`.
|
||||
- `npm run build:all` builds the product client, Electron, and server.
|
||||
- `npm run build:all` builds the product client, Docusaurus docs, Electron, and server.
|
||||
- `npm run test` runs the product-client Vitest suite.
|
||||
- `npm run lint` runs ESLint across the repo.
|
||||
- `npm run lint:fix` formats Angular templates, sorts template properties, and applies ESLint fixes.
|
||||
@@ -54,6 +57,7 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
|
||||
| `server/src/` | Express app, websocket runtime, config, CQRS, and persistence layers |
|
||||
| `e2e/` | Playwright tests, helpers, fixtures, and page objects |
|
||||
| `website/src/` | Marketing-site pages, assets, and SSR entry points |
|
||||
| `docs-site/` | Docusaurus source for Electron-hosted application and plugin documentation |
|
||||
| `tools/` | Build, release, formatting, and packaging scripts |
|
||||
|
||||
## Product Client Docs
|
||||
|
||||
75
docs-site/docs/desktop-and-local-api.md
Normal file
75
docs-site/docs/desktop-and-local-api.md
Normal file
@@ -0,0 +1,75 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Desktop and Local API
|
||||
|
||||
## Electron Hosting Model
|
||||
|
||||
The desktop app hosts local documentation through the existing Electron Local API server. This server is implemented with Node's `http` module in the Electron main process and uses async request handlers for routing, file reads, and streamed responses.
|
||||
|
||||
The endpoint is manually activated. Opening the Docusaurus docs from the desktop title bar enables the local server and docs endpoint if necessary, then opens the system browser to the generated static site.
|
||||
|
||||
This avoids:
|
||||
|
||||
- starting a Docusaurus development server inside Electron;
|
||||
- blocking the renderer thread;
|
||||
- serving docs from a remote host;
|
||||
- exposing the endpoint unless the user chooses to activate it.
|
||||
|
||||
## Local Server Settings
|
||||
|
||||
| Setting | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | `false` | Starts or stops the local HTTP server. |
|
||||
| `port` | `17878` | Listening port. |
|
||||
| `exposeOnLan` | `false` | Uses `127.0.0.1` by default; when true, binds to `0.0.0.0`. |
|
||||
| `scalarEnabled` | `false` | Enables `/docs` for the Scalar OpenAPI reference. |
|
||||
| `docusaurusEnabled` | `false` | Enables `/docusaurus` for the built Docusaurus documentation. |
|
||||
| `allowedSignalingServers` | `[]` | Server URLs allowed for Local API login. |
|
||||
|
||||
## Routes
|
||||
|
||||
| Endpoint | Purpose | Auth |
|
||||
| --- | --- | --- |
|
||||
| `GET /api/health` | Liveness, app version, timestamp, and LAN exposure status. | No |
|
||||
| `GET /api/openapi.json` | OpenAPI 3.1 document for local automation clients. | No |
|
||||
| `GET /docs` | Scalar API reference when Scalar docs are enabled. | No |
|
||||
| `GET /docusaurus` | Docusaurus documentation entrypoint when Docusaurus docs are enabled. | No |
|
||||
| `GET /docusaurus/*` | Static Docusaurus assets and pages. | No |
|
||||
| `POST /api/auth/login` | Exchanges username, password, and allowed signaling server URL for a local bearer token. | No |
|
||||
| `POST /api/auth/logout` | Revokes the current local bearer token. | Bearer |
|
||||
| `GET /api/profile` | Reads the current local user profile. | Bearer |
|
||||
| `GET /api/rooms` | Lists rooms known to this device. | Bearer |
|
||||
| `GET /api/rooms/{roomId}/messages` | Reads local room messages with `limit` and `offset`. | Bearer |
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
1. Add trusted signaling server URLs in desktop settings.
|
||||
2. Start the Local API server.
|
||||
3. Call `POST /api/auth/login` with `username`, `password`, and `serverUrl`.
|
||||
4. MetoYou validates credentials through the signaling server.
|
||||
5. The desktop app issues an opaque local bearer token.
|
||||
6. Use `Authorization: Bearer <token>` for protected routes.
|
||||
|
||||
Bearer tokens are local to the running desktop app and are cleared when the Local API server stops.
|
||||
|
||||
## Static Documentation Build
|
||||
|
||||
Docusaurus is a static site generator. The repo builds `docs-site/` into `docs-site/build/`, and Electron serves those files from the local API server.
|
||||
|
||||
Development commands:
|
||||
|
||||
```bash
|
||||
cd docs-site
|
||||
npm install
|
||||
npm run start
|
||||
```
|
||||
|
||||
Build command:
|
||||
|
||||
```bash
|
||||
npm run build:docs
|
||||
```
|
||||
|
||||
Packaged desktop builds include the generated static output as an Electron extra resource.
|
||||
87
docs-site/docs/developer/contributing.md
Normal file
87
docs-site/docs/developer/contributing.md
Normal file
@@ -0,0 +1,87 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Contributing
|
||||
|
||||
MetoYou is an npm-managed monorepo.
|
||||
|
||||
## Packages
|
||||
|
||||
| Path | Purpose |
|
||||
| --- | --- |
|
||||
| `toju-app/` | Angular renderer, chat client, voice UI, plugin runtime. |
|
||||
| `electron/` | Electron main process, preload bridge, local database, local REST API, docs host. |
|
||||
| `server/` | Node/TypeScript signaling server and server-directory HTTP API. |
|
||||
| `website/` | Angular marketing site. |
|
||||
| `docs-site/` | Docusaurus documentation site. |
|
||||
| `e2e/` | Playwright browser and WebRTC tests. |
|
||||
|
||||
## Setup
|
||||
|
||||
Install root dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
Install server dependencies when working on the signaling server:
|
||||
|
||||
```bash
|
||||
cd server
|
||||
npm install
|
||||
```
|
||||
|
||||
## Development Commands
|
||||
|
||||
From the repository root:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Useful focused commands:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm run build:electron
|
||||
npm run build:docs
|
||||
npm run server:build
|
||||
npm run lint
|
||||
npm run test
|
||||
npm run test:e2e -- tests/chat-dm-flow.spec.ts
|
||||
```
|
||||
|
||||
Run the Docusaurus dev server:
|
||||
|
||||
```bash
|
||||
cd docs-site
|
||||
npm install
|
||||
npm run start
|
||||
```
|
||||
|
||||
Build static docs for Electron packaging:
|
||||
|
||||
```bash
|
||||
npm run build:docs
|
||||
```
|
||||
|
||||
## Repository Rules
|
||||
|
||||
- Keep changes inside the package that owns the behavior.
|
||||
- Do not edit generated output in `dist/`, `dist-electron/`, `dist-server/`, `server/dist/`, `.angular/`, or `node_modules/`.
|
||||
- Renderer-facing Electron capabilities must stay aligned across implementation, preload, and renderer bridge types.
|
||||
- Signal-server plugin support stores metadata only. Plugin execution belongs to the client runtime.
|
||||
- Update this documentation when user workflows, plugin APIs, REST routes, DOM structure, or development commands change.
|
||||
|
||||
## Documentation Checklist
|
||||
|
||||
When you change a related area, update these pages:
|
||||
|
||||
| Change | Docs to check |
|
||||
| --- | --- |
|
||||
| Voice UI or settings | User Guide: Voice Channels and Calls, Developer Guide: App Pages and DOM Structure. |
|
||||
| Text channels, messages, DMs | User Guide: Text and Direct Messages, plugin message API pages. |
|
||||
| Plugin manifest/API/runtime | Plugin Development pages and LLM Plugin Builder Guide. |
|
||||
| Local REST API routes or schemas | Developer Guide: Local REST API and `electron/api/openapi.ts`. |
|
||||
| Docusaurus hosting | Developer Guide: Docusaurus Site and Desktop and Local API. |
|
||||
65
docs-site/docs/developer/docusaurus-site.md
Normal file
65
docs-site/docs/developer/docusaurus-site.md
Normal file
@@ -0,0 +1,65 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Docusaurus Site
|
||||
|
||||
The Docusaurus documentation lives in `docs-site/` and builds to static files in `docs-site/build/`.
|
||||
|
||||
## Structure
|
||||
|
||||
```text
|
||||
docs-site/
|
||||
docusaurus.config.ts
|
||||
sidebars.ts
|
||||
docs/
|
||||
intro.md
|
||||
user-guide/
|
||||
developer/
|
||||
plugin-development/
|
||||
src/css/custom.css
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
Use the Docusaurus development server while writing docs:
|
||||
|
||||
```bash
|
||||
cd docs-site
|
||||
npm run start
|
||||
```
|
||||
|
||||
Build the static site:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
From the repo root, use:
|
||||
|
||||
```bash
|
||||
npm run build:docs
|
||||
```
|
||||
|
||||
## Electron Hosting
|
||||
|
||||
Electron serves the built site through the local API server when Docusaurus docs are enabled.
|
||||
|
||||
| Route | Purpose |
|
||||
| --- | --- |
|
||||
| `/docusaurus` | Docusaurus entrypoint. |
|
||||
| `/docusaurus/*` | Static Docusaurus assets and generated pages. |
|
||||
|
||||
The endpoint is off until the user opens documentation from the desktop app or enables it through local API settings. Electron serves static files only; it does not run `docusaurus start`.
|
||||
|
||||
## Sidebar Rules
|
||||
|
||||
Navigation is controlled by `docs-site/sidebars.ts`. Add every new page there unless it is intentionally hidden. Use categories for larger sections so non-technical users can find the user guide separately from developer material.
|
||||
|
||||
## Content Rules
|
||||
|
||||
- User docs should avoid implementation jargon.
|
||||
- Developer docs should name exact files, commands, routes, capabilities, and data shapes.
|
||||
- Plugin API examples should use literal sample input data.
|
||||
- REST docs should stay aligned with `electron/api/openapi.ts` and `electron/api/router.ts`.
|
||||
- DOM docs should stay aligned with Angular routes and component selectors.
|
||||
145
docs-site/docs/developer/dom-structure.md
Normal file
145
docs-site/docs/developer/dom-structure.md
Normal file
@@ -0,0 +1,145 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# App Pages and DOM Structure
|
||||
|
||||
This page maps the app routes and important DOM areas. It is useful for plugin authors, testers, and contributors who need stable mental models of where UI mounts.
|
||||
|
||||
## Angular Routes
|
||||
|
||||
| Route | Component | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `/` | Redirect | Redirects to `/search`. |
|
||||
| `/login` | `LoginComponent` | User login. |
|
||||
| `/register` | `RegisterComponent` | User registration. |
|
||||
| `/invite/:inviteId` | `InviteComponent` | Resolve and accept invite links. |
|
||||
| `/search` | `ServerSearchComponent` | Search and join servers. |
|
||||
| `/room/:roomId` | `ChatRoomComponent` | Main server page with text, voice, members, and plugin panels. |
|
||||
| `/dm` | `DmWorkspaceComponent` | Direct-message workspace. |
|
||||
| `/dm/:conversationId` | `DmWorkspaceComponent` | A selected direct-message conversation. |
|
||||
| `/settings` | `SettingsComponent` | App, voice, server, plugin, desktop, theme, local API settings. |
|
||||
| `/plugin-store` | `PluginStoreComponent` | Browse plugin sources and install/update plugins. |
|
||||
| `/plugins/:pluginId/:pageId` | `PluginPageHostComponent` | Host for plugin app pages registered with `api.ui.registerAppPage()`. |
|
||||
|
||||
## Page Shell
|
||||
|
||||
The renderer is an Angular app. The common shell contains router outlet content plus persistent app surfaces such as the server rail, title bar integrations, settings modals, and floating voice controls.
|
||||
|
||||
High-level structure:
|
||||
|
||||
```html
|
||||
<app-root>
|
||||
<router-outlet></router-outlet>
|
||||
<!-- global dialogs, overlays, floating voice controls, and desktop integrations -->
|
||||
</app-root>
|
||||
```
|
||||
|
||||
## Server Page DOM
|
||||
|
||||
The server page is the most important page for plugins.
|
||||
|
||||
```html
|
||||
<app-chat-room>
|
||||
<app-servers-rail></app-servers-rail>
|
||||
<app-rooms-side-panel>
|
||||
<section>Text Channels</section>
|
||||
<section>Voice Channels</section>
|
||||
<section data-testid="plugin-room-side-panel">
|
||||
<app-plugin-render-host></app-plugin-render-host>
|
||||
</section>
|
||||
<section>Members</section>
|
||||
</app-rooms-side-panel>
|
||||
<main>
|
||||
<app-voice-workspace></app-voice-workspace>
|
||||
<app-chat-messages>
|
||||
<app-message-list></app-message-list>
|
||||
<app-typing-indicator></app-typing-indicator>
|
||||
<app-message-composer></app-message-composer>
|
||||
<app-klipy-gif-picker></app-klipy-gif-picker>
|
||||
</app-chat-messages>
|
||||
</main>
|
||||
</app-chat-room>
|
||||
```
|
||||
|
||||
## Text Channel Area
|
||||
|
||||
Text channel UI is owned by the chat domain.
|
||||
|
||||
```html
|
||||
<app-chat-messages>
|
||||
<app-message-list>
|
||||
<app-message-item></app-message-item>
|
||||
</app-message-list>
|
||||
<app-message-overlays></app-message-overlays>
|
||||
<app-typing-indicator></app-typing-indicator>
|
||||
<app-message-composer></app-message-composer>
|
||||
</app-chat-messages>
|
||||
```
|
||||
|
||||
Plugin touchpoints:
|
||||
|
||||
- `api.ui.registerComposerAction()` adds composer actions.
|
||||
- `api.ui.registerEmbedRenderer()` renders declared custom embed payloads.
|
||||
- `api.ui.mountElement()` can mount into a selector such as `app-chat-messages` when the plugin has `ui.dom`.
|
||||
|
||||
## Voice Area
|
||||
|
||||
Voice UI is split between channel membership, controls, and media workspace.
|
||||
|
||||
```html
|
||||
<app-rooms-side-panel>
|
||||
<section>Voice Channels</section>
|
||||
</app-rooms-side-panel>
|
||||
<app-voice-controls></app-voice-controls>
|
||||
<app-floating-voice-controls></app-floating-voice-controls>
|
||||
<app-voice-workspace>
|
||||
<app-voice-workspace-stream-tile></app-voice-workspace-stream-tile>
|
||||
</app-voice-workspace>
|
||||
```
|
||||
|
||||
Plugin touchpoints:
|
||||
|
||||
- `api.media.playAudioClip()` plays local audio.
|
||||
- `api.media.addCustomAudioStream()` contributes audio to voice handling.
|
||||
- `api.media.addCustomVideoStream()` contributes a video stream.
|
||||
- `api.channels.addAudioChannel()` creates a voice channel entry when the plugin has channel management rights.
|
||||
|
||||
## Plugin Store and Manager DOM
|
||||
|
||||
```html
|
||||
<app-plugin-store>
|
||||
<!-- source management, search, plugin cards, install/update/uninstall actions -->
|
||||
</app-plugin-store>
|
||||
|
||||
<app-plugin-manager>
|
||||
<!-- installed plugins, capability grants, activate/reload/unload, logs, docs -->
|
||||
</app-plugin-manager>
|
||||
```
|
||||
|
||||
Plugin pages registered through `api.ui.registerAppPage()` render at `/plugins/:pluginId/:pageId`:
|
||||
|
||||
```html
|
||||
<app-plugin-page-host>
|
||||
<app-plugin-render-host></app-plugin-render-host>
|
||||
</app-plugin-page-host>
|
||||
```
|
||||
|
||||
## Plugin Render Host
|
||||
|
||||
`PluginRenderHostComponent` accepts plugin render functions that return either an `HTMLElement` or a string. Returning an `HTMLElement` is preferred for interactive UI. Returned strings are rendered as simple text content.
|
||||
|
||||
## Stable Selectors for Tests and Plugins
|
||||
|
||||
Prefer plugin APIs over DOM selectors. When direct DOM mounting is necessary, use stable app selectors and keep cleanup through the returned disposable.
|
||||
|
||||
Common targets:
|
||||
|
||||
| Selector | Area |
|
||||
| --- | --- |
|
||||
| `body` | Global overlays or modals. |
|
||||
| `app-chat-messages` | Main text channel surface. |
|
||||
| `app-rooms-side-panel` | Server side panel. |
|
||||
| `[data-testid="plugin-room-side-panel"]` | Plugin side-panel area in the server sidebar. |
|
||||
|
||||
Avoid depending on Tailwind utility classes; they are layout details and may change.
|
||||
1432
docs-site/docs/developer/llm-plugin-builder-guide.md
Normal file
1432
docs-site/docs/developer/llm-plugin-builder-guide.md
Normal file
File diff suppressed because it is too large
Load Diff
300
docs-site/docs/developer/rest-api.md
Normal file
300
docs-site/docs/developer/rest-api.md
Normal file
@@ -0,0 +1,300 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Local REST API
|
||||
|
||||
The MetoYou desktop app exposes an optional local HTTP API for scripts and tools. It is implemented in Electron and reads local desktop data.
|
||||
|
||||
## Enable the API
|
||||
|
||||
1. Open Settings.
|
||||
2. Open Local API settings.
|
||||
3. Enable the local server.
|
||||
4. Choose a port. The default is `17878`.
|
||||
5. Add trusted signaling server URLs for authentication.
|
||||
6. Enable Scalar docs if you want `/docs`.
|
||||
7. Enable Docusaurus docs if you want `/docusaurus`.
|
||||
|
||||
By default the server binds to `127.0.0.1`. Only enable LAN exposure when you understand the risk.
|
||||
|
||||
## Authentication
|
||||
|
||||
Protected routes require a bearer token. Get one by posting username, password, and an allowed signaling server URL.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/auth/login \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"username": "alice",
|
||||
"password": "correct horse battery staple",
|
||||
"serverUrl": "https://tojusignal.example.com"
|
||||
}'
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{
|
||||
"token": "local_4cddf95c5b8c4b6f9e0c",
|
||||
"expiresAt": 1777477200000,
|
||||
"user": {
|
||||
"id": "user-alice-01",
|
||||
"username": "alice",
|
||||
"displayName": "Alice"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use the token:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/profile \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
Logout revokes the current token:
|
||||
|
||||
```bash
|
||||
curl -i -X POST http://127.0.0.1:17878/api/auth/logout \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
## OpenAPI and Scalar
|
||||
|
||||
| Route | Auth | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `GET /api/openapi.json` | No | OpenAPI 3.1 document. |
|
||||
| `GET /docs` | No | Scalar API reference when enabled. |
|
||||
|
||||
## Public Routes
|
||||
|
||||
### GET /api/health
|
||||
|
||||
Checks whether the local API server is running.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/health
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "ok",
|
||||
"version": "1.0.0",
|
||||
"timestamp": 1777473600000,
|
||||
"exposeOnLan": false
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/openapi.json
|
||||
|
||||
Returns the machine-readable API document.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/openapi.json
|
||||
```
|
||||
|
||||
### POST /api/auth/login
|
||||
|
||||
Issues a local bearer token after credentials are validated by an allowed signaling server.
|
||||
|
||||
Request body:
|
||||
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"password": "correct horse battery staple",
|
||||
"serverUrl": "https://tojusignal.example.com"
|
||||
}
|
||||
```
|
||||
|
||||
Common errors:
|
||||
|
||||
| Status | Error code | Meaning |
|
||||
| --- | --- | --- |
|
||||
| 400 | `INVALID_REQUEST` | Missing username, password, or server URL. |
|
||||
| 403 | `NO_ALLOWED_SERVERS` | No allowed signaling servers are configured. |
|
||||
| 403 | `SERVER_NOT_ALLOWED` | The server URL is not in the allowed list. |
|
||||
| 401 | `INVALID_CREDENTIALS` | Signaling server rejected the login. |
|
||||
| 502 | `UPSTREAM_UNREACHABLE` | The signaling server could not be reached. |
|
||||
|
||||
## Protected Routes
|
||||
|
||||
All routes below require:
|
||||
|
||||
```http
|
||||
Authorization: Bearer local_4cddf95c5b8c4b6f9e0c
|
||||
```
|
||||
|
||||
### GET /api/profile
|
||||
|
||||
Reads the current local user profile.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/profile \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET /api/rooms
|
||||
|
||||
Lists rooms known to this device.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/rooms \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}`
|
||||
|
||||
Reads one room by id.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75 \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}/users`
|
||||
|
||||
Lists users known for a room.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/users \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}/messages`
|
||||
|
||||
Lists local messages for a room. `limit` defaults to `100` and is clamped from `1` to `500`. `offset` defaults to `0`.
|
||||
|
||||
```bash
|
||||
curl -s 'http://127.0.0.1:17878/api/rooms/room-7ebdde75/messages?limit=50&offset=0' \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}/messages/since`
|
||||
|
||||
Lists local messages after a required timestamp.
|
||||
|
||||
```bash
|
||||
curl -s 'http://127.0.0.1:17878/api/rooms/room-7ebdde75/messages/since?sinceTimestamp=1777470000000' \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}/bans`
|
||||
|
||||
Lists active bans for a room.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/bans \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/rooms/{roomId}/bans/{userId}`
|
||||
|
||||
Checks whether a user is banned in a room.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/bans/user-muse-01 \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{ "isBanned": false }
|
||||
```
|
||||
|
||||
### GET `/api/messages/{messageId}`
|
||||
|
||||
Reads one local message by id.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001 \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/messages/{messageId}/reactions`
|
||||
|
||||
Lists reactions for a message.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001/reactions \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/messages/{messageId}/attachments`
|
||||
|
||||
Lists attachments for a message.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001/attachments \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET `/api/users/{userId}`
|
||||
|
||||
Reads one user by id.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/users/user-muse-01 \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET /api/attachments
|
||||
|
||||
Lists all attachments stored on this device.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/attachments \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
### GET /api/plugin-data
|
||||
|
||||
Reads a plugin data value from the local desktop database. `scope` must be `local` or `server`. Provide `serverId` when reading server-scoped data.
|
||||
|
||||
```bash
|
||||
curl -s 'http://127.0.0.1:17878/api/plugin-data?pluginId=example.soundboard&key=favorites&scope=server&serverId=room-7ebdde75' \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{
|
||||
"value": [
|
||||
{ "label": "Chime", "url": "https://cdn.example.com/chime.wav" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### GET `/api/meta/{key}`
|
||||
|
||||
Reads a desktop metadata value by key.
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:17878/api/meta/metoyou_currentUserId \
|
||||
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
|
||||
```
|
||||
|
||||
Example response:
|
||||
|
||||
```json
|
||||
{
|
||||
"key": "metoyou_currentUserId",
|
||||
"value": "user-alice-01"
|
||||
}
|
||||
```
|
||||
|
||||
## Data Model Notes
|
||||
|
||||
Rooms, users, messages, reactions, attachments, and bans are returned from local desktop persistence. Many schemas allow additional properties because the local database can carry richer app state than the REST docs need to guarantee.
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Keep the API bound to `127.0.0.1` unless LAN access is required.
|
||||
- Only add signaling servers you trust to the allowed list.
|
||||
- Bearer tokens are local to the running desktop app.
|
||||
- Stop the local API server to clear issued tokens.
|
||||
48
docs-site/docs/intro.md
Normal file
48
docs-site/docs/intro.md
Normal file
@@ -0,0 +1,48 @@
|
||||
---
|
||||
slug: /
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# MetoYou Documentation
|
||||
|
||||
MetoYou is a desktop-first chat app with text channels, voice channels, direct messages, plugins, local desktop storage, a local REST API, and a Docusaurus documentation site bundled into the app.
|
||||
|
||||
This site is split into three paths:
|
||||
|
||||
- **User Guide** explains the app in non-technical terms: servers, text channels, voice channels, screen sharing, direct messages, plugins, and desktop settings.
|
||||
- **Developer Guide** explains how to run the repo, how the app is structured, how Docusaurus is served, the app DOM/page structure, and the local REST API.
|
||||
- **Plugin Development** explains how to build plugins, declare capabilities, distribute bundles, and call every exposed plugin API with concrete examples.
|
||||
|
||||
The Electron app can host this documentation locally. The docs endpoint is not a separate web server process: it is served from the same opt-in local HTTP server used for the Local API, and it only serves static files generated by Docusaurus.
|
||||
|
||||
## What Is Included
|
||||
|
||||
| Area | What it covers |
|
||||
| --- | --- |
|
||||
| Product client | Login, server discovery, channels, messages, voice, direct messages, themes, and plugin UI. |
|
||||
| Desktop shell | Window controls, notifications, tray behavior, app data import/export, updates, local plugins, and hosted documentation. |
|
||||
| Local HTTP API | A loopback-first API for local scripts and tools, with OpenAPI and Scalar reference docs. |
|
||||
| Plugin runtime | Browser-safe client plugins with explicit capabilities, lifecycle hooks, UI contributions, data storage, message bus, and server plugin requirements. |
|
||||
|
||||
## Runtime Boundaries
|
||||
|
||||
MetoYou keeps responsibilities split by package:
|
||||
|
||||
- `toju-app/` is the Angular product client and plugin runtime.
|
||||
- `electron/` is the main process, preload bridge, IPC, local persistence, and local HTTP host.
|
||||
- `server/` is the signaling and server-directory service.
|
||||
- `e2e/` contains Playwright coverage for browser and WebRTC workflows.
|
||||
- `docs-site/` is this Docusaurus site.
|
||||
|
||||
The desktop documentation endpoint serves the static `docs-site/build` output. It does not run the Docusaurus development server inside Electron.
|
||||
|
||||
## Fast Links
|
||||
|
||||
- Start using the app: [First Steps](./user-guide/first-steps.md)
|
||||
- Join voice: [Voice Channels and Calls](./user-guide/voice-channels.md)
|
||||
- Install plugins: [Plugins for Users](./user-guide/plugins.md)
|
||||
- Run the repo: [Contributing](./developer/contributing.md)
|
||||
- Understand pages and DOM: [App Pages and DOM Structure](./developer/dom-structure.md)
|
||||
- Use the REST API: [Local REST API](./developer/rest-api.md)
|
||||
- Build a plugin: [Create a Plugin](./plugin-development/create-a-plugin.md)
|
||||
- Give an LLM plugin context: [LLM Plugin Builder Guide](./developer/llm-plugin-builder-guide.md)
|
||||
329
docs-site/docs/plugin-development/api-reference.md
Normal file
329
docs-site/docs/plugin-development/api-reference.md
Normal file
@@ -0,0 +1,329 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Plugin API Reference
|
||||
|
||||
`TojuClientPluginApi` is the object passed to a plugin activation context. The runtime freezes the API object before passing it to plugin code.
|
||||
|
||||
This page is the compact map. Use the focused API pages for concrete copy-paste examples with literal input data.
|
||||
|
||||
## Focused API Pages
|
||||
|
||||
- [Context and Logging](./api/context-and-logging.md)
|
||||
- [Profile API](./api/profile.md)
|
||||
- [Users and Roles API](./api/users-and-roles.md)
|
||||
- [Server API](./api/server.md)
|
||||
- [Channels API](./api/channels.md)
|
||||
- [Messages and Typing API](./api/messages-and-typing.md)
|
||||
- [Events API](./api/events.md)
|
||||
- [Message Bus API](./api/message-bus.md)
|
||||
- [P2P and Media API](./api/p2p-and-media.md)
|
||||
- [Storage API](./api/storage.md)
|
||||
- [UI API](./api/ui.md)
|
||||
|
||||
## Activation Types
|
||||
|
||||
```ts
|
||||
interface TojuPluginDisposable {
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
interface TojuPluginActivationContext {
|
||||
api: TojuClientPluginApi;
|
||||
manifest: TojuPluginManifest;
|
||||
pluginId: string;
|
||||
subscriptions: TojuPluginDisposable[];
|
||||
}
|
||||
|
||||
interface TojuClientPluginModule {
|
||||
activate?: (context: TojuPluginActivationContext) => Promise<void> | void;
|
||||
deactivate?: (context: TojuPluginActivationContext) => Promise<void> | void;
|
||||
onPluginDataChanged?: (context: TojuPluginActivationContext, event: unknown) => Promise<void> | void;
|
||||
onServerRequirementsChanged?: (context: TojuPluginActivationContext, snapshot: PluginRequirementsSnapshot) => Promise<void> | void;
|
||||
ready?: (context: TojuPluginActivationContext) => Promise<void> | void;
|
||||
}
|
||||
```
|
||||
|
||||
## Profiles
|
||||
|
||||
```ts
|
||||
interface PluginApiProfileUpdate {
|
||||
description?: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
interface PluginApiAvatarUpdate {
|
||||
avatarHash: string;
|
||||
avatarMime: string;
|
||||
avatarUrl: string;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `profile.getCurrent()` | `profile.read` | Returns the current `User` or `null`. |
|
||||
| `profile.update(profile)` | `profile.write` | Updates display name and optional description. |
|
||||
| `profile.updateAvatar(avatar)` | `profile.write` | Updates avatar URL, MIME type, and hash metadata. |
|
||||
|
||||
## Users and Roles
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `users.getCurrent()` | `users.read` | Returns current `User` or `null`. |
|
||||
| `users.list()` | `users.read` | Returns known users. |
|
||||
| `users.readMembers()` | `users.read` | Returns active room members. |
|
||||
| `users.setRole(userId, role)` | `roles.manage` | Updates a user's role. |
|
||||
| `users.kick(userId)` | `users.manage` | Kicks a user. |
|
||||
| `users.ban(userId, reason?)` | `users.manage` | Bans a user with optional reason. |
|
||||
| `roles.list()` | `roles.read` | Returns room roles. |
|
||||
| `roles.setAssignments(assignments)` | `roles.manage` | Replaces role assignments. |
|
||||
|
||||
## Server
|
||||
|
||||
```ts
|
||||
interface PluginApiServerSettingsUpdate {
|
||||
description?: string;
|
||||
isPrivate?: boolean;
|
||||
maxUsers?: number;
|
||||
name?: string;
|
||||
password?: string;
|
||||
topic?: string;
|
||||
}
|
||||
|
||||
interface PluginApiPluginUserRequest {
|
||||
avatarUrl?: string;
|
||||
displayName: string;
|
||||
id?: string;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `server.getCurrent()` | `server.read` | Returns the current `Room` or `null`. |
|
||||
| `server.registerPluginUser(request)` | `users.manage` | Adds a plugin-owned user and returns its id. |
|
||||
| `server.updatePermissions(permissions)` | `server.manage` | Updates partial room permissions. |
|
||||
| `server.updateSettings(settings)` | `server.manage` | Updates room settings. |
|
||||
|
||||
## Channels
|
||||
|
||||
```ts
|
||||
interface PluginApiChannelRequest {
|
||||
id?: string;
|
||||
name: string;
|
||||
position?: number;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `channels.list()` | `channels.read` | Returns current room channels. |
|
||||
| `channels.select(channelId)` | `channels.read` | Selects a channel. |
|
||||
| `channels.addAudioChannel(request)` | `channels.manage` | Adds a voice channel. |
|
||||
| `channels.addVideoChannel(request)` | `channels.manage` | Registers a video channel section. |
|
||||
| `channels.rename(channelId, name)` | `channels.manage` | Renames a channel. |
|
||||
| `channels.remove(channelId)` | `channels.manage` | Removes a channel. |
|
||||
|
||||
## Messages
|
||||
|
||||
```ts
|
||||
interface PluginApiMessageAsPluginUserRequest {
|
||||
channelId?: string;
|
||||
content: string;
|
||||
pluginUserId: string;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `messages.readCurrent()` | `messages.read` | Returns current visible messages. |
|
||||
| `messages.send(content, channelId?)` | `messages.send` | Sends a message and returns the created `Message`. |
|
||||
| `messages.sendAsPluginUser(request)` | `messages.send` | Emits a message from a registered plugin user. |
|
||||
| `messages.setTyping(isTyping, channelId?)` | `messages.send` | Broadcasts current typing state for a channel. |
|
||||
| `messages.subscribeTyping(handler)` | `messages.read` | Subscribes to peer typing state. |
|
||||
| `messages.edit(messageId, content)` | `messages.editOwn` | Edits a plugin message. |
|
||||
| `messages.delete(messageId)` | `messages.deleteOwn` | Deletes a plugin message. |
|
||||
| `messages.moderateDelete(messageId)` | `messages.moderate` | Performs a moderation delete. |
|
||||
| `messages.sync(messages)` | `messages.sync` | Syncs an array of messages into state. |
|
||||
|
||||
## Events
|
||||
|
||||
```ts
|
||||
interface PluginApiEventSubscription {
|
||||
eventName: string;
|
||||
handler: (event: PluginEventEnvelope) => void;
|
||||
}
|
||||
|
||||
interface PluginEventEnvelope<TPayload = unknown> {
|
||||
emittedAt?: number;
|
||||
eventId?: string;
|
||||
eventName: string;
|
||||
payload: TPayload;
|
||||
pluginId: string;
|
||||
serverId: string;
|
||||
sourcePluginUserId?: string;
|
||||
sourceUserId?: string;
|
||||
type: 'plugin_event';
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `events.publishServer(eventName, payload)` | `events.server.publish` | Sends a declared plugin event through the signaling server. |
|
||||
| `events.subscribeServer(subscription)` | `events.server.subscribe` | Subscribes to a declared server plugin event. |
|
||||
| `events.publishP2p(eventName, payload)` | `events.p2p.publish` | Sends a declared plugin event over peer paths. |
|
||||
| `events.subscribeP2p(subscription)` | `events.p2p.subscribe` | Registers a P2P event subscription. |
|
||||
|
||||
## Message Bus
|
||||
|
||||
```ts
|
||||
interface PluginApiMessageBusEnvelope {
|
||||
channelId?: string;
|
||||
eventId: string;
|
||||
messages?: Message[];
|
||||
payload?: unknown;
|
||||
pluginId: string;
|
||||
roomId: string;
|
||||
sentAt: number;
|
||||
sourcePeerId?: string;
|
||||
sourceUserId?: string;
|
||||
topic: string;
|
||||
}
|
||||
|
||||
interface PluginApiMessageBusLatestRequest {
|
||||
channelId?: string;
|
||||
includeDeleted?: boolean;
|
||||
limit?: number;
|
||||
sinceTimestamp?: number;
|
||||
targetPeerId?: string;
|
||||
topic?: string;
|
||||
}
|
||||
|
||||
interface PluginApiMessageBusPublishRequest extends PluginApiMessageBusLatestRequest {
|
||||
includeLatestMessages?: boolean;
|
||||
includeSelf?: boolean;
|
||||
payload?: unknown;
|
||||
topic: string;
|
||||
}
|
||||
|
||||
interface PluginApiMessageBusSubscription {
|
||||
channelId?: string;
|
||||
handler: (event: PluginApiMessageBusEnvelope) => void;
|
||||
latestMessageLimit?: number;
|
||||
replayLatest?: boolean;
|
||||
topic?: string;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `messageBus.publish(request)` | `events.p2p.publish`, optionally `messages.read` | Publishes a plugin-bus event, optionally including latest messages. |
|
||||
| `messageBus.sendLatestMessages(request?)` | `events.p2p.publish` and `messages.read` | Sends a latest-message snapshot. |
|
||||
| `messageBus.subscribe(subscription)` | `events.p2p.subscribe`, optionally `messages.read` | Subscribes to plugin-bus events, optionally replaying latest messages. |
|
||||
|
||||
## P2P and Media
|
||||
|
||||
```ts
|
||||
interface PluginApiAudioClipRequest {
|
||||
volume?: number;
|
||||
url: string;
|
||||
}
|
||||
|
||||
interface PluginApiCustomStreamRequest {
|
||||
label?: string;
|
||||
stream: MediaStream;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `p2p.connectedPeers()` | `p2p.data` | Returns connected peer ids. |
|
||||
| `p2p.broadcastData(eventName, payload)` | `p2p.data` | Broadcasts plugin data. |
|
||||
| `p2p.sendData(peerId, eventName, payload)` | `p2p.data` | Sends plugin data targeted to a peer. |
|
||||
| `media.playAudioClip(request)` | `media.playAudio` | Plays an audio URL at optional volume. |
|
||||
| `media.addCustomAudioStream(request)` | `media.addAudioStream` | Contributes an audio `MediaStream`. |
|
||||
| `media.addCustomVideoStream(request)` | `media.addVideoStream` | Registers a video `MediaStream` contribution. |
|
||||
| `media.setInputVolume(volume)` | `audio.volume` | Sets local input volume. |
|
||||
| `media.setOutputVolume(volume)` | `audio.volume` | Sets local output volume. |
|
||||
|
||||
## Storage
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `clientData.read(key)` | `storage.local` | Reads async plugin-local data. |
|
||||
| `clientData.write(key, value)` | `storage.local` | Writes async plugin-local data. |
|
||||
| `clientData.remove(key)` | `storage.local` | Removes async plugin-local data. |
|
||||
| `serverData.read(key)` | `storage.serverData.read` | Reads local per-user/per-server data. |
|
||||
| `serverData.write(key, value)` | `storage.serverData.write` | Writes local per-user/per-server data. |
|
||||
| `serverData.remove(key)` | `storage.serverData.write` | Removes local per-user/per-server data. |
|
||||
| `storage.get(key)` | `storage.local` | Legacy synchronous local read. |
|
||||
| `storage.set(key, value)` | `storage.local` | Legacy synchronous local write. |
|
||||
| `storage.remove(key)` | `storage.local` | Legacy synchronous local remove. |
|
||||
|
||||
## UI Contributions
|
||||
|
||||
```ts
|
||||
interface PluginApiActionContribution {
|
||||
icon?: string;
|
||||
label: string;
|
||||
run: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
interface PluginApiPageContribution {
|
||||
label: string;
|
||||
path: string;
|
||||
render: () => HTMLElement | string;
|
||||
}
|
||||
|
||||
interface PluginApiPanelContribution {
|
||||
label: string;
|
||||
order?: number;
|
||||
render: () => HTMLElement | string;
|
||||
}
|
||||
|
||||
interface PluginApiSettingsPageContribution {
|
||||
label: string;
|
||||
order?: number;
|
||||
render: () => HTMLElement | string;
|
||||
settingsKey?: string;
|
||||
}
|
||||
|
||||
interface PluginApiChannelSectionContribution {
|
||||
label: string;
|
||||
order?: number;
|
||||
type?: 'audio' | 'custom' | 'video';
|
||||
}
|
||||
|
||||
interface PluginApiEmbedRendererContribution {
|
||||
embedType: string;
|
||||
render: (payload: unknown) => HTMLElement | string;
|
||||
}
|
||||
|
||||
interface PluginApiDomMountRequest {
|
||||
element: HTMLElement;
|
||||
position?: InsertPosition;
|
||||
target: Element | string;
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `ui.registerAppPage(id, contribution)` | `ui.pages` | Adds a plugin app page. |
|
||||
| `ui.registerSettingsPage(id, contribution)` | `ui.settings` | Adds a plugin settings page. |
|
||||
| `ui.registerSidePanel(id, contribution)` | `ui.sidePanel` | Adds a side panel. |
|
||||
| `ui.registerChannelSection(id, contribution)` | `ui.channelsSection` | Adds a channel section. |
|
||||
| `ui.registerComposerAction(id, contribution)` | `ui.pages` | Adds a composer action. |
|
||||
| `ui.registerProfileAction(id, contribution)` | `ui.pages` | Adds a profile action. |
|
||||
| `ui.registerToolbarAction(id, contribution)` | `ui.pages` | Adds a toolbar action. |
|
||||
| `ui.registerEmbedRenderer(id, contribution)` | `ui.embeds` | Adds an embed renderer. |
|
||||
| `ui.mountElement(id, request)` | `ui.dom` | Mounts plugin-owned DOM into a target element or selector. |
|
||||
|
||||
## Context and Logger
|
||||
|
||||
| Method | Capability | Description |
|
||||
| --- | --- | --- |
|
||||
| `context.getCurrent()` | None | Reads current user, server, active text channel, and active voice channel. |
|
||||
| `logger.debug(message, data?)` | None | Writes a debug plugin log entry. |
|
||||
| `logger.info(message, data?)` | None | Writes an info plugin log entry. |
|
||||
| `logger.warn(message, data?)` | None | Writes a warning plugin log entry. |
|
||||
| `logger.error(message, data?)` | None | Writes an error plugin log entry. |
|
||||
85
docs-site/docs/plugin-development/api/channels.md
Normal file
85
docs-site/docs/plugin-development/api/channels.md
Normal file
@@ -0,0 +1,85 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Channels API
|
||||
|
||||
The channels API reads, selects, creates, renames, and removes server channels.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `channels.list()` | `channels.read` |
|
||||
| `channels.select(channelId)` | `channels.read` |
|
||||
| `channels.addAudioChannel(request)` | `channels.manage` |
|
||||
| `channels.addVideoChannel(request)` | `channels.manage` |
|
||||
| `channels.rename(channelId, name)` | `channels.manage` |
|
||||
| `channels.remove(channelId)` | `channels.manage` |
|
||||
|
||||
## List Channels
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const channels = context.api.channels.list();
|
||||
|
||||
context.api.logger.info('Channels', channels.map((channel) => ({
|
||||
id: channel.id,
|
||||
name: channel.name,
|
||||
type: channel.type
|
||||
})));
|
||||
}
|
||||
```
|
||||
|
||||
Example channel list:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "id": "general", "name": "general", "type": "text", "position": 0 },
|
||||
{ "id": "support", "name": "support", "type": "text", "position": 1 },
|
||||
{ "id": "lobby", "name": "Lobby", "type": "audio", "position": 10 }
|
||||
]
|
||||
```
|
||||
|
||||
## Select a Channel
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.channels.select('support');
|
||||
}
|
||||
```
|
||||
|
||||
## Add a Voice Channel
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.channels.addAudioChannel({
|
||||
id: 'raid-voice',
|
||||
name: 'Raid Voice',
|
||||
position: 20
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Add a Video Channel Section
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.channels.addVideoChannel({
|
||||
id: 'watch-party-video',
|
||||
name: 'Watch Party',
|
||||
position: 30
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Rename and Remove
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.channels.rename('raid-voice', 'Raid Voice - Tonight');
|
||||
context.api.channels.remove('old-event-room');
|
||||
}
|
||||
```
|
||||
|
||||
Channel creation, rename, and removal should be user-confirmed because they change the shared server structure.
|
||||
73
docs-site/docs/plugin-development/api/context-and-logging.md
Normal file
73
docs-site/docs/plugin-development/api/context-and-logging.md
Normal file
@@ -0,0 +1,73 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Context and Logging
|
||||
|
||||
Context and logging are available to every plugin. They do not require privileged capabilities.
|
||||
|
||||
## context.getCurrent()
|
||||
|
||||
Reads the current interaction context.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const current = context.api.context.getCurrent();
|
||||
|
||||
context.api.logger.info('Current context', {
|
||||
serverName: current.server?.name ?? 'No server open',
|
||||
textChannel: current.textChannel?.name ?? 'No text channel selected',
|
||||
voiceChannel: current.voiceChannel?.name ?? 'Not connected to voice',
|
||||
user: current.user?.displayName ?? 'No user'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example context shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "manual",
|
||||
"server": { "id": "room-7ebdde75", "name": "Friday Game Night" },
|
||||
"textChannel": { "id": "general", "name": "general", "type": "text" },
|
||||
"voiceChannel": { "id": "lobby", "name": "Lobby", "type": "audio" },
|
||||
"user": { "id": "user-alice-01", "displayName": "Alice" }
|
||||
}
|
||||
```
|
||||
|
||||
## Action Context
|
||||
|
||||
Composer, toolbar, and profile actions receive context directly.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerToolbarAction('where-am-i', {
|
||||
label: 'Where am I?',
|
||||
run: (actionContext) => {
|
||||
context.api.logger.info('Toolbar action context', {
|
||||
source: actionContext.source,
|
||||
serverId: actionContext.server?.id,
|
||||
textChannelId: actionContext.textChannel?.id,
|
||||
voiceChannelId: actionContext.voiceChannel?.id
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Capability required: `ui.pages` for the toolbar action. The context object itself needs no extra capability.
|
||||
|
||||
## Logger Methods
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { logger } = context.api;
|
||||
|
||||
logger.debug('Preparing plugin', { pluginId: context.pluginId });
|
||||
logger.info('Plugin activated', { version: context.manifest.version });
|
||||
logger.warn('Optional service unavailable', { service: 'weather.example.com' });
|
||||
logger.error('Failed to parse saved preference', { key: 'soundboard:favorites' });
|
||||
}
|
||||
```
|
||||
|
||||
Logs are visible in the Plugin Manager. Avoid logging passwords, bearer tokens, or private message contents.
|
||||
100
docs-site/docs/plugin-development/api/events.md
Normal file
100
docs-site/docs/plugin-development/api/events.md
Normal file
@@ -0,0 +1,100 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Events API
|
||||
|
||||
Plugin events allow plugins to publish and subscribe to declared server or P2P events.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `events.publishServer(eventName, payload)` | `events.server.publish` |
|
||||
| `events.subscribeServer(subscription)` | `events.server.subscribe` |
|
||||
| `events.publishP2p(eventName, payload)` | `events.p2p.publish` |
|
||||
| `events.subscribeP2p(subscription)` | `events.p2p.subscribe` |
|
||||
|
||||
## Declare Events in the Manifest
|
||||
|
||||
```json
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"eventName": "poll:vote",
|
||||
"direction": "p2pHint",
|
||||
"scope": "channel",
|
||||
"maxPayloadBytes": 2048
|
||||
},
|
||||
{
|
||||
"eventName": "moderation:flag",
|
||||
"direction": "serverRelay",
|
||||
"scope": "server",
|
||||
"maxPayloadBytes": 4096
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Publish and Subscribe to P2P Events
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.events.subscribeP2p({
|
||||
eventName: 'poll:vote',
|
||||
handler: (event) => {
|
||||
context.api.logger.info('Vote received', {
|
||||
optionId: event.payload?.optionId,
|
||||
voterName: event.payload?.voterName,
|
||||
eventId: event.eventId
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
context.api.events.publishP2p('poll:vote', {
|
||||
pollId: 'raid-night-2026-04-29',
|
||||
optionId: 'dungeon',
|
||||
voterName: 'Alice'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Publish and Subscribe to Server Events
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.events.subscribeServer({
|
||||
eventName: 'moderation:flag',
|
||||
handler: (event) => {
|
||||
context.api.logger.warn('Moderation flag received', {
|
||||
messageId: event.payload?.messageId,
|
||||
reason: event.payload?.reason
|
||||
});
|
||||
}
|
||||
}));
|
||||
|
||||
context.api.events.publishServer('moderation:flag', {
|
||||
messageId: 'msg-20260429-flagged',
|
||||
reason: 'Possible spam link',
|
||||
reportedBy: 'user-alice-01'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example event envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "plugin_event",
|
||||
"eventName": "poll:vote",
|
||||
"pluginId": "example.polls",
|
||||
"serverId": "room-7ebdde75",
|
||||
"eventId": "event-1777473600000-1",
|
||||
"emittedAt": 1777473600000,
|
||||
"payload": {
|
||||
"pollId": "raid-night-2026-04-29",
|
||||
"optionId": "dungeon",
|
||||
"voterName": "Alice"
|
||||
}
|
||||
}
|
||||
```
|
||||
95
docs-site/docs/plugin-development/api/message-bus.md
Normal file
95
docs-site/docs/plugin-development/api/message-bus.md
Normal file
@@ -0,0 +1,95 @@
|
||||
---
|
||||
sidebar_position: 8
|
||||
---
|
||||
|
||||
# Message Bus API
|
||||
|
||||
The plugin message bus sends plugin-only P2P events. It can also include bounded latest-message snapshots for plugins that coordinate around recent chat state.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `messageBus.publish(request)` | `events.p2p.publish`, plus `messages.read` if `includeLatestMessages` is true |
|
||||
| `messageBus.sendLatestMessages(request?)` | `events.p2p.publish` and `messages.read` |
|
||||
| `messageBus.subscribe(subscription)` | `events.p2p.subscribe`, plus `messages.read` if replaying latest messages |
|
||||
|
||||
## Subscribe
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.messageBus.subscribe({
|
||||
topic: 'poll:votes',
|
||||
channelId: 'general',
|
||||
replayLatest: true,
|
||||
latestMessageLimit: 10,
|
||||
handler: (event) => {
|
||||
context.api.logger.info('Poll bus event', {
|
||||
topic: event.topic,
|
||||
choice: event.payload?.choice,
|
||||
messageCount: event.messages?.length ?? 0
|
||||
});
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Publish
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const envelope = context.api.messageBus.publish({
|
||||
topic: 'poll:votes',
|
||||
channelId: 'general',
|
||||
payload: {
|
||||
pollId: 'raid-night-2026-04-29',
|
||||
choice: 'healer',
|
||||
voter: 'Alice'
|
||||
},
|
||||
includeLatestMessages: true,
|
||||
includeSelf: true,
|
||||
latestMessageLimit: 10,
|
||||
sinceTimestamp: 1777470000000
|
||||
});
|
||||
|
||||
context.api.logger.info('Published poll event', { eventId: envelope.eventId });
|
||||
}
|
||||
```
|
||||
|
||||
Example envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"eventId": "plugin-bus-1777473600000-1",
|
||||
"pluginId": "example.polls",
|
||||
"roomId": "room-7ebdde75",
|
||||
"channelId": "general",
|
||||
"topic": "poll:votes",
|
||||
"sentAt": 1777473600000,
|
||||
"payload": {
|
||||
"pollId": "raid-night-2026-04-29",
|
||||
"choice": "healer",
|
||||
"voter": "Alice"
|
||||
},
|
||||
"messages": [
|
||||
{ "id": "msg-1", "content": "Raid tonight?", "channelId": "general" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Send Latest Messages
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.messageBus.sendLatestMessages({
|
||||
topic: 'chat:snapshot',
|
||||
channelId: 'support',
|
||||
limit: 25,
|
||||
includeDeleted: false,
|
||||
sinceTimestamp: 1777460000000,
|
||||
targetPeerId: 'peer-muse-laptop'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Use the message bus for plugin coordination. Do not use it for normal user chat messages; use `messages.send()` for that.
|
||||
144
docs-site/docs/plugin-development/api/messages-and-typing.md
Normal file
144
docs-site/docs/plugin-development/api/messages-and-typing.md
Normal file
@@ -0,0 +1,144 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Messages and Typing API
|
||||
|
||||
The messages API reads current messages, sends messages, edits or deletes plugin-owned messages, moderates messages, syncs messages, and exposes typing state.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `messages.readCurrent()` | `messages.read` |
|
||||
| `messages.send(content, channelId?)` | `messages.send` |
|
||||
| `messages.sendAsPluginUser(request)` | `messages.send` |
|
||||
| `messages.setTyping(isTyping, channelId?)` | `messages.send` |
|
||||
| `messages.subscribeTyping(handler)` | `messages.read` |
|
||||
| `messages.edit(messageId, content)` | `messages.editOwn` |
|
||||
| `messages.delete(messageId)` | `messages.deleteOwn` |
|
||||
| `messages.moderateDelete(messageId)` | `messages.moderate` |
|
||||
| `messages.sync(messages)` | `messages.sync` |
|
||||
|
||||
## Read Current Messages
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const messages = context.api.messages.readCurrent();
|
||||
|
||||
context.api.logger.info('Current messages', messages.slice(-3).map((message) => ({
|
||||
id: message.id,
|
||||
channelId: message.channelId,
|
||||
senderName: message.senderName,
|
||||
content: message.content
|
||||
})));
|
||||
}
|
||||
```
|
||||
|
||||
## Send a Message
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const created = context.api.messages.send(
|
||||
'Reminder: raid starts at 20:00. Bring repairs and snacks.',
|
||||
'general'
|
||||
);
|
||||
|
||||
context.api.logger.info('Sent reminder', { messageId: created.id });
|
||||
}
|
||||
```
|
||||
|
||||
## Send as a Plugin User
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const botUserId = context.api.server.registerPluginUser({
|
||||
id: 'poll-bot',
|
||||
displayName: 'Poll Bot'
|
||||
});
|
||||
|
||||
context.api.messages.sendAsPluginUser({
|
||||
pluginUserId: botUserId,
|
||||
channelId: 'general',
|
||||
content: 'Poll is open: react with 1 for dungeon, 2 for arena, 3 for crafting.'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Capabilities required: `users.manage` and `messages.send`.
|
||||
|
||||
## Edit and Delete Plugin-Owned Messages
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const message = context.api.messages.send('Draft event reminder', 'announcements');
|
||||
|
||||
context.api.messages.edit(message.id, 'Event reminder: voice meetup starts in 15 minutes.');
|
||||
context.api.messages.delete(message.id);
|
||||
}
|
||||
```
|
||||
|
||||
## Moderation Delete
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.messages.moderateDelete('msg-spam-20260429-001');
|
||||
}
|
||||
```
|
||||
|
||||
Use moderation from explicit moderator actions, not automatic activation.
|
||||
|
||||
## Typing State
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.messages.setTyping(true, 'general');
|
||||
|
||||
setTimeout(() => {
|
||||
context.api.messages.setTyping(false, 'general');
|
||||
}, 1500);
|
||||
|
||||
context.subscriptions.push(context.api.messages.subscribeTyping((event) => {
|
||||
context.api.logger.info('Typing event', {
|
||||
displayName: event.displayName,
|
||||
isTyping: event.isTyping,
|
||||
channelId: event.channelId,
|
||||
serverId: event.serverId,
|
||||
voiceChannel: event.voiceChannel?.name ?? null
|
||||
});
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Example typing event:
|
||||
|
||||
```json
|
||||
{
|
||||
"serverId": "room-7ebdde75",
|
||||
"channelId": "general",
|
||||
"userId": "user-muse-01",
|
||||
"displayName": "Muse",
|
||||
"isTyping": true
|
||||
}
|
||||
```
|
||||
|
||||
## Sync Messages
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.messages.sync([
|
||||
{
|
||||
id: 'external-standup-001',
|
||||
roomId: 'room-7ebdde75',
|
||||
channelId: 'standup',
|
||||
senderId: 'standup-importer',
|
||||
senderName: 'Standup Importer',
|
||||
content: 'Imported note: Alice is working on plugin docs.',
|
||||
timestamp: 1777473600000,
|
||||
isDeleted: false
|
||||
}
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
Sync should preserve message ids and timestamps from the source system when possible.
|
||||
128
docs-site/docs/plugin-development/api/p2p-and-media.md
Normal file
128
docs-site/docs/plugin-development/api/p2p-and-media.md
Normal file
@@ -0,0 +1,128 @@
|
||||
---
|
||||
sidebar_position: 9
|
||||
---
|
||||
|
||||
# P2P and Media API
|
||||
|
||||
P2P APIs send plugin data to connected peers. Media APIs play audio and contribute custom streams.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `p2p.connectedPeers()` | `p2p.data` |
|
||||
| `p2p.broadcastData(eventName, payload)` | `p2p.data` |
|
||||
| `p2p.sendData(peerId, eventName, payload)` | `p2p.data` |
|
||||
| `media.playAudioClip(request)` | `media.playAudio` |
|
||||
| `media.addCustomAudioStream(request)` | `media.addAudioStream` |
|
||||
| `media.addCustomVideoStream(request)` | `media.addVideoStream` |
|
||||
| `media.setInputVolume(volume)` | `audio.volume` |
|
||||
| `media.setOutputVolume(volume)` | `audio.volume` |
|
||||
|
||||
## Connected Peers
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const peerIds = context.api.p2p.connectedPeers();
|
||||
|
||||
context.api.logger.info('Connected peers', { peerIds });
|
||||
}
|
||||
```
|
||||
|
||||
## Broadcast Data
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.p2p.broadcastData('soundboard:played', {
|
||||
soundId: 'airhorn-short',
|
||||
label: 'Airhorn',
|
||||
playedBy: 'Alice',
|
||||
playedAt: 1777473600000
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Send Data to One Peer
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.p2p.sendData('peer-muse-laptop', 'private-tool:ping', {
|
||||
requestId: 'ping-20260429-001',
|
||||
message: 'Are you receiving plugin data?'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Play an Audio Clip
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
await context.api.media.playAudioClip({
|
||||
url: 'https://cdn.example.com/metoyou/sounds/chime.wav',
|
||||
volume: 0.65
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Add a Custom Audio Stream
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
const audioContext = new AudioContext();
|
||||
const oscillator = audioContext.createOscillator();
|
||||
const gain = audioContext.createGain();
|
||||
const destination = audioContext.createMediaStreamDestination();
|
||||
|
||||
oscillator.type = 'sine';
|
||||
oscillator.frequency.value = 440;
|
||||
gain.gain.value = 0.03;
|
||||
oscillator.connect(gain);
|
||||
gain.connect(destination);
|
||||
oscillator.start();
|
||||
|
||||
await context.api.media.addCustomAudioStream({
|
||||
label: 'Tuning tone',
|
||||
stream: destination.stream
|
||||
});
|
||||
|
||||
setTimeout(async () => {
|
||||
oscillator.stop();
|
||||
await audioContext.close();
|
||||
}, 1000);
|
||||
}
|
||||
```
|
||||
|
||||
## Add a Custom Video Stream
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 1280;
|
||||
canvas.height = 720;
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
ctx.fillStyle = '#111827';
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = '#ffffff';
|
||||
ctx.font = '48px sans-serif';
|
||||
ctx.fillText('Plugin camera scene', 80, 120);
|
||||
|
||||
const stream = canvas.captureStream(15);
|
||||
|
||||
await context.api.media.addCustomVideoStream({
|
||||
label: 'Plugin camera scene',
|
||||
stream
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Set Volumes
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.media.setInputVolume(0.85);
|
||||
context.api.media.setOutputVolume(0.75);
|
||||
}
|
||||
```
|
||||
|
||||
Use media APIs with visible controls and clear user consent. Unexpected audio or video is a poor user experience.
|
||||
66
docs-site/docs/plugin-development/api/profile.md
Normal file
66
docs-site/docs/plugin-development/api/profile.md
Normal file
@@ -0,0 +1,66 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Profile API
|
||||
|
||||
The profile API reads and updates the current user's local profile details.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `profile.getCurrent()` | `profile.read` |
|
||||
| `profile.update(profile)` | `profile.write` |
|
||||
| `profile.updateAvatar(avatar)` | `profile.write` |
|
||||
|
||||
## Read Current Profile
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const user = context.api.profile.getCurrent();
|
||||
|
||||
context.api.logger.info('Current profile', {
|
||||
id: user?.id,
|
||||
displayName: user?.displayName,
|
||||
username: user?.username
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example result:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "user-alice-01",
|
||||
"username": "alice",
|
||||
"displayName": "Alice",
|
||||
"description": "Raids on Fridays",
|
||||
"avatarUrl": "/avatars/alice.webp"
|
||||
}
|
||||
```
|
||||
|
||||
## Update Display Profile
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.profile.update({
|
||||
displayName: 'Alice - Support Lead',
|
||||
description: 'Available for onboarding and support questions.'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Update Avatar
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.profile.updateAvatar({
|
||||
avatarUrl: 'https://cdn.example.com/metoyou/avatars/alice-support.png',
|
||||
avatarMime: 'image/png',
|
||||
avatarHash: 'sha256:9df5d5e4b0d8f41f3a3cf5d1f5a2c1f4'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Use `profile.write` carefully. A plugin that changes a user's identity should explain why in its readme and UI.
|
||||
81
docs-site/docs/plugin-development/api/server.md
Normal file
81
docs-site/docs/plugin-development/api/server.md
Normal file
@@ -0,0 +1,81 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Server API
|
||||
|
||||
The server API reads the active server, registers plugin-owned users, and updates server settings or permissions.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `server.getCurrent()` | `server.read` |
|
||||
| `server.registerPluginUser(request)` | `users.manage` |
|
||||
| `server.updatePermissions(permissions)` | `server.manage` |
|
||||
| `server.updateSettings(settings)` | `server.manage` |
|
||||
|
||||
## Read Current Server
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const server = context.api.server.getCurrent();
|
||||
|
||||
context.api.logger.info('Current server', {
|
||||
id: server?.id,
|
||||
name: server?.name,
|
||||
topic: server?.topic,
|
||||
isPrivate: server?.isPrivate
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Register a Plugin User
|
||||
|
||||
Plugin users are useful for bot-style messages.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const botUserId = context.api.server.registerPluginUser({
|
||||
id: 'standup-helper-bot',
|
||||
displayName: 'Standup Helper',
|
||||
avatarUrl: 'https://cdn.example.com/metoyou/plugins/standup-helper.png'
|
||||
});
|
||||
|
||||
context.api.messages.sendAsPluginUser({
|
||||
pluginUserId: botUserId,
|
||||
channelId: 'general',
|
||||
content: 'Standup reminder: share yesterday, today, and blockers.'
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Capabilities required: `users.manage` and `messages.send`.
|
||||
|
||||
## Update Server Settings
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.server.updateSettings({
|
||||
name: 'Friday Game Night',
|
||||
topic: 'Co-op games, voice chat, and clips',
|
||||
description: 'A friendly server for Friday sessions.',
|
||||
maxUsers: 64,
|
||||
isPrivate: false
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Update Permissions
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.server.updatePermissions({
|
||||
allowVoice: true,
|
||||
allowVideo: true,
|
||||
allowScreenShare: true
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Only update settings or permissions as part of an explicit admin flow. Plugins should not silently rename servers or change access rules.
|
||||
101
docs-site/docs/plugin-development/api/storage.md
Normal file
101
docs-site/docs/plugin-development/api/storage.md
Normal file
@@ -0,0 +1,101 @@
|
||||
---
|
||||
sidebar_position: 10
|
||||
---
|
||||
|
||||
# Storage API
|
||||
|
||||
Plugins can store local client data and per-server data. Desktop builds use Electron persistence when available; browser fallback uses renderer storage.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `clientData.read(key)` | `storage.local` |
|
||||
| `clientData.write(key, value)` | `storage.local` |
|
||||
| `clientData.remove(key)` | `storage.local` |
|
||||
| `serverData.read(key)` | `storage.serverData.read` |
|
||||
| `serverData.write(key, value)` | `storage.serverData.write` |
|
||||
| `serverData.remove(key)` | `storage.serverData.write` |
|
||||
| `storage.get(key)` | `storage.local` |
|
||||
| `storage.set(key, value)` | `storage.local` |
|
||||
| `storage.remove(key)` | `storage.local` |
|
||||
|
||||
## Client Data
|
||||
|
||||
Client data belongs to this local user and client.
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
await context.api.clientData.write('soundboard:volume', {
|
||||
masterVolume: 0.7,
|
||||
updatedAt: 1777473600000
|
||||
});
|
||||
|
||||
const value = await context.api.clientData.read('soundboard:volume');
|
||||
|
||||
context.api.logger.info('Loaded client data', value);
|
||||
}
|
||||
```
|
||||
|
||||
## Server Data
|
||||
|
||||
Server data is local per-user/per-server state. It is not arbitrary signal-server persistence.
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
await context.api.serverData.write('soundboard:favorites', [
|
||||
{ id: 'chime', label: 'Chime', url: 'https://cdn.example.com/chime.wav' },
|
||||
{ id: 'ready', label: 'Ready Check', url: 'https://cdn.example.com/ready.wav' }
|
||||
]);
|
||||
|
||||
const favorites = await context.api.serverData.read('soundboard:favorites');
|
||||
|
||||
context.api.logger.info('Loaded server favorites', favorites);
|
||||
}
|
||||
```
|
||||
|
||||
## Remove Data
|
||||
|
||||
```js
|
||||
export async function activate(context) {
|
||||
await context.api.clientData.remove('soundboard:volume');
|
||||
await context.api.serverData.remove('soundboard:favorites');
|
||||
}
|
||||
```
|
||||
|
||||
## Legacy Synchronous Storage
|
||||
|
||||
The `storage.*` methods are legacy local storage helpers. Prefer `clientData.*` for new plugins when async reads are acceptable.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.storage.set('quick-toggle', { enabled: true });
|
||||
|
||||
const saved = context.api.storage.get('quick-toggle');
|
||||
|
||||
context.api.logger.info('Legacy storage value', saved);
|
||||
|
||||
context.api.storage.remove('quick-toggle');
|
||||
}
|
||||
```
|
||||
|
||||
## Manifest Data Declarations
|
||||
|
||||
Declare important data keys in the manifest.
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"key": "soundboard:volume",
|
||||
"scope": "client",
|
||||
"storage": "local"
|
||||
},
|
||||
{
|
||||
"key": "soundboard:favorites",
|
||||
"scope": "server",
|
||||
"storage": "serverData"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
235
docs-site/docs/plugin-development/api/ui.md
Normal file
235
docs-site/docs/plugin-development/api/ui.md
Normal file
@@ -0,0 +1,235 @@
|
||||
---
|
||||
sidebar_position: 11
|
||||
---
|
||||
|
||||
# UI API
|
||||
|
||||
The UI API lets plugins add pages, settings pages, side panels, channel sections, actions, embed renderers, and controlled DOM mounts.
|
||||
|
||||
Prefer registered UI contributions over direct DOM mounting. Contribution APIs let Angular render the plugin UI when the matching app surface exists. Direct DOM mounting runs immediately and throws if the target selector is not present.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `ui.registerAppPage(id, contribution)` | `ui.pages` |
|
||||
| `ui.registerSettingsPage(id, contribution)` | `ui.settings` |
|
||||
| `ui.registerSidePanel(id, contribution)` | `ui.sidePanel` |
|
||||
| `ui.registerChannelSection(id, contribution)` | `ui.channelsSection` |
|
||||
| `ui.registerComposerAction(id, contribution)` | `ui.pages` |
|
||||
| `ui.registerProfileAction(id, contribution)` | `ui.pages` |
|
||||
| `ui.registerToolbarAction(id, contribution)` | `ui.pages` |
|
||||
| `ui.registerEmbedRenderer(id, contribution)` | `ui.embeds` |
|
||||
| `ui.mountElement(id, request)` | `ui.dom` |
|
||||
|
||||
Every registration returns a disposable. Push it into `context.subscriptions`.
|
||||
|
||||
## App Page
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerAppPage('dashboard', {
|
||||
label: 'Raid Dashboard',
|
||||
path: '/plugins/example.raid-helper/dashboard',
|
||||
render: () => {
|
||||
const root = document.createElement('section');
|
||||
root.innerHTML = '<h1>Raid Dashboard</h1><p>Tonight: dungeon practice.</p>';
|
||||
return root;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
The page is hosted by `/plugins/:pluginId/:pageId`.
|
||||
|
||||
## Settings Page
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerSettingsPage('preferences', {
|
||||
label: 'Raid Helper',
|
||||
settingsKey: 'raid-helper',
|
||||
order: 20,
|
||||
render: () => {
|
||||
const wrapper = document.createElement('section');
|
||||
const label = document.createElement('label');
|
||||
const checkbox = document.createElement('input');
|
||||
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = true;
|
||||
label.append(checkbox, ' Enable ready-check reminders');
|
||||
wrapper.append(label);
|
||||
return wrapper;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Side Panel
|
||||
|
||||
Use `ui.registerSidePanel` for content that belongs in the server sidebar plugin area. Do not mount directly into `[data-testid="plugin-room-side-panel"]`; that host is route-specific and may not exist during plugin activation.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerSidePanel('soundboard', {
|
||||
label: 'Soundboard',
|
||||
order: 10,
|
||||
render: () => {
|
||||
const panel = document.createElement('div');
|
||||
const button = document.createElement('button');
|
||||
|
||||
button.type = 'button';
|
||||
button.textContent = 'Play chime';
|
||||
button.onclick = () => context.api.media.playAudioClip({
|
||||
url: 'https://cdn.example.com/chime.wav',
|
||||
volume: 0.6
|
||||
});
|
||||
panel.append(button);
|
||||
return panel;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Capabilities required: `ui.sidePanel` and `media.playAudio`.
|
||||
|
||||
## Channel Section
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerChannelSection('events', {
|
||||
label: 'Event Rooms',
|
||||
type: 'custom',
|
||||
order: 50
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Composer Action
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerComposerAction('insert-standup', {
|
||||
icon: 'ST',
|
||||
label: 'Insert standup prompt',
|
||||
run: (actionContext) => {
|
||||
context.api.messages.send(
|
||||
'Standup: yesterday I..., today I..., blocked by...',
|
||||
actionContext.textChannel?.id
|
||||
);
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Capabilities required: `ui.pages` and `messages.send`.
|
||||
|
||||
## Profile Action
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerProfileAction('wave', {
|
||||
label: 'Wave',
|
||||
run: (actionContext) => {
|
||||
context.api.messages.send(`Waving at ${actionContext.user?.displayName ?? 'someone'}!`);
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Toolbar Action
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerToolbarAction('open-dashboard', {
|
||||
label: 'Raid Helper',
|
||||
run: () => {
|
||||
context.api.logger.info('Open the Raid Helper plugin page from /plugins/example.raid-helper/dashboard');
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Embed Renderer
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.subscriptions.push(context.api.ui.registerEmbedRenderer('raid-card', {
|
||||
embedType: 'raid.card',
|
||||
render: (payload) => {
|
||||
const card = document.createElement('article');
|
||||
const title = document.createElement('h3');
|
||||
const body = document.createElement('p');
|
||||
|
||||
title.textContent = payload?.title ?? 'Raid';
|
||||
body.textContent = payload?.description ?? 'No description provided.';
|
||||
card.append(title, body);
|
||||
return card;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Example message content for this embed:
|
||||
|
||||
```text
|
||||
toju:embed:raid.card:{"title":"Friday Raid","description":"Meet in Lobby at 20:00."}
|
||||
```
|
||||
|
||||
## DOM Mount
|
||||
|
||||
Use DOM mounting only when normal UI contribution points are not enough. `ui.mountElement` resolves its target immediately. If the target does not exist, plugin activation fails with `Plugin mount target not found: <selector>`.
|
||||
|
||||
Safe uses:
|
||||
|
||||
- Mounting a global overlay, badge, or modal into `body` during activation.
|
||||
- Mounting into a route-specific element only after checking that element exists.
|
||||
|
||||
Avoid:
|
||||
|
||||
- Mounting sidebar content into `[data-testid="plugin-room-side-panel"]`. Use `ui.registerSidePanel`.
|
||||
- Mounting chat content into `app-chat-messages` during activation without checking for the element.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const badge = document.createElement('div');
|
||||
badge.textContent = 'Raid helper active';
|
||||
badge.style.position = 'fixed';
|
||||
badge.style.right = '16px';
|
||||
badge.style.bottom = '16px';
|
||||
badge.style.padding = '8px 10px';
|
||||
badge.style.background = '#111827';
|
||||
badge.style.color = 'white';
|
||||
badge.style.borderRadius = '6px';
|
||||
|
||||
context.subscriptions.push(context.api.ui.mountElement('active-badge', {
|
||||
target: 'body',
|
||||
position: 'beforeend',
|
||||
element: badge
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
Route-specific mount example with a guard:
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const target = document.querySelector('app-chat-messages');
|
||||
|
||||
if (!target) {
|
||||
context.api.logger.warn('Chat messages host is not rendered yet; skipping chat mount');
|
||||
return;
|
||||
}
|
||||
|
||||
const banner = document.createElement('div');
|
||||
banner.textContent = 'Raid helper active in this chat.';
|
||||
|
||||
context.subscriptions.push(context.api.ui.mountElement('chat-banner', {
|
||||
target,
|
||||
position: 'afterbegin',
|
||||
element: banner
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
The runtime tags plugin-owned DOM and removes it on unload, but plugins should still keep mounts minimal and accessible.
|
||||
89
docs-site/docs/plugin-development/api/users-and-roles.md
Normal file
89
docs-site/docs/plugin-development/api/users-and-roles.md
Normal file
@@ -0,0 +1,89 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Users and Roles API
|
||||
|
||||
The users and roles APIs read known users, read room members, and perform moderation or role changes when granted.
|
||||
|
||||
## Required Capabilities
|
||||
|
||||
| Method | Capability |
|
||||
| --- | --- |
|
||||
| `users.getCurrent()` | `users.read` |
|
||||
| `users.list()` | `users.read` |
|
||||
| `users.readMembers()` | `users.read` |
|
||||
| `users.setRole(userId, role)` | `roles.manage` |
|
||||
| `users.kick(userId)` | `users.manage` |
|
||||
| `users.ban(userId, reason?)` | `users.manage` |
|
||||
| `roles.list()` | `roles.read` |
|
||||
| `roles.setAssignments(assignments)` | `roles.manage` |
|
||||
|
||||
## Read Users
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const currentUser = context.api.users.getCurrent();
|
||||
const knownUsers = context.api.users.list();
|
||||
const roomMembers = context.api.users.readMembers();
|
||||
|
||||
context.api.logger.info('Room user summary', {
|
||||
currentUser: currentUser?.displayName,
|
||||
knownUserCount: knownUsers.length,
|
||||
memberCount: roomMembers.length
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example member data:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "id": "member-1", "userId": "user-alice-01", "displayName": "Alice", "role": "admin" },
|
||||
{ "id": "member-2", "userId": "user-muse-01", "displayName": "Muse", "role": "member" }
|
||||
]
|
||||
```
|
||||
|
||||
## Read Roles
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const roles = context.api.roles.list();
|
||||
|
||||
context.api.logger.info('Available roles', roles.map((role) => ({
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
permissions: role.permissions
|
||||
})));
|
||||
}
|
||||
```
|
||||
|
||||
## Set a User Role
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.users.setRole('user-muse-01', 'moderator');
|
||||
}
|
||||
```
|
||||
|
||||
## Replace Role Assignments
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.roles.setAssignments([
|
||||
{ userId: 'user-alice-01', roleId: 'admin' },
|
||||
{ userId: 'user-muse-01', roleId: 'moderator' }
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
## Kick or Ban a User
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
context.api.users.kick('user-spam-01');
|
||||
context.api.users.ban('user-spam-02', 'Repeated spam in support channels');
|
||||
}
|
||||
```
|
||||
|
||||
Moderation calls should normally be behind an explicit user action in plugin UI. Do not run destructive moderation automatically on activation.
|
||||
50
docs-site/docs/plugin-development/capabilities.md
Normal file
50
docs-site/docs/plugin-development/capabilities.md
Normal file
@@ -0,0 +1,50 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Capabilities
|
||||
|
||||
Capabilities protect privileged app surfaces. A plugin must declare a capability in its manifest and the user must grant it before the runtime allows the corresponding API call.
|
||||
|
||||
| Capability | API areas | Notes |
|
||||
| --- | --- | --- |
|
||||
| `profile.read` | `profile.getCurrent()` | Reads the current user. |
|
||||
| `profile.write` | `profile.update()`, `profile.updateAvatar()` | Updates local profile fields and avatar metadata. |
|
||||
| `users.read` | `users.getCurrent()`, `users.list()`, `users.readMembers()` | Reads users and server members. |
|
||||
| `users.manage` | `users.kick()`, `users.ban()`, `server.registerPluginUser()` | Can create plugin users and moderate members. |
|
||||
| `roles.read` | `roles.list()` | Reads server roles. |
|
||||
| `roles.manage` | `roles.setAssignments()`, `users.setRole()` | Changes role assignments or user roles. |
|
||||
| `messages.read` | `messages.readCurrent()`, message bus latest snapshots | Reads current channel messages. |
|
||||
| `messages.send` | `messages.send()`, `messages.sendAsPluginUser()` | Sends messages as the current user or registered plugin user. |
|
||||
| `messages.editOwn` | `messages.edit()` | Edits plugin-owned messages. |
|
||||
| `messages.deleteOwn` | `messages.delete()` | Deletes plugin-owned messages. |
|
||||
| `messages.moderate` | `messages.moderateDelete()` | Moderation delete path. |
|
||||
| `messages.sync` | `messages.sync()` | Syncs message arrays into client state. |
|
||||
| `channels.read` | `channels.list()`, `channels.select()` | Reads and selects channels. |
|
||||
| `channels.manage` | `channels.addAudioChannel()`, `channels.addVideoChannel()`, `channels.remove()`, `channels.rename()` | Mutates channel or channel-section state. |
|
||||
| `server.read` | `server.getCurrent()` | Reads active server. |
|
||||
| `server.manage` | `server.updatePermissions()`, `server.updateSettings()` | Updates server permissions or settings. |
|
||||
| `p2p.data` | `p2p.connectedPeers()`, `p2p.broadcastData()`, `p2p.sendData()` | Uses plugin peer data paths. |
|
||||
| `p2p.media` | Reserved peer media features. | Included for media-facing plugins. |
|
||||
| `media.playAudio` | `media.playAudioClip()` | Plays an audio URL locally. |
|
||||
| `media.addAudioStream` | `media.addCustomAudioStream()` | Adds a custom stream to voice handling. |
|
||||
| `media.addVideoStream` | `media.addCustomVideoStream()` | Registers custom video stream contribution. |
|
||||
| `audio.volume` | `media.setInputVolume()`, `media.setOutputVolume()` | Adjusts local voice volume. |
|
||||
| `audio.effects` | Reserved audio effect features. | Included for audio processing plugins. |
|
||||
| `ui.settings` | `ui.registerSettingsPage()` | Adds settings pages. |
|
||||
| `ui.pages` | `ui.registerAppPage()`, `ui.registerComposerAction()`, `ui.registerProfileAction()`, `ui.registerToolbarAction()` | Adds app pages and actions. |
|
||||
| `ui.sidePanel` | `ui.registerSidePanel()` | Adds side panels. |
|
||||
| `ui.channelsSection` | `ui.registerChannelSection()` | Adds channel sections. |
|
||||
| `ui.embeds` | `ui.registerEmbedRenderer()` | Renders custom embeds. |
|
||||
| `ui.dom` | `ui.mountElement()` | Mounts plugin-owned DOM into app targets. |
|
||||
| `storage.local` | `storage.*`, `clientData.*` | Reads and writes plugin-local data. |
|
||||
| `storage.serverData.read` | `serverData.read()` | Reads local per-user/per-server plugin data. |
|
||||
| `storage.serverData.write` | `serverData.write()`, `serverData.remove()` | Writes or removes local per-user/per-server plugin data. |
|
||||
| `events.server.publish` | `events.publishServer()` | Publishes declared server plugin events. |
|
||||
| `events.server.subscribe` | `events.subscribeServer()` | Subscribes to declared server plugin events. |
|
||||
| `events.p2p.publish` | `events.publishP2p()`, `messageBus.publish()`, `messageBus.sendLatestMessages()` | Publishes declared P2P/plugin bus events. |
|
||||
| `events.p2p.subscribe` | `events.subscribeP2p()`, `messageBus.subscribe()` | Subscribes to declared P2P/plugin bus events. |
|
||||
|
||||
## Recommended Practice
|
||||
|
||||
Request the fewest capabilities possible. Separate broad features into optional plugin modules when a single plugin would otherwise need many unrelated grants.
|
||||
106
docs-site/docs/plugin-development/create-a-plugin.md
Normal file
106
docs-site/docs/plugin-development/create-a-plugin.md
Normal file
@@ -0,0 +1,106 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Create a Plugin
|
||||
|
||||
MetoYou plugins are browser-safe ES modules loaded by the Angular renderer. A plugin receives a frozen `TojuClientPluginApi`, declares every privileged capability in its manifest, and registers cleanup work through disposables.
|
||||
|
||||
## Folder Layout
|
||||
|
||||
A local desktop plugin is discovered from an immediate child folder under the app data `plugins` directory.
|
||||
|
||||
```text
|
||||
my-plugin/
|
||||
toju-plugin.json
|
||||
main.js
|
||||
README.md
|
||||
icon.svg
|
||||
```
|
||||
|
||||
The manifest file can be named `toju-plugin.json` or `plugin.json`. Entrypoints and readmes must stay inside the plugin folder.
|
||||
|
||||
## Minimal Manifest
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "example.hello-world",
|
||||
"title": "Hello World",
|
||||
"description": "Adds a toolbar action that sends a message.",
|
||||
"version": "1.0.0",
|
||||
"kind": "client",
|
||||
"scope": "client",
|
||||
"apiVersion": "1.0.0",
|
||||
"compatibility": {
|
||||
"minimumTojuVersion": "1.0.0"
|
||||
},
|
||||
"entrypoint": "./main.js",
|
||||
"capabilities": ["messages.send", "ui.pages"]
|
||||
}
|
||||
```
|
||||
|
||||
## Entrypoint
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { api } = context;
|
||||
|
||||
api.logger.info('Hello World activated');
|
||||
|
||||
const disposable = api.ui.registerToolbarAction('hello', {
|
||||
label: 'Hello',
|
||||
run: () => api.messages.send('Hello from my plugin')
|
||||
});
|
||||
|
||||
context.subscriptions.push(disposable);
|
||||
}
|
||||
|
||||
export function ready(context) {
|
||||
context.api.logger.info('All ready plugins have loaded');
|
||||
}
|
||||
|
||||
export function deactivate(context) {
|
||||
context.api.logger.info('Hello World deactivated');
|
||||
}
|
||||
```
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
| Hook | When it runs | Use it for |
|
||||
| --- | --- | --- |
|
||||
| `activate(context)` | During explicit plugin activation. | Register UI, subscribe to events, initialize state. |
|
||||
| `ready(context)` | After the load-order pass has activated ready plugins. | Cross-plugin coordination that needs other plugins loaded. |
|
||||
| `deactivate(context)` | During unload or reload. | Flush state and log shutdown. Disposables are also cleaned up by the host. |
|
||||
| `onPluginDataChanged(context, event)` | When plugin data changes are observed. | React to plugin-scoped persistence changes. |
|
||||
| `onServerRequirementsChanged(context, snapshot)` | When server plugin requirements change. | Adapt to required, optional, blocked, or incompatible server plugins. |
|
||||
|
||||
## Cleanup
|
||||
|
||||
Every API registration returns a disposable. Push it into `context.subscriptions`.
|
||||
|
||||
```js
|
||||
const subscription = api.messageBus.subscribe({
|
||||
topic: 'poll:votes',
|
||||
handler: (event) => api.logger.info('vote received', event.payload)
|
||||
});
|
||||
|
||||
context.subscriptions.push(subscription);
|
||||
```
|
||||
|
||||
The plugin host disposes subscriptions in reverse order when the plugin unloads.
|
||||
|
||||
## Capability Grants
|
||||
|
||||
A plugin can only call privileged APIs after the matching capability is declared in the manifest and granted by the user. Keep the manifest narrow. For example, a plugin that only adds a settings page does not need message or user management capabilities.
|
||||
|
||||
## Testing Locally
|
||||
|
||||
1. Create the plugin folder in the desktop plugins directory.
|
||||
2. Open the Plugin Manager.
|
||||
3. Register or refresh local plugins.
|
||||
4. Grant required capabilities.
|
||||
5. Activate the plugin.
|
||||
6. Inspect plugin logs in the manager.
|
||||
|
||||
For broad API examples, compare against the E2E fixture plugin under `toju-app/public/plugins/e2e-all-api/`.
|
||||
204
docs-site/docs/plugin-development/examples.md
Normal file
204
docs-site/docs/plugin-development/examples.md
Normal file
@@ -0,0 +1,204 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Examples
|
||||
|
||||
## Toolbar Message Plugin
|
||||
|
||||
`toju-plugin.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "example.toolbar-message",
|
||||
"title": "Toolbar Message",
|
||||
"description": "Adds a toolbar action that sends a reusable message.",
|
||||
"version": "1.0.0",
|
||||
"kind": "client",
|
||||
"scope": "client",
|
||||
"apiVersion": "1.0.0",
|
||||
"compatibility": {
|
||||
"minimumTojuVersion": "1.0.0",
|
||||
"verifiedTojuVersion": "1.0.0"
|
||||
},
|
||||
"entrypoint": "./main.js",
|
||||
"capabilities": ["messages.send", "ui.pages"]
|
||||
}
|
||||
```
|
||||
|
||||
`main.js`
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { api } = context;
|
||||
|
||||
context.subscriptions.push(api.ui.registerToolbarAction('standup-message', {
|
||||
label: 'Standup',
|
||||
run: () => api.messages.send('Standup: yesterday, today, blocked')
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Settings Page Plugin
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "example.settings-page",
|
||||
"title": "Settings Page Example",
|
||||
"description": "Adds a plugin settings page and stores a local preference.",
|
||||
"version": "1.0.0",
|
||||
"kind": "client",
|
||||
"apiVersion": "1.0.0",
|
||||
"compatibility": { "minimumTojuVersion": "1.0.0" },
|
||||
"entrypoint": "./main.js",
|
||||
"capabilities": ["ui.settings", "storage.local"],
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean", "default": true }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { api } = context;
|
||||
|
||||
context.subscriptions.push(api.ui.registerSettingsPage('preferences', {
|
||||
label: 'Example Preferences',
|
||||
render: () => {
|
||||
const root = document.createElement('section');
|
||||
const button = document.createElement('button');
|
||||
|
||||
button.type = 'button';
|
||||
button.textContent = 'Remember preference';
|
||||
button.onclick = () => api.storage.set('enabled', true);
|
||||
root.append(button);
|
||||
return root;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Server-Scoped Soundboard
|
||||
|
||||
A server-scoped plugin can be installed as a server requirement and auto-installed for server members when marked required.
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "example.soundboard",
|
||||
"title": "Server Soundboard",
|
||||
"description": "Adds a soundboard side panel and announces played sounds.",
|
||||
"version": "1.0.0",
|
||||
"kind": "client",
|
||||
"scope": "server",
|
||||
"apiVersion": "1.0.0",
|
||||
"compatibility": { "minimumTojuVersion": "1.0.0" },
|
||||
"entrypoint": "./main.js",
|
||||
"capabilities": [
|
||||
"server.read",
|
||||
"users.manage",
|
||||
"ui.sidePanel",
|
||||
"media.playAudio",
|
||||
"messages.send"
|
||||
],
|
||||
"pluginUser": {
|
||||
"displayName": "Soundboard",
|
||||
"label": "Audio helper"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { api } = context;
|
||||
const botId = api.server.registerPluginUser({
|
||||
id: 'soundboard-bot',
|
||||
displayName: 'Soundboard'
|
||||
});
|
||||
|
||||
context.subscriptions.push(api.ui.registerSidePanel('sounds', {
|
||||
label: 'Soundboard',
|
||||
render: () => {
|
||||
const panel = document.createElement('div');
|
||||
const button = document.createElement('button');
|
||||
|
||||
button.type = 'button';
|
||||
button.textContent = 'Play chime';
|
||||
button.onclick = async () => {
|
||||
await api.media.playAudioClip({ url: './chime.wav', volume: 0.7 });
|
||||
api.messages.sendAsPluginUser({ pluginUserId: botId, content: 'Played chime' });
|
||||
};
|
||||
|
||||
panel.append(button);
|
||||
return panel;
|
||||
}
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## Message Bus Plugin
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "example.poll-bus",
|
||||
"title": "Poll Bus",
|
||||
"description": "Uses the plugin message bus for lightweight P2P poll votes.",
|
||||
"version": "1.0.0",
|
||||
"kind": "client",
|
||||
"apiVersion": "1.0.0",
|
||||
"compatibility": { "minimumTojuVersion": "1.0.0" },
|
||||
"entrypoint": "./main.js",
|
||||
"capabilities": ["events.p2p.publish", "events.p2p.subscribe", "messages.read"]
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const { api } = context;
|
||||
|
||||
context.subscriptions.push(api.messageBus.subscribe({
|
||||
topic: 'poll:votes',
|
||||
replayLatest: true,
|
||||
latestMessageLimit: 20,
|
||||
handler: (event) => api.logger.info('Vote received', event.payload)
|
||||
}));
|
||||
|
||||
api.messageBus.publish({
|
||||
topic: 'poll:votes',
|
||||
payload: { option: 'A' },
|
||||
includeLatestMessages: true,
|
||||
includeSelf: true,
|
||||
latestMessageLimit: 20
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Custom DOM Mount
|
||||
|
||||
Use `ui.dom` sparingly and cleanly. The runtime tags mounted elements with plugin ownership metadata and removes remaining mounted elements when the plugin unloads.
|
||||
|
||||
```js
|
||||
export function activate(context) {
|
||||
const badge = document.createElement('div');
|
||||
|
||||
badge.textContent = 'Plugin active';
|
||||
badge.style.position = 'absolute';
|
||||
badge.style.right = '1rem';
|
||||
badge.style.bottom = '1rem';
|
||||
|
||||
context.subscriptions.push(context.api.ui.mountElement('active-badge', {
|
||||
target: 'body',
|
||||
element: badge
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
## All-API Fixture
|
||||
|
||||
The repo includes an E2E fixture at `toju-app/public/plugins/e2e-all-api/`. It intentionally calls every public plugin API surface so Playwright coverage can validate the runtime. Use it as a compatibility reference, not as the minimal style for production plugins.
|
||||
164
docs-site/docs/plugin-development/manifest.md
Normal file
164
docs-site/docs/plugin-development/manifest.md
Normal file
@@ -0,0 +1,164 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Manifest Model
|
||||
|
||||
The manifest is the source of truth for plugin identity, compatibility, runtime shape, capabilities, data, events, UI hints, and distribution metadata.
|
||||
|
||||
```ts
|
||||
type TojuPluginInstallScope = 'client' | 'server';
|
||||
type PluginEventDirection = 'clientToServer' | 'serverRelay' | 'p2pHint';
|
||||
type PluginEventScope = 'server' | 'channel' | 'user' | 'plugin';
|
||||
|
||||
type PluginCapabilityId =
|
||||
| 'profile.read'
|
||||
| 'profile.write'
|
||||
| 'users.read'
|
||||
| 'users.manage'
|
||||
| 'roles.read'
|
||||
| 'roles.manage'
|
||||
| 'messages.read'
|
||||
| 'messages.send'
|
||||
| 'messages.editOwn'
|
||||
| 'messages.deleteOwn'
|
||||
| 'messages.moderate'
|
||||
| 'messages.sync'
|
||||
| 'channels.read'
|
||||
| 'channels.manage'
|
||||
| 'server.read'
|
||||
| 'server.manage'
|
||||
| 'p2p.data'
|
||||
| 'p2p.media'
|
||||
| 'media.playAudio'
|
||||
| 'media.addAudioStream'
|
||||
| 'media.addVideoStream'
|
||||
| 'audio.volume'
|
||||
| 'audio.effects'
|
||||
| 'ui.settings'
|
||||
| 'ui.pages'
|
||||
| 'ui.sidePanel'
|
||||
| 'ui.channelsSection'
|
||||
| 'ui.embeds'
|
||||
| 'ui.dom'
|
||||
| 'storage.local'
|
||||
| 'storage.serverData.read'
|
||||
| 'storage.serverData.write'
|
||||
| 'events.server.publish'
|
||||
| 'events.server.subscribe'
|
||||
| 'events.p2p.publish'
|
||||
| 'events.p2p.subscribe';
|
||||
|
||||
interface TojuPluginManifest {
|
||||
schemaVersion: 1;
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
version: string;
|
||||
kind: 'client' | 'library';
|
||||
scope?: TojuPluginInstallScope;
|
||||
apiVersion: string;
|
||||
compatibility: {
|
||||
minimumTojuVersion: string;
|
||||
maximumTojuVersion?: string;
|
||||
verifiedTojuVersion?: string;
|
||||
};
|
||||
entrypoint?: string;
|
||||
bundle?: {
|
||||
url: string;
|
||||
entrypoint?: string;
|
||||
};
|
||||
readme?: string;
|
||||
homepage?: string;
|
||||
bugs?: string;
|
||||
changelog?: string;
|
||||
license?: string;
|
||||
authors?: {
|
||||
name: string;
|
||||
email?: string;
|
||||
url?: string;
|
||||
}[];
|
||||
capabilities?: PluginCapabilityId[];
|
||||
events?: {
|
||||
eventName: string;
|
||||
direction: PluginEventDirection;
|
||||
scope: PluginEventScope;
|
||||
maxPayloadBytes?: number;
|
||||
schema?: string;
|
||||
}[];
|
||||
data?: {
|
||||
key: string;
|
||||
schema?: string;
|
||||
scope: string;
|
||||
storage: 'local' | 'serverData';
|
||||
}[];
|
||||
relationships?: {
|
||||
after?: string[];
|
||||
before?: string[];
|
||||
conflicts?: string[];
|
||||
optional?: { id: string; versionRange?: string }[];
|
||||
requires?: { id: string; versionRange?: string }[];
|
||||
};
|
||||
load?: {
|
||||
priority?: 'bootstrap' | 'high' | 'default' | 'low';
|
||||
};
|
||||
pluginUser?: {
|
||||
avatar?: string;
|
||||
displayName: string;
|
||||
label?: string;
|
||||
};
|
||||
settings?: Record<string, unknown>;
|
||||
ui?: Record<string, unknown>;
|
||||
}
|
||||
```
|
||||
|
||||
## Required Fields
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `schemaVersion` | Manifest schema version. Currently `1`. |
|
||||
| `id` | Stable plugin id. Use a reverse-DNS or package-style id. |
|
||||
| `title` | Human-readable plugin name. |
|
||||
| `description` | Short explanation shown in plugin UI. |
|
||||
| `version` | Plugin version. |
|
||||
| `kind` | `client` for runtime plugins, `library` for shared dependency-style entries. |
|
||||
| `apiVersion` | Plugin API version expected by the plugin. |
|
||||
| `compatibility.minimumTojuVersion` | Oldest app version the plugin supports. |
|
||||
|
||||
## Scope
|
||||
|
||||
`scope: "client"` installs the plugin for the current client. Omit `scope` for the same behavior.
|
||||
|
||||
`scope: "server"` marks a plugin as server-scoped. Server-scoped store entries can be installed to a chat server as requirements. Required server plugins are auto-installed for members when that server opens; optional requirements stay listed but do not auto-install.
|
||||
|
||||
When a user installs a server-scoped plugin into the server they are currently viewing, MetoYou enables that plugin id locally and activates the plugin immediately after the local manifest is registered. Installing a server-scoped plugin for another server records the activation preference so it activates when that server is opened.
|
||||
|
||||
## Entrypoint and Bundle
|
||||
|
||||
Use `entrypoint` for a browser-resolvable module relative to the manifest. Use `bundle.url` when publishing a cached browser bundle through a plugin source manifest. Desktop installs cache bundle files into app data and load the cached manifest afterward.
|
||||
|
||||
## Events
|
||||
|
||||
Every server or P2P plugin event should be declared before it is published or subscribed to.
|
||||
|
||||
```json
|
||||
{
|
||||
"events": [
|
||||
{
|
||||
"eventName": "poll:vote",
|
||||
"direction": "p2pHint",
|
||||
"scope": "channel",
|
||||
"maxPayloadBytes": 2048
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Data Declarations
|
||||
|
||||
Use `data` to document plugin-owned data keys and intended storage.
|
||||
|
||||
- `local` maps to client-local plugin data.
|
||||
- `serverData` maps to local per-user/per-server plugin data.
|
||||
|
||||
Signal server HTTP persistence for arbitrary plugin data is disabled by design.
|
||||
66
docs-site/docs/user-guide/first-steps.md
Normal file
66
docs-site/docs/user-guide/first-steps.md
Normal file
@@ -0,0 +1,66 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# First Steps
|
||||
|
||||
MetoYou is a chat app for servers, text conversations, direct messages, and live voice. You do not need to understand the technical parts to use it.
|
||||
|
||||
## Main Words
|
||||
|
||||
| Word | Meaning |
|
||||
| --- | --- |
|
||||
| Server | A shared space for a community, team, or group. |
|
||||
| Text channel | A named chat room inside a server. Messages stay in that channel. |
|
||||
| Voice channel | A named live room inside a server. Join it when you want to talk, share camera, or share screen. |
|
||||
| Direct message | A private conversation outside a server channel. |
|
||||
| Plugin | An add-on that can add buttons, panels, tools, integrations, or server-specific features. |
|
||||
|
||||
## Sign In
|
||||
|
||||
1. Open MetoYou.
|
||||
2. Sign in with your username and password.
|
||||
3. If you use more than one signaling server, choose the server endpoint that owns your account.
|
||||
|
||||
A signaling server handles accounts, server discovery, membership, and connection setup. In normal use you can think of it as the place MetoYou checks when you log in and join servers.
|
||||
|
||||
## Find a Server
|
||||
|
||||
1. Open the server search page.
|
||||
2. Search by server name or browse the available list.
|
||||
3. Select a server.
|
||||
4. Join directly if it is public, enter the password if it is protected, or use an invite link if someone sent you one.
|
||||
|
||||
After joining, the server appears in the vertical server rail on the left. Click a server icon there to switch servers.
|
||||
|
||||
## Read and Send Messages
|
||||
|
||||
1. Click a server in the left rail.
|
||||
2. Pick a text channel under **Text Channels**.
|
||||
3. Type in the composer at the bottom of the chat.
|
||||
4. Press Enter or use the send button.
|
||||
|
||||
Text channels keep different topics separate. For example, a server might have `general`, `announcements`, and `support` as separate text channels.
|
||||
|
||||
## Start Talking
|
||||
|
||||
1. Open a server.
|
||||
2. Pick a voice channel under **Voice Channels**.
|
||||
3. Click the voice channel to join.
|
||||
4. Use the voice controls to mute, deafen, start camera, share screen, or leave.
|
||||
|
||||
Voice is live. Text messages are written chat. They can happen at the same time, but they are different channel types.
|
||||
|
||||
## Use Direct Messages
|
||||
|
||||
Direct messages are one-to-one conversations. They are separate from server text channels, so they do not depend on which server you are viewing.
|
||||
|
||||
## Open Settings
|
||||
|
||||
Settings contain account, voice, plugin, server, desktop, update, local API, theme, and data controls. Desktop users can also manage local data import/export and local documentation/API hosting.
|
||||
|
||||
## Install Plugins
|
||||
|
||||
Plugins are installed from the Plugin Store or Plugin Manager. Some plugins are global client plugins. Other plugins are server-scoped and only apply to a specific server.
|
||||
|
||||
See [Plugins for Users](./plugins.md) for the full non-technical plugin guide.
|
||||
82
docs-site/docs/user-guide/plugins.md
Normal file
82
docs-site/docs/user-guide/plugins.md
Normal file
@@ -0,0 +1,82 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
# Plugins for Users
|
||||
|
||||
Plugins add features to MetoYou. They can add pages, buttons, panels, settings, sounds, message tools, custom embeds, or server-specific behavior.
|
||||
|
||||
## Types of Plugins
|
||||
|
||||
| Type | What it means |
|
||||
| --- | --- |
|
||||
| Client plugin | Installed for your app. It follows you across servers when active. |
|
||||
| Server plugin | Installed for a specific server. It may be required, recommended, optional, blocked, or incompatible. |
|
||||
| Library plugin | Shared plugin code used by other plugins. It is not normally something users interact with directly. |
|
||||
|
||||
## Install from the Plugin Store
|
||||
|
||||
1. Open the Plugin Store from the title bar or Settings.
|
||||
2. Browse or search available plugins.
|
||||
3. Open the plugin details.
|
||||
4. Read the description, version, source, and capability list.
|
||||
5. Choose install.
|
||||
6. Review and grant only the capabilities you trust.
|
||||
7. Activate the plugin.
|
||||
|
||||
Server-scoped plugins installed to the server you are currently viewing are enabled and activated automatically after install, so their panels, actions, or embeds can appear immediately.
|
||||
|
||||
## Install a Local Plugin
|
||||
|
||||
Desktop builds can discover local plugin folders from the app data plugins directory.
|
||||
|
||||
1. Put the plugin folder in the desktop plugins directory.
|
||||
2. Open Settings.
|
||||
3. Open the Plugin Manager.
|
||||
4. Refresh or register local plugins.
|
||||
5. Grant capabilities and activate the plugin.
|
||||
|
||||
## Server Plugin Prompts
|
||||
|
||||
When a server uses plugins, MetoYou may show a prompt.
|
||||
|
||||
| Status | Meaning |
|
||||
| --- | --- |
|
||||
| Required | You must install the plugin to join or continue using that server. |
|
||||
| Recommended | The server suggests the plugin, but you can choose. |
|
||||
| Optional | The plugin is available for the server, but not required. |
|
||||
| Blocked | The server marks the plugin as not allowed. |
|
||||
| Incompatible | The plugin version does not work with your app version or the server requirement. |
|
||||
|
||||
Required plugins are still installed locally on your device. The signaling server stores requirement metadata only; it does not run plugin code.
|
||||
|
||||
## Capability Grants
|
||||
|
||||
Plugins must ask for capabilities before using sensitive features.
|
||||
|
||||
Examples:
|
||||
|
||||
| Capability area | Why a plugin might ask |
|
||||
| --- | --- |
|
||||
| Messages | Send messages, read current messages, moderate messages, or render embeds. |
|
||||
| Users and roles | Read member lists, create plugin users, or manage users. |
|
||||
| Voice and media | Play audio, add an audio stream, add a video stream, or adjust volume. |
|
||||
| UI | Add pages, settings pages, side panels, toolbar buttons, or DOM elements. |
|
||||
| Storage | Save plugin preferences locally or per server. |
|
||||
|
||||
Only grant capabilities to plugins you trust.
|
||||
|
||||
## Manage Plugins
|
||||
|
||||
The Plugin Manager lets you:
|
||||
|
||||
- activate, deactivate, reload, or unload plugins;
|
||||
- grant or revoke capabilities;
|
||||
- inspect plugin logs;
|
||||
- see plugin UI contribution counts;
|
||||
- review server plugin requirements;
|
||||
- uninstall plugins.
|
||||
|
||||
## Plugin Safety Notes
|
||||
|
||||
Plugins are browser-safe JavaScript modules loaded by the client. They do not run on the signaling server. A plugin can only call privileged MetoYou APIs when its manifest declares the capability and you grant it.
|
||||
65
docs-site/docs/user-guide/servers-and-channels.md
Normal file
65
docs-site/docs/user-guide/servers-and-channels.md
Normal file
@@ -0,0 +1,65 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Servers and Channels
|
||||
|
||||
A server is the main shared space in MetoYou. Servers contain members, channels, permissions, optional plugins, and server settings.
|
||||
|
||||
## Server Rail
|
||||
|
||||
The server rail is the vertical list of servers on the left side of the app.
|
||||
|
||||
- Click a server icon to open it.
|
||||
- Use the add/search control to find or join more servers.
|
||||
- A badge can show unread activity.
|
||||
- Server context actions can include invite, leave, or server settings depending on your permissions.
|
||||
|
||||
## Text Channels
|
||||
|
||||
Text channels are written conversations. Each text channel has its own message list.
|
||||
|
||||
Common examples:
|
||||
|
||||
| Channel | Use |
|
||||
| --- | --- |
|
||||
| `general` | Everyday chat. |
|
||||
| `announcements` | Updates from owners or admins. |
|
||||
| `support` | Help requests. |
|
||||
| `clips` | Shared media or links. |
|
||||
|
||||
Messages, replies, reactions, attachments, GIFs, typing indicators, and plugin-created messages are scoped to the active text channel.
|
||||
|
||||
## Voice Channels
|
||||
|
||||
Voice channels are live spaces. Joining a voice channel connects your microphone and lets you use camera or screen sharing when enabled.
|
||||
|
||||
Voice channel examples:
|
||||
|
||||
| Channel | Use |
|
||||
| --- | --- |
|
||||
| `Lobby` | Casual drop-in voice. |
|
||||
| `Gaming` | In-game voice. |
|
||||
| `Meeting` | Focused calls. |
|
||||
| `Support Room` | Live help. |
|
||||
|
||||
## Text Channels vs Voice Channels
|
||||
|
||||
| Text channel | Voice channel |
|
||||
| --- | --- |
|
||||
| Written messages. | Live audio and media. |
|
||||
| You can read later. | You join and leave in real time. |
|
||||
| Uses the message composer. | Uses voice controls. |
|
||||
| Good for searchable discussions. | Good for conversations, calls, screen shares, and quick coordination. |
|
||||
|
||||
## Server Members
|
||||
|
||||
The member list shows people known to the server. Online members appear separately from offline members. Depending on permissions, owners, admins, or moderators can move users between voice channels, kick users, ban users, or change roles.
|
||||
|
||||
## Invites
|
||||
|
||||
Invite links help other users join a server. If a server is private or password-protected, the invite or password controls who can enter.
|
||||
|
||||
## Server Plugins
|
||||
|
||||
A server can recommend or require plugins. Required server plugins may block joining until you choose whether to install them. Optional and recommended plugins can be skipped.
|
||||
33
docs-site/docs/user-guide/settings.md
Normal file
33
docs-site/docs/user-guide/settings.md
Normal file
@@ -0,0 +1,33 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
# Settings and Data
|
||||
|
||||
Settings control the app, voice, plugins, servers, themes, updates, local APIs, and desktop behavior.
|
||||
|
||||
## Common Settings
|
||||
|
||||
| Area | What you can manage |
|
||||
| --- | --- |
|
||||
| Account | Current profile, display details, and avatar metadata. |
|
||||
| Voice | Devices, volumes, bitrate, latency, noise reduction, screen share preferences. |
|
||||
| Plugins | Installed plugins, capability grants, plugin logs, and plugin store sources. |
|
||||
| Server | Server details, channels, roles, moderation, plugin requirements, and member controls. |
|
||||
| Theme | App colors and visual preferences. |
|
||||
| Desktop | Tray behavior, auto-start, hardware acceleration, updates, and local data tools. |
|
||||
| Local API | Local HTTP server, API docs, Docusaurus docs, and allowed signaling servers. |
|
||||
|
||||
## Local Data
|
||||
|
||||
Desktop MetoYou stores local app data on your device. That can include rooms, messages, users, plugin data, settings, and metadata. The desktop settings include data import/export tools.
|
||||
|
||||
## Local API and Documentation Hosting
|
||||
|
||||
The desktop app can start a local HTTP server. It is off by default. When enabled, it can serve:
|
||||
|
||||
- Local REST API endpoints under `/api/...`;
|
||||
- Scalar REST API docs at `/docs`;
|
||||
- this Docusaurus site at `/docusaurus`.
|
||||
|
||||
Authentication for protected local API routes uses a local bearer token. Login is checked against an allowed signaling server that you configure in settings.
|
||||
37
docs-site/docs/user-guide/text-and-direct-messages.md
Normal file
37
docs-site/docs/user-guide/text-and-direct-messages.md
Normal file
@@ -0,0 +1,37 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Text and Direct Messages
|
||||
|
||||
Text channels and direct messages both use written chat, but they are meant for different situations.
|
||||
|
||||
## Text Channels
|
||||
|
||||
Text channels belong to a server. Everyone with access to that server and channel can participate.
|
||||
|
||||
You can use text channels to:
|
||||
|
||||
- send normal messages;
|
||||
- edit or delete your own messages when allowed;
|
||||
- react to messages;
|
||||
- send attachments;
|
||||
- browse and send GIFs when available;
|
||||
- see typing indicators;
|
||||
- read synced message history stored on your device.
|
||||
|
||||
## Direct Messages
|
||||
|
||||
Direct messages are private conversations outside a server channel. Use them when a message is meant for one person instead of the server.
|
||||
|
||||
## Attachments and Media
|
||||
|
||||
Attachments can appear as files, images, audio, or video depending on the file type and what the app can preview. If an image or link cannot load directly, the app can use fallback paths where available.
|
||||
|
||||
## Message Sync
|
||||
|
||||
MetoYou stores messages locally and syncs recent messages with peers when connections are available. If you were offline, messages may appear after peers reconnect and exchange their recent message lists.
|
||||
|
||||
## Plugin Messages
|
||||
|
||||
Some plugins can send messages, create bot-style plugin users, render custom embeds, or add composer buttons. MetoYou asks for plugin capability grants before plugins can use privileged message features.
|
||||
73
docs-site/docs/user-guide/voice-channels.md
Normal file
73
docs-site/docs/user-guide/voice-channels.md
Normal file
@@ -0,0 +1,73 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# Voice Channels and Calls
|
||||
|
||||
Voice channels are live rooms inside a server. Join one when you want to talk, share camera, or share your screen.
|
||||
|
||||
## Join a Voice Channel
|
||||
|
||||
1. Open the server from the left server rail.
|
||||
2. Find **Voice Channels** in the server side panel.
|
||||
3. Click the voice channel you want to join.
|
||||
4. Allow microphone access if your system asks.
|
||||
5. Use the voice controls to manage your call.
|
||||
|
||||
When you join, other users in the same voice channel can hear you unless you are muted. Users in other voice channels are not part of your live voice room.
|
||||
|
||||
## Voice Controls
|
||||
|
||||
The voice controls can include:
|
||||
|
||||
| Control | What it does |
|
||||
| --- | --- |
|
||||
| Mute microphone | Stops sending your microphone audio. |
|
||||
| Deafen | Stops playback and usually mutes your microphone too. |
|
||||
| Camera | Starts or stops webcam video. |
|
||||
| Screen share | Shares a screen or window. |
|
||||
| Settings | Opens voice device and quality settings. |
|
||||
| Leave | Disconnects from the voice channel. |
|
||||
|
||||
## Screen Sharing
|
||||
|
||||
1. Join a voice channel.
|
||||
2. Click screen share.
|
||||
3. Choose a screen or window.
|
||||
4. Choose whether to include system audio when available.
|
||||
5. Stop sharing from the voice controls when done.
|
||||
|
||||
The screen share picker can show screens and windows. Desktop audio support depends on operating system support and the selected source.
|
||||
|
||||
## Voice Workspace
|
||||
|
||||
When someone shares camera or screen, the voice workspace can expand into a larger media area. It can show focused streams, a grid of streams, or a minimized mini-window.
|
||||
|
||||
## Floating Voice Controls
|
||||
|
||||
If you navigate away from the server while still connected to voice, MetoYou can show floating voice controls. Use them to return to the voice server or leave the call.
|
||||
|
||||
## Voice Settings
|
||||
|
||||
Voice settings can include:
|
||||
|
||||
- input device;
|
||||
- output device;
|
||||
- input volume;
|
||||
- output volume;
|
||||
- audio bitrate;
|
||||
- latency profile;
|
||||
- noise reduction;
|
||||
- screen share quality;
|
||||
- system audio preference.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Try this |
|
||||
| --- | --- |
|
||||
| Nobody hears you | Check mute, input device, system microphone permission, and input volume. |
|
||||
| You hear nobody | Check deafen, output device, output volume, and whether others are in the same voice channel. |
|
||||
| Screen share is missing | Check desktop permissions and try a different screen or window. |
|
||||
| Voice drops after switching servers | Return to the server with the active voice session or leave and rejoin the voice channel. |
|
||||
|
||||
Voice and screen sharing use peer-to-peer WebRTC media. The signaling server helps users connect, but the media itself travels through peer connections.
|
||||
56
docs-site/docs/using-metoyou.md
Normal file
56
docs-site/docs/using-metoyou.md
Normal file
@@ -0,0 +1,56 @@
|
||||
---
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
# Using MetoYou
|
||||
|
||||
## Sign In
|
||||
|
||||
MetoYou signs in through a signaling server. The signaling server validates the user account, coordinates server membership, relays selected realtime messages, and helps peers establish WebRTC connections.
|
||||
|
||||
For the desktop Local API, the same signaling server allow-list is used before local bearer tokens can be issued. This keeps local automation tied to servers you explicitly trust.
|
||||
|
||||
## Find or Join Servers
|
||||
|
||||
Use the server search flow to find known servers. A server can be public, private, or password-protected depending on its settings. Invite links can be created from the title bar menu while a server is active.
|
||||
|
||||
A server contains:
|
||||
|
||||
- basic profile information such as name, topic, description, privacy, and maximum users;
|
||||
- text channels;
|
||||
- voice or custom channel sections;
|
||||
- roles and permissions;
|
||||
- members and voice state;
|
||||
- optional server-scoped plugin requirements.
|
||||
|
||||
## Text Channels and Messages
|
||||
|
||||
Text channels are selected inside the active server. Messages are persisted locally by the client and synchronized through realtime events while connected. Plugins with the relevant capabilities can read, send, edit, delete, moderate, or sync messages.
|
||||
|
||||
Direct messages use the same shell but are not part of a room channel context.
|
||||
|
||||
## Voice, Video, and Screen Sharing
|
||||
|
||||
Voice and media are peer-to-peer. The signaling server coordinates connection setup, while media streams travel through WebRTC peer connections.
|
||||
|
||||
Desktop builds include platform integrations such as Linux display-server detection and optional monitor audio routing for screen sharing. Plugin media APIs can contribute custom audio or video streams when the user grants the necessary capabilities.
|
||||
|
||||
## Plugins
|
||||
|
||||
Open the Plugin Store from the title bar package button or menu. The plugin manager separates global client plugins from server-scoped plugins. Installed plugins can be activated, reloaded, unloaded, disabled, inspected for logs, and granted capabilities.
|
||||
|
||||
Plugins are explicit runtime modules. MetoYou loads browser-safe ES modules, passes a frozen API object, and cleans up registered disposables when a plugin unloads.
|
||||
|
||||
## Desktop Settings
|
||||
|
||||
Desktop settings cover:
|
||||
|
||||
- auto-start and close-to-tray behavior;
|
||||
- hardware acceleration and Linux VA-API video encode options;
|
||||
- update manifests and target update versions;
|
||||
- local HTTP API hosting;
|
||||
- Scalar API documentation;
|
||||
- Docusaurus app/plugin documentation;
|
||||
- allowed signaling servers for local API authentication;
|
||||
- local plugin discovery and store sources;
|
||||
- themes and user data import/export.
|
||||
71
docs-site/docusaurus.config.ts
Normal file
71
docs-site/docusaurus.config.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import type { Config } from '@docusaurus/types';
|
||||
import type * as Preset from '@docusaurus/preset-classic';
|
||||
|
||||
const config: Config = {
|
||||
title: 'MetoYou Docs',
|
||||
tagline: 'Desktop chat, local APIs, and plugin development',
|
||||
url: 'http://127.0.0.1',
|
||||
baseUrl: '/docusaurus/',
|
||||
organizationName: 'metoyou',
|
||||
projectName: 'metoyou',
|
||||
onBrokenLinks: 'throw',
|
||||
onBrokenMarkdownLinks: 'warn',
|
||||
i18n: {
|
||||
defaultLocale: 'en',
|
||||
locales: ['en']
|
||||
},
|
||||
presets: [
|
||||
[
|
||||
'classic',
|
||||
{
|
||||
docs: {
|
||||
routeBasePath: '/',
|
||||
sidebarPath: './sidebars.ts'
|
||||
},
|
||||
blog: false,
|
||||
theme: {
|
||||
customCss: './src/css/custom.css'
|
||||
}
|
||||
} satisfies Preset.Options
|
||||
]
|
||||
],
|
||||
themeConfig: {
|
||||
navbar: {
|
||||
title: 'MetoYou Docs',
|
||||
items: [
|
||||
{ type: 'docSidebar', sidebarId: 'mainSidebar', position: 'left', label: 'Guides' },
|
||||
{ to: '/user-guide/first-steps', label: 'User Guide', position: 'left' },
|
||||
{ to: '/developer/contributing', label: 'Developer Guide', position: 'left' },
|
||||
{ to: '/plugin-development/create-a-plugin', label: 'Plugin Guide', position: 'left' },
|
||||
{ to: '/developer/rest-api', label: 'REST API', position: 'left' }
|
||||
]
|
||||
},
|
||||
footer: {
|
||||
style: 'dark',
|
||||
links: [
|
||||
{
|
||||
title: 'Docs',
|
||||
items: [
|
||||
{ label: 'First Steps', to: '/user-guide/first-steps' },
|
||||
{ label: 'Voice Channels', to: '/user-guide/voice-channels' },
|
||||
{ label: 'Plugins for Users', to: '/user-guide/plugins' },
|
||||
{ label: 'Contributing', to: '/developer/contributing' },
|
||||
{ label: 'Create a Plugin', to: '/plugin-development/create-a-plugin' },
|
||||
{ label: 'Plugin API Reference', to: '/plugin-development/api-reference' },
|
||||
{ label: 'Local REST API', to: '/developer/rest-api' }
|
||||
]
|
||||
}
|
||||
],
|
||||
copyright: 'MetoYou local documentation. Built with Docusaurus.'
|
||||
},
|
||||
prism: {
|
||||
additionalLanguages: [
|
||||
'bash',
|
||||
'json',
|
||||
'typescript'
|
||||
]
|
||||
}
|
||||
} satisfies Preset.ThemeConfig
|
||||
};
|
||||
|
||||
export default config;
|
||||
18490
docs-site/package-lock.json
generated
Normal file
18490
docs-site/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
docs-site/package.json
Normal file
28
docs-site/package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "metoyou-docs",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "docusaurus start --host 127.0.0.1",
|
||||
"build": "docusaurus build",
|
||||
"serve": "docusaurus serve --host 127.0.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "3.10.0",
|
||||
"@docusaurus/preset-classic": "3.10.0",
|
||||
"@mdx-js/react": "^3.1.1",
|
||||
"clsx": "^2.1.1",
|
||||
"prism-react-renderer": "^2.4.1",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "3.10.0",
|
||||
"@docusaurus/tsconfig": "3.10.0",
|
||||
"@docusaurus/types": "3.10.0",
|
||||
"typescript": "~5.9.2"
|
||||
},
|
||||
"overrides": {
|
||||
"webpack": "5.101.3"
|
||||
}
|
||||
}
|
||||
62
docs-site/sidebars.ts
Normal file
62
docs-site/sidebars.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { SidebarsConfig } from '@docusaurus/plugin-content-docs';
|
||||
|
||||
const sidebars: SidebarsConfig = {
|
||||
mainSidebar: [
|
||||
'intro',
|
||||
{
|
||||
type: 'category',
|
||||
label: 'User Guide',
|
||||
items: [
|
||||
'user-guide/first-steps',
|
||||
'user-guide/servers-and-channels',
|
||||
'user-guide/text-and-direct-messages',
|
||||
'user-guide/voice-channels',
|
||||
'user-guide/plugins',
|
||||
'user-guide/settings',
|
||||
'using-metoyou'
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Developer Guide',
|
||||
items: [
|
||||
'developer/contributing',
|
||||
'developer/docusaurus-site',
|
||||
'developer/dom-structure',
|
||||
'developer/rest-api',
|
||||
'developer/llm-plugin-builder-guide',
|
||||
'desktop-and-local-api'
|
||||
]
|
||||
},
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Plugin Development',
|
||||
items: [
|
||||
'plugin-development/create-a-plugin',
|
||||
'plugin-development/manifest',
|
||||
'plugin-development/capabilities',
|
||||
'plugin-development/api-reference',
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Plugin API Examples',
|
||||
items: [
|
||||
'plugin-development/api/context-and-logging',
|
||||
'plugin-development/api/profile',
|
||||
'plugin-development/api/users-and-roles',
|
||||
'plugin-development/api/server',
|
||||
'plugin-development/api/channels',
|
||||
'plugin-development/api/messages-and-typing',
|
||||
'plugin-development/api/events',
|
||||
'plugin-development/api/message-bus',
|
||||
'plugin-development/api/p2p-and-media',
|
||||
'plugin-development/api/storage',
|
||||
'plugin-development/api/ui'
|
||||
]
|
||||
},
|
||||
'plugin-development/examples'
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
export default sidebars;
|
||||
40
docs-site/src/css/custom.css
Normal file
40
docs-site/src/css/custom.css
Normal file
@@ -0,0 +1,40 @@
|
||||
:root {
|
||||
--ifm-color-primary: #2f9ab2;
|
||||
--ifm-color-primary-dark: #2a8ba0;
|
||||
--ifm-color-primary-darker: #287f94;
|
||||
--ifm-color-primary-darkest: #216979;
|
||||
--ifm-color-primary-light: #36abc5;
|
||||
--ifm-color-primary-lighter: #43b4ce;
|
||||
--ifm-color-primary-lightest: #6cc5d8;
|
||||
--ifm-code-font-size: 92%;
|
||||
--ifm-border-radius: 6px;
|
||||
}
|
||||
|
||||
[data-theme='dark'] {
|
||||
--ifm-background-color: #101318;
|
||||
--ifm-background-surface-color: #171b22;
|
||||
--ifm-navbar-background-color: #12161d;
|
||||
--ifm-footer-background-color: #0b0e13;
|
||||
--ifm-color-primary: #58c4dc;
|
||||
--ifm-color-primary-dark: #36b7d3;
|
||||
--ifm-color-primary-darker: #27aeca;
|
||||
--ifm-color-primary-darkest: #208fa6;
|
||||
--ifm-color-primary-light: #79d1e3;
|
||||
--ifm-color-primary-lighter: #8bd7e7;
|
||||
--ifm-color-primary-lightest: #bde9f1;
|
||||
}
|
||||
|
||||
.hero--primary {
|
||||
--ifm-hero-background-color: #151b24;
|
||||
--ifm-hero-text-color: #f6f8fb;
|
||||
}
|
||||
|
||||
.theme-doc-markdown table code,
|
||||
.theme-doc-markdown li code,
|
||||
.theme-doc-markdown p code {
|
||||
border: 1px solid var(--ifm-color-emphasis-300);
|
||||
}
|
||||
|
||||
.plugin-api-table td:first-child {
|
||||
white-space: nowrap;
|
||||
}
|
||||
3
e2e/fixtures/plugins/api-test-plugin/README.md
Normal file
3
e2e/fixtures/plugins/api-test-plugin/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# E2E Plugin API Fixture
|
||||
|
||||
This plugin is intentionally tiny. Tests use its manifest to exercise plugin discovery, server support metadata, server data, and plugin event relay APIs without executing plugin code.
|
||||
6
e2e/fixtures/plugins/api-test-plugin/dist/main.js
vendored
Normal file
6
e2e/fixtures/plugins/api-test-plugin/dist/main.js
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
id: 'e2e.plugin-api',
|
||||
activate(api) {
|
||||
api?.logger?.info?.('E2E Plugin API Fixture activated');
|
||||
}
|
||||
};
|
||||
49
e2e/fixtures/plugins/api-test-plugin/toju-plugin.json
Normal file
49
e2e/fixtures/plugins/api-test-plugin/toju-plugin.json
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"apiVersion": "1.0.0",
|
||||
"capabilities": [
|
||||
"storage.serverData.read",
|
||||
"storage.serverData.write",
|
||||
"events.server.publish",
|
||||
"events.server.subscribe",
|
||||
"events.p2p.publish",
|
||||
"events.p2p.subscribe"
|
||||
],
|
||||
"compatibility": {
|
||||
"minimumTojuVersion": "1.0.0",
|
||||
"verifiedTojuVersion": "1.0.0"
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"key": "settings",
|
||||
"scope": "server",
|
||||
"storage": "serverData"
|
||||
},
|
||||
{
|
||||
"key": "presence",
|
||||
"scope": "user",
|
||||
"storage": "serverData"
|
||||
}
|
||||
],
|
||||
"description": "Fixture plugin used by automated tests for plugin support APIs.",
|
||||
"entrypoint": "./dist/main.js",
|
||||
"events": [
|
||||
{
|
||||
"direction": "serverRelay",
|
||||
"eventName": "e2e:relay",
|
||||
"maxPayloadBytes": 2048,
|
||||
"scope": "server"
|
||||
},
|
||||
{
|
||||
"direction": "p2pHint",
|
||||
"eventName": "e2e:p2p",
|
||||
"maxPayloadBytes": 512,
|
||||
"scope": "user"
|
||||
}
|
||||
],
|
||||
"id": "e2e.plugin-api",
|
||||
"kind": "client",
|
||||
"readme": "./README.md",
|
||||
"schemaVersion": 1,
|
||||
"title": "E2E Plugin API Fixture",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
42
e2e/helpers/plugin-api-test-fixture.ts
Normal file
42
e2e/helpers/plugin-api-test-fixture.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
|
||||
export const TEST_PLUGIN_FIXTURE_DIR = join(__dirname, '..', 'fixtures', 'plugins', 'api-test-plugin');
|
||||
export const TEST_PLUGIN_ID = 'e2e.plugin-api';
|
||||
export const TEST_PLUGIN_RELAY_EVENT = 'e2e:relay';
|
||||
export const TEST_PLUGIN_P2P_EVENT = 'e2e:p2p';
|
||||
|
||||
export interface PluginApiTestManifestEvent {
|
||||
direction: 'clientToServer' | 'serverRelay' | 'p2pHint';
|
||||
eventName: string;
|
||||
maxPayloadBytes?: number;
|
||||
scope: 'server' | 'channel' | 'user' | 'plugin';
|
||||
}
|
||||
|
||||
export interface PluginApiTestManifest {
|
||||
description: string;
|
||||
events: PluginApiTestManifestEvent[];
|
||||
id: string;
|
||||
title: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
export async function readPluginApiTestManifest(): Promise<PluginApiTestManifest> {
|
||||
const manifestPath = join(TEST_PLUGIN_FIXTURE_DIR, 'toju-plugin.json');
|
||||
const manifestText = await readFile(manifestPath, 'utf8');
|
||||
|
||||
return JSON.parse(manifestText) as PluginApiTestManifest;
|
||||
}
|
||||
|
||||
export function getPluginApiTestEvent(
|
||||
manifest: PluginApiTestManifest,
|
||||
eventName: string
|
||||
): PluginApiTestManifestEvent {
|
||||
const eventDefinition = manifest.events.find((event) => event.eventName === eventName);
|
||||
|
||||
if (!eventDefinition) {
|
||||
throw new Error(`Expected fixture plugin to define ${eventName}`);
|
||||
}
|
||||
|
||||
return eventDefinition;
|
||||
}
|
||||
@@ -69,6 +69,7 @@ function applySeededEndpointStorageState(storageState: SeededEndpointStorageStat
|
||||
'toju-primary',
|
||||
'toju-sweden'
|
||||
]));
|
||||
|
||||
storage.setItem('metoyou_general_settings', generalSettings);
|
||||
|
||||
if (currentUserId) {
|
||||
|
||||
@@ -10,7 +10,9 @@ export class LoginPage {
|
||||
readonly registerLink: Locator;
|
||||
|
||||
constructor(private page: Page) {
|
||||
this.form = page.locator('#login-username').locator('xpath=ancestor::div[contains(@class, "space-y-3")]').first();
|
||||
this.form = page.locator('#login-username').locator('xpath=ancestor::div[contains(@class, "space-y-3")]')
|
||||
.first();
|
||||
|
||||
this.usernameInput = page.locator('#login-username');
|
||||
this.passwordInput = page.locator('#login-password');
|
||||
this.serverSelect = page.locator('#login-server');
|
||||
|
||||
@@ -79,12 +79,19 @@ export class ServerSearchPage {
|
||||
await this.page.getByRole('button', { name }).click();
|
||||
}
|
||||
|
||||
async joinServerFromSearch(name: string) {
|
||||
async joinServerFromSearch(name: string, options: { acceptPluginDownloads?: boolean } = {}) {
|
||||
await this.searchInput.fill(name);
|
||||
|
||||
const serverCard = this.page.locator('div[title]', { hasText: name }).first();
|
||||
|
||||
await expect(serverCard).toBeVisible({ timeout: 15_000 });
|
||||
await serverCard.dblclick();
|
||||
|
||||
if (options.acceptPluginDownloads) {
|
||||
const pluginConsentDialog = this.page.getByRole('dialog', { name: /uses plugins/ });
|
||||
|
||||
await expect(pluginConsentDialog).toBeVisible({ timeout: 20_000 });
|
||||
await pluginConsentDialog.getByRole('button', { name: 'Accept and join' }).click();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,10 +25,7 @@ interface PersistentClient {
|
||||
userDataDir: string;
|
||||
}
|
||||
|
||||
const CLIENT_LAUNCH_ARGS = [
|
||||
'--use-fake-device-for-media-stream',
|
||||
'--use-fake-ui-for-media-stream'
|
||||
];
|
||||
const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'];
|
||||
|
||||
test.describe('User session data isolation', () => {
|
||||
test.describe.configure({ timeout: 240_000 });
|
||||
@@ -43,6 +40,7 @@ test.describe('User session data isolation', () => {
|
||||
};
|
||||
const aliceServerName = `Alice Session Server ${suffix}`;
|
||||
const aliceMessage = `Alice persisted message ${suffix}`;
|
||||
|
||||
let client: PersistentClient | null = null;
|
||||
|
||||
try {
|
||||
@@ -82,6 +80,7 @@ test.describe('User session data isolation', () => {
|
||||
const bobServerName = `Bob Private Server ${suffix}`;
|
||||
const aliceMessage = `Alice history ${suffix}`;
|
||||
const bobMessage = `Bob history ${suffix}`;
|
||||
|
||||
let client: PersistentClient | null = null;
|
||||
|
||||
try {
|
||||
@@ -136,7 +135,7 @@ async function launchPersistentClient(userDataDir: string, testServerPort: numbe
|
||||
|
||||
await installTestServerEndpoint(context, testServerPort);
|
||||
|
||||
const page = context.pages()[0] ?? await context.newPage();
|
||||
const page = context.pages()[0] ?? (await context.newPage());
|
||||
|
||||
return {
|
||||
context,
|
||||
@@ -202,6 +201,7 @@ async function createServerAndSendMessage(page: Page, serverName: string, messag
|
||||
await searchPage.createServer(serverName, {
|
||||
description: `User session isolation coverage for ${serverName}`
|
||||
});
|
||||
|
||||
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
|
||||
|
||||
await messagesPage.sendMessage(messageText);
|
||||
@@ -209,11 +209,15 @@ async function createServerAndSendMessage(page: Page, serverName: string, messag
|
||||
}
|
||||
|
||||
async function expectSavedRoomAndHistory(page: Page, roomName: string, messageText: string): Promise<void> {
|
||||
const roomButton = getSavedRoomButton(page, roomName);
|
||||
const railRoomButton = getRailSavedRoomButton(page, roomName);
|
||||
const messagesPage = new ChatMessagesPage(page);
|
||||
|
||||
await expect(roomButton).toBeVisible({ timeout: 20_000 });
|
||||
await roomButton.click();
|
||||
await expect(railRoomButton).toBeVisible({ timeout: 20_000 });
|
||||
await page.goto('/search', { waitUntil: 'domcontentloaded' });
|
||||
const searchRoomButton = getSearchSavedRoomButton(page, roomName);
|
||||
|
||||
await expect(searchRoomButton).toBeVisible({ timeout: 20_000 });
|
||||
await searchRoomButton.click();
|
||||
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
|
||||
await expect(messagesPage.getMessageItemByText(messageText)).toBeVisible({ timeout: 20_000 });
|
||||
}
|
||||
@@ -230,17 +234,29 @@ async function expectBlankSlate(page: Page, hiddenRoomNames: string[]): Promise<
|
||||
}
|
||||
|
||||
async function expectSavedRoomVisible(page: Page, roomName: string): Promise<void> {
|
||||
await expect(getSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
|
||||
await expect(getRailSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
|
||||
await page.goto('/search', { waitUntil: 'domcontentloaded' });
|
||||
await expect(getSearchSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
|
||||
}
|
||||
|
||||
async function expectSavedRoomHidden(page: Page, roomName: string): Promise<void> {
|
||||
await expect(getSavedRoomButton(page, roomName)).toHaveCount(0);
|
||||
await expect(getRailSavedRoomButton(page, roomName)).toHaveCount(0);
|
||||
|
||||
if (!page.url().includes('/search')) {
|
||||
await page.goto('/search', { waitUntil: 'domcontentloaded' });
|
||||
}
|
||||
|
||||
await expect(getSearchSavedRoomButton(page, roomName)).toHaveCount(0);
|
||||
}
|
||||
|
||||
function getSavedRoomButton(page: Page, roomName: string) {
|
||||
function getRailSavedRoomButton(page: Page, roomName: string) {
|
||||
return page.locator(`button[title="${roomName}"]`).first();
|
||||
}
|
||||
|
||||
function getSearchSavedRoomButton(page: Page, roomName: string) {
|
||||
return page.locator('app-server-search').getByRole('button', { name: roomName, exact: true });
|
||||
}
|
||||
|
||||
async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts = 4): Promise<T> {
|
||||
let lastError: unknown;
|
||||
|
||||
@@ -259,11 +275,10 @@ async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError instanceof Error
|
||||
? lastError
|
||||
: new Error(`Navigation failed after ${attempts} attempts`);
|
||||
throw lastError instanceof Error ? lastError : new Error(`Navigation failed after ${attempts} attempts`);
|
||||
}
|
||||
|
||||
function uniqueName(prefix: string): string {
|
||||
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36)
|
||||
.slice(2, 8)}`;
|
||||
}
|
||||
503
e2e/tests/chat/server-icon-sync.spec.ts
Normal file
503
e2e/tests/chat/server-icon-sync.spec.ts
Normal file
@@ -0,0 +1,503 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
chromium,
|
||||
type BrowserContext,
|
||||
type Locator,
|
||||
type Page,
|
||||
type Route
|
||||
} from '@playwright/test';
|
||||
import { test, expect } from '../../fixtures/multi-client';
|
||||
import { installTestServerEndpoint } from '../../helpers/seed-test-endpoint';
|
||||
import { installWebRTCTracking } from '../../helpers/webrtc-helpers';
|
||||
import { LoginPage } from '../../pages/login.page';
|
||||
import { RegisterPage } from '../../pages/register.page';
|
||||
import { ServerSearchPage } from '../../pages/server-search.page';
|
||||
import { ChatMessagesPage } from '../../pages/chat-messages.page';
|
||||
|
||||
interface TestUser {
|
||||
displayName: string;
|
||||
password: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface ImageUploadPayload {
|
||||
buffer: Buffer;
|
||||
dataUrl: string;
|
||||
mimeType: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface PersistentClient {
|
||||
context: BrowserContext;
|
||||
page: Page;
|
||||
user: TestUser;
|
||||
userDataDir: string;
|
||||
}
|
||||
|
||||
const STATIC_GIF_BASE64 = 'R0lGODlhAQABAPAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
|
||||
const GIF_FRAME_MARKER = Buffer.from([
|
||||
0x21,
|
||||
0xf9,
|
||||
0x04
|
||||
]);
|
||||
const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'];
|
||||
const SERVER_ICON_SYNC_TIMEOUT_MS = 45_000;
|
||||
|
||||
test.describe('Server icon sync', () => {
|
||||
test.describe.configure({ timeout: 240_000 });
|
||||
|
||||
test('loads the chat-server image for online, late-joining, restarted, and discovery users', async ({ testServer }) => {
|
||||
const suffix = uniqueName('server-icon');
|
||||
const serverName = `Icon Sync Server ${suffix}`;
|
||||
const icon = buildGifUpload('server-icon');
|
||||
const aliceUser: TestUser = {
|
||||
username: `alice_${suffix}`,
|
||||
displayName: 'Alice',
|
||||
password: 'TestPass123!'
|
||||
};
|
||||
const bobUser: TestUser = {
|
||||
username: `bob_${suffix}`,
|
||||
displayName: 'Bob',
|
||||
password: 'TestPass123!'
|
||||
};
|
||||
const carolUser: TestUser = {
|
||||
username: `carol_${suffix}`,
|
||||
displayName: 'Carol',
|
||||
password: 'TestPass123!'
|
||||
};
|
||||
const daveUser: TestUser = {
|
||||
username: `dave_${suffix}`,
|
||||
displayName: 'Dave',
|
||||
password: 'TestPass123!'
|
||||
};
|
||||
const clients: PersistentClient[] = [];
|
||||
|
||||
try {
|
||||
const alice = await createPersistentClient(aliceUser, testServer.port);
|
||||
const bob = await createPersistentClient(bobUser, testServer.port);
|
||||
|
||||
clients.push(alice, bob);
|
||||
|
||||
await test.step('Alice creates a server and Bob joins before the icon changes', async () => {
|
||||
await registerUser(alice);
|
||||
await registerUser(bob);
|
||||
|
||||
await new ServerSearchPage(alice.page).createServer(serverName, {
|
||||
description: 'Server icon synchronization E2E coverage'
|
||||
});
|
||||
|
||||
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
|
||||
|
||||
await joinServerFromSearch(bob.page, serverName);
|
||||
await waitForRoomReady(alice.page);
|
||||
await waitForRoomReady(bob.page);
|
||||
await waitForConnectedPeerCount(alice.page, 1);
|
||||
await waitForConnectedPeerCount(bob.page, 1);
|
||||
});
|
||||
|
||||
const roomUrl = alice.page.url();
|
||||
|
||||
await test.step('Alice uploads a server icon and sees it in every owner-facing place', async () => {
|
||||
await uploadServerIconFromSettings(alice.page, serverName, icon);
|
||||
|
||||
await expectServerSettingsIcon(alice.page, serverName, icon.dataUrl);
|
||||
await closeSettingsModal(alice.page);
|
||||
await expectRoomHeaderIcon(alice.page, serverName, icon.dataUrl);
|
||||
await expectRailIcon(alice.page, serverName, icon.dataUrl);
|
||||
});
|
||||
|
||||
await test.step('Bob was online during the change and receives the icon live', async () => {
|
||||
await expectRoomHeaderIcon(bob.page, serverName, icon.dataUrl);
|
||||
await expectRailIcon(bob.page, serverName, icon.dataUrl);
|
||||
});
|
||||
|
||||
const carol = await createPersistentClient(carolUser, testServer.port);
|
||||
|
||||
clients.push(carol);
|
||||
|
||||
await test.step('Carol joins after the change and loads the existing server icon', async () => {
|
||||
await registerUser(carol);
|
||||
await joinServerFromSearch(carol.page, serverName);
|
||||
await waitForRoomReady(carol.page);
|
||||
await waitForConnectedPeerCount(alice.page, 2);
|
||||
|
||||
await expectRoomHeaderIcon(carol.page, serverName, icon.dataUrl);
|
||||
await expectRailIcon(carol.page, serverName, icon.dataUrl);
|
||||
});
|
||||
|
||||
await test.step('Bob keeps the server icon after a full app restart', async () => {
|
||||
await restartPersistentClient(bob, testServer.port);
|
||||
await openRoomAfterRestart(bob, roomUrl);
|
||||
|
||||
await expectRoomHeaderIcon(bob.page, serverName, icon.dataUrl);
|
||||
await expectRailIcon(bob.page, serverName, icon.dataUrl);
|
||||
});
|
||||
|
||||
const dave = await createPersistentClient(daveUser, testServer.port);
|
||||
|
||||
clients.push(dave);
|
||||
|
||||
await test.step('Dave has not joined, but discovery loads the icon through a temporary peer sync', async () => {
|
||||
await registerUser(dave);
|
||||
await stripServerIconFromDirectorySearch(dave.page, serverName);
|
||||
await dave.page.goto('/search', { waitUntil: 'domcontentloaded' });
|
||||
await new ServerSearchPage(dave.page).searchInput.fill(serverName);
|
||||
|
||||
await expectSearchResultIcon(dave.page, serverName, icon.dataUrl);
|
||||
await expect(dave.page).toHaveURL(/\/search/);
|
||||
});
|
||||
} finally {
|
||||
await Promise.all(
|
||||
clients.map(async (client) => {
|
||||
await closePersistentClient(client);
|
||||
await rm(client.userDataDir, { recursive: true, force: true });
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function createPersistentClient(user: TestUser, testServerPort: number): Promise<PersistentClient> {
|
||||
const userDataDir = await mkdtemp(join(tmpdir(), 'metoyou-server-icon-e2e-'));
|
||||
const session = await launchPersistentSession(userDataDir, testServerPort);
|
||||
|
||||
return {
|
||||
context: session.context,
|
||||
page: session.page,
|
||||
user,
|
||||
userDataDir
|
||||
};
|
||||
}
|
||||
|
||||
async function restartPersistentClient(client: PersistentClient, testServerPort: number): Promise<void> {
|
||||
await closePersistentClient(client);
|
||||
|
||||
const session = await launchPersistentSession(client.userDataDir, testServerPort);
|
||||
|
||||
client.context = session.context;
|
||||
client.page = session.page;
|
||||
}
|
||||
|
||||
async function closePersistentClient(client: PersistentClient): Promise<void> {
|
||||
try {
|
||||
await client.context.close();
|
||||
} catch {
|
||||
// Ignore repeated cleanup attempts during finally.
|
||||
}
|
||||
}
|
||||
|
||||
async function launchPersistentSession(userDataDir: string, testServerPort: number): Promise<{ context: BrowserContext; page: Page }> {
|
||||
const context = await chromium.launchPersistentContext(userDataDir, {
|
||||
args: CLIENT_LAUNCH_ARGS,
|
||||
baseURL: 'http://localhost:4200',
|
||||
permissions: ['microphone', 'camera']
|
||||
});
|
||||
|
||||
await installTestServerEndpoint(context, testServerPort);
|
||||
|
||||
const page = context.pages()[0] ?? (await context.newPage());
|
||||
|
||||
await installWebRTCTracking(page);
|
||||
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
async function registerUser(client: PersistentClient): Promise<void> {
|
||||
const registerPage = new RegisterPage(client.page);
|
||||
|
||||
await retryTransientNavigation(() => registerPage.goto());
|
||||
await registerPage.register(client.user.username, client.user.displayName, client.user.password);
|
||||
await expect(client.page).toHaveURL(/\/search/, { timeout: 15_000 });
|
||||
}
|
||||
|
||||
async function joinServerFromSearch(page: Page, serverName: string): Promise<void> {
|
||||
await new ServerSearchPage(page).joinServerFromSearch(serverName);
|
||||
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
|
||||
}
|
||||
|
||||
async function openRoomAfterRestart(client: PersistentClient, roomUrl: string): Promise<void> {
|
||||
await retryTransientNavigation(() => client.page.goto(roomUrl, { waitUntil: 'domcontentloaded' }));
|
||||
|
||||
if (client.page.url().includes('/login')) {
|
||||
const loginPage = new LoginPage(client.page);
|
||||
|
||||
await loginPage.login(client.user.username, client.user.password);
|
||||
await expect(client.page).toHaveURL(/\/(search|room)\//, { timeout: 15_000 });
|
||||
await client.page.goto(roomUrl, { waitUntil: 'domcontentloaded' });
|
||||
}
|
||||
|
||||
await waitForRoomReady(client.page);
|
||||
}
|
||||
|
||||
async function uploadServerIconFromSettings(page: Page, serverName: string, icon: ImageUploadPayload): Promise<void> {
|
||||
await openServerSettings(page, serverName);
|
||||
|
||||
const fileInput = page.locator('#server-icon-upload');
|
||||
|
||||
await expect(fileInput).toBeAttached({ timeout: 10_000 });
|
||||
await fileInput.setInputFiles({
|
||||
name: icon.name,
|
||||
mimeType: icon.mimeType,
|
||||
buffer: icon.buffer
|
||||
});
|
||||
}
|
||||
|
||||
async function openServerSettings(page: Page, serverName: string): Promise<void> {
|
||||
await page.locator('app-title-bar button[title="Menu"]').click();
|
||||
|
||||
const titleBarMenu = page.locator('app-title-bar .absolute.right-0.top-full').first();
|
||||
|
||||
await expect(titleBarMenu).toBeVisible({ timeout: 5_000 });
|
||||
await titleBarMenu.getByRole('button', { name: 'Settings' }).click();
|
||||
|
||||
const dialog = page.locator('app-settings-modal');
|
||||
const serverSettingsTitle = dialog.getByRole('heading', { name: 'Server Settings' });
|
||||
|
||||
try {
|
||||
await expect(serverSettingsTitle).toBeVisible({ timeout: 2_000 });
|
||||
} catch {
|
||||
await openSettingsModalThroughAngularDevMode(page);
|
||||
await expect(serverSettingsTitle).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
const serverSelect = dialog.locator('select').first();
|
||||
|
||||
if ((await serverSelect.count()) > 0) {
|
||||
await expect(serverSelect).toContainText(serverName, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
await dialog.getByRole('button', { name: 'Server', exact: true }).click();
|
||||
await expect(page.locator('app-server-settings')).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function openSettingsModalThroughAngularDevMode(page: Page): Promise<void> {
|
||||
await page.evaluate(() => {
|
||||
interface SettingsModalComponentHandle {
|
||||
modal?: {
|
||||
open: (page: string) => void;
|
||||
};
|
||||
}
|
||||
interface AngularDebugApi {
|
||||
getComponent: (element: Element) => SettingsModalComponentHandle;
|
||||
applyChanges?: (component: SettingsModalComponentHandle) => void;
|
||||
}
|
||||
|
||||
const host = document.querySelector('app-settings-modal');
|
||||
const debugApi = (window as Window & { ng?: AngularDebugApi }).ng;
|
||||
const component = host && debugApi?.getComponent(host);
|
||||
|
||||
if (!component?.modal?.open) {
|
||||
throw new Error('Angular debug API could not open settings modal');
|
||||
}
|
||||
|
||||
component.modal.open('server');
|
||||
debugApi.applyChanges?.(component);
|
||||
});
|
||||
}
|
||||
|
||||
async function closeSettingsModal(page: Page): Promise<void> {
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.locator('app-settings-modal').getByRole('heading', { name: 'Settings', exact: true })).not.toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function stripServerIconFromDirectorySearch(page: Page, serverName: string): Promise<void> {
|
||||
await page.route('**/api/servers**', async (route: Route) => {
|
||||
const response = await route.fetch();
|
||||
const contentType = response.headers()['content-type'] ?? '';
|
||||
|
||||
if (!contentType.includes('application/json')) {
|
||||
await route.fulfill({ response });
|
||||
return;
|
||||
}
|
||||
|
||||
const body = await response.json();
|
||||
|
||||
if (!body || !Array.isArray(body.servers)) {
|
||||
await route.fulfill({ response, json: body });
|
||||
return;
|
||||
}
|
||||
|
||||
await route.fulfill({
|
||||
response,
|
||||
json: {
|
||||
...body,
|
||||
servers: body.servers.map((server: Record<string, unknown>) => {
|
||||
if (server['name'] !== serverName) {
|
||||
return server;
|
||||
}
|
||||
|
||||
const { icon: _icon, ...serverWithoutIcon } = server;
|
||||
|
||||
return serverWithoutIcon;
|
||||
})
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForRoomReady(page: Page): Promise<void> {
|
||||
const messagesPage = new ChatMessagesPage(page);
|
||||
|
||||
await messagesPage.waitForReady();
|
||||
await expect(page.locator('app-rooms-side-panel').last()).toBeVisible({ timeout: 15_000 });
|
||||
}
|
||||
|
||||
async function waitForConnectedPeerCount(page: Page, count: number, timeout = 30_000): Promise<void> {
|
||||
await page.waitForFunction(
|
||||
(expectedCount) => {
|
||||
const connections =
|
||||
(
|
||||
window as {
|
||||
__rtcConnections?: RTCPeerConnection[];
|
||||
}
|
||||
).__rtcConnections ?? [];
|
||||
|
||||
return connections.filter((connection) => connection.connectionState === 'connected').length >= expectedCount;
|
||||
},
|
||||
count,
|
||||
{ timeout }
|
||||
);
|
||||
}
|
||||
|
||||
async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts = 4): Promise<T> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
return await navigate();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const isTransientNavigationError = message.includes('ERR_EMPTY_RESPONSE') || message.includes('ERR_CONNECTION_RESET');
|
||||
|
||||
if (!isTransientNavigationError || attempt === attempts) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError instanceof Error ? lastError : new Error(`Navigation failed after ${attempts} attempts`);
|
||||
}
|
||||
|
||||
async function expectServerSettingsIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
|
||||
const settingsPanel = page.locator('app-server-settings');
|
||||
const image = settingsPanel.locator('[style*="background-image"]').first();
|
||||
|
||||
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'settings server icon');
|
||||
}
|
||||
|
||||
async function expectRoomHeaderIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
|
||||
const channelsPanel = page.locator('app-rooms-side-panel').first();
|
||||
const image = channelsPanel.locator('[style*="background-image"]').first();
|
||||
|
||||
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'room header server icon');
|
||||
}
|
||||
|
||||
async function expectRailIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
|
||||
const image = page.locator(`app-servers-rail button[title="${serverName}"] [style*="background-image"]`).first();
|
||||
|
||||
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'servers rail icon');
|
||||
}
|
||||
|
||||
async function expectSearchResultIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
|
||||
const serverCard = page.locator('app-server-search div[title]', { hasText: serverName }).first();
|
||||
const image = serverCard.locator('[style*="background-image"]').first();
|
||||
|
||||
await expect(serverCard).toBeVisible({ timeout: 20_000 });
|
||||
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'search result server icon');
|
||||
}
|
||||
|
||||
async function expectBackgroundImageLoadedWithUrl(image: Locator, expectedDataUrl: string, label: string): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
if ((await image.count()) === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return image.evaluate((element) => getComputedStyle(element).backgroundImage);
|
||||
},
|
||||
{
|
||||
timeout: SERVER_ICON_SYNC_TIMEOUT_MS,
|
||||
message: `${label} background should update`
|
||||
}
|
||||
)
|
||||
.toContain(expectedDataUrl);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
if ((await image.count()) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return image.evaluate(
|
||||
(element) =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
const backgroundImage = getComputedStyle(element).backgroundImage;
|
||||
const match = /^url\("?(.*?)"?\)$/.exec(backgroundImage);
|
||||
const img = new Image();
|
||||
|
||||
if (!match?.[1]) {
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
|
||||
img.onload = () => resolve(img.naturalWidth > 0 && img.naturalHeight > 0);
|
||||
img.onerror = () => resolve(false);
|
||||
img.src = match[1];
|
||||
})
|
||||
);
|
||||
},
|
||||
{
|
||||
timeout: SERVER_ICON_SYNC_TIMEOUT_MS,
|
||||
message: `${label} should load`
|
||||
}
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
function buildGifUpload(label: string): ImageUploadPayload {
|
||||
const baseGif = Buffer.from(STATIC_GIF_BASE64, 'base64');
|
||||
const frameStart = baseGif.indexOf(GIF_FRAME_MARKER);
|
||||
|
||||
if (frameStart < 0) {
|
||||
throw new Error('Failed to locate GIF frame marker for server icon payload');
|
||||
}
|
||||
|
||||
const header = baseGif.subarray(0, frameStart);
|
||||
const frame = baseGif.subarray(frameStart, baseGif.length - 1);
|
||||
const commentData = Buffer.from(label, 'ascii');
|
||||
const commentExtension = Buffer.concat([
|
||||
Buffer.from([
|
||||
0x21,
|
||||
0xfe,
|
||||
commentData.length
|
||||
]),
|
||||
commentData,
|
||||
Buffer.from([0x00])
|
||||
]);
|
||||
const buffer = Buffer.concat([
|
||||
header,
|
||||
commentExtension,
|
||||
frame,
|
||||
frame,
|
||||
Buffer.from([0x3b])
|
||||
]);
|
||||
const base64 = buffer.toString('base64');
|
||||
|
||||
return {
|
||||
buffer,
|
||||
dataUrl: `data:image/gif;base64,${base64}`,
|
||||
mimeType: 'image/gif',
|
||||
name: `server-icon-${label}.gif`
|
||||
};
|
||||
}
|
||||
|
||||
function uniqueName(prefix: string): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36)
|
||||
.slice(2, 8)}`;
|
||||
}
|
||||
186
e2e/tests/plugins/plugin-api-two-users.spec.ts
Normal file
186
e2e/tests/plugins/plugin-api-two-users.spec.ts
Normal file
@@ -0,0 +1,186 @@
|
||||
import { type Page } from '@playwright/test';
|
||||
import {
|
||||
expect,
|
||||
test,
|
||||
type Client
|
||||
} from '../../fixtures/multi-client';
|
||||
import { ChatMessagesPage } from '../../pages/chat-messages.page';
|
||||
import { ChatRoomPage } from '../../pages/chat-room.page';
|
||||
import { RegisterPage } from '../../pages/register.page';
|
||||
import { ServerSearchPage } from '../../pages/server-search.page';
|
||||
|
||||
const PLUGIN_SOURCE_URL = 'http://localhost:4200/plugins/e2e-plugin-source.json';
|
||||
const PLUGIN_TITLE = 'E2E All API Plugin';
|
||||
const EDITED_MESSAGE = 'Plugin API edited message';
|
||||
const ORIGINAL_MESSAGE = 'Plugin API original message';
|
||||
const DELETED_MESSAGE = 'Plugin API deleted message';
|
||||
const DELETED_MESSAGE_CONTENT = '[Message deleted]';
|
||||
const PLUGIN_BOT_MESSAGE = 'Plugin bot message from all-api fixture';
|
||||
const CUSTOM_EMBED_TEXT = 'E2E custom embed: Plugin API custom embed';
|
||||
const SOUND_BOARD_TEXT = 'E2E soundboard ready';
|
||||
const SOUND_BOARD_LABEL = 'E2E Soundboard';
|
||||
const SOUND_BOARD_PLAYED_MESSAGE = 'E2E soundboard played Airhorn to voice channel';
|
||||
const VOICE_CHANNEL = 'Plugin Voice';
|
||||
|
||||
test.describe('Plugin API multi-user runtime', () => {
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test('runs chat, embed, soundboard, and profile APIs between two users', async ({ createClient }) => {
|
||||
const scenario = await createPluginApiScenario(createClient);
|
||||
|
||||
await test.step('Alice has the server plugin active', async () => {
|
||||
await expect(soundboardComposerButton(scenario.alice.page)).toBeVisible({ timeout: 20_000 });
|
||||
await expect(scenario.alice.page.getByText(SOUND_BOARD_TEXT, { exact: true })).toBeVisible({ timeout: 20_000 });
|
||||
await expect(scenario.alice.page.getByTestId('e2e-plugin-owned-dom')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
|
||||
});
|
||||
|
||||
await test.step('Activate the server plugin for Bob as the embed/soundboard receiver', async () => {
|
||||
await installGrantAndActivatePlugin(scenario.bob.page, false);
|
||||
await closeSettingsModal(scenario.bob.page);
|
||||
await expect(soundboardComposerButton(scenario.bob.page)).toBeVisible({ timeout: 20_000 });
|
||||
await expect(scenario.bob.page.getByText(SOUND_BOARD_TEXT, { exact: true })).toBeVisible({ timeout: 20_000 });
|
||||
await expect(scenario.bob.page.getByTestId('e2e-plugin-owned-dom')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
|
||||
});
|
||||
|
||||
await test.step('Alice opens the plugin soundboard modal and plays a sound to voice', async () => {
|
||||
await soundboardComposerButton(scenario.alice.page).click();
|
||||
await expect(scenario.alice.page.getByRole('dialog', { name: SOUND_BOARD_LABEL })).toBeVisible({ timeout: 20_000 });
|
||||
await expect(scenario.alice.page.getByTestId('e2e-soundboard-modal')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
|
||||
await scenario.alice.page.getByRole('button', { name: 'Play airhorn to voice' }).click();
|
||||
await expect(scenario.alice.page.getByTestId('e2e-soundboard-status')).toHaveText(SOUND_BOARD_PLAYED_MESSAGE, { timeout: 20_000 });
|
||||
});
|
||||
|
||||
await test.step('Bob receives messages sent and edited by Alice through the plugin API', async () => {
|
||||
await expect(scenario.bobMessages.getMessageItemByText(EDITED_MESSAGE)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(scenario.bobMessages.getMessageItemByText(ORIGINAL_MESSAGE)).toHaveCount(0);
|
||||
await expect(scenario.bob.page.getByText('(edited)')).toBeVisible({ timeout: 20_000 });
|
||||
});
|
||||
|
||||
await test.step('Bob sees plugin API deletion state and plugin-user messages', async () => {
|
||||
await expect(scenario.bobMessages.getMessageItemByText(DELETED_MESSAGE_CONTENT)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(scenario.bobMessages.getMessageItemByText(DELETED_MESSAGE)).toHaveCount(0);
|
||||
await expect(scenario.bobMessages.getMessageItemByText(PLUGIN_BOT_MESSAGE)).toBeVisible({ timeout: 30_000 });
|
||||
await expect(scenario.bobMessages.getMessageItemByText(SOUND_BOARD_PLAYED_MESSAGE)).toBeVisible({ timeout: 30_000 });
|
||||
});
|
||||
|
||||
await test.step('Bob renders Alice custom embed through the plugin embed API', async () => {
|
||||
await expect(scenario.bob.page.getByTestId('plugin-message-embeds')).toContainText(CUSTOM_EMBED_TEXT, { timeout: 30_000 });
|
||||
});
|
||||
|
||||
await test.step('Bob sees Alice profile name changed by the plugin API', async () => {
|
||||
await expect(scenario.bobMessages.getMessageItemByText(EDITED_MESSAGE)).toContainText('Alice Plugin Renamed', { timeout: 30_000 });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
interface PluginApiScenario {
|
||||
alice: Client;
|
||||
aliceRoom: ChatRoomPage;
|
||||
bob: Client;
|
||||
bobRoom: ChatRoomPage;
|
||||
aliceMessages: ChatMessagesPage;
|
||||
bobMessages: ChatMessagesPage;
|
||||
}
|
||||
|
||||
async function createPluginApiScenario(createClient: () => Promise<Client>): Promise<PluginApiScenario> {
|
||||
const suffix = uniqueName('plugin-api');
|
||||
const serverName = `Plugin API Server ${suffix}`;
|
||||
const alice = await createClient();
|
||||
const bob = await createClient();
|
||||
|
||||
await registerUser(alice.page, `alice_${suffix}`, 'Alice');
|
||||
await registerUser(bob.page, `bob_${suffix}`, 'Bob');
|
||||
|
||||
const aliceSearch = new ServerSearchPage(alice.page);
|
||||
|
||||
await aliceSearch.createServer(serverName, { description: 'Two-user plugin API E2E coverage' });
|
||||
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 30_000 });
|
||||
|
||||
const aliceRoom = new ChatRoomPage(alice.page);
|
||||
|
||||
await aliceRoom.ensureVoiceChannelExists(VOICE_CHANNEL);
|
||||
await installGrantAndActivatePlugin(alice.page, true);
|
||||
await closeSettingsModal(alice.page);
|
||||
await expect(soundboardComposerButton(alice.page)).toBeVisible({ timeout: 20_000 });
|
||||
|
||||
const bobSearch = new ServerSearchPage(bob.page);
|
||||
|
||||
await bobSearch.joinServerFromSearch(serverName, { acceptPluginDownloads: true });
|
||||
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 30_000 });
|
||||
|
||||
const bobRoom = new ChatRoomPage(bob.page);
|
||||
|
||||
await aliceRoom.joinVoiceChannel(VOICE_CHANNEL);
|
||||
await bobRoom.joinVoiceChannel(VOICE_CHANNEL);
|
||||
await expect(aliceRoom.voiceControls).toBeVisible({ timeout: 30_000 });
|
||||
await expect(bobRoom.voiceControls).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
const aliceMessages = new ChatMessagesPage(alice.page);
|
||||
const bobMessages = new ChatMessagesPage(bob.page);
|
||||
|
||||
await aliceMessages.waitForReady();
|
||||
await bobMessages.waitForReady();
|
||||
await expect(alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' })).toBeVisible({ timeout: 30_000 });
|
||||
await expect(bob.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Alice' })).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
return {
|
||||
alice,
|
||||
aliceRoom,
|
||||
bob,
|
||||
bobRoom,
|
||||
aliceMessages,
|
||||
bobMessages
|
||||
};
|
||||
}
|
||||
|
||||
async function registerUser(page: Page, username: string, displayName: string): Promise<void> {
|
||||
const registerPage = new RegisterPage(page);
|
||||
|
||||
await registerPage.goto();
|
||||
await registerPage.register(username, displayName, 'TestPass123!');
|
||||
await expect(page).toHaveURL(/\/search/, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function installGrantAndActivatePlugin(page: Page, installFromStore: boolean): Promise<void> {
|
||||
await page.getByRole('button', { name: 'Plugin Store' }).click();
|
||||
await expect(page).toHaveURL(/\/plugin-store/, { timeout: 20_000 });
|
||||
await expect(page.getByTestId('plugin-store-page')).toBeVisible({ timeout: 20_000 });
|
||||
|
||||
if (installFromStore) {
|
||||
await page.getByLabel('Plugin source manifest URL').fill(PLUGIN_SOURCE_URL);
|
||||
await page.getByRole('button', { name: 'Add Source' }).click();
|
||||
await expect(page.getByRole('heading', { name: PLUGIN_TITLE })).toBeVisible({ timeout: 20_000 });
|
||||
await page.getByRole('button', { exact: true, name: /^(Install|Install to Server)$/ }).click();
|
||||
await expect(page.getByRole('dialog', { name: PLUGIN_TITLE })).toBeVisible({ timeout: 10_000 });
|
||||
await page.getByRole('button', { name: 'Install and Activate' }).click();
|
||||
await expect(page.locator('article', { hasText: PLUGIN_TITLE }).getByText('Installed')).toBeVisible({ timeout: 20_000 });
|
||||
}
|
||||
|
||||
await page.getByRole('button', { name: 'Manage Plugins' }).click();
|
||||
await expect(page.getByTestId('plugin-manager')).toBeVisible({ timeout: 20_000 });
|
||||
await expect(page.locator('article', { hasText: PLUGIN_TITLE })).toBeVisible({ timeout: 20_000 });
|
||||
await page.locator('article', { hasText: PLUGIN_TITLE })
|
||||
.getByRole('button', { name: 'Select' })
|
||||
.click();
|
||||
|
||||
await page.getByRole('button', { name: 'Grant all requested' }).click();
|
||||
await page.getByRole('button', { name: 'Activate ready plugins' }).click();
|
||||
await expect(page.locator('article', { hasText: PLUGIN_TITLE }).getByText('ready', { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
await page.getByRole('button', { name: 'Logs' }).click();
|
||||
await expect(page.getByText('all-api plugin completed')).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
async function closeSettingsModal(page: Page): Promise<void> {
|
||||
await page.keyboard.press('Escape');
|
||||
await expect(page.getByTestId('plugin-manager')).toHaveCount(0);
|
||||
}
|
||||
|
||||
function uniqueName(prefix: string): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(36)
|
||||
.slice(2, 8)}`;
|
||||
}
|
||||
|
||||
function soundboardComposerButton(page: Page) {
|
||||
return page.locator('app-chat-message-composer')
|
||||
.getByRole('button', { exact: true, name: SOUND_BOARD_LABEL });
|
||||
}
|
||||
93
e2e/tests/plugins/plugin-manager-ui.spec.ts
Normal file
93
e2e/tests/plugins/plugin-manager-ui.spec.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { expect, test } from '../../fixtures/multi-client';
|
||||
import { RegisterPage } from '../../pages/register.page';
|
||||
import { ServerSearchPage } from '../../pages/server-search.page';
|
||||
|
||||
test.describe('Plugin manager UI', () => {
|
||||
test.describe.configure({ timeout: 180_000 });
|
||||
|
||||
test('installs, grants, activates, and logs an all-API test plugin', async ({ createClient }) => {
|
||||
const client = await createClient();
|
||||
const { page } = client;
|
||||
const suffix = Date.now();
|
||||
const register = new RegisterPage(page);
|
||||
const search = new ServerSearchPage(page);
|
||||
|
||||
await test.step('Register user and create server context', async () => {
|
||||
await register.goto();
|
||||
await register.register(`plugin_${suffix}`, 'Plugin Tester', 'TestPass123!');
|
||||
await expect(page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
|
||||
await search.createServer(`Plugin API Server ${suffix}`, {
|
||||
description: 'Plugin manager UI E2E coverage'
|
||||
});
|
||||
|
||||
await expect(page).toHaveURL(/\/room\//, { timeout: 30_000 });
|
||||
});
|
||||
|
||||
await test.step('Open visible Plugin Store button', async () => {
|
||||
await page.getByRole('button', { name: 'Plugin Store' }).click();
|
||||
await expect(page).toHaveURL(/\/plugin-store/, { timeout: 10_000 });
|
||||
await expect(page.getByTestId('plugin-store-page')).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
await test.step('Install fixture plugin from source manifest', async () => {
|
||||
await page.getByLabel('Plugin source manifest URL').fill('http://localhost:4200/plugins/e2e-plugin-source.json');
|
||||
await page.getByRole('button', { name: 'Add Source' }).click();
|
||||
await expect(page.getByRole('heading', { name: 'E2E All API Plugin' })).toBeVisible({ timeout: 15_000 });
|
||||
await page.getByRole('button', { name: 'Readme' }).click();
|
||||
await expect(page.getByText('Fixture plugin for Playwright coverage.')).toBeVisible({ timeout: 10_000 });
|
||||
await page.getByRole('button', { exact: true, name: /^(Install|Install to Server)$/ }).click();
|
||||
const installDialog = page.getByRole('dialog', { name: 'E2E All API Plugin' });
|
||||
|
||||
await expect(installDialog).toBeVisible({ timeout: 10_000 });
|
||||
await expect(installDialog.getByText('Install to server', { exact: true })).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Install and Activate' }).click();
|
||||
await expect(page.locator('article', { hasText: 'E2E All API Plugin' }).getByText('Installed')).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
await test.step('Open plugin manager from the store page', async () => {
|
||||
await page.getByRole('button', { name: 'Manage Plugins' }).click();
|
||||
await expect(page.getByTestId('plugin-manager')).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.getByTestId('plugin-manager').getByRole('heading', { name: 'Server plugins' })).toBeVisible();
|
||||
await expect(page.getByText('E2E All API Plugin')).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step('Grant capabilities and activate runtime', async () => {
|
||||
const manager = page.getByTestId('plugin-manager');
|
||||
const pluginCard = manager.locator('article', { hasText: 'E2E All API Plugin' });
|
||||
|
||||
await manager.getByRole('button', { name: 'Installed' }).click();
|
||||
await expect(pluginCard).toBeVisible({ timeout: 10_000 });
|
||||
await pluginCard.getByRole('button', { name: 'Select' }).click();
|
||||
|
||||
await page.getByRole('button', { name: 'Grant all requested' }).click();
|
||||
await page.getByRole('button', { name: 'Activate ready plugins' }).click();
|
||||
await expect(page.locator('article', { hasText: 'E2E All API Plugin' }).getByText('ready', { exact: true })).toBeVisible({ timeout: 20_000 });
|
||||
});
|
||||
|
||||
await test.step('Verify plugin exercised APIs through logs and extension points', async () => {
|
||||
const manager = page.getByTestId('plugin-manager');
|
||||
|
||||
await manager.getByRole('button', { name: 'Logs' }).click();
|
||||
await expect(page.getByText('all-api plugin completed')).toBeVisible({ timeout: 20_000 });
|
||||
await expect(page.getByText('all-api plugin ready')).toBeVisible({ timeout: 10_000 });
|
||||
await manager.getByRole('button', { name: 'Extension points' }).click();
|
||||
await expect(page.getByTestId('plugin-extension-counts')).toContainText('Settings pages');
|
||||
await expect(page.getByTestId('plugin-extension-counts')).toContainText('Embed renderers');
|
||||
await expect(page.getByTestId('plugin-extension-counts')).toContainText('1');
|
||||
await expect(page.getByTestId('plugin-conflict-diagnostics')).toContainText(
|
||||
'No duplicate route, action, embed, channel, panel, or settings contribution ids detected.'
|
||||
);
|
||||
|
||||
await manager.getByRole('button', { exact: true, name: 'Requirements' }).click();
|
||||
await expect(page.getByTestId('plugin-server-requirements')).toContainText('E2E All API Plugin');
|
||||
await expect(page.getByTestId('plugin-server-requirements')).toContainText('enabled');
|
||||
|
||||
await manager.getByRole('button', { exact: true, name: 'Settings' }).click();
|
||||
await expect(page.getByTestId('plugin-generated-settings')).toContainText('E2E settings contribution');
|
||||
await expect(page.getByTestId('plugin-generated-settings')).toContainText('"enabled"');
|
||||
|
||||
await manager.getByRole('button', { exact: true, name: 'Docs' }).click();
|
||||
await expect(page.getByTestId('plugin-installed-docs')).toContainText('Calls every public Toju plugin API surface');
|
||||
});
|
||||
});
|
||||
});
|
||||
369
e2e/tests/plugins/plugin-support-api.spec.ts
Normal file
369
e2e/tests/plugins/plugin-support-api.spec.ts
Normal file
@@ -0,0 +1,369 @@
|
||||
import type { APIRequestContext, APIResponse } from '@playwright/test';
|
||||
import WebSocket from 'ws';
|
||||
import { expect, test } from '../../fixtures/multi-client';
|
||||
import {
|
||||
getPluginApiTestEvent,
|
||||
readPluginApiTestManifest,
|
||||
TEST_PLUGIN_ID,
|
||||
TEST_PLUGIN_P2P_EVENT,
|
||||
TEST_PLUGIN_RELAY_EVENT
|
||||
} from '../../helpers/plugin-api-test-fixture';
|
||||
|
||||
const OWNER_USER_ID = 'plugin-api-owner';
|
||||
|
||||
interface CreatedServerResponse {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface PluginRequirementResponse {
|
||||
requirement: {
|
||||
pluginId: string;
|
||||
reason?: string;
|
||||
status: string;
|
||||
versionRange?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PluginEventDefinitionResponse {
|
||||
eventDefinition: {
|
||||
direction: string;
|
||||
eventName: string;
|
||||
maxPayloadBytes: number;
|
||||
pluginId: string;
|
||||
scope: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PluginSnapshotResponse {
|
||||
eventDefinitions: PluginEventDefinitionResponse['eventDefinition'][];
|
||||
requirements: PluginRequirementResponse['requirement'][];
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
interface SocketMessage {
|
||||
[key: string]: unknown;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
interface TestSocket {
|
||||
close: () => Promise<void>;
|
||||
messages: SocketMessage[];
|
||||
send: (message: SocketMessage) => void;
|
||||
}
|
||||
|
||||
test.describe('Plugin support API', () => {
|
||||
test('covers plugin requirement, event, data, and websocket APIs with the fixture plugin', async ({ request, testServer }) => {
|
||||
const manifest = await readPluginApiTestManifest();
|
||||
const server = await createServer(request, testServer.url, `Plugin API ${Date.now()}`);
|
||||
const relayEvent = getPluginApiTestEvent(manifest, TEST_PLUGIN_RELAY_EVENT);
|
||||
const p2pEvent = getPluginApiTestEvent(manifest, TEST_PLUGIN_P2P_EVENT);
|
||||
const pluginsApi = `${testServer.url}/api/servers/${encodeURIComponent(server.id)}/plugins`;
|
||||
|
||||
await test.step('Initial snapshot is empty', async () => {
|
||||
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
|
||||
|
||||
expect(snapshot).toEqual(expect.objectContaining({
|
||||
eventDefinitions: [],
|
||||
requirements: [],
|
||||
serverId: server.id
|
||||
}));
|
||||
});
|
||||
|
||||
await test.step('Requirement API enforces server management permission', async () => {
|
||||
const response = await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
|
||||
data: {
|
||||
actorUserId: 'not-the-owner',
|
||||
status: 'required'
|
||||
}
|
||||
});
|
||||
const body = await expectJson<{ errorCode: string }>(response, 403);
|
||||
|
||||
expect(body.errorCode).toBe('NOT_AUTHORIZED');
|
||||
});
|
||||
|
||||
await test.step('Requirement and event definition APIs persist the test plugin contract', async () => {
|
||||
const requirement = await expectJson<PluginRequirementResponse>(await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
|
||||
data: {
|
||||
actorUserId: OWNER_USER_ID,
|
||||
reason: manifest.description,
|
||||
status: 'required',
|
||||
versionRange: `^${manifest.version}`
|
||||
}
|
||||
}));
|
||||
|
||||
expect(requirement.requirement).toEqual(expect.objectContaining({
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
reason: manifest.description,
|
||||
status: 'required',
|
||||
versionRange: `^${manifest.version}`
|
||||
}));
|
||||
|
||||
const relayDefinition = await upsertEventDefinition(request, pluginsApi, relayEvent);
|
||||
const p2pDefinition = await upsertEventDefinition(request, pluginsApi, p2pEvent);
|
||||
|
||||
expect(relayDefinition.eventDefinition).toEqual(expect.objectContaining({
|
||||
direction: 'serverRelay',
|
||||
eventName: TEST_PLUGIN_RELAY_EVENT,
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
scope: 'server'
|
||||
}));
|
||||
|
||||
expect(p2pDefinition.eventDefinition).toEqual(expect.objectContaining({
|
||||
direction: 'p2pHint',
|
||||
eventName: TEST_PLUGIN_P2P_EVENT,
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
scope: 'user'
|
||||
}));
|
||||
|
||||
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
|
||||
|
||||
expect(snapshot.requirements.map((entry) => entry.pluginId)).toEqual([TEST_PLUGIN_ID]);
|
||||
expect(snapshot.eventDefinitions.map((entry) => entry.eventName).sort()).toEqual([TEST_PLUGIN_P2P_EVENT, TEST_PLUGIN_RELAY_EVENT]);
|
||||
});
|
||||
|
||||
await test.step('Plugin data API refuses arbitrary server persistence', async () => {
|
||||
const stored = await expectJson<{ errorCode: string }>(await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/data/settings`, {
|
||||
data: {
|
||||
actorUserId: OWNER_USER_ID,
|
||||
schemaVersion: 1,
|
||||
scope: 'server',
|
||||
value: {
|
||||
enabled: true,
|
||||
pluginVersion: manifest.version
|
||||
}
|
||||
}
|
||||
}), 410);
|
||||
|
||||
expect(stored.errorCode).toBe('PLUGIN_DATA_DISABLED');
|
||||
|
||||
const listed = await expectJson<{ errorCode: string }>(await request.get(`${pluginsApi}/${TEST_PLUGIN_ID}/data`, {
|
||||
params: {
|
||||
key: 'settings',
|
||||
scope: 'server',
|
||||
userId: OWNER_USER_ID
|
||||
}
|
||||
}), 410);
|
||||
|
||||
expect(listed.errorCode).toBe('PLUGIN_DATA_DISABLED');
|
||||
|
||||
const afterDelete = await expectJson<{ errorCode: string }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/data/settings`, {
|
||||
data: {
|
||||
actorUserId: OWNER_USER_ID,
|
||||
scope: 'server'
|
||||
}
|
||||
}), 410);
|
||||
|
||||
expect(afterDelete.errorCode).toBe('PLUGIN_DATA_DISABLED');
|
||||
});
|
||||
|
||||
await test.step('WebSocket plugin API sends snapshots, relays server events, and rejects p2p relays', async () => {
|
||||
const alice = await openTestSocket(testServer.url);
|
||||
const bob = await openTestSocket(testServer.url);
|
||||
|
||||
try {
|
||||
alice.send({ type: 'identify', oderId: OWNER_USER_ID, displayName: 'Plugin Owner' });
|
||||
bob.send({ type: 'identify', oderId: 'plugin-api-peer', displayName: 'Plugin Peer' });
|
||||
alice.send({ type: 'join_server', serverId: server.id });
|
||||
bob.send({ type: 'join_server', serverId: server.id });
|
||||
|
||||
const aliceSnapshot = await waitForSocketMessage(alice, (message) => message.type === 'plugin_requirements');
|
||||
const bobSnapshot = await waitForSocketMessage(bob, (message) => message.type === 'plugin_requirements');
|
||||
const bobEventNames = (bobSnapshot['snapshot'] as PluginSnapshotResponse).eventDefinitions
|
||||
.map((entry) => entry.eventName)
|
||||
.sort();
|
||||
|
||||
expect((aliceSnapshot['snapshot'] as PluginSnapshotResponse).requirements[0]?.pluginId).toBe(TEST_PLUGIN_ID);
|
||||
expect(bobEventNames).toEqual([TEST_PLUGIN_P2P_EVENT, TEST_PLUGIN_RELAY_EVENT]);
|
||||
|
||||
alice.send({
|
||||
type: 'plugin_event',
|
||||
eventId: 'relay-event-1',
|
||||
eventName: TEST_PLUGIN_RELAY_EVENT,
|
||||
payload: { message: 'hello from fixture plugin' },
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
serverId: server.id,
|
||||
sourcePluginUserId: 'fixture-plugin-user'
|
||||
});
|
||||
|
||||
const relayedEvent = await waitForSocketMessage(bob, (message) => message.type === 'plugin_event');
|
||||
|
||||
expect(relayedEvent).toEqual(expect.objectContaining({
|
||||
eventId: 'relay-event-1',
|
||||
eventName: TEST_PLUGIN_RELAY_EVENT,
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
serverId: server.id,
|
||||
sourcePluginUserId: 'fixture-plugin-user',
|
||||
sourceUserId: OWNER_USER_ID
|
||||
}));
|
||||
|
||||
expect(relayedEvent['payload']).toEqual({ message: 'hello from fixture plugin' });
|
||||
expect(typeof relayedEvent['emittedAt']).toBe('number');
|
||||
|
||||
alice.send({
|
||||
type: 'plugin_event',
|
||||
eventId: 'p2p-event-1',
|
||||
eventName: TEST_PLUGIN_P2P_EVENT,
|
||||
payload: { hint: true },
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
serverId: server.id
|
||||
});
|
||||
|
||||
const p2pError = await waitForSocketMessage(
|
||||
alice,
|
||||
(message) => message.type === 'plugin_error' && message['eventId'] === 'p2p-event-1'
|
||||
);
|
||||
|
||||
expect(p2pError['code']).toBe('PLUGIN_EVENT_NOT_RELAYABLE');
|
||||
|
||||
alice.send({
|
||||
type: 'plugin_event',
|
||||
eventId: 'missing-event-1',
|
||||
eventName: 'e2e:missing',
|
||||
payload: {},
|
||||
pluginId: TEST_PLUGIN_ID,
|
||||
serverId: server.id
|
||||
});
|
||||
|
||||
const missingError = await waitForSocketMessage(
|
||||
alice,
|
||||
(message) => message.type === 'plugin_error' && message['eventId'] === 'missing-event-1'
|
||||
);
|
||||
|
||||
expect(missingError['code']).toBe('PLUGIN_EVENT_NOT_REGISTERED');
|
||||
} finally {
|
||||
await Promise.all([alice.close(), bob.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
await test.step('Delete APIs remove event definitions and requirements', async () => {
|
||||
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/events/${TEST_PLUGIN_RELAY_EVENT}`, {
|
||||
data: { actorUserId: OWNER_USER_ID }
|
||||
}));
|
||||
|
||||
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/events/${TEST_PLUGIN_P2P_EVENT}`, {
|
||||
data: { actorUserId: OWNER_USER_ID }
|
||||
}));
|
||||
|
||||
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
|
||||
data: { actorUserId: OWNER_USER_ID }
|
||||
}));
|
||||
|
||||
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
|
||||
|
||||
expect(snapshot.eventDefinitions).toEqual([]);
|
||||
expect(snapshot.requirements).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
async function createServer(
|
||||
request: APIRequestContext,
|
||||
baseUrl: string,
|
||||
serverName: string
|
||||
): Promise<CreatedServerResponse> {
|
||||
const response = await request.post(`${baseUrl}/api/servers`, {
|
||||
data: {
|
||||
channels: [
|
||||
{
|
||||
id: 'general-text',
|
||||
name: 'general',
|
||||
position: 0,
|
||||
type: 'text'
|
||||
}
|
||||
],
|
||||
description: 'Server for plugin API E2E coverage',
|
||||
id: `plugin-api-${Date.now()}`,
|
||||
isPrivate: false,
|
||||
name: serverName,
|
||||
ownerId: OWNER_USER_ID,
|
||||
ownerPublicKey: 'plugin-api-owner-public-key',
|
||||
tags: ['plugins']
|
||||
}
|
||||
});
|
||||
|
||||
return await expectJson<CreatedServerResponse>(response, 201);
|
||||
}
|
||||
|
||||
async function upsertEventDefinition(
|
||||
request: APIRequestContext,
|
||||
pluginsApi: string,
|
||||
eventDefinition: ReturnType<typeof getPluginApiTestEvent>
|
||||
): Promise<PluginEventDefinitionResponse> {
|
||||
return await expectJson<PluginEventDefinitionResponse>(await request.put(
|
||||
`${pluginsApi}/${TEST_PLUGIN_ID}/events/${encodeURIComponent(eventDefinition.eventName)}`,
|
||||
{
|
||||
data: {
|
||||
actorUserId: OWNER_USER_ID,
|
||||
direction: eventDefinition.direction,
|
||||
maxPayloadBytes: eventDefinition.maxPayloadBytes,
|
||||
schemaJson: '{"type":"object"}',
|
||||
scope: eventDefinition.scope
|
||||
}
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
async function expectJson<T>(response: APIResponse, status = 200): Promise<T> {
|
||||
expect(response.status()).toBe(status);
|
||||
|
||||
return await response.json() as T;
|
||||
}
|
||||
|
||||
async function openTestSocket(baseUrl: string): Promise<TestSocket> {
|
||||
const socketUrl = baseUrl.replace(/^http/, 'ws');
|
||||
const socket = new WebSocket(socketUrl);
|
||||
const messages: SocketMessage[] = [];
|
||||
|
||||
socket.on('message', (data) => {
|
||||
messages.push(JSON.parse(data.toString()) as SocketMessage);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once('open', () => resolve());
|
||||
socket.once('error', reject);
|
||||
});
|
||||
|
||||
await waitForSocketMessage({ messages, send: () => {}, close: async () => {} }, (message) => message.type === 'connected');
|
||||
|
||||
return {
|
||||
close: async () => {
|
||||
if (socket.readyState === WebSocket.CLOSED) {
|
||||
return;
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
socket.once('close', () => resolve());
|
||||
socket.close();
|
||||
});
|
||||
},
|
||||
messages,
|
||||
send: (message: SocketMessage) => {
|
||||
socket.send(JSON.stringify(message));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function waitForSocketMessage(
|
||||
socket: Pick<TestSocket, 'messages'>,
|
||||
predicate: (message: SocketMessage) => boolean,
|
||||
timeoutMs = 10_000
|
||||
): Promise<SocketMessage> {
|
||||
const startedAt = Date.now();
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
const interval = setInterval(() => {
|
||||
const message = socket.messages.find(predicate);
|
||||
|
||||
if (message) {
|
||||
clearInterval(interval);
|
||||
resolve(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt > timeoutMs) {
|
||||
clearInterval(interval);
|
||||
reject(new Error('Timed out waiting for websocket message'));
|
||||
}
|
||||
}, 25);
|
||||
});
|
||||
}
|
||||
@@ -28,5 +28,6 @@ Electron main-process package for MetoYou / Toju. This directory owns desktop bo
|
||||
## Notes
|
||||
|
||||
- When adding a renderer-facing capability, update the Electron implementation, `preload.ts`, and the renderer bridge in `toju-app/` together.
|
||||
- Plugin client data is stored in the local Electron SQLite database in the dedicated user-scoped `plugin_data` table. Renderer plugins reach it through CQRS commands/queries exposed by the preload bridge; the signal server must not be used for arbitrary plugin data persistence.
|
||||
- Treat `dist/electron/` and `dist-electron/` as generated output.
|
||||
- See [AGENTS.md](AGENTS.md) for package-level editing rules.
|
||||
|
||||
69
electron/api/auth-store.ts
Normal file
69
electron/api/auth-store.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
export interface IssuedToken {
|
||||
token: string;
|
||||
userId: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
signalingServerUrl: string;
|
||||
issuedAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
const tokens = new Map<string, IssuedToken>();
|
||||
|
||||
export function issueToken(params: {
|
||||
userId: string;
|
||||
username: string;
|
||||
displayName: string;
|
||||
signalingServerUrl: string;
|
||||
}): IssuedToken {
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const issuedAt = Date.now();
|
||||
const issued: IssuedToken = {
|
||||
token,
|
||||
issuedAt,
|
||||
expiresAt: issuedAt + TOKEN_TTL_MS,
|
||||
userId: params.userId,
|
||||
username: params.username,
|
||||
displayName: params.displayName,
|
||||
signalingServerUrl: params.signalingServerUrl
|
||||
};
|
||||
|
||||
tokens.set(token, issued);
|
||||
return issued;
|
||||
}
|
||||
|
||||
export function consumeToken(token: string): IssuedToken | null {
|
||||
const issued = tokens.get(token);
|
||||
|
||||
if (!issued) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (issued.expiresAt < Date.now()) {
|
||||
tokens.delete(token);
|
||||
return null;
|
||||
}
|
||||
|
||||
return issued;
|
||||
}
|
||||
|
||||
export function revokeToken(token: string): void {
|
||||
tokens.delete(token);
|
||||
}
|
||||
|
||||
export function clearAllTokens(): void {
|
||||
tokens.clear();
|
||||
}
|
||||
|
||||
export function pruneExpiredTokens(): void {
|
||||
const now = Date.now();
|
||||
|
||||
for (const [token, issued] of tokens) {
|
||||
if (issued.expiresAt < now) {
|
||||
tokens.delete(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
133
electron/api/docs-html.ts
Normal file
133
electron/api/docs-html.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
function getScalarBundleCandidates(): string[] {
|
||||
const processWithResources = process as NodeJS.Process & { resourcesPath?: string };
|
||||
const candidates: string[] = [];
|
||||
|
||||
if (processWithResources.resourcesPath) {
|
||||
candidates.push(path.join(processWithResources.resourcesPath, 'scalar', 'api-reference.js'));
|
||||
}
|
||||
|
||||
candidates.push(path.join(process.cwd(), 'node_modules', '@scalar', 'api-reference', 'dist', 'browser', 'standalone.js'));
|
||||
|
||||
try {
|
||||
candidates.push(path.join(path.dirname(require.resolve('@scalar/api-reference')), 'browser', 'standalone.js'));
|
||||
} catch {
|
||||
// ignore; the packaged app path above is the production path
|
||||
}
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
export async function getScalarApiReferenceBundlePath(): Promise<string | null> {
|
||||
for (const candidate of getScalarBundleCandidates()) {
|
||||
try {
|
||||
await fs.access(candidate);
|
||||
return candidate;
|
||||
} catch {
|
||||
// try the next candidate
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getDocsHtml(specUrl: string): string {
|
||||
const scalarConfig = {
|
||||
url: specUrl,
|
||||
theme: 'default',
|
||||
layout: 'modern',
|
||||
proxyUrl: '',
|
||||
telemetry: false,
|
||||
persistAuth: false,
|
||||
showDeveloperTools: 'never',
|
||||
hideDownloadButton: false,
|
||||
hideTestRequestButton: false,
|
||||
hideClientButton: false,
|
||||
externalUrls: {
|
||||
dashboardUrl: '',
|
||||
registryUrl: '',
|
||||
proxyUrl: '',
|
||||
apiBaseUrl: ''
|
||||
},
|
||||
agent: {
|
||||
disabled: true,
|
||||
hideAddApi: true
|
||||
},
|
||||
mcp: {
|
||||
disabled: true
|
||||
}
|
||||
};
|
||||
const contentSecurityPolicy = [
|
||||
"default-src 'none'",
|
||||
"script-src 'self' 'nonce-metoyou-local-api-docs'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data: blob:",
|
||||
"font-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
"frame-ancestors 'none'"
|
||||
].join('; ');
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="${contentSecurityPolicy}"
|
||||
/>
|
||||
<title>MetoYou Local API</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background: #0b0d11;
|
||||
color: #e6e9ee;
|
||||
}
|
||||
.placeholder {
|
||||
max-width: 720px;
|
||||
margin: 8vh auto;
|
||||
padding: 2rem;
|
||||
background: #14181f;
|
||||
border: 1px solid #232a35;
|
||||
border-radius: 12px;
|
||||
}
|
||||
h1 { margin-top: 0; }
|
||||
a { color: #7aa2f7; }
|
||||
code { background: #1f262f; padding: 0.1rem 0.4rem; border-radius: 4px; }
|
||||
#api-reference { min-height: 100vh; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="api-reference"></div>
|
||||
<noscript>
|
||||
<div class="placeholder">
|
||||
<h1>API Documentation</h1>
|
||||
<p>JavaScript is required to render Scalar. The OpenAPI specification is available directly:</p>
|
||||
<p><a href="${specUrl}">${specUrl}</a></p>
|
||||
</div>
|
||||
</noscript>
|
||||
<script nonce="metoyou-local-api-docs" src="/scalar/api-reference.js"></script>
|
||||
<script nonce="metoyou-local-api-docs">
|
||||
(function () {
|
||||
var config = ${JSON.stringify(scalarConfig)};
|
||||
|
||||
if (!window.Scalar || typeof window.Scalar.createApiReference !== 'function') {
|
||||
var root = document.getElementById('api-reference');
|
||||
root.innerHTML = '<div class="placeholder"><h1>API Documentation</h1>'
|
||||
+ '<p>The bundled Scalar UI could not be loaded.</p>'
|
||||
+ '<p>Spec: <a href="' + config.url + '">' + config.url + '</a></p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
window.Scalar.createApiReference('#api-reference', config);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
108
electron/api/docusaurus-static.ts
Normal file
108
electron/api/docusaurus-static.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import * as path from 'path';
|
||||
import { HttpError } from './http-helpers';
|
||||
|
||||
const MIME_TYPES_BY_EXTENSION: Record<string, string> = {
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.gif': 'image/gif',
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.ico': 'image/x-icon',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.js': 'application/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.map': 'application/json; charset=utf-8',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml; charset=utf-8',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.webp': 'image/webp',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2'
|
||||
};
|
||||
|
||||
function getDocsRootCandidates(): string[] {
|
||||
const processWithResources = process as NodeJS.Process & { resourcesPath?: string };
|
||||
const candidates: string[] = [];
|
||||
|
||||
if (processWithResources.resourcesPath) {
|
||||
candidates.push(path.join(processWithResources.resourcesPath, 'docusaurus'));
|
||||
}
|
||||
|
||||
candidates.push(path.join(process.cwd(), 'docs-site', 'build'));
|
||||
|
||||
return candidates;
|
||||
}
|
||||
|
||||
async function getDocusaurusBuildRoot(): Promise<string | null> {
|
||||
for (const candidate of getDocsRootCandidates()) {
|
||||
try {
|
||||
const stat = await fs.stat(candidate);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
return candidate;
|
||||
}
|
||||
} catch {
|
||||
// try next candidate
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPathInside(parent: string, child: string): boolean {
|
||||
const relative = path.relative(parent, child);
|
||||
|
||||
return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
|
||||
}
|
||||
|
||||
function resolveAssetPath(root: string, pathname: string): string {
|
||||
const withoutPrefix = pathname.replace(/^\/docusaurus\/?/u, '');
|
||||
const decoded = decodeURIComponent(withoutPrefix);
|
||||
const normalized = decoded.endsWith('/') || decoded === '' ? path.join(decoded, 'index.html') : decoded;
|
||||
const absolutePath = path.resolve(root, normalized);
|
||||
|
||||
if (!isPathInside(root, absolutePath)) {
|
||||
throw new HttpError(400, 'Invalid Docusaurus asset path', 'INVALID_DOCS_PATH');
|
||||
}
|
||||
|
||||
return absolutePath;
|
||||
}
|
||||
|
||||
export async function resolveDocusaurusRoute(pathname: string): Promise<{ filePath: string; contentType: string }> {
|
||||
const root = await getDocusaurusBuildRoot();
|
||||
|
||||
if (!root) {
|
||||
throw new HttpError(
|
||||
503,
|
||||
'Docusaurus build is not available. Run npm run build:docs before opening the docs endpoint.',
|
||||
'DOCUSAURUS_BUILD_MISSING'
|
||||
);
|
||||
}
|
||||
|
||||
let filePath = resolveAssetPath(root, pathname);
|
||||
|
||||
try {
|
||||
const stat = await fs.stat(filePath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
filePath = path.join(filePath, 'index.html');
|
||||
}
|
||||
} catch {
|
||||
const directoryIndexPath = path.join(filePath, 'index.html');
|
||||
|
||||
try {
|
||||
await fs.access(directoryIndexPath);
|
||||
filePath = directoryIndexPath;
|
||||
} catch {
|
||||
filePath = path.join(root, '404.html');
|
||||
}
|
||||
}
|
||||
|
||||
if (!isPathInside(root, filePath)) {
|
||||
throw new HttpError(400, 'Invalid Docusaurus asset path', 'INVALID_DOCS_PATH');
|
||||
}
|
||||
|
||||
const contentType = MIME_TYPES_BY_EXTENSION[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
|
||||
|
||||
return { filePath, contentType };
|
||||
}
|
||||
108
electron/api/http-helpers.ts
Normal file
108
electron/api/http-helpers.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { IncomingMessage, ServerResponse } from 'http';
|
||||
|
||||
export interface RequestContext {
|
||||
method: string;
|
||||
url: URL;
|
||||
pathname: string;
|
||||
headers: IncomingMessage['headers'];
|
||||
remoteAddress: string;
|
||||
bearerToken: string | null;
|
||||
}
|
||||
|
||||
const MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MiB
|
||||
|
||||
export function getBearerToken(headers: IncomingMessage['headers']): string | null {
|
||||
const raw = headers.authorization;
|
||||
|
||||
if (typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = raw.trim();
|
||||
|
||||
if (!/^bearer\s+/iu.test(trimmed)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const token = trimmed.replace(/^bearer\s+/iu, '').trim();
|
||||
|
||||
return token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export async function readJsonBody<T>(req: IncomingMessage): Promise<T> {
|
||||
const length = Number(req.headers['content-length'] ?? 0);
|
||||
|
||||
if (length > MAX_BODY_BYTES) {
|
||||
throw new HttpError(413, 'Request body too large', 'BODY_TOO_LARGE');
|
||||
}
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
|
||||
let received = 0;
|
||||
|
||||
for await (const chunk of req) {
|
||||
const buffer = chunk instanceof Buffer ? chunk : Buffer.from(chunk as string);
|
||||
|
||||
received += buffer.length;
|
||||
|
||||
if (received > MAX_BODY_BYTES) {
|
||||
throw new HttpError(413, 'Request body too large', 'BODY_TOO_LARGE');
|
||||
}
|
||||
|
||||
chunks.push(buffer);
|
||||
}
|
||||
|
||||
if (chunks.length === 0) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
throw new HttpError(400, 'Invalid JSON body', 'INVALID_JSON');
|
||||
}
|
||||
}
|
||||
|
||||
export function sendJson(res: ServerResponse, status: number, payload: unknown): void {
|
||||
if (!res.headersSent) {
|
||||
res.statusCode = status;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
export function sendText(res: ServerResponse, status: number, text: string, contentType = 'text/plain; charset=utf-8'): void {
|
||||
if (!res.headersSent) {
|
||||
res.statusCode = status;
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
res.end(text);
|
||||
}
|
||||
|
||||
export class HttpError extends Error {
|
||||
readonly status: number;
|
||||
readonly code: string;
|
||||
|
||||
constructor(status: number, message: string, code: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function sendError(res: ServerResponse, error: unknown): void {
|
||||
if (error instanceof HttpError) {
|
||||
sendJson(res, error.status, { error: error.message, errorCode: error.code });
|
||||
return;
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : 'Internal server error';
|
||||
|
||||
sendJson(res, 500, { error: message, errorCode: 'INTERNAL_ERROR' });
|
||||
}
|
||||
8
electron/api/index.ts
Normal file
8
electron/api/index.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export {
|
||||
applyLocalApiSettings,
|
||||
getLocalApiSnapshot,
|
||||
startLocalApiServer,
|
||||
stopLocalApiServer,
|
||||
type LocalApiSnapshot,
|
||||
type LocalApiStatus
|
||||
} from './local-api-server';
|
||||
286
electron/api/local-api-server.ts
Normal file
286
electron/api/local-api-server.ts
Normal file
@@ -0,0 +1,286 @@
|
||||
import {
|
||||
createServer,
|
||||
IncomingMessage,
|
||||
Server,
|
||||
ServerResponse
|
||||
} from 'http';
|
||||
import { createReadStream } from 'fs';
|
||||
import { AddressInfo } from 'net';
|
||||
import { pipeline } from 'stream/promises';
|
||||
import { getDataSource } from '../db/database';
|
||||
import { LocalApiSettings, readDesktopSettings } from '../desktop-settings';
|
||||
import { authenticate, matchRoute } from './router';
|
||||
import { clearAllTokens } from './auth-store';
|
||||
import {
|
||||
HttpError,
|
||||
RequestContext,
|
||||
getBearerToken,
|
||||
readJsonBody,
|
||||
sendError,
|
||||
sendJson,
|
||||
sendText
|
||||
} from './http-helpers';
|
||||
|
||||
export type LocalApiStatus = 'stopped' | 'starting' | 'running' | 'error';
|
||||
|
||||
export interface LocalApiSnapshot {
|
||||
status: LocalApiStatus;
|
||||
host: string | null;
|
||||
port: number | null;
|
||||
baseUrl: string | null;
|
||||
error: string | null;
|
||||
exposeOnLan: boolean;
|
||||
scalarEnabled: boolean;
|
||||
docusaurusEnabled: boolean;
|
||||
}
|
||||
|
||||
let server: Server | null = null;
|
||||
let currentStatus: LocalApiStatus = 'stopped';
|
||||
let currentBindHost: string | null = null;
|
||||
let currentBindPort: number | null = null;
|
||||
let currentError: string | null = null;
|
||||
let activeSettings: LocalApiSettings | null = null;
|
||||
|
||||
function pickBindHost(settings: LocalApiSettings): string {
|
||||
return settings.exposeOnLan ? '0.0.0.0' : '127.0.0.1';
|
||||
}
|
||||
|
||||
function buildBaseUrl(host: string, port: number): string {
|
||||
const safeHost = host === '0.0.0.0' ? '127.0.0.1' : host;
|
||||
|
||||
return `http://${safeHost}:${port}`;
|
||||
}
|
||||
|
||||
async function sendFile(res: ServerResponse, status: number, filePath: string, contentType: string): Promise<void> {
|
||||
if (!res.headersSent) {
|
||||
res.statusCode = status;
|
||||
res.setHeader('Content-Type', contentType);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
}
|
||||
|
||||
await pipeline(createReadStream(filePath), res);
|
||||
}
|
||||
|
||||
export function getLocalApiSnapshot(): LocalApiSnapshot {
|
||||
const settings = activeSettings ?? readDesktopSettings().localApi;
|
||||
|
||||
return {
|
||||
status: currentStatus,
|
||||
host: currentBindHost,
|
||||
port: currentBindPort,
|
||||
baseUrl: currentBindHost && currentBindPort ? buildBaseUrl(currentBindHost, currentBindPort) : null,
|
||||
error: currentError,
|
||||
exposeOnLan: settings.exposeOnLan,
|
||||
scalarEnabled: settings.scalarEnabled,
|
||||
docusaurusEnabled: settings.docusaurusEnabled
|
||||
};
|
||||
}
|
||||
|
||||
async function handleRequest(req: IncomingMessage, res: ServerResponse, settings: LocalApiSettings): Promise<void> {
|
||||
// CORS for loopback origin only. Local-first; not a public API.
|
||||
const origin = req.headers.origin;
|
||||
const allowOrigin = origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/iu.test(origin) ? origin : 'null';
|
||||
|
||||
res.setHeader('Access-Control-Allow-Origin', allowOrigin);
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
||||
res.setHeader('Access-Control-Max-Age', '600');
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.statusCode = 204;
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let urlObj: URL;
|
||||
|
||||
try {
|
||||
urlObj = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
|
||||
} catch {
|
||||
sendJson(res, 400, { error: 'Invalid URL', errorCode: 'INVALID_URL' });
|
||||
return;
|
||||
}
|
||||
|
||||
const requestContext: RequestContext = {
|
||||
method: (req.method ?? 'GET').toUpperCase(),
|
||||
url: urlObj,
|
||||
pathname: urlObj.pathname,
|
||||
headers: req.headers,
|
||||
remoteAddress: req.socket.remoteAddress ?? '',
|
||||
bearerToken: getBearerToken(req.headers)
|
||||
};
|
||||
const { match, methodNotAllowed } = matchRoute(requestContext.method, requestContext.pathname);
|
||||
|
||||
if (!match) {
|
||||
if (methodNotAllowed) {
|
||||
sendJson(res, 405, { error: 'Method not allowed', errorCode: 'METHOD_NOT_ALLOWED' });
|
||||
} else {
|
||||
sendJson(res, 404, { error: 'Not found', errorCode: 'NOT_FOUND' });
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (match.requiresAuth) {
|
||||
const issued = authenticate(requestContext.bearerToken);
|
||||
|
||||
if (!issued) {
|
||||
sendJson(res, 401, { error: 'Authentication required', errorCode: 'UNAUTHORIZED' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const dataSource = getDataSource() ?? null;
|
||||
|
||||
if (match.requiresDatabase && (!dataSource || !dataSource.isInitialized)) {
|
||||
sendJson(res, 503, { error: 'Database not initialised', errorCode: 'DB_UNAVAILABLE' });
|
||||
return;
|
||||
}
|
||||
|
||||
let bodyCache: unknown | undefined;
|
||||
|
||||
try {
|
||||
const baseUrl = buildBaseUrl(currentBindHost ?? '127.0.0.1', currentBindPort ?? settings.port);
|
||||
const result = await match.handler({
|
||||
request: requestContext,
|
||||
settings,
|
||||
baseUrl,
|
||||
dataSource,
|
||||
bodyBuffer: async () => {
|
||||
if (bodyCache === undefined) {
|
||||
bodyCache = await readJsonBody<unknown>(req);
|
||||
}
|
||||
|
||||
return bodyCache;
|
||||
}
|
||||
});
|
||||
|
||||
if (result.status === 204) {
|
||||
res.statusCode = 204;
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.filePath) {
|
||||
await sendFile(res, result.status, result.filePath, result.contentType ?? 'application/octet-stream');
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.rawBody !== undefined) {
|
||||
sendText(res, result.status, result.rawBody, result.contentType ?? 'text/plain; charset=utf-8');
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(res, result.status, result.body);
|
||||
} catch (error) {
|
||||
if (!(error instanceof HttpError)) {
|
||||
console.error('[LocalApi] Request handler error:', error);
|
||||
}
|
||||
|
||||
sendError(res, error);
|
||||
}
|
||||
}
|
||||
|
||||
export interface StartResult {
|
||||
ok: boolean;
|
||||
snapshot: LocalApiSnapshot;
|
||||
}
|
||||
|
||||
export async function startLocalApiServer(settings: LocalApiSettings): Promise<StartResult> {
|
||||
if (server) {
|
||||
await stopLocalApiServer();
|
||||
}
|
||||
|
||||
activeSettings = { ...settings, allowedSignalingServers: [...settings.allowedSignalingServers] };
|
||||
currentStatus = 'starting';
|
||||
currentError = null;
|
||||
currentBindHost = pickBindHost(settings);
|
||||
currentBindPort = settings.port;
|
||||
const httpServer = createServer((req, res) => {
|
||||
void handleRequest(req, res, activeSettings ?? settings).catch((error) => {
|
||||
console.error('[LocalApi] Unhandled request error:', error);
|
||||
|
||||
try {
|
||||
sendError(res, error);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return await new Promise<StartResult>((resolve) => {
|
||||
httpServer.once('error', (error) => {
|
||||
currentStatus = 'error';
|
||||
currentError = (error as Error).message;
|
||||
currentBindPort = null;
|
||||
server = null;
|
||||
activeSettings = null;
|
||||
console.error('[LocalApi] Failed to start:', error);
|
||||
resolve({ ok: false, snapshot: getLocalApiSnapshot() });
|
||||
});
|
||||
|
||||
httpServer.listen(settings.port, pickBindHost(settings), () => {
|
||||
const address = httpServer.address() as AddressInfo | null;
|
||||
|
||||
server = httpServer;
|
||||
currentStatus = 'running';
|
||||
currentBindPort = address?.port ?? settings.port;
|
||||
currentError = null;
|
||||
console.log(`[LocalApi] Listening on http://${currentBindHost}:${currentBindPort}`);
|
||||
resolve({ ok: true, snapshot: getLocalApiSnapshot() });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function stopLocalApiServer(): Promise<LocalApiSnapshot> {
|
||||
const httpServer = server;
|
||||
|
||||
if (!httpServer) {
|
||||
currentStatus = 'stopped';
|
||||
currentBindHost = null;
|
||||
currentBindPort = null;
|
||||
activeSettings = null;
|
||||
return getLocalApiSnapshot();
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
httpServer.close(() => resolve());
|
||||
// close() waits for connections; force-close keep-alives so it returns promptly.
|
||||
httpServer.closeAllConnections?.();
|
||||
});
|
||||
|
||||
server = null;
|
||||
currentStatus = 'stopped';
|
||||
currentBindHost = null;
|
||||
currentBindPort = null;
|
||||
currentError = null;
|
||||
activeSettings = null;
|
||||
clearAllTokens();
|
||||
console.log('[LocalApi] Stopped');
|
||||
return getLocalApiSnapshot();
|
||||
}
|
||||
|
||||
export async function applyLocalApiSettings(): Promise<LocalApiSnapshot> {
|
||||
const settings = readDesktopSettings().localApi;
|
||||
|
||||
if (!settings.enabled) {
|
||||
return await stopLocalApiServer();
|
||||
}
|
||||
|
||||
// If already running with the same bind config, no-op (settings like
|
||||
// scalarEnabled / allowedSignalingServers are read on every request).
|
||||
if (
|
||||
server
|
||||
&& activeSettings
|
||||
&& currentStatus === 'running'
|
||||
&& activeSettings.port === settings.port
|
||||
&& activeSettings.exposeOnLan === settings.exposeOnLan
|
||||
) {
|
||||
activeSettings = { ...settings, allowedSignalingServers: [...settings.allowedSignalingServers] };
|
||||
return getLocalApiSnapshot();
|
||||
}
|
||||
|
||||
const result = await startLocalApiServer(settings);
|
||||
|
||||
return result.snapshot;
|
||||
}
|
||||
540
electron/api/openapi.ts
Normal file
540
electron/api/openapi.ts
Normal file
@@ -0,0 +1,540 @@
|
||||
export interface OpenApiBuildOptions {
|
||||
baseUrl: string;
|
||||
appVersion: string;
|
||||
}
|
||||
|
||||
export function buildOpenApiDocument(options: OpenApiBuildOptions): unknown {
|
||||
const { baseUrl, appVersion } = options;
|
||||
const roomIdPathParameter = { name: 'roomId', in: 'path', required: true, schema: { type: 'string' } };
|
||||
const userIdPathParameter = { name: 'userId', in: 'path', required: true, schema: { type: 'string' } };
|
||||
const messageIdPathParameter = { name: 'messageId', in: 'path', required: true, schema: { type: 'string' } };
|
||||
const sinceTimestampQueryParameter = {
|
||||
name: 'sinceTimestamp',
|
||||
in: 'query',
|
||||
required: true,
|
||||
schema: { type: 'integer', minimum: 0, format: 'int64' }
|
||||
};
|
||||
|
||||
return {
|
||||
openapi: '3.1.0',
|
||||
info: {
|
||||
title: 'MetoYou Local Desktop API',
|
||||
version: appVersion,
|
||||
description:
|
||||
'Authenticated local HTTP API exposed by the MetoYou desktop app. '
|
||||
+ 'Authentication is performed against a configured signaling server. '
|
||||
+ 'Bearer tokens issued here are scoped to this device only.'
|
||||
},
|
||||
servers: [{ url: baseUrl }],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'opaque'
|
||||
}
|
||||
},
|
||||
schemas: {
|
||||
Error: {
|
||||
type: 'object',
|
||||
required: ['error'],
|
||||
properties: {
|
||||
error: { type: 'string' },
|
||||
errorCode: { type: 'string' }
|
||||
}
|
||||
},
|
||||
LoginRequest: {
|
||||
type: 'object',
|
||||
required: [
|
||||
'username',
|
||||
'password',
|
||||
'serverUrl'
|
||||
],
|
||||
properties: {
|
||||
username: { type: 'string' },
|
||||
password: { type: 'string' },
|
||||
serverUrl: {
|
||||
type: 'string',
|
||||
format: 'uri',
|
||||
description: 'Base URL of the signaling server to authenticate against. Must be in the allowed list configured in the desktop app.'
|
||||
}
|
||||
}
|
||||
},
|
||||
LoginResponse: {
|
||||
type: 'object',
|
||||
required: [
|
||||
'token',
|
||||
'expiresAt',
|
||||
'user'
|
||||
],
|
||||
properties: {
|
||||
token: { type: 'string' },
|
||||
expiresAt: { type: 'integer', format: 'int64' },
|
||||
user: { $ref: '#/components/schemas/AuthUser' }
|
||||
}
|
||||
},
|
||||
AuthUser: {
|
||||
type: 'object',
|
||||
required: [
|
||||
'id',
|
||||
'username',
|
||||
'displayName'
|
||||
],
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
username: { type: 'string' },
|
||||
displayName: { type: 'string' }
|
||||
}
|
||||
},
|
||||
Profile: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
username: { type: 'string' },
|
||||
displayName: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
avatarUrl: { type: 'string' },
|
||||
status: { type: 'string' }
|
||||
}
|
||||
},
|
||||
Room: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
name: { type: 'string' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
User: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
oderId: { type: 'string' },
|
||||
username: { type: 'string' },
|
||||
displayName: { type: 'string' },
|
||||
status: { type: 'string' },
|
||||
role: { type: 'string' },
|
||||
isOnline: { type: 'boolean' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
Message: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
roomId: { type: 'string' },
|
||||
channelId: { type: 'string' },
|
||||
senderId: { type: 'string' },
|
||||
senderName: { type: 'string' },
|
||||
content: { type: 'string' },
|
||||
timestamp: { type: 'integer', format: 'int64' },
|
||||
editedAt: { type: 'integer', format: 'int64' },
|
||||
isDeleted: { type: 'boolean' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
Reaction: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
messageId: { type: 'string' },
|
||||
userId: { type: 'string' },
|
||||
oderId: { type: 'string' },
|
||||
emoji: { type: 'string' },
|
||||
timestamp: { type: 'integer', format: 'int64' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
Attachment: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
messageId: { type: 'string' },
|
||||
filename: { type: 'string' },
|
||||
size: { type: 'integer' },
|
||||
mime: { type: 'string' },
|
||||
isImage: { type: 'boolean' },
|
||||
filePath: { type: 'string' },
|
||||
savedPath: { type: 'string' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
Ban: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
oderId: { type: 'string' },
|
||||
roomId: { type: 'string' },
|
||||
userId: { type: 'string' },
|
||||
bannedBy: { type: 'string' },
|
||||
displayName: { type: 'string' },
|
||||
reason: { type: 'string' },
|
||||
expiresAt: { type: 'integer', format: 'int64' },
|
||||
timestamp: { type: 'integer', format: 'int64' }
|
||||
},
|
||||
additionalProperties: true
|
||||
},
|
||||
PluginDataValue: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
value: {}
|
||||
}
|
||||
},
|
||||
MetaValue: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
key: { type: 'string' },
|
||||
value: { type: ['string', 'null'] }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
security: [{ bearerAuth: [] }],
|
||||
paths: {
|
||||
'/api/health': {
|
||||
get: {
|
||||
security: [],
|
||||
summary: 'Liveness probe',
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Service is alive',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: { type: 'string' },
|
||||
version: { type: 'string' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/openapi.json': {
|
||||
get: {
|
||||
security: [],
|
||||
summary: 'OpenAPI specification',
|
||||
responses: { '200': { description: 'This document' } }
|
||||
}
|
||||
},
|
||||
'/api/auth/login': {
|
||||
post: {
|
||||
security: [],
|
||||
summary: 'Exchange username/password (validated by a signaling server) for a bearer token',
|
||||
requestBody: {
|
||||
required: true,
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/LoginRequest' }
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Token issued',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/LoginResponse' }
|
||||
}
|
||||
}
|
||||
},
|
||||
'401': {
|
||||
description: 'Invalid credentials',
|
||||
content: {
|
||||
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
|
||||
}
|
||||
},
|
||||
'403': {
|
||||
description: 'Signaling server URL not allowed',
|
||||
content: {
|
||||
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/auth/logout': {
|
||||
post: {
|
||||
summary: 'Revoke the current bearer token',
|
||||
responses: { '204': { description: 'Token revoked' } }
|
||||
}
|
||||
},
|
||||
'/api/profile': {
|
||||
get: {
|
||||
summary: 'Get the current user profile',
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Current user profile',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/Profile' }
|
||||
}
|
||||
}
|
||||
},
|
||||
'404': {
|
||||
description: 'No current user is set on this device',
|
||||
content: {
|
||||
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms': {
|
||||
get: {
|
||||
summary: 'List rooms (servers) known to this device',
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Rooms array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'array',
|
||||
items: { $ref: '#/components/schemas/Room' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}': {
|
||||
get: {
|
||||
summary: 'Get a room by id',
|
||||
parameters: [roomIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Room details',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/Room' }
|
||||
}
|
||||
}
|
||||
},
|
||||
'404': {
|
||||
description: 'Room not found',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}/users': {
|
||||
get: {
|
||||
summary: 'List users known for a room',
|
||||
parameters: [roomIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Users array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/User' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}/messages': {
|
||||
get: {
|
||||
summary: 'List messages for a room',
|
||||
parameters: [
|
||||
roomIdPathParameter,
|
||||
{ name: 'limit', in: 'query', required: false, schema: { type: 'integer', minimum: 1, maximum: 500 } },
|
||||
{ name: 'offset', in: 'query', required: false, schema: { type: 'integer', minimum: 0 } }
|
||||
],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Messages array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'array',
|
||||
items: { $ref: '#/components/schemas/Message' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}/messages/since': {
|
||||
get: {
|
||||
summary: 'List room messages after a timestamp',
|
||||
parameters: [roomIdPathParameter, sinceTimestampQueryParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Messages array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Message' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}/bans': {
|
||||
get: {
|
||||
summary: 'List active bans for a room',
|
||||
parameters: [roomIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Bans array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Ban' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/rooms/{roomId}/bans/{userId}': {
|
||||
get: {
|
||||
summary: 'Check whether a user is banned in a room',
|
||||
parameters: [roomIdPathParameter, userIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Ban status',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: {
|
||||
type: 'object',
|
||||
required: ['isBanned'],
|
||||
properties: { isBanned: { type: 'boolean' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/messages/{messageId}': {
|
||||
get: {
|
||||
summary: 'Get a message by id',
|
||||
parameters: [messageIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Message details',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/Message' }
|
||||
}
|
||||
}
|
||||
},
|
||||
'404': {
|
||||
description: 'Message not found',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/messages/{messageId}/reactions': {
|
||||
get: {
|
||||
summary: 'List reactions for a message',
|
||||
parameters: [messageIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Reactions array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Reaction' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/messages/{messageId}/attachments': {
|
||||
get: {
|
||||
summary: 'List attachments for a message',
|
||||
parameters: [messageIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Attachments array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Attachment' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/users/{userId}': {
|
||||
get: {
|
||||
summary: 'Get a user by id',
|
||||
parameters: [userIdPathParameter],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'User details',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/User' }
|
||||
}
|
||||
}
|
||||
},
|
||||
'404': {
|
||||
description: 'User not found',
|
||||
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/attachments': {
|
||||
get: {
|
||||
summary: 'List all attachments stored on this device',
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Attachments array',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array', items: { $ref: '#/components/schemas/Attachment' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/plugin-data': {
|
||||
get: {
|
||||
summary: 'Read a plugin data value',
|
||||
parameters: [
|
||||
{ name: 'pluginId', in: 'query', required: true, schema: { type: 'string' } },
|
||||
{ name: 'key', in: 'query', required: true, schema: { type: 'string' } },
|
||||
{ name: 'scope', in: 'query', required: true, schema: { type: 'string', enum: ['local', 'server'] } },
|
||||
{ name: 'serverId', in: 'query', required: false, schema: { type: 'string' } }
|
||||
],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Plugin data value',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/PluginDataValue' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'/api/meta/{key}': {
|
||||
get: {
|
||||
summary: 'Read a desktop metadata value',
|
||||
parameters: [{ name: 'key', in: 'path', required: true, schema: { type: 'string' } }],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Metadata value',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { $ref: '#/components/schemas/MetaValue' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
511
electron/api/router.ts
Normal file
511
electron/api/router.ts
Normal file
@@ -0,0 +1,511 @@
|
||||
import { app, net } from 'electron';
|
||||
import { DataSource } from 'typeorm';
|
||||
import { buildQueryHandlers } from '../cqrs/queries';
|
||||
import {
|
||||
QueryType,
|
||||
QueryTypeKey,
|
||||
Query
|
||||
} from '../cqrs/types';
|
||||
import {
|
||||
issueToken,
|
||||
consumeToken,
|
||||
revokeToken,
|
||||
IssuedToken
|
||||
} from './auth-store';
|
||||
import { buildOpenApiDocument } from './openapi';
|
||||
import { HttpError, RequestContext } from './http-helpers';
|
||||
import { getDocsHtml, getScalarApiReferenceBundlePath } from './docs-html';
|
||||
import { resolveDocusaurusRoute } from './docusaurus-static';
|
||||
import { LocalApiSettings } from '../desktop-settings';
|
||||
|
||||
export interface RouteResponse {
|
||||
status: number;
|
||||
body: unknown;
|
||||
contentType?: string;
|
||||
filePath?: string;
|
||||
rawBody?: string;
|
||||
}
|
||||
|
||||
export interface RouteContext {
|
||||
request: RequestContext;
|
||||
settings: LocalApiSettings;
|
||||
baseUrl: string;
|
||||
dataSource: DataSource | null;
|
||||
bodyBuffer: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
type RouteHandler = (context: RouteContext) => Promise<RouteResponse>;
|
||||
|
||||
interface RouteMatch {
|
||||
handler: RouteHandler;
|
||||
params: Record<string, string>;
|
||||
requiresAuth: boolean;
|
||||
requiresDatabase: boolean;
|
||||
}
|
||||
|
||||
interface RouteDefinition {
|
||||
method: string;
|
||||
pattern: RegExp;
|
||||
paramKeys: string[];
|
||||
handler: RouteHandler;
|
||||
requiresAuth: boolean;
|
||||
requiresDatabase: boolean;
|
||||
}
|
||||
|
||||
function compilePattern(template: string): { pattern: RegExp; paramKeys: string[] } {
|
||||
const paramKeys: string[] = [];
|
||||
const escaped = template.replace(/[.*+?^${}()|[\]\\]/g, (match) => {
|
||||
if (match === '*' || match === '+' || match === '?')
|
||||
return `\\${match}`;
|
||||
|
||||
return `\\${match}`;
|
||||
});
|
||||
const source = template.replace(/\{([^}]+)\}/g, (_full, key: string) => {
|
||||
paramKeys.push(key);
|
||||
return '([^/]+)';
|
||||
});
|
||||
|
||||
void escaped;
|
||||
|
||||
return { pattern: new RegExp(`^${source}$`), paramKeys };
|
||||
}
|
||||
|
||||
function defineRoute(method: string, template: string, handler: RouteHandler, requiresAuth: boolean, requiresDatabase = true): RouteDefinition {
|
||||
const compiled = compilePattern(template);
|
||||
|
||||
return { method: method.toUpperCase(), pattern: compiled.pattern, paramKeys: compiled.paramKeys, handler, requiresAuth, requiresDatabase };
|
||||
}
|
||||
|
||||
function runQuery<T>(dataSource: DataSource, query: Query): Promise<T> {
|
||||
const handlers = buildQueryHandlers(dataSource) as Record<QueryTypeKey, (q: Query) => Promise<unknown>>;
|
||||
const handler = handlers[query.type as QueryTypeKey];
|
||||
|
||||
if (!handler) {
|
||||
throw new HttpError(500, `No handler registered for query: ${query.type}`, 'UNKNOWN_QUERY');
|
||||
}
|
||||
|
||||
return handler(query) as Promise<T>;
|
||||
}
|
||||
|
||||
function requireDataSource(dataSource: DataSource | null): DataSource {
|
||||
if (!dataSource) {
|
||||
throw new HttpError(503, 'Database not initialised', 'DB_UNAVAILABLE');
|
||||
}
|
||||
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
|
||||
const parsed = typeof value === 'string' ? Number(value) : NaN;
|
||||
|
||||
if (!Number.isFinite(parsed))
|
||||
return fallback;
|
||||
|
||||
return Math.max(min, Math.min(max, Math.floor(parsed)));
|
||||
}
|
||||
|
||||
function getTrailingPathParam(pathname: string, pattern: RegExp, name: string): string {
|
||||
const value = pattern.exec(pathname)?.[1];
|
||||
|
||||
if (!value) {
|
||||
throw new HttpError(400, `${name} is required`, 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
return decodeURIComponent(value);
|
||||
}
|
||||
|
||||
function getRequiredQueryParam(ctx: RouteContext, name: string): string {
|
||||
const value = ctx.request.url.searchParams.get(name)?.trim() ?? '';
|
||||
|
||||
if (!value) {
|
||||
throw new HttpError(400, `${name} is required`, 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function getRequiredTimestamp(ctx: RouteContext, name: string): number {
|
||||
const raw = getRequiredQueryParam(ctx, name);
|
||||
const value = Number(raw);
|
||||
|
||||
if (!Number.isFinite(value) || value < 0) {
|
||||
throw new HttpError(400, `${name} must be a non-negative timestamp`, 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
return Math.floor(value);
|
||||
}
|
||||
|
||||
const ROUTES: RouteDefinition[] = [
|
||||
defineRoute('GET', '/api/health', async (ctx): Promise<RouteResponse> => ({
|
||||
status: 200,
|
||||
body: { status: 'ok', version: app.getVersion(), timestamp: Date.now(), exposeOnLan: ctx.settings.exposeOnLan }
|
||||
}), false, false),
|
||||
|
||||
defineRoute('GET', '/api/openapi.json', async (ctx): Promise<RouteResponse> => ({
|
||||
status: 200,
|
||||
body: buildOpenApiDocument({ baseUrl: ctx.baseUrl, appVersion: app.getVersion() })
|
||||
}), false, false),
|
||||
|
||||
defineRoute('GET', '/docs', async (ctx): Promise<RouteResponse> => {
|
||||
if (!ctx.settings.scalarEnabled) {
|
||||
return {
|
||||
status: 404,
|
||||
body: null,
|
||||
contentType: 'text/plain; charset=utf-8',
|
||||
rawBody: 'API documentation is disabled. Enable Scalar in desktop settings to view it.'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
body: null,
|
||||
contentType: 'text/html; charset=utf-8',
|
||||
rawBody: getDocsHtml(`${ctx.baseUrl}/api/openapi.json`)
|
||||
};
|
||||
}, false, false),
|
||||
|
||||
defineRoute('GET', '/docusaurus(?:/.*)?', async (ctx): Promise<RouteResponse> => {
|
||||
if (!ctx.settings.docusaurusEnabled) {
|
||||
return {
|
||||
status: 404,
|
||||
body: null,
|
||||
contentType: 'text/plain; charset=utf-8',
|
||||
rawBody: 'Docusaurus documentation is disabled. Open documentation from the desktop app to activate it.'
|
||||
};
|
||||
}
|
||||
|
||||
const docsRoute = await resolveDocusaurusRoute(ctx.request.pathname);
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
body: null,
|
||||
contentType: docsRoute.contentType,
|
||||
filePath: docsRoute.filePath
|
||||
};
|
||||
}, false, false),
|
||||
|
||||
defineRoute('GET', '/scalar/api-reference.js', async (ctx): Promise<RouteResponse> => {
|
||||
if (!ctx.settings.scalarEnabled) {
|
||||
return {
|
||||
status: 404,
|
||||
body: null,
|
||||
contentType: 'text/plain; charset=utf-8',
|
||||
rawBody: 'API documentation is disabled. Enable Scalar in desktop settings to view it.'
|
||||
};
|
||||
}
|
||||
|
||||
const bundlePath = await getScalarApiReferenceBundlePath();
|
||||
|
||||
if (!bundlePath) {
|
||||
throw new HttpError(503, 'Scalar API reference bundle is not available in this build', 'SCALAR_BUNDLE_MISSING');
|
||||
}
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
body: null,
|
||||
contentType: 'application/javascript; charset=utf-8',
|
||||
filePath: bundlePath
|
||||
};
|
||||
}, false, false),
|
||||
|
||||
defineRoute('POST', '/api/auth/login', async (ctx): Promise<RouteResponse> => {
|
||||
const body = await ctx.bodyBuffer() as { username?: unknown; password?: unknown; serverUrl?: unknown };
|
||||
const username = typeof body.username === 'string' ? body.username.trim() : '';
|
||||
const password = typeof body.password === 'string' ? body.password : '';
|
||||
const serverUrl = typeof body.serverUrl === 'string' ? body.serverUrl.trim().replace(/\/+$/u, '') : '';
|
||||
|
||||
if (!username || !password || !serverUrl) {
|
||||
throw new HttpError(400, 'username, password, and serverUrl are required', 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
if (!/^https?:\/\//iu.test(serverUrl)) {
|
||||
throw new HttpError(400, 'serverUrl must be an http or https URL', 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
if (ctx.settings.allowedSignalingServers.length === 0) {
|
||||
throw new HttpError(403, 'No signaling servers are allowed for local API authentication. Add one in desktop settings.', 'NO_ALLOWED_SERVERS');
|
||||
}
|
||||
|
||||
if (!ctx.settings.allowedSignalingServers.includes(serverUrl)) {
|
||||
throw new HttpError(403, 'Signaling server URL is not in the allowed list', 'SERVER_NOT_ALLOWED');
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
response = await net.fetch(`${serverUrl}/api/users/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
} catch (error) {
|
||||
throw new HttpError(502, `Failed to reach signaling server: ${(error as Error).message}`, 'UPSTREAM_UNREACHABLE');
|
||||
}
|
||||
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new HttpError(401, 'Invalid credentials', 'INVALID_CREDENTIALS');
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new HttpError(502, `Signaling server rejected login (${response.status})`, 'UPSTREAM_ERROR');
|
||||
}
|
||||
|
||||
const remote = await response.json() as { id?: string; username?: string; displayName?: string };
|
||||
|
||||
if (!remote.id || !remote.username) {
|
||||
throw new HttpError(502, 'Signaling server returned an unexpected response', 'UPSTREAM_BAD_RESPONSE');
|
||||
}
|
||||
|
||||
const issued = issueToken({
|
||||
userId: remote.id,
|
||||
username: remote.username,
|
||||
displayName: remote.displayName ?? remote.username,
|
||||
signalingServerUrl: serverUrl
|
||||
});
|
||||
|
||||
return {
|
||||
status: 200,
|
||||
body: {
|
||||
token: issued.token,
|
||||
expiresAt: issued.expiresAt,
|
||||
user: {
|
||||
id: issued.userId,
|
||||
username: issued.username,
|
||||
displayName: issued.displayName
|
||||
}
|
||||
}
|
||||
};
|
||||
}, false),
|
||||
|
||||
defineRoute('POST', '/api/auth/logout', async (ctx): Promise<RouteResponse> => {
|
||||
if (ctx.request.bearerToken) {
|
||||
revokeToken(ctx.request.bearerToken);
|
||||
}
|
||||
|
||||
return { status: 204, body: null };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/profile', async (ctx): Promise<RouteResponse> => {
|
||||
const user = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetCurrentUser,
|
||||
payload: {}
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new HttpError(404, 'No current user is set on this device', 'NO_CURRENT_USER');
|
||||
}
|
||||
|
||||
return { status: 200, body: user };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms', async (ctx): Promise<RouteResponse> => {
|
||||
const rooms = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetAllRooms,
|
||||
payload: {}
|
||||
});
|
||||
|
||||
return { status: 200, body: rooms ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}', async (ctx): Promise<RouteResponse> => {
|
||||
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)$/u, 'roomId');
|
||||
const room = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetRoom,
|
||||
payload: { roomId }
|
||||
});
|
||||
|
||||
if (!room) {
|
||||
throw new HttpError(404, 'Room not found on this device', 'ROOM_NOT_FOUND');
|
||||
}
|
||||
|
||||
return { status: 200, body: room };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}/users', async (ctx): Promise<RouteResponse> => {
|
||||
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/users$/u, 'roomId');
|
||||
const users = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetUsersByRoom,
|
||||
payload: { roomId }
|
||||
});
|
||||
|
||||
return { status: 200, body: users ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}/messages', async (ctx): Promise<RouteResponse> => {
|
||||
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/messages$/u, 'roomId');
|
||||
const limit = clampInt(ctx.request.url.searchParams.get('limit'), 1, 500, 100);
|
||||
const offset = clampInt(ctx.request.url.searchParams.get('offset'), 0, Number.MAX_SAFE_INTEGER, 0);
|
||||
const messages = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetMessages,
|
||||
payload: { roomId, limit, offset }
|
||||
});
|
||||
|
||||
return { status: 200, body: messages ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}/messages/since', async (ctx): Promise<RouteResponse> => {
|
||||
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/messages\/since$/u, 'roomId');
|
||||
const sinceTimestamp = getRequiredTimestamp(ctx, 'sinceTimestamp');
|
||||
const messages = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetMessagesSince,
|
||||
payload: { roomId, sinceTimestamp }
|
||||
});
|
||||
|
||||
return { status: 200, body: messages ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}/bans', async (ctx): Promise<RouteResponse> => {
|
||||
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/bans$/u, 'roomId');
|
||||
const bans = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetBansForRoom,
|
||||
payload: { roomId }
|
||||
});
|
||||
|
||||
return { status: 200, body: bans ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/rooms/{roomId}/bans/{userId}', async (ctx): Promise<RouteResponse> => {
|
||||
const match = /\/api\/rooms\/([^/]+)\/bans\/([^/]+)$/u.exec(ctx.request.pathname);
|
||||
|
||||
if (!match) {
|
||||
throw new HttpError(400, 'roomId and userId are required', 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
const isBanned = await runQuery<boolean>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.IsUserBanned,
|
||||
payload: { roomId: decodeURIComponent(match[1]), userId: decodeURIComponent(match[2]) }
|
||||
});
|
||||
|
||||
return { status: 200, body: { isBanned } };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/messages/{messageId}', async (ctx): Promise<RouteResponse> => {
|
||||
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)$/u, 'messageId');
|
||||
const message = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetMessageById,
|
||||
payload: { messageId }
|
||||
});
|
||||
|
||||
if (!message) {
|
||||
throw new HttpError(404, 'Message not found on this device', 'MESSAGE_NOT_FOUND');
|
||||
}
|
||||
|
||||
return { status: 200, body: message };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/messages/{messageId}/reactions', async (ctx): Promise<RouteResponse> => {
|
||||
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)\/reactions$/u, 'messageId');
|
||||
const reactions = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetReactionsForMessage,
|
||||
payload: { messageId }
|
||||
});
|
||||
|
||||
return { status: 200, body: reactions ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/messages/{messageId}/attachments', async (ctx): Promise<RouteResponse> => {
|
||||
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)\/attachments$/u, 'messageId');
|
||||
const attachments = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetAttachmentsForMessage,
|
||||
payload: { messageId }
|
||||
});
|
||||
|
||||
return { status: 200, body: attachments ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/users/{userId}', async (ctx): Promise<RouteResponse> => {
|
||||
const userId = getTrailingPathParam(ctx.request.pathname, /\/api\/users\/([^/]+)$/u, 'userId');
|
||||
const user = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetUser,
|
||||
payload: { userId }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new HttpError(404, 'User not found on this device', 'USER_NOT_FOUND');
|
||||
}
|
||||
|
||||
return { status: 200, body: user };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/attachments', async (ctx): Promise<RouteResponse> => {
|
||||
const attachments = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetAllAttachments,
|
||||
payload: {}
|
||||
});
|
||||
|
||||
return { status: 200, body: attachments ?? [] };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/plugin-data', async (ctx): Promise<RouteResponse> => {
|
||||
const pluginId = getRequiredQueryParam(ctx, 'pluginId');
|
||||
const key = getRequiredQueryParam(ctx, 'key');
|
||||
const scope = getRequiredQueryParam(ctx, 'scope');
|
||||
|
||||
if (scope !== 'local' && scope !== 'server') {
|
||||
throw new HttpError(400, 'scope must be local or server', 'INVALID_REQUEST');
|
||||
}
|
||||
|
||||
const value = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetPluginData,
|
||||
payload: {
|
||||
key,
|
||||
pluginId,
|
||||
scope,
|
||||
serverId: ctx.request.url.searchParams.get('serverId') ?? undefined
|
||||
}
|
||||
});
|
||||
|
||||
return { status: 200, body: { value } };
|
||||
}, true),
|
||||
|
||||
defineRoute('GET', '/api/meta/{key}', async (ctx): Promise<RouteResponse> => {
|
||||
const key = getTrailingPathParam(ctx.request.pathname, /\/api\/meta\/([^/]+)$/u, 'key');
|
||||
const value = await runQuery<string | null>(requireDataSource(ctx.dataSource), {
|
||||
type: QueryType.GetMeta,
|
||||
payload: { key }
|
||||
});
|
||||
|
||||
return { status: 200, body: { key, value } };
|
||||
}, true)
|
||||
];
|
||||
|
||||
export interface RoutingResult {
|
||||
match: RouteMatch | null;
|
||||
methodNotAllowed: boolean;
|
||||
}
|
||||
|
||||
export function matchRoute(method: string, pathname: string): RoutingResult {
|
||||
let methodNotAllowed = false;
|
||||
|
||||
for (const route of ROUTES) {
|
||||
const result = route.pattern.exec(pathname);
|
||||
|
||||
if (!result)
|
||||
continue;
|
||||
|
||||
if (route.method !== method) {
|
||||
methodNotAllowed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
for (let index = 0; index < route.paramKeys.length; index++) {
|
||||
params[route.paramKeys[index]] = result[index + 1];
|
||||
}
|
||||
|
||||
return {
|
||||
match: { handler: route.handler, params, requiresAuth: route.requiresAuth, requiresDatabase: route.requiresDatabase },
|
||||
methodNotAllowed: false
|
||||
};
|
||||
}
|
||||
|
||||
return { match: null, methodNotAllowed };
|
||||
}
|
||||
|
||||
export function authenticate(token: string | null): IssuedToken | null {
|
||||
if (!token)
|
||||
return null;
|
||||
|
||||
return consumeToken(token);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { app, BrowserWindow } from 'electron';
|
||||
import { cleanupLinuxScreenShareAudioRouting } from '../audio/linux-screen-share-routing';
|
||||
import { initializeDesktopUpdater, shutdownDesktopUpdater } from '../update/desktop-updater';
|
||||
import { synchronizeAutoStartSetting } from './auto-start';
|
||||
import { applyLocalApiSettings, stopLocalApiServer } from '../api';
|
||||
import {
|
||||
initializeDatabase,
|
||||
destroyDatabase,
|
||||
@@ -21,6 +22,14 @@ import {
|
||||
} from '../ipc';
|
||||
import { startIdleMonitor, stopIdleMonitor } from '../idle/idle-monitor';
|
||||
|
||||
function startLocalApiAfterWindowReady(): void {
|
||||
setImmediate(() => {
|
||||
void applyLocalApiSettings().catch((error: unknown) => {
|
||||
console.error('[LocalApi] Failed to apply settings after window startup:', error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function registerAppLifecycle(): void {
|
||||
app.whenReady().then(async () => {
|
||||
const dockIconPath = getDockIconPath();
|
||||
@@ -35,6 +44,7 @@ export function registerAppLifecycle(): void {
|
||||
await synchronizeAutoStartSetting();
|
||||
initializeDesktopUpdater();
|
||||
await createWindow();
|
||||
startLocalApiAfterWindowReady();
|
||||
startIdleMonitor();
|
||||
|
||||
app.on('activate', () => {
|
||||
@@ -60,6 +70,7 @@ export function registerAppLifecycle(): void {
|
||||
event.preventDefault();
|
||||
shutdownDesktopUpdater();
|
||||
stopIdleMonitor();
|
||||
await stopLocalApiServer();
|
||||
await cleanupLinuxScreenShareAudioRouting();
|
||||
await destroyDatabase();
|
||||
app.quit();
|
||||
|
||||
@@ -11,7 +11,8 @@ import {
|
||||
ReactionEntity,
|
||||
BanEntity,
|
||||
AttachmentEntity,
|
||||
MetaEntity
|
||||
MetaEntity,
|
||||
PluginDataEntity
|
||||
} from '../../../entities';
|
||||
|
||||
export async function handleClearAllData(dataSource: DataSource): Promise<void> {
|
||||
@@ -27,4 +28,5 @@ export async function handleClearAllData(dataSource: DataSource): Promise<void>
|
||||
await dataSource.getRepository(BanEntity).clear();
|
||||
await dataSource.getRepository(AttachmentEntity).clear();
|
||||
await dataSource.getRepository(MetaEntity).clear();
|
||||
await dataSource.getRepository(PluginDataEntity).clear();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { MessageEntity } from '../../../entities';
|
||||
import { ClearRoomMessagesCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleClearRoomMessages(command: ClearRoomMessagesCommand, dataSource: DataSource): Promise<void> {
|
||||
const repo = dataSource.getRepository(MessageEntity);
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
await repo.delete({ roomId: command.payload.roomId });
|
||||
if (!currentUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await repo.delete({ roomId: command.payload.roomId, ownerUserId: currentUserId });
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { MessageEntity } from '../../../entities';
|
||||
import { DeleteMessageCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleDeleteMessage(command: DeleteMessageCommand, dataSource: DataSource): Promise<void> {
|
||||
const repo = dataSource.getRepository(MessageEntity);
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
await repo.delete({ id: command.payload.messageId });
|
||||
if (!currentUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await repo.delete({ id: command.payload.messageId, ownerUserId: currentUserId });
|
||||
}
|
||||
|
||||
21
electron/cqrs/commands/handlers/deletePluginData.ts
Normal file
21
electron/cqrs/commands/handlers/deletePluginData.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
import { PluginDataEntity } from '../../../entities';
|
||||
import { DeletePluginDataCommand } from '../../types';
|
||||
|
||||
export async function handleDeletePluginData(command: DeletePluginDataCommand, dataSource: DataSource): Promise<void> {
|
||||
const { payload } = command;
|
||||
const ownerUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!ownerUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await dataSource.getRepository(PluginDataEntity).delete({
|
||||
key: payload.key,
|
||||
ownerUserId,
|
||||
pluginId: payload.pluginId,
|
||||
scope: payload.scope,
|
||||
serverId: payload.serverId ?? ''
|
||||
});
|
||||
}
|
||||
@@ -3,23 +3,39 @@ import {
|
||||
RoomChannelPermissionEntity,
|
||||
RoomChannelEntity,
|
||||
RoomEntity,
|
||||
RoomOwnerEntity,
|
||||
RoomMemberEntity,
|
||||
RoomRoleEntity,
|
||||
RoomUserRoleEntity,
|
||||
MessageEntity
|
||||
} from '../../../entities';
|
||||
import { DeleteRoomCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleDeleteRoom(command: DeleteRoomCommand, dataSource: DataSource): Promise<void> {
|
||||
const { roomId } = command.payload;
|
||||
|
||||
await dataSource.transaction(async (manager) => {
|
||||
const currentUserId = await getCurrentUserScope(manager);
|
||||
|
||||
if (!currentUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await manager.getRepository(RoomOwnerEntity).delete({ roomId, userId: currentUserId });
|
||||
await manager.getRepository(MessageEntity).delete({ roomId, ownerUserId: currentUserId });
|
||||
|
||||
const remainingOwners = await manager.getRepository(RoomOwnerEntity).count({ where: { roomId } });
|
||||
|
||||
if (remainingOwners > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await manager.getRepository(RoomChannelPermissionEntity).delete({ roomId });
|
||||
await manager.getRepository(RoomChannelEntity).delete({ roomId });
|
||||
await manager.getRepository(RoomMemberEntity).delete({ roomId });
|
||||
await manager.getRepository(RoomRoleEntity).delete({ roomId });
|
||||
await manager.getRepository(RoomUserRoleEntity).delete({ roomId });
|
||||
await manager.getRepository(RoomEntity).delete({ id: roomId });
|
||||
await manager.getRepository(MessageEntity).delete({ roomId });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,15 +2,18 @@ import { DataSource } from 'typeorm';
|
||||
import { MessageEntity } from '../../../entities';
|
||||
import { replaceMessageReactions } from '../../relations';
|
||||
import { SaveMessageCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleSaveMessage(command: SaveMessageCommand, dataSource: DataSource): Promise<void> {
|
||||
const { message } = command.payload;
|
||||
|
||||
await dataSource.transaction(async (manager) => {
|
||||
const currentUserId = await getCurrentUserScope(manager);
|
||||
const repo = manager.getRepository(MessageEntity);
|
||||
const entity = repo.create({
|
||||
id: message.id,
|
||||
roomId: message.roomId,
|
||||
ownerUserId: currentUserId,
|
||||
channelId: message.channelId ?? null,
|
||||
senderId: message.senderId,
|
||||
senderName: message.senderName,
|
||||
|
||||
10
electron/cqrs/commands/handlers/saveMeta.ts
Normal file
10
electron/cqrs/commands/handlers/saveMeta.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { MetaEntity } from '../../../entities';
|
||||
import { SaveMetaCommand } from '../../types';
|
||||
|
||||
export async function handleSaveMeta(command: SaveMetaCommand, dataSource: DataSource): Promise<void> {
|
||||
await dataSource.getRepository(MetaEntity).save({
|
||||
key: command.payload.key,
|
||||
value: command.payload.value
|
||||
});
|
||||
}
|
||||
23
electron/cqrs/commands/handlers/savePluginData.ts
Normal file
23
electron/cqrs/commands/handlers/savePluginData.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
import { PluginDataEntity } from '../../../entities';
|
||||
import { SavePluginDataCommand } from '../../types';
|
||||
|
||||
export async function handleSavePluginData(command: SavePluginDataCommand, dataSource: DataSource): Promise<void> {
|
||||
const { payload } = command;
|
||||
const ownerUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!ownerUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await dataSource.getRepository(PluginDataEntity).save({
|
||||
key: payload.key,
|
||||
ownerUserId,
|
||||
pluginId: payload.pluginId,
|
||||
scope: payload.scope,
|
||||
serverId: payload.serverId ?? '',
|
||||
updatedAt: Date.now(),
|
||||
valueJson: JSON.stringify(payload.value ?? null)
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { RoomEntity } from '../../../entities';
|
||||
import { RoomEntity, RoomOwnerEntity } from '../../../entities';
|
||||
import { replaceRoomRelations } from '../../relations';
|
||||
import { SaveRoomCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
function extractSlowModeInterval(room: SaveRoomCommand['payload']['room']): number {
|
||||
if (typeof room.slowModeInterval === 'number' && Number.isFinite(room.slowModeInterval)) {
|
||||
@@ -21,6 +22,7 @@ export async function handleSaveRoom(command: SaveRoomCommand, dataSource: DataS
|
||||
const { room } = command.payload;
|
||||
|
||||
await dataSource.transaction(async (manager) => {
|
||||
const currentUserId = await getCurrentUserScope(manager);
|
||||
const repo = manager.getRepository(RoomEntity);
|
||||
const entity = repo.create({
|
||||
id: room.id,
|
||||
@@ -43,6 +45,15 @@ export async function handleSaveRoom(command: SaveRoomCommand, dataSource: DataS
|
||||
});
|
||||
|
||||
await repo.save(entity);
|
||||
|
||||
if (currentUserId) {
|
||||
await manager.getRepository(RoomOwnerEntity).save({
|
||||
roomId: room.id,
|
||||
userId: currentUserId,
|
||||
savedAt: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
await replaceRoomRelations(manager, room.id, {
|
||||
channels: room.channels ?? [],
|
||||
members: room.members ?? [],
|
||||
|
||||
@@ -2,13 +2,20 @@ import { DataSource } from 'typeorm';
|
||||
import { MessageEntity } from '../../../entities';
|
||||
import { replaceMessageReactions } from '../../relations';
|
||||
import { UpdateMessageCommand } from '../../types';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleUpdateMessage(command: UpdateMessageCommand, dataSource: DataSource): Promise<void> {
|
||||
const { messageId, updates } = command.payload;
|
||||
|
||||
await dataSource.transaction(async (manager) => {
|
||||
const currentUserId = await getCurrentUserScope(manager);
|
||||
|
||||
if (!currentUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = manager.getRepository(MessageEntity);
|
||||
const existing = await repo.findOne({ where: { id: messageId } });
|
||||
const existing = await repo.findOne({ where: { id: messageId, ownerUserId: currentUserId } });
|
||||
|
||||
if (!existing)
|
||||
return;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
boolToInt,
|
||||
TransformMap
|
||||
} from './utils/applyUpdates';
|
||||
import { getCurrentUserScope, userOwnsRoom } from '../../current-user-scope';
|
||||
|
||||
const ROOM_TRANSFORMS: TransformMap = {
|
||||
hasPassword: boolToInt,
|
||||
@@ -32,6 +33,12 @@ export async function handleUpdateRoom(command: UpdateRoomCommand, dataSource: D
|
||||
const { roomId, updates } = command.payload;
|
||||
|
||||
await dataSource.transaction(async (manager) => {
|
||||
const currentUserId = await getCurrentUserScope(manager);
|
||||
|
||||
if (!await userOwnsRoom(manager, roomId, currentUserId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const repo = manager.getRepository(RoomEntity);
|
||||
const existing = await repo.findOne({ where: { id: roomId } });
|
||||
|
||||
|
||||
@@ -18,7 +18,10 @@ import {
|
||||
SaveBanCommand,
|
||||
RemoveBanCommand,
|
||||
SaveAttachmentCommand,
|
||||
DeleteAttachmentsForMessageCommand
|
||||
DeleteAttachmentsForMessageCommand,
|
||||
SavePluginDataCommand,
|
||||
DeletePluginDataCommand,
|
||||
SaveMetaCommand
|
||||
} from '../types';
|
||||
import { handleSaveMessage } from './handlers/saveMessage';
|
||||
import { handleDeleteMessage } from './handlers/deleteMessage';
|
||||
@@ -36,6 +39,9 @@ import { handleSaveBan } from './handlers/saveBan';
|
||||
import { handleRemoveBan } from './handlers/removeBan';
|
||||
import { handleSaveAttachment } from './handlers/saveAttachment';
|
||||
import { handleDeleteAttachmentsForMessage } from './handlers/deleteAttachmentsForMessage';
|
||||
import { handleSavePluginData } from './handlers/savePluginData';
|
||||
import { handleDeletePluginData } from './handlers/deletePluginData';
|
||||
import { handleSaveMeta } from './handlers/saveMeta';
|
||||
import { handleClearAllData } from './handlers/clearAllData';
|
||||
|
||||
export const buildCommandHandlers = (dataSource: DataSource): Record<CommandTypeKey, (command: Command) => Promise<unknown>> => ({
|
||||
@@ -55,5 +61,8 @@ export const buildCommandHandlers = (dataSource: DataSource): Record<CommandType
|
||||
[CommandType.RemoveBan]: (cmd) => handleRemoveBan(cmd as RemoveBanCommand, dataSource),
|
||||
[CommandType.SaveAttachment]: (cmd) => handleSaveAttachment(cmd as SaveAttachmentCommand, dataSource),
|
||||
[CommandType.DeleteAttachmentsForMessage]: (cmd) => handleDeleteAttachmentsForMessage(cmd as DeleteAttachmentsForMessageCommand, dataSource),
|
||||
[CommandType.SavePluginData]: (cmd) => handleSavePluginData(cmd as SavePluginDataCommand, dataSource),
|
||||
[CommandType.DeletePluginData]: (cmd) => handleDeletePluginData(cmd as DeletePluginDataCommand, dataSource),
|
||||
[CommandType.SaveMeta]: (cmd) => handleSaveMeta(cmd as SaveMetaCommand, dataSource),
|
||||
[CommandType.ClearAllData]: () => handleClearAllData(dataSource)
|
||||
});
|
||||
|
||||
24
electron/cqrs/current-user-scope.ts
Normal file
24
electron/cqrs/current-user-scope.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { DataSource, EntityManager } from 'typeorm';
|
||||
import { MetaEntity, RoomOwnerEntity } from '../entities';
|
||||
|
||||
export async function getCurrentUserScope(dataSourceOrManager: DataSource | EntityManager): Promise<string | null> {
|
||||
const repo = dataSourceOrManager.getRepository(MetaEntity);
|
||||
const meta = await repo.findOne({ where: { key: 'currentUserId' } });
|
||||
|
||||
return meta?.value?.trim() || null;
|
||||
}
|
||||
|
||||
export async function userOwnsRoom(
|
||||
dataSourceOrManager: DataSource | EntityManager,
|
||||
roomId: string,
|
||||
userId: string | null
|
||||
): Promise<boolean> {
|
||||
if (!userId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const repo = dataSourceOrManager.getRepository(RoomOwnerEntity);
|
||||
const owner = await repo.findOne({ where: { roomId, userId } });
|
||||
|
||||
return !!owner;
|
||||
}
|
||||
@@ -1,11 +1,28 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { RoomEntity } from '../../../entities';
|
||||
import { RoomEntity, RoomOwnerEntity } from '../../../entities';
|
||||
import { rowToRoom } from '../../mappers';
|
||||
import { loadRoomRelationsMap } from '../../relations';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleGetAllRooms(dataSource: DataSource) {
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!currentUserId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const repo = dataSource.getRepository(RoomEntity);
|
||||
const rows = await repo.find();
|
||||
const ownershipRows = await dataSource.getRepository(RoomOwnerEntity).find({ where: { userId: currentUserId } });
|
||||
const roomIds = ownershipRows.map((owner) => owner.roomId);
|
||||
|
||||
if (roomIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await repo
|
||||
.createQueryBuilder('room')
|
||||
.where('room.id IN (:...roomIds)', { roomIds })
|
||||
.getMany();
|
||||
const relationsByRoomId = await loadRoomRelationsMap(dataSource, rows.map((row) => row.id));
|
||||
|
||||
return rows.map((row) => rowToRoom(row, relationsByRoomId.get(row.id)));
|
||||
|
||||
@@ -3,10 +3,17 @@ import { MessageEntity } from '../../../entities';
|
||||
import { GetMessageByIdQuery } from '../../types';
|
||||
import { rowToMessage } from '../../mappers';
|
||||
import { loadMessageReactionsMap } from '../../relations';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleGetMessageById(query: GetMessageByIdQuery, dataSource: DataSource) {
|
||||
const repo = dataSource.getRepository(MessageEntity);
|
||||
const row = await repo.findOne({ where: { id: query.payload.messageId } });
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!currentUserId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = await repo.findOne({ where: { id: query.payload.messageId, ownerUserId: currentUserId } });
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
|
||||
@@ -3,12 +3,19 @@ import { MessageEntity } from '../../../entities';
|
||||
import { GetMessagesQuery } from '../../types';
|
||||
import { rowToMessage } from '../../mappers';
|
||||
import { loadMessageReactionsMap } from '../../relations';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleGetMessages(query: GetMessagesQuery, dataSource: DataSource) {
|
||||
const repo = dataSource.getRepository(MessageEntity);
|
||||
const { roomId, limit = 100, offset = 0 } = query.payload;
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!currentUserId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await repo.find({
|
||||
where: { roomId },
|
||||
where: { roomId, ownerUserId: currentUserId },
|
||||
order: { timestamp: 'ASC' },
|
||||
take: limit,
|
||||
skip: offset
|
||||
|
||||
@@ -3,13 +3,21 @@ import { MessageEntity } from '../../../entities';
|
||||
import { GetMessagesSinceQuery } from '../../types';
|
||||
import { rowToMessage } from '../../mappers';
|
||||
import { loadMessageReactionsMap } from '../../relations';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
|
||||
export async function handleGetMessagesSince(query: GetMessagesSinceQuery, dataSource: DataSource) {
|
||||
const repo = dataSource.getRepository(MessageEntity);
|
||||
const { roomId, sinceTimestamp } = query.payload;
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!currentUserId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await repo.find({
|
||||
where: {
|
||||
roomId,
|
||||
ownerUserId: currentUserId,
|
||||
timestamp: MoreThan(sinceTimestamp)
|
||||
},
|
||||
order: { timestamp: 'ASC' }
|
||||
|
||||
11
electron/cqrs/queries/handlers/getMeta.ts
Normal file
11
electron/cqrs/queries/handlers/getMeta.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { MetaEntity } from '../../../entities';
|
||||
import { GetMetaQuery } from '../../types';
|
||||
|
||||
export async function handleGetMeta(query: GetMetaQuery, dataSource: DataSource): Promise<string | null> {
|
||||
const meta = await dataSource.getRepository(MetaEntity).findOne({
|
||||
where: { key: query.payload.key }
|
||||
});
|
||||
|
||||
return meta?.value ?? null;
|
||||
}
|
||||
33
electron/cqrs/queries/handlers/getPluginData.ts
Normal file
33
electron/cqrs/queries/handlers/getPluginData.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { DataSource } from 'typeorm';
|
||||
import { getCurrentUserScope } from '../../current-user-scope';
|
||||
import { PluginDataEntity } from '../../../entities';
|
||||
import { GetPluginDataQuery } from '../../types';
|
||||
|
||||
export async function handleGetPluginData(query: GetPluginDataQuery, dataSource: DataSource): Promise<unknown> {
|
||||
const { payload } = query;
|
||||
const ownerUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!ownerUserId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const record = await dataSource.getRepository(PluginDataEntity).findOne({
|
||||
where: {
|
||||
key: payload.key,
|
||||
ownerUserId,
|
||||
pluginId: payload.pluginId,
|
||||
scope: payload.scope,
|
||||
serverId: payload.serverId ?? ''
|
||||
}
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(record.valueJson) as unknown;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,15 @@ import { RoomEntity } from '../../../entities';
|
||||
import { GetRoomQuery } from '../../types';
|
||||
import { rowToRoom } from '../../mappers';
|
||||
import { loadRoomRelationsMap } from '../../relations';
|
||||
import { getCurrentUserScope, userOwnsRoom } from '../../current-user-scope';
|
||||
|
||||
export async function handleGetRoom(query: GetRoomQuery, dataSource: DataSource) {
|
||||
const currentUserId = await getCurrentUserScope(dataSource);
|
||||
|
||||
if (!await userOwnsRoom(dataSource, query.payload.roomId, currentUserId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const repo = dataSource.getRepository(RoomEntity);
|
||||
const row = await repo.findOne({ where: { id: query.payload.roomId } });
|
||||
|
||||
|
||||
@@ -8,11 +8,12 @@ import {
|
||||
GetMessageByIdQuery,
|
||||
GetReactionsForMessageQuery,
|
||||
GetUserQuery,
|
||||
GetCurrentUserIdQuery,
|
||||
GetRoomQuery,
|
||||
GetBansForRoomQuery,
|
||||
IsUserBannedQuery,
|
||||
GetAttachmentsForMessageQuery
|
||||
GetAttachmentsForMessageQuery,
|
||||
GetPluginDataQuery,
|
||||
GetMetaQuery
|
||||
} from '../types';
|
||||
import { handleGetMessages } from './handlers/getMessages';
|
||||
import { handleGetMessagesSince } from './handlers/getMessagesSince';
|
||||
@@ -28,6 +29,8 @@ import { handleGetBansForRoom } from './handlers/getBansForRoom';
|
||||
import { handleIsUserBanned } from './handlers/isUserBanned';
|
||||
import { handleGetAttachmentsForMessage } from './handlers/getAttachmentsForMessage';
|
||||
import { handleGetAllAttachments } from './handlers/getAllAttachments';
|
||||
import { handleGetPluginData } from './handlers/getPluginData';
|
||||
import { handleGetMeta } from './handlers/getMeta';
|
||||
|
||||
export const buildQueryHandlers = (dataSource: DataSource): Record<QueryTypeKey, (query: Query) => Promise<unknown>> => ({
|
||||
[QueryType.GetMessages]: (query) => handleGetMessages(query as GetMessagesQuery, dataSource),
|
||||
@@ -43,5 +46,7 @@ export const buildQueryHandlers = (dataSource: DataSource): Record<QueryTypeKey,
|
||||
[QueryType.GetBansForRoom]: (query) => handleGetBansForRoom(query as GetBansForRoomQuery, dataSource),
|
||||
[QueryType.IsUserBanned]: (query) => handleIsUserBanned(query as IsUserBannedQuery, dataSource),
|
||||
[QueryType.GetAttachmentsForMessage]: (query) => handleGetAttachmentsForMessage(query as GetAttachmentsForMessageQuery, dataSource),
|
||||
[QueryType.GetAllAttachments]: () => handleGetAllAttachments(dataSource)
|
||||
[QueryType.GetAllAttachments]: () => handleGetAllAttachments(dataSource),
|
||||
[QueryType.GetPluginData]: (query) => handleGetPluginData(query as GetPluginDataQuery, dataSource),
|
||||
[QueryType.GetMeta]: (query) => handleGetMeta(query as GetMetaQuery, dataSource)
|
||||
});
|
||||
|
||||
@@ -15,6 +15,9 @@ export const CommandType = {
|
||||
RemoveBan: 'remove-ban',
|
||||
SaveAttachment: 'save-attachment',
|
||||
DeleteAttachmentsForMessage: 'delete-attachments-for-message',
|
||||
SavePluginData: 'save-plugin-data',
|
||||
DeletePluginData: 'delete-plugin-data',
|
||||
SaveMeta: 'save-meta',
|
||||
ClearAllData: 'clear-all-data'
|
||||
} as const;
|
||||
|
||||
@@ -34,7 +37,9 @@ export const QueryType = {
|
||||
GetBansForRoom: 'get-bans-for-room',
|
||||
IsUserBanned: 'is-user-banned',
|
||||
GetAttachmentsForMessage: 'get-attachments-for-message',
|
||||
GetAllAttachments: 'get-all-attachments'
|
||||
GetAllAttachments: 'get-all-attachments',
|
||||
GetPluginData: 'get-plugin-data',
|
||||
GetMeta: 'get-meta'
|
||||
} as const;
|
||||
|
||||
export type QueryTypeKey = typeof QueryType[keyof typeof QueryType];
|
||||
@@ -172,6 +177,16 @@ export interface AttachmentPayload {
|
||||
savedPath?: string;
|
||||
}
|
||||
|
||||
export type PluginDataScopePayload = 'local' | 'server';
|
||||
|
||||
export interface PluginDataPayload {
|
||||
key: string;
|
||||
pluginId: string;
|
||||
scope: PluginDataScopePayload;
|
||||
serverId?: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
export interface SaveMessageCommand { type: typeof CommandType.SaveMessage; payload: { message: MessagePayload } }
|
||||
export interface DeleteMessageCommand { type: typeof CommandType.DeleteMessage; payload: { messageId: string } }
|
||||
export interface UpdateMessageCommand { type: typeof CommandType.UpdateMessage; payload: { messageId: string; updates: Partial<MessagePayload> } }
|
||||
@@ -188,6 +203,9 @@ export interface SaveBanCommand { type: typeof CommandType.SaveBan; payload: { b
|
||||
export interface RemoveBanCommand { type: typeof CommandType.RemoveBan; payload: { oderId: string } }
|
||||
export interface SaveAttachmentCommand { type: typeof CommandType.SaveAttachment; payload: { attachment: AttachmentPayload } }
|
||||
export interface DeleteAttachmentsForMessageCommand { type: typeof CommandType.DeleteAttachmentsForMessage; payload: { messageId: string } }
|
||||
export interface SavePluginDataCommand { type: typeof CommandType.SavePluginData; payload: PluginDataPayload }
|
||||
export interface DeletePluginDataCommand { type: typeof CommandType.DeletePluginData; payload: Omit<PluginDataPayload, 'value'> }
|
||||
export interface SaveMetaCommand { type: typeof CommandType.SaveMeta; payload: { key: string; value: string | null } }
|
||||
export interface ClearAllDataCommand { type: typeof CommandType.ClearAllData; payload: Record<string, never> }
|
||||
|
||||
export type Command =
|
||||
@@ -207,6 +225,9 @@ export type Command =
|
||||
| RemoveBanCommand
|
||||
| SaveAttachmentCommand
|
||||
| DeleteAttachmentsForMessageCommand
|
||||
| SavePluginDataCommand
|
||||
| DeletePluginDataCommand
|
||||
| SaveMetaCommand
|
||||
| ClearAllDataCommand;
|
||||
|
||||
export interface GetMessagesQuery { type: typeof QueryType.GetMessages; payload: { roomId: string; limit?: number; offset?: number } }
|
||||
@@ -223,6 +244,8 @@ export interface GetBansForRoomQuery { type: typeof QueryType.GetBansForRoom; pa
|
||||
export interface IsUserBannedQuery { type: typeof QueryType.IsUserBanned; payload: { userId: string; roomId: string } }
|
||||
export interface GetAttachmentsForMessageQuery { type: typeof QueryType.GetAttachmentsForMessage; payload: { messageId: string } }
|
||||
export interface GetAllAttachmentsQuery { type: typeof QueryType.GetAllAttachments; payload: Record<string, never> }
|
||||
export interface GetPluginDataQuery { type: typeof QueryType.GetPluginData; payload: Omit<PluginDataPayload, 'value'> }
|
||||
export interface GetMetaQuery { type: typeof QueryType.GetMeta; payload: { key: string } }
|
||||
|
||||
export type Query =
|
||||
| GetMessagesQuery
|
||||
@@ -238,4 +261,6 @@ export type Query =
|
||||
| GetBansForRoomQuery
|
||||
| IsUserBannedQuery
|
||||
| GetAttachmentsForMessageQuery
|
||||
| GetAllAttachmentsQuery;
|
||||
| GetAllAttachmentsQuery
|
||||
| GetPluginDataQuery
|
||||
| GetMetaQuery;
|
||||
|
||||
@@ -22,12 +22,12 @@ const ZIP_UTF8_FLAG = 0x0800;
|
||||
const ZIP_STORE_METHOD = 0;
|
||||
const ZIP_VERSION = 20;
|
||||
const MAX_UINT32 = 0xffffffff;
|
||||
|
||||
const crcTable = buildCrcTable();
|
||||
|
||||
export function createZipArchive(entries: ZipArchiveEntry[]): Buffer {
|
||||
const localParts: Buffer[] = [];
|
||||
const centralEntries: CentralDirectoryEntry[] = [];
|
||||
|
||||
let offset = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
@@ -93,7 +93,6 @@ export function createZipArchive(entries: ZipArchiveEntry[]): Buffer {
|
||||
|
||||
return Buffer.concat([header, entry.name]);
|
||||
});
|
||||
|
||||
const centralDirectorySize = offset - centralDirectoryOffset;
|
||||
|
||||
if (centralEntries.length > 0xffff || centralDirectoryOffset > MAX_UINT32 || centralDirectorySize > MAX_UINT32) {
|
||||
@@ -111,7 +110,11 @@ export function createZipArchive(entries: ZipArchiveEntry[]): Buffer {
|
||||
end.writeUInt32LE(centralDirectoryOffset, 16);
|
||||
end.writeUInt16LE(0, 20);
|
||||
|
||||
return Buffer.concat([...localParts, ...centralParts, end]);
|
||||
return Buffer.concat([
|
||||
...localParts,
|
||||
...centralParts,
|
||||
end
|
||||
]);
|
||||
}
|
||||
|
||||
export function readZipArchive(data: Buffer): ZipArchiveEntry[] {
|
||||
@@ -124,6 +127,7 @@ export function readZipArchive(data: Buffer): ZipArchiveEntry[] {
|
||||
const entryCount = data.readUInt16LE(endOffset + 10);
|
||||
const centralDirectoryOffset = data.readUInt32LE(endOffset + 16);
|
||||
const entries: ZipArchiveEntry[] = [];
|
||||
|
||||
let offset = centralDirectoryOffset;
|
||||
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
|
||||
@@ -43,12 +43,11 @@ export async function openCurrentDataFolder(): Promise<boolean> {
|
||||
|
||||
export async function exportUserData(): Promise<ExportUserDataResult> {
|
||||
const dataPath = app.getPath('userData');
|
||||
const defaultFileName = `metoyou-data-${new Date().toISOString().slice(0, 10)}.dat`;
|
||||
const defaultFileName = `metoyou-data-${new Date().toISOString()
|
||||
.slice(0, 10)}.dat`;
|
||||
const { canceled, filePath } = await dialog.showSaveDialog({
|
||||
defaultPath: path.join(app.getPath('documents'), defaultFileName),
|
||||
filters: [
|
||||
{ extensions: ['dat'], name: 'MetoYou data archive' }
|
||||
],
|
||||
filters: [{ extensions: ['dat'], name: 'MetoYou data archive' }],
|
||||
title: 'Export MetoYou data'
|
||||
});
|
||||
|
||||
@@ -88,9 +87,7 @@ export async function exportUserData(): Promise<ExportUserDataResult> {
|
||||
|
||||
export async function importUserData(): Promise<ImportUserDataResult> {
|
||||
const { canceled, filePaths } = await dialog.showOpenDialog({
|
||||
filters: [
|
||||
{ extensions: ['dat', 'zip'], name: 'MetoYou data archive' }
|
||||
],
|
||||
filters: [{ extensions: ['dat', 'zip'], name: 'MetoYou data archive' }],
|
||||
properties: ['openFile'],
|
||||
title: 'Import MetoYou data'
|
||||
});
|
||||
@@ -184,7 +181,8 @@ async function collectDataFiles(directoryPath: string): Promise<string[]> {
|
||||
async function moveCurrentDataAside(): Promise<string | undefined> {
|
||||
const dataPath = app.getPath('userData');
|
||||
const backupRoot = path.join(dataPath, BACKUP_DIRECTORY_NAME);
|
||||
const backupPath = path.join(backupRoot, `before-import-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
||||
const backupPath = path.join(backupRoot, `before-import-${new Date().toISOString()
|
||||
.replace(/[:.]/g, '-')}`);
|
||||
const entries = await fsp.readdir(dataPath, { withFileTypes: true }).catch(() => []);
|
||||
|
||||
await fsp.mkdir(backupPath, { recursive: true });
|
||||
@@ -204,6 +202,7 @@ async function moveCurrentDataAside(): Promise<string | undefined> {
|
||||
await copyPath(sourcePath, targetPath);
|
||||
await fsp.rm(sourcePath, { force: true, recursive: true });
|
||||
});
|
||||
|
||||
movedAny = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ import {
|
||||
ReactionEntity,
|
||||
BanEntity,
|
||||
AttachmentEntity,
|
||||
MetaEntity
|
||||
MetaEntity,
|
||||
PluginDataEntity
|
||||
} from './entities';
|
||||
|
||||
const projectRootDatabaseFilePath = path.join(__dirname, '..', '..', settings.databaseName);
|
||||
@@ -51,7 +52,8 @@ export const AppDataSource = new DataSource({
|
||||
ReactionEntity,
|
||||
BanEntity,
|
||||
AttachmentEntity,
|
||||
MetaEntity
|
||||
MetaEntity,
|
||||
PluginDataEntity
|
||||
],
|
||||
migrations: [path.join(__dirname, 'migrations', '*.{ts,js}')],
|
||||
synchronize: false,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
MessageEntity,
|
||||
UserEntity,
|
||||
RoomEntity,
|
||||
RoomOwnerEntity,
|
||||
RoomChannelEntity,
|
||||
RoomMemberEntity,
|
||||
RoomRoleEntity,
|
||||
@@ -16,7 +17,8 @@ import {
|
||||
ReactionEntity,
|
||||
BanEntity,
|
||||
AttachmentEntity,
|
||||
MetaEntity
|
||||
MetaEntity,
|
||||
PluginDataEntity
|
||||
} from '../entities';
|
||||
import { settings } from '../settings';
|
||||
|
||||
@@ -26,8 +28,18 @@ let dbBackupPath = '';
|
||||
|
||||
// SQLite files start with this 16-byte header string.
|
||||
const SQLITE_MAGIC = 'SQLite format 3\0';
|
||||
const SAVE_RETRY_DELAYS_MS = [25, 75, 150, 300, 600];
|
||||
const RETRYABLE_SAVE_ERROR_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);
|
||||
const SAVE_RETRY_DELAYS_MS = [
|
||||
25,
|
||||
75,
|
||||
150,
|
||||
300,
|
||||
600
|
||||
];
|
||||
const RETRYABLE_SAVE_ERROR_CODES = new Set([
|
||||
'EPERM',
|
||||
'EACCES',
|
||||
'EBUSY'
|
||||
]);
|
||||
|
||||
let saveQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
@@ -163,6 +175,7 @@ export async function initializeDatabase(): Promise<void> {
|
||||
MessageEntity,
|
||||
UserEntity,
|
||||
RoomEntity,
|
||||
RoomOwnerEntity,
|
||||
RoomChannelEntity,
|
||||
RoomMemberEntity,
|
||||
RoomRoleEntity,
|
||||
@@ -171,7 +184,8 @@ export async function initializeDatabase(): Promise<void> {
|
||||
ReactionEntity,
|
||||
BanEntity,
|
||||
AttachmentEntity,
|
||||
MetaEntity
|
||||
MetaEntity,
|
||||
PluginDataEntity
|
||||
],
|
||||
migrations: [path.join(__dirname, '..', 'migrations', '*.js'), path.join(__dirname, '..', 'migrations', '*.ts')],
|
||||
synchronize: false,
|
||||
|
||||
@@ -4,11 +4,21 @@ import * as path from 'path';
|
||||
|
||||
export type AutoUpdateMode = 'auto' | 'off' | 'version';
|
||||
|
||||
export interface LocalApiSettings {
|
||||
enabled: boolean;
|
||||
port: number;
|
||||
exposeOnLan: boolean;
|
||||
scalarEnabled: boolean;
|
||||
docusaurusEnabled: boolean;
|
||||
allowedSignalingServers: string[];
|
||||
}
|
||||
|
||||
export interface DesktopSettings {
|
||||
autoUpdateMode: AutoUpdateMode;
|
||||
autoStart: boolean;
|
||||
closeToTray: boolean;
|
||||
hardwareAcceleration: boolean;
|
||||
localApi: LocalApiSettings;
|
||||
manifestUrls: string[];
|
||||
preferredVersion: string | null;
|
||||
vaapiVideoEncode: boolean;
|
||||
@@ -19,11 +29,20 @@ export interface DesktopSettingsSnapshot extends DesktopSettings {
|
||||
restartRequired: boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_LOCAL_API_SETTINGS: LocalApiSettings = {
|
||||
enabled: false,
|
||||
port: 17878,
|
||||
exposeOnLan: false,
|
||||
scalarEnabled: false,
|
||||
docusaurusEnabled: false,
|
||||
allowedSignalingServers: []
|
||||
};
|
||||
const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
autoUpdateMode: 'auto',
|
||||
autoStart: true,
|
||||
closeToTray: true,
|
||||
hardwareAcceleration: true,
|
||||
localApi: { ...DEFAULT_LOCAL_API_SETTINGS },
|
||||
manifestUrls: [],
|
||||
preferredVersion: null,
|
||||
vaapiVideoEncode: false
|
||||
@@ -61,6 +80,61 @@ function normalizeManifestUrls(value: unknown): string[] {
|
||||
return manifestUrls;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const port = Math.floor(value);
|
||||
|
||||
if (port < 1 || port > 65535) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeAllowedSignalingServers(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const urls: string[] = [];
|
||||
|
||||
for (const entry of value) {
|
||||
if (typeof entry !== 'string') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const trimmed = entry.trim().replace(/\/+$/u, '');
|
||||
|
||||
if (!trimmed || urls.includes(trimmed)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!/^https?:\/\//iu.test(trimmed)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
urls.push(trimmed);
|
||||
}
|
||||
|
||||
return urls;
|
||||
}
|
||||
|
||||
function normalizeLocalApiSettings(value: unknown): LocalApiSettings {
|
||||
const source = (value && typeof value === 'object') ? value as Partial<LocalApiSettings> : {};
|
||||
|
||||
return {
|
||||
enabled: typeof source.enabled === 'boolean' ? source.enabled : DEFAULT_LOCAL_API_SETTINGS.enabled,
|
||||
port: normalizePort(source.port, DEFAULT_LOCAL_API_SETTINGS.port),
|
||||
exposeOnLan: typeof source.exposeOnLan === 'boolean' ? source.exposeOnLan : DEFAULT_LOCAL_API_SETTINGS.exposeOnLan,
|
||||
scalarEnabled: typeof source.scalarEnabled === 'boolean' ? source.scalarEnabled : DEFAULT_LOCAL_API_SETTINGS.scalarEnabled,
|
||||
docusaurusEnabled: typeof source.docusaurusEnabled === 'boolean' ? source.docusaurusEnabled : DEFAULT_LOCAL_API_SETTINGS.docusaurusEnabled,
|
||||
allowedSignalingServers: normalizeAllowedSignalingServers(source.allowedSignalingServers)
|
||||
};
|
||||
}
|
||||
|
||||
export function getDesktopSettingsSnapshot(): DesktopSettingsSnapshot {
|
||||
const storedSettings = readDesktopSettings();
|
||||
const runtimeHardwareAcceleration = app.isHardwareAccelerationEnabled();
|
||||
@@ -97,6 +171,7 @@ export function readDesktopSettings(): DesktopSettings {
|
||||
hardwareAcceleration: typeof parsed.hardwareAcceleration === 'boolean'
|
||||
? parsed.hardwareAcceleration
|
||||
: DEFAULT_DESKTOP_SETTINGS.hardwareAcceleration,
|
||||
localApi: normalizeLocalApiSettings(parsed.localApi),
|
||||
manifestUrls: normalizeManifestUrls(parsed.manifestUrls),
|
||||
preferredVersion: normalizePreferredVersion(parsed.preferredVersion)
|
||||
};
|
||||
@@ -106,9 +181,13 @@ export function readDesktopSettings(): DesktopSettings {
|
||||
}
|
||||
|
||||
export function updateDesktopSettings(patch: Partial<DesktopSettings>): DesktopSettingsSnapshot {
|
||||
const previousSettings = readDesktopSettings();
|
||||
const mergedSettings = {
|
||||
...readDesktopSettings(),
|
||||
...patch
|
||||
...previousSettings,
|
||||
...patch,
|
||||
localApi: patch.localApi
|
||||
? { ...previousSettings.localApi, ...patch.localApi }
|
||||
: previousSettings.localApi
|
||||
};
|
||||
const nextSettings: DesktopSettings = {
|
||||
autoUpdateMode: normalizeAutoUpdateMode(mergedSettings.autoUpdateMode),
|
||||
@@ -121,6 +200,7 @@ export function updateDesktopSettings(patch: Partial<DesktopSettings>): DesktopS
|
||||
hardwareAcceleration: typeof mergedSettings.hardwareAcceleration === 'boolean'
|
||||
? mergedSettings.hardwareAcceleration
|
||||
: DEFAULT_DESKTOP_SETTINGS.hardwareAcceleration,
|
||||
localApi: normalizeLocalApiSettings(mergedSettings.localApi),
|
||||
manifestUrls: normalizeManifestUrls(mergedSettings.manifestUrls),
|
||||
preferredVersion: normalizePreferredVersion(mergedSettings.preferredVersion),
|
||||
vaapiVideoEncode: typeof mergedSettings.vaapiVideoEncode === 'boolean'
|
||||
|
||||
@@ -12,6 +12,9 @@ export class MessageEntity {
|
||||
@Column('text')
|
||||
roomId!: string;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
ownerUserId!: string | null;
|
||||
|
||||
@Column('text', { nullable: true })
|
||||
channelId!: string | null;
|
||||
|
||||
|
||||
29
electron/entities/PluginDataEntity.ts
Normal file
29
electron/entities/PluginDataEntity.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
PrimaryColumn
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('plugin_data')
|
||||
export class PluginDataEntity {
|
||||
@PrimaryColumn('text')
|
||||
ownerUserId!: string;
|
||||
|
||||
@PrimaryColumn('text')
|
||||
pluginId!: string;
|
||||
|
||||
@PrimaryColumn('text')
|
||||
scope!: string;
|
||||
|
||||
@PrimaryColumn('text')
|
||||
serverId!: string;
|
||||
|
||||
@PrimaryColumn('text')
|
||||
key!: string;
|
||||
|
||||
@Column('text')
|
||||
valueJson!: string;
|
||||
|
||||
@Column('integer')
|
||||
updatedAt!: number;
|
||||
}
|
||||
19
electron/entities/RoomOwnerEntity.ts
Normal file
19
electron/entities/RoomOwnerEntity.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import {
|
||||
Column,
|
||||
Entity,
|
||||
Index,
|
||||
PrimaryColumn
|
||||
} from 'typeorm';
|
||||
|
||||
@Entity('room_owners')
|
||||
export class RoomOwnerEntity {
|
||||
@PrimaryColumn('text')
|
||||
roomId!: string;
|
||||
|
||||
@PrimaryColumn('text')
|
||||
@Index()
|
||||
userId!: string;
|
||||
|
||||
@Column('integer')
|
||||
savedAt!: number;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
export { MessageEntity } from './MessageEntity';
|
||||
export { UserEntity } from './UserEntity';
|
||||
export { RoomEntity } from './RoomEntity';
|
||||
export { RoomOwnerEntity } from './RoomOwnerEntity';
|
||||
export { RoomChannelEntity } from './RoomChannelEntity';
|
||||
export { RoomMemberEntity } from './RoomMemberEntity';
|
||||
export { RoomRoleEntity } from './RoomRoleEntity';
|
||||
@@ -10,3 +11,4 @@ export { ReactionEntity } from './ReactionEntity';
|
||||
export { BanEntity } from './BanEntity';
|
||||
export { AttachmentEntity } from './AttachmentEntity';
|
||||
export { MetaEntity } from './MetaEntity';
|
||||
export { PluginDataEntity } from './PluginDataEntity';
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
updateDesktopSettings,
|
||||
type DesktopSettings
|
||||
} from '../desktop-settings';
|
||||
import { applyLocalApiSettings, getLocalApiSnapshot } from '../api';
|
||||
import {
|
||||
activateLinuxScreenShareAudioRouting,
|
||||
deactivateLinuxScreenShareAudioRouting,
|
||||
@@ -49,6 +50,7 @@ import {
|
||||
readSavedTheme,
|
||||
writeSavedTheme
|
||||
} from '../theme-library';
|
||||
import { getLocalPluginsPath, listLocalPluginManifests } from '../plugin-library';
|
||||
import {
|
||||
eraseUserData,
|
||||
exportUserData,
|
||||
@@ -349,6 +351,8 @@ export function setupSystemHandlers(): void {
|
||||
ipcMain.handle('import-user-data', async () => await importUserData());
|
||||
ipcMain.handle('erase-user-data', async () => await eraseUserData());
|
||||
ipcMain.handle('get-saved-themes-path', async () => await getSavedThemesPath());
|
||||
ipcMain.handle('get-local-plugins-path', async () => await getLocalPluginsPath());
|
||||
ipcMain.handle('list-local-plugin-manifests', async () => await listLocalPluginManifests());
|
||||
ipcMain.handle('list-saved-themes', async () => await listSavedThemes());
|
||||
ipcMain.handle('read-saved-theme', async (_event, fileName: string) => await readSavedTheme(fileName));
|
||||
ipcMain.handle('write-saved-theme', async (_event, fileName: string, text: string) => {
|
||||
@@ -449,9 +453,57 @@ export function setupSystemHandlers(): void {
|
||||
await synchronizeAutoStartSetting(snapshot.autoStart);
|
||||
updateCloseToTraySetting(snapshot.closeToTray);
|
||||
await handleDesktopSettingsChanged();
|
||||
await applyLocalApiSettings();
|
||||
return snapshot;
|
||||
});
|
||||
|
||||
ipcMain.handle('get-local-api-status', () => getLocalApiSnapshot());
|
||||
|
||||
ipcMain.handle('open-local-api-docs', async () => {
|
||||
const snapshot = getLocalApiSnapshot();
|
||||
|
||||
if (snapshot.status !== 'running' || !snapshot.baseUrl) {
|
||||
return { opened: false, reason: 'Local API is not running' };
|
||||
}
|
||||
|
||||
if (!snapshot.scalarEnabled) {
|
||||
return { opened: false, reason: 'Scalar docs are disabled' };
|
||||
}
|
||||
|
||||
await shell.openExternal(`${snapshot.baseUrl}/docs`);
|
||||
return { opened: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('open-docusaurus-docs', async () => {
|
||||
let snapshot = getLocalApiSnapshot();
|
||||
|
||||
if (snapshot.status !== 'running' || !snapshot.baseUrl || !snapshot.docusaurusEnabled) {
|
||||
const currentSettings = getDesktopSettingsSnapshot();
|
||||
|
||||
updateDesktopSettings({
|
||||
localApi: {
|
||||
...currentSettings.localApi,
|
||||
enabled: true,
|
||||
docusaurusEnabled: true
|
||||
}
|
||||
});
|
||||
|
||||
await applyLocalApiSettings();
|
||||
snapshot = getLocalApiSnapshot();
|
||||
}
|
||||
|
||||
if (snapshot.status !== 'running' || !snapshot.baseUrl) {
|
||||
return { opened: false, reason: snapshot.error ?? 'Local documentation server is not running' };
|
||||
}
|
||||
|
||||
if (!snapshot.docusaurusEnabled) {
|
||||
return { opened: false, reason: 'Docusaurus docs are disabled' };
|
||||
}
|
||||
|
||||
await shell.openExternal(`${snapshot.baseUrl}/docusaurus/`);
|
||||
return { opened: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('relaunch-app', () => {
|
||||
app.relaunch();
|
||||
app.exit(0);
|
||||
|
||||
25
electron/migrations/1000000000008-AddPluginData.ts
Normal file
25
electron/migrations/1000000000008-AddPluginData.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddPluginData1000000000008 implements MigrationInterface {
|
||||
name = 'AddPluginData1000000000008';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE IF NOT EXISTS "plugin_data" (
|
||||
"pluginId" TEXT NOT NULL,
|
||||
"scope" TEXT NOT NULL,
|
||||
"serverId" TEXT NOT NULL DEFAULT '',
|
||||
"key" TEXT NOT NULL,
|
||||
"valueJson" TEXT NOT NULL,
|
||||
"updatedAt" INTEGER NOT NULL,
|
||||
PRIMARY KEY ("pluginId", "scope", "serverId", "key")
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_plugin_data_plugin_scope" ON "plugin_data" ("pluginId", "scope")`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP INDEX IF EXISTS "idx_plugin_data_plugin_scope"`);
|
||||
await queryRunner.query(`DROP TABLE IF EXISTS "plugin_data"`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class UserScopedRoomsAndMessages1000000000009 implements MigrationInterface {
|
||||
name = 'UserScopedRoomsAndMessages1000000000009';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE IF NOT EXISTS "room_owners" (
|
||||
"roomId" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"savedAt" INTEGER NOT NULL,
|
||||
PRIMARY KEY ("roomId", "userId")
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_room_owners_userId" ON "room_owners" ("userId")`);
|
||||
|
||||
const columns = await queryRunner.query(`PRAGMA table_info("messages")`) as Array<{ name?: string }>;
|
||||
const hasOwnerUserId = columns.some((column) => column.name === 'ownerUserId');
|
||||
|
||||
if (!hasOwnerUserId) {
|
||||
await queryRunner.query(`ALTER TABLE "messages" ADD COLUMN "ownerUserId" TEXT`);
|
||||
}
|
||||
|
||||
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_messages_owner_room" ON "messages" ("ownerUserId", "roomId")`);
|
||||
|
||||
const metaRows = await queryRunner.query(`SELECT "value" FROM "meta" WHERE "key" = 'currentUserId' LIMIT 1`) as Array<{ value?: string | null }>;
|
||||
const currentUserId = metaRows[0]?.value?.trim();
|
||||
|
||||
if (!currentUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await queryRunner.query(
|
||||
`INSERT OR IGNORE INTO "room_owners" ("roomId", "userId", "savedAt") SELECT "id", ?, ? FROM "rooms"`,
|
||||
[currentUserId, now]
|
||||
);
|
||||
await queryRunner.query(
|
||||
`UPDATE "messages" SET "ownerUserId" = ? WHERE "ownerUserId" IS NULL`,
|
||||
[currentUserId]
|
||||
);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`DROP INDEX IF EXISTS "idx_messages_owner_room"`);
|
||||
await queryRunner.query(`DROP INDEX IF EXISTS "idx_room_owners_userId"`);
|
||||
await queryRunner.query(`DROP TABLE IF EXISTS "room_owners"`);
|
||||
}
|
||||
}
|
||||
56
electron/migrations/1000000000010-UserScopedPluginData.ts
Normal file
56
electron/migrations/1000000000010-UserScopedPluginData.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class UserScopedPluginData1000000000010 implements MigrationInterface {
|
||||
name = 'UserScopedPluginData1000000000010';
|
||||
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
const columns = await queryRunner.query(`PRAGMA table_info("plugin_data")`) as Array<{ name?: string }>;
|
||||
const hasOwnerUserId = columns.some((column) => column.name === 'ownerUserId');
|
||||
|
||||
if (hasOwnerUserId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const metaRows = await queryRunner.query(`SELECT "value" FROM "meta" WHERE "key" = 'currentUserId' LIMIT 1`) as Array<{ value?: string | null }>;
|
||||
const currentUserId = metaRows[0]?.value?.trim() ?? '';
|
||||
|
||||
await queryRunner.query(`
|
||||
CREATE TABLE "temporary_plugin_data" (
|
||||
"ownerUserId" TEXT NOT NULL,
|
||||
"pluginId" TEXT NOT NULL,
|
||||
"scope" TEXT NOT NULL,
|
||||
"serverId" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"valueJson" TEXT NOT NULL,
|
||||
"updatedAt" INTEGER NOT NULL,
|
||||
PRIMARY KEY ("ownerUserId", "pluginId", "scope", "serverId", "key")
|
||||
)
|
||||
`);
|
||||
await queryRunner.query(
|
||||
`INSERT INTO "temporary_plugin_data" ("ownerUserId", "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt")
|
||||
SELECT ?, "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt" FROM "plugin_data"`,
|
||||
[currentUserId]
|
||||
);
|
||||
await queryRunner.query(`DROP TABLE "plugin_data"`);
|
||||
await queryRunner.query(`ALTER TABLE "temporary_plugin_data" RENAME TO "plugin_data"`);
|
||||
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_plugin_data_owner_plugin_scope" ON "plugin_data" ("ownerUserId", "pluginId", "scope")`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`CREATE TABLE "temporary_plugin_data" (
|
||||
"pluginId" TEXT NOT NULL,
|
||||
"scope" TEXT NOT NULL,
|
||||
"serverId" TEXT NOT NULL,
|
||||
"key" TEXT NOT NULL,
|
||||
"valueJson" TEXT NOT NULL,
|
||||
"updatedAt" INTEGER NOT NULL,
|
||||
PRIMARY KEY ("pluginId", "scope", "serverId", "key")
|
||||
)`);
|
||||
await queryRunner.query(`INSERT OR REPLACE INTO "temporary_plugin_data" ("pluginId", "scope", "serverId", "key", "valueJson", "updatedAt")
|
||||
SELECT "pluginId", "scope", "serverId", "key", "valueJson", "updatedAt" FROM "plugin_data"`);
|
||||
await queryRunner.query(`DROP INDEX IF EXISTS "idx_plugin_data_owner_plugin_scope"`);
|
||||
await queryRunner.query(`DROP TABLE "plugin_data"`);
|
||||
await queryRunner.query(`ALTER TABLE "temporary_plugin_data" RENAME TO "plugin_data"`);
|
||||
await queryRunner.query(`CREATE INDEX IF NOT EXISTS "idx_plugin_data_plugin_scope" ON "plugin_data" ("pluginId", "scope")`);
|
||||
}
|
||||
}
|
||||
126
electron/plugin-library.spec.ts
Normal file
126
electron/plugin-library.spec.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi
|
||||
} from 'vitest';
|
||||
import {
|
||||
cp,
|
||||
mkdtemp,
|
||||
mkdir,
|
||||
rm,
|
||||
writeFile
|
||||
} from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { tmpdir } from 'os';
|
||||
import { TEST_PLUGIN_FIXTURE_DIR, TEST_PLUGIN_ID } from '../e2e/helpers/plugin-api-test-fixture';
|
||||
|
||||
const { mockGetPath } = vi.hoisted(() => ({
|
||||
mockGetPath: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: mockGetPath
|
||||
}
|
||||
}));
|
||||
|
||||
import { getLocalPluginsPath, listLocalPluginManifests } from './plugin-library';
|
||||
|
||||
describe('plugin-library', () => {
|
||||
let userDataPath: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
userDataPath = await mkdtemp(join(tmpdir(), 'metoyou-plugin-library-'));
|
||||
mockGetPath.mockReturnValue(userDataPath);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(userDataPath, { recursive: true, force: true });
|
||||
mockGetPath.mockReset();
|
||||
});
|
||||
|
||||
it('creates and reports the local plugins folder', async () => {
|
||||
const pluginsPath = await getLocalPluginsPath();
|
||||
const result = await listLocalPluginManifests();
|
||||
|
||||
expect(pluginsPath).toBe(join(userDataPath, 'plugins'));
|
||||
expect(result).toEqual({
|
||||
errors: [],
|
||||
plugins: [],
|
||||
pluginsPath
|
||||
});
|
||||
});
|
||||
|
||||
it('discovers immediate child plugin manifests and safe relative files', async () => {
|
||||
const pluginRoot = join(userDataPath, 'plugins', 'api-test-plugin');
|
||||
|
||||
await cp(TEST_PLUGIN_FIXTURE_DIR, pluginRoot, { recursive: true });
|
||||
|
||||
const result = await listLocalPluginManifests();
|
||||
|
||||
expect(result.errors).toEqual([]);
|
||||
expect(result.plugins).toHaveLength(1);
|
||||
expect(result.plugins[0]).toEqual(expect.objectContaining({
|
||||
entrypointPath: join(pluginRoot, 'dist', 'main.js'),
|
||||
manifestPath: join(pluginRoot, 'toju-plugin.json'),
|
||||
pluginRoot,
|
||||
readmePath: join(pluginRoot, 'README.md')
|
||||
}));
|
||||
|
||||
expect(result.plugins[0]?.manifest).toEqual(expect.objectContaining({ id: TEST_PLUGIN_ID }));
|
||||
});
|
||||
|
||||
it('reports invalid JSON and keeps scanning other plugins', async () => {
|
||||
const invalidRoot = join(userDataPath, 'plugins', 'invalid-plugin');
|
||||
const validRoot = join(userDataPath, 'plugins', 'valid-plugin');
|
||||
|
||||
await mkdir(invalidRoot, { recursive: true });
|
||||
await mkdir(validRoot, { recursive: true });
|
||||
await writeFile(join(invalidRoot, 'plugin.json'), '{', 'utf8');
|
||||
await writeFile(join(validRoot, 'plugin.json'), JSON.stringify({
|
||||
apiVersion: '1.0.0',
|
||||
compatibility: { minimumTojuVersion: '1.0.0' },
|
||||
description: 'Valid plugin',
|
||||
entrypoint: './main.js',
|
||||
id: 'valid.plugin',
|
||||
kind: 'client',
|
||||
schemaVersion: 1,
|
||||
title: 'Valid Plugin',
|
||||
version: '1.0.0'
|
||||
}), 'utf8');
|
||||
|
||||
const result = await listLocalPluginManifests();
|
||||
|
||||
expect(result.plugins.map((plugin) => plugin.pluginRoot)).toEqual([validRoot]);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.errors[0]).toEqual(expect.objectContaining({
|
||||
manifestPath: join(invalidRoot, 'plugin.json'),
|
||||
pluginRoot: invalidRoot
|
||||
}));
|
||||
});
|
||||
|
||||
it('does not resolve entrypoints outside the plugin folder', async () => {
|
||||
const pluginRoot = join(userDataPath, 'plugins', 'unsafe-plugin');
|
||||
|
||||
await mkdir(pluginRoot, { recursive: true });
|
||||
await writeFile(join(userDataPath, 'plugins', 'outside.js'), 'export default {};', 'utf8');
|
||||
await writeFile(join(pluginRoot, 'plugin.json'), JSON.stringify({
|
||||
apiVersion: '1.0.0',
|
||||
compatibility: { minimumTojuVersion: '1.0.0' },
|
||||
description: 'Unsafe plugin',
|
||||
entrypoint: '../outside.js',
|
||||
id: 'unsafe.plugin',
|
||||
kind: 'client',
|
||||
schemaVersion: 1,
|
||||
title: 'Unsafe Plugin',
|
||||
version: '1.0.0'
|
||||
}), 'utf8');
|
||||
|
||||
const result = await listLocalPluginManifests();
|
||||
|
||||
expect(result.plugins[0]?.entrypointPath).toBeUndefined();
|
||||
});
|
||||
});
|
||||
165
electron/plugin-library.ts
Normal file
165
electron/plugin-library.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { app } from 'electron';
|
||||
import * as fsp from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
|
||||
const PLUGINS_FOLDER_NAME = 'plugins';
|
||||
const MANIFEST_FILE_NAMES = ['toju-plugin.json', 'plugin.json'] as const;
|
||||
|
||||
export interface LocalPluginManifestDescriptor {
|
||||
discoveredAt: number;
|
||||
entrypointPath?: string;
|
||||
pluginRootUrl: string;
|
||||
manifest: unknown;
|
||||
manifestPath: string;
|
||||
pluginRoot: string;
|
||||
readmePath?: string;
|
||||
}
|
||||
|
||||
export interface LocalPluginDiscoveryError {
|
||||
manifestPath?: string;
|
||||
message: string;
|
||||
pluginRoot?: string;
|
||||
}
|
||||
|
||||
export interface LocalPluginDiscoveryResult {
|
||||
errors: LocalPluginDiscoveryError[];
|
||||
plugins: LocalPluginManifestDescriptor[];
|
||||
pluginsPath: string;
|
||||
}
|
||||
|
||||
function resolvePluginsPath(): string {
|
||||
return path.join(app.getPath('userData'), PLUGINS_FOLDER_NAME);
|
||||
}
|
||||
|
||||
async function ensurePluginsPath(): Promise<string> {
|
||||
const pluginsPath = resolvePluginsPath();
|
||||
|
||||
await fsp.mkdir(pluginsPath, { recursive: true });
|
||||
|
||||
return pluginsPath;
|
||||
}
|
||||
|
||||
async function realpathOrSelf(filePath: string): Promise<string> {
|
||||
try {
|
||||
return await fsp.realpath(filePath);
|
||||
} catch {
|
||||
return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
function isPathInside(parentPath: string, candidatePath: string): boolean {
|
||||
const relativePath = path.relative(parentPath, candidatePath);
|
||||
|
||||
return !!relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath);
|
||||
}
|
||||
|
||||
function readManifestPath(manifestRecord: Record<string, unknown>, key: string): string | undefined {
|
||||
const value = manifestRecord[key];
|
||||
|
||||
return typeof value === 'string' && value.trim()
|
||||
? value.trim()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
async function resolveManifestRelativeFile(pluginRoot: string, relativeFilePath: string | undefined): Promise<string | undefined> {
|
||||
if (!relativeFilePath || path.isAbsolute(relativeFilePath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const normalizedPath = path.normalize(relativeFilePath);
|
||||
|
||||
if (normalizedPath.startsWith('..')) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const candidatePath = path.join(pluginRoot, normalizedPath);
|
||||
const [realPluginRoot, realCandidatePath] = await Promise.all([realpathOrSelf(pluginRoot), realpathOrSelf(candidatePath)]);
|
||||
|
||||
if (!isPathInside(realPluginRoot, realCandidatePath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const stats = await fsp.stat(realCandidatePath);
|
||||
|
||||
return stats.isFile() ? realCandidatePath : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function findManifestPath(pluginRoot: string): Promise<string | undefined> {
|
||||
for (const fileName of MANIFEST_FILE_NAMES) {
|
||||
const manifestPath = path.join(pluginRoot, fileName);
|
||||
|
||||
try {
|
||||
const stats = await fsp.stat(manifestPath);
|
||||
|
||||
if (stats.isFile()) {
|
||||
return manifestPath;
|
||||
}
|
||||
} catch {
|
||||
// Missing manifest candidates are expected while scanning folders.
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function readPluginManifest(pluginRoot: string, manifestPath: string): Promise<LocalPluginManifestDescriptor> {
|
||||
const text = await fsp.readFile(manifestPath, 'utf8');
|
||||
const manifest = JSON.parse(text) as unknown;
|
||||
const manifestRecord = manifest && typeof manifest === 'object' && !Array.isArray(manifest)
|
||||
? manifest as Record<string, unknown>
|
||||
: {};
|
||||
const entrypointPromise = resolveManifestRelativeFile(pluginRoot, readManifestPath(manifestRecord, 'entrypoint'));
|
||||
const readmePromise = resolveManifestRelativeFile(pluginRoot, readManifestPath(manifestRecord, 'readme'));
|
||||
const [entrypointPath, readmePath] = await Promise.all([entrypointPromise, readmePromise]);
|
||||
|
||||
return {
|
||||
discoveredAt: Date.now(),
|
||||
entrypointPath,
|
||||
pluginRootUrl: pathToFileURL(pluginRoot + path.sep).toString(),
|
||||
manifest,
|
||||
manifestPath,
|
||||
pluginRoot,
|
||||
readmePath
|
||||
};
|
||||
}
|
||||
|
||||
export async function getLocalPluginsPath(): Promise<string> {
|
||||
return await ensurePluginsPath();
|
||||
}
|
||||
|
||||
export async function listLocalPluginManifests(): Promise<LocalPluginDiscoveryResult> {
|
||||
const pluginsPath = await ensurePluginsPath();
|
||||
const entries = await fsp.readdir(pluginsPath, { withFileTypes: true });
|
||||
const plugins: LocalPluginManifestDescriptor[] = [];
|
||||
const errors: LocalPluginDiscoveryError[] = [];
|
||||
|
||||
for (const entry of entries.filter((candidate) => candidate.isDirectory())) {
|
||||
const pluginRoot = path.join(pluginsPath, entry.name);
|
||||
const manifestPath = await findManifestPath(pluginRoot);
|
||||
|
||||
if (!manifestPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
plugins.push(await readPluginManifest(pluginRoot, manifestPath));
|
||||
} catch (error) {
|
||||
errors.push({
|
||||
manifestPath,
|
||||
message: error instanceof Error ? error.message : 'Unable to read plugin manifest',
|
||||
pluginRoot
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
errors,
|
||||
plugins: plugins.sort((left, right) => left.pluginRoot.localeCompare(right.pluginRoot)),
|
||||
pluginsPath
|
||||
};
|
||||
}
|
||||
@@ -109,6 +109,50 @@ export interface SavedThemeFileDescriptor {
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface LocalPluginManifestDescriptor {
|
||||
discoveredAt: number;
|
||||
entrypointPath?: string;
|
||||
pluginRootUrl: string;
|
||||
manifest: unknown;
|
||||
manifestPath: string;
|
||||
pluginRoot: string;
|
||||
readmePath?: string;
|
||||
}
|
||||
|
||||
export interface LocalApiSettings {
|
||||
enabled: boolean;
|
||||
port: number;
|
||||
exposeOnLan: boolean;
|
||||
scalarEnabled: boolean;
|
||||
docusaurusEnabled: boolean;
|
||||
allowedSignalingServers: string[];
|
||||
}
|
||||
|
||||
export type LocalApiStatus = 'stopped' | 'starting' | 'running' | 'error';
|
||||
|
||||
export interface LocalApiSnapshot {
|
||||
status: LocalApiStatus;
|
||||
host: string | null;
|
||||
port: number | null;
|
||||
baseUrl: string | null;
|
||||
error: string | null;
|
||||
exposeOnLan: boolean;
|
||||
scalarEnabled: boolean;
|
||||
docusaurusEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface LocalPluginDiscoveryError {
|
||||
manifestPath?: string;
|
||||
message: string;
|
||||
pluginRoot?: string;
|
||||
}
|
||||
|
||||
export interface LocalPluginDiscoveryResult {
|
||||
errors: LocalPluginDiscoveryError[];
|
||||
plugins: LocalPluginManifestDescriptor[];
|
||||
pluginsPath: string;
|
||||
}
|
||||
|
||||
export interface ExportUserDataResult {
|
||||
cancelled: boolean;
|
||||
exported: boolean;
|
||||
@@ -181,6 +225,8 @@ export interface ElectronAPI {
|
||||
importUserData: () => Promise<ImportUserDataResult>;
|
||||
eraseUserData: () => Promise<EraseUserDataResult>;
|
||||
getSavedThemesPath: () => Promise<string>;
|
||||
getLocalPluginsPath: () => Promise<string>;
|
||||
listLocalPluginManifests: () => Promise<LocalPluginDiscoveryResult>;
|
||||
listSavedThemes: () => Promise<SavedThemeFileDescriptor[]>;
|
||||
readSavedTheme: (fileName: string) => Promise<string>;
|
||||
writeSavedTheme: (fileName: string, text: string) => Promise<boolean>;
|
||||
@@ -191,10 +237,12 @@ export interface ElectronAPI {
|
||||
autoStart: boolean;
|
||||
closeToTray: boolean;
|
||||
hardwareAcceleration: boolean;
|
||||
localApi: LocalApiSettings;
|
||||
manifestUrls: string[];
|
||||
preferredVersion: string | null;
|
||||
runtimeHardwareAcceleration: boolean;
|
||||
restartRequired: boolean;
|
||||
vaapiVideoEncode: boolean;
|
||||
}>;
|
||||
showDesktopNotification: (payload: DesktopNotificationPayload) => Promise<boolean>;
|
||||
requestWindowAttention: () => Promise<boolean>;
|
||||
@@ -211,6 +259,7 @@ export interface ElectronAPI {
|
||||
autoStart?: boolean;
|
||||
closeToTray?: boolean;
|
||||
hardwareAcceleration?: boolean;
|
||||
localApi?: Partial<LocalApiSettings>;
|
||||
manifestUrls?: string[];
|
||||
preferredVersion?: string | null;
|
||||
vaapiVideoEncode?: boolean;
|
||||
@@ -219,11 +268,16 @@ export interface ElectronAPI {
|
||||
autoStart: boolean;
|
||||
closeToTray: boolean;
|
||||
hardwareAcceleration: boolean;
|
||||
localApi: LocalApiSettings;
|
||||
manifestUrls: string[];
|
||||
preferredVersion: string | null;
|
||||
runtimeHardwareAcceleration: boolean;
|
||||
restartRequired: boolean;
|
||||
vaapiVideoEncode: boolean;
|
||||
}>;
|
||||
getLocalApiStatus: () => Promise<LocalApiSnapshot>;
|
||||
openLocalApiDocs: () => Promise<{ opened: boolean; reason?: string }>;
|
||||
openDocusaurusDocs: () => Promise<{ opened: boolean; reason?: string }>;
|
||||
relaunchApp: () => Promise<boolean>;
|
||||
onDeepLinkReceived: (listener: (url: string) => void) => () => void;
|
||||
readClipboardFiles: () => Promise<ClipboardFilePayload[]>;
|
||||
@@ -294,6 +348,8 @@ const electronAPI: ElectronAPI = {
|
||||
importUserData: () => ipcRenderer.invoke('import-user-data'),
|
||||
eraseUserData: () => ipcRenderer.invoke('erase-user-data'),
|
||||
getSavedThemesPath: () => ipcRenderer.invoke('get-saved-themes-path'),
|
||||
getLocalPluginsPath: () => ipcRenderer.invoke('get-local-plugins-path'),
|
||||
listLocalPluginManifests: () => ipcRenderer.invoke('list-local-plugin-manifests'),
|
||||
listSavedThemes: () => ipcRenderer.invoke('list-saved-themes'),
|
||||
readSavedTheme: (fileName) => ipcRenderer.invoke('read-saved-theme', fileName),
|
||||
writeSavedTheme: (fileName, text) => ipcRenderer.invoke('write-saved-theme', fileName, text),
|
||||
@@ -331,6 +387,9 @@ const electronAPI: ElectronAPI = {
|
||||
};
|
||||
},
|
||||
setDesktopSettings: (patch) => ipcRenderer.invoke('set-desktop-settings', patch),
|
||||
getLocalApiStatus: () => ipcRenderer.invoke('get-local-api-status'),
|
||||
openLocalApiDocs: () => ipcRenderer.invoke('open-local-api-docs'),
|
||||
openDocusaurusDocs: () => ipcRenderer.invoke('open-docusaurus-docs'),
|
||||
relaunchApp: () => ipcRenderer.invoke('relaunch-app'),
|
||||
onDeepLinkReceived: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, url: string) => {
|
||||
|
||||
2918
package-lock.json
generated
2918
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
27
package.json
27
package.json
@@ -13,8 +13,9 @@
|
||||
"bundle:rnnoise": "esbuild node_modules/@timephy/rnnoise-wasm/dist/NoiseSuppressorWorklet.js --bundle --format=esm --outfile=toju-app/public/rnnoise-worklet.js",
|
||||
"start": "cd \"toju-app\" && ng serve",
|
||||
"build": "cd \"toju-app\" && ng build",
|
||||
"build:docs": "cd docs-site && npm run build",
|
||||
"build:electron": "tsc -p tsconfig.electron.json",
|
||||
"build:all": "npm run build && npm run build:electron && cd server && npm run build",
|
||||
"build:all": "npm run build && npm run build:docs && npm run build:electron && cd server && npm run build",
|
||||
"build:prod": "cd \"toju-app\" && ng build --configuration production --base-href='./'",
|
||||
"watch": "cd \"toju-app\" && ng build --watch --configuration development",
|
||||
"test": "cd \"toju-app\" && vitest run",
|
||||
@@ -29,12 +30,12 @@
|
||||
"migration:create": "typeorm migration:create electron/migrations/New",
|
||||
"migration:run": "typeorm migration:run -d dist/electron/data-source.js",
|
||||
"migration:revert": "typeorm migration:revert -d dist/electron/data-source.js",
|
||||
"electron:build": "npm run build:prod && npm run build:electron && electron-builder",
|
||||
"electron:build:win": "npm run build:prod && npm run build:electron && electron-builder --win",
|
||||
"electron:build:mac": "npm run build:prod && npm run build:electron && electron-builder --mac",
|
||||
"electron:build:linux": "npm run build:prod && npm run build:electron && electron-builder --linux",
|
||||
"electron:build:all": "npm run build:prod && npm run build:electron && electron-builder --win --mac --linux",
|
||||
"build:prod:all": "npm run build:prod && npm run build:electron && cd server && npm run build",
|
||||
"electron:build": "npm run build:prod && npm run build:docs && npm run build:electron && electron-builder",
|
||||
"electron:build:win": "npm run build:prod && npm run build:docs && npm run build:electron && electron-builder --win",
|
||||
"electron:build:mac": "npm run build:prod && npm run build:docs && npm run build:electron && electron-builder --mac",
|
||||
"electron:build:linux": "npm run build:prod && npm run build:docs && npm run build:electron && electron-builder --linux",
|
||||
"electron:build:all": "npm run build:prod && npm run build:docs && npm run build:electron && electron-builder --win --mac --linux",
|
||||
"build:prod:all": "npm run build:prod && npm run build:docs && npm run build:electron && cd server && npm run build",
|
||||
"build:prod:win": "npm run build:prod:all && electron-builder --win",
|
||||
"dev": "npm run build:electron && npm run electron:full",
|
||||
"dev:app": "npm run electron:dev",
|
||||
@@ -78,6 +79,7 @@
|
||||
"@ngrx/entity": "^21.0.1",
|
||||
"@ngrx/store": "^21.0.1",
|
||||
"@ngrx/store-devtools": "^21.0.1",
|
||||
"@scalar/api-reference": "^1.53.1",
|
||||
"@spartan-ng/brain": "^0.0.1-alpha.589",
|
||||
"@spartan-ng/cli": "^0.0.1-alpha.589",
|
||||
"@spartan-ng/ui-core": "^0.0.1-alpha.380",
|
||||
@@ -169,6 +171,17 @@
|
||||
"filter": [
|
||||
"**/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"from": "node_modules/@scalar/api-reference/dist/browser/standalone.js",
|
||||
"to": "scalar/api-reference.js"
|
||||
},
|
||||
{
|
||||
"from": "docs-site/build",
|
||||
"to": "docusaurus",
|
||||
"filter": [
|
||||
"**/*"
|
||||
]
|
||||
}
|
||||
],
|
||||
"nodeGypRebuild": false,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user