From 857e34f3ca71104d6e4fa9647bd6021a0b102fe7 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Sat, 28 Nov 2026 10:59:14 -0500 Subject: [PATCH 01/22] add plugin package --- packages/plugin/README.md | 13 + packages/plugin/package.json | 32 ++ packages/plugin/src/index.ts | 471 +++++++++++++++++++++++++++++ packages/plugin/src/vite.ts | 149 +++++++++ packages/plugin/tsconfig.base.json | 16 + packages/plugin/tsconfig.json | 7 + pnpm-workspace.yaml | 2 + 7 files changed, 690 insertions(+) create mode 100644 packages/plugin/README.md create mode 100644 packages/plugin/package.json create mode 100644 packages/plugin/src/index.ts create mode 100644 packages/plugin/src/vite.ts create mode 100644 packages/plugin/tsconfig.base.json create mode 100644 packages/plugin/tsconfig.json diff --git a/packages/plugin/README.md b/packages/plugin/README.md new file mode 100644 index 00000000..9d24725f --- /dev/null +++ b/packages/plugin/README.md @@ -0,0 +1,13 @@ +# `@usehyperion/plugin` + +```ts +// vite.config.ts +import { defineConfig } from "vite"; +import { hyperion } from "@usehyperion/plugin/vite"; + +export default defineConfig({ + plugins: [hyperion()], +}); +``` + +The output is an ES module and a `manifest.json` that the app installs. diff --git a/packages/plugin/package.json b/packages/plugin/package.json new file mode 100644 index 00000000..298edcf1 --- /dev/null +++ b/packages/plugin/package.json @@ -0,0 +1,32 @@ +{ + "name": "@usehyperion/plugin", + "version": "0.1.0", + "private": true, + "description": "Types and build tooling for Hyperion plugins", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./vite": "./src/vite.ts", + "./tsconfig.json": "./tsconfig.base.json", + "./package.json": "./package.json" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.0.0", + "@types/node": "^26.6.6", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^7.0.0", + "svelte": "^5.57.3", + "vite": "*" + }, + "peerDependenciesMeta": { + "@sveltejs/vite-plugin-svelte": { + "optional": true + }, + "vite": { + "optional": true + } + } +} diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts new file mode 100644 index 00000000..b7973f47 --- /dev/null +++ b/packages/plugin/src/index.ts @@ -0,0 +1,471 @@ +/** + * The Hyperion plugin API. + * + * Every export in this module is public, so keep the surface small. Describe + * data with plain interfaces, not with the app's own classes. The app + * implements these types, and this module never imports from the app. + * + * The only runtime code here is {@linkcode definePlugin}, which returns its + * argument unchanged. A plugin reaches the app through the + * {@linkcode PluginContext} that it gets in {@linkcode PluginDefinition.setup}. + */ +import type { Component } from "svelte"; + +export interface PluginManifest { + /** + * Uses only lowercase letters, digits, and single dashes between them. The + * app stores the plugin's settings under this id, so changing it loses the + * user's settings. + */ + readonly id: string; + + /** + * The name shown in the plugin settings. + */ + readonly name: string; + + /** + * Shown under the switch that enables the plugin. Supports the same + * Markdown as {@linkcode PluginSetting} descriptions. + */ + readonly description: string; + readonly version: string; +} + +/** + * The `manifest.json` that the Vite plugin writes next to a built plugin. + */ +export interface BuiltManifest extends PluginManifest { + /** + * The semver range of `@usehyperion/plugin` that the plugin was written + * against, taken from the plugin's dependencies. + */ + readonly api: string; + + /** + * The exact Svelte version that compiled the plugin's components. Compiled + * components only work with a matching Svelte runtime. + */ + readonly svelte: string; + + /** + * The path of the plugin's module, relative to the manifest. + */ + readonly entry: string; +} + +export interface Emote { + /** + * The {@linkcode EmoteProviderOptions.name} of the provider that supplied + * the emote. + */ + readonly provider: string; + + /** + * The emote's id at its provider. + */ + readonly id: string; + + /** + * The name the provider gives the emote. + */ + readonly name: string; + + /** + * A different name the emote has in one channel, if the channel renamed it. + */ + alias?: string; + + /** + * The name that users see and type. Set it to the alias if there is one, + * and to the name if there is not. + */ + displayName: string; + + /** + * The width of the source image in pixels. + */ + readonly width: number; + + /** + * The height of the source image in pixels. + */ + readonly height: number; + + /** + * The width in pixels that the emote takes up in a chat message. It can be + * different from the image width. + */ + readonly displayWidth: number; + + /** + * The height in pixels that the emote takes up in a chat message. + */ + readonly displayHeight: number; + + /** + * The image candidates for the `srcset` attribute. Each entry has the + * format ` x`, for example `https://cdn.example/1x 1x`. + */ + readonly srcset: string[]; + + /** + * When true, the emote has no width of its own and the app draws it on top + * of the emote before it. + */ + readonly zeroWidth?: boolean; +} + +export type EmoteData = Omit; + +/** + * The channel fields that the app guarantees to plugins. + */ +export interface PluginChannel { + /** + * The Twitch user id of the channel owner. + */ + readonly id: string; + + /** + * The lowercase Twitch login name of the channel owner. + */ + readonly login: string; +} + +export interface LoadContext { + /** + * The app aborts this signal when it no longer needs the result. This + * happens when the user disables the provider or when a reload replaces the + * load. Pass it to {@linkcode PluginHttp.json} so the request stops too. + */ + readonly signal: AbortSignal; +} + +/** + * Registers a source of emotes with {@linkcode PluginContext.emotes}. + */ +export interface EmoteProviderOptions { + /** + * Shown in the emote picker and in emote tooltips. The app uses the name to + * identify the provider, so registration throws if another provider already + * uses it. + */ + readonly name: string; + + /** + * The icon for the provider's tab in the emote picker. + */ + readonly icon: Component; + + /** + * The URL of an image that the emote picker shows as the avatar of the + * provider's global emotes. + */ + readonly logo: string; + + /** + * Returns whether the app loads and shows the provider's emotes. The app + * reads it in a reactive context, so the emotes load or disappear when a + * value read inside it changes. The provider is always enabled if you omit + * it. + */ + readonly enabled?: () => boolean; + + /** + * Loads the emotes that users can use in every channel. + */ + readonly global?: (ctx: LoadContext) => Promise; + + /** + * Loads the emotes of one channel. Resolve to an empty array when the + * channel has no emotes from this provider. If the provider's API responds + * with 404 for such a channel, pass {@linkcode RequestOptions.notFound} to + * {@linkcode PluginHttp.json}. + */ + readonly channel?: (channel: PluginChannel, ctx: LoadContext) => Promise; + + /** + * How many seconds the app uses cached emotes before it fetches them again. + * The default is 5 minutes. + */ + readonly fresh?: number; +} + +export interface BadgeData { + /** + * Identifies the badge among this provider's badges. The keys of + * {@linkcode BadgeSet.users} refer to this value. + */ + readonly version: string; + + readonly title: string; + + /** + * The alt text of the badge image. The default is the title. + */ + readonly description?: string; + + /** + * A CSS background color for the badge. + */ + readonly color?: string; + + readonly imageUrl: string; +} + +/** + * A provider's badges and the users who have them. + */ +export interface BadgeSet { + readonly badges: BadgeData[]; + + /** + * The Twitch user ids that have each badge, keyed by + * {@linkcode BadgeData.version}. The app ignores versions that are not in + * {@linkcode badges}. + */ + readonly users: Record; +} + +/** + * Registers a source of badges with {@linkcode PluginContext.badges}. + */ +export interface BadgeProviderOptions { + /** + * A readable name for the provider. The app identifies the badges by the + * plugin id, not by this name. + */ + readonly name: string; + + /** + * Returns whether the app loads and shows the provider's badges. The app + * reads it in a reactive context, so the badges load or disappear when a + * value read inside it changes. The provider is always enabled if you omit + * it. + */ + readonly enabled?: () => boolean; + + /** + * Loads all of the provider's badges and the users who have them. + */ + readonly load: (ctx: LoadContext) => Promise; +} + +interface SettingBase { + readonly label: string; + + /** + * Shown under the label. Supports inline code, links, bold, and italics. + */ + readonly description?: string; + + /** + * More words that match this setting in the settings search. The search + * already matches the label and description. + */ + readonly keywords?: string[]; +} + +interface ChoiceItem { + readonly label: string; + + /** + * The value that the setting stores when the user selects this item. + */ + readonly value: string; + readonly description?: string; +} + +/** + * One user-facing setting. The `type` selects the control that the settings + * page shows, and `default` sets the value type that + * {@linkcode PluginContext.settings} returns for it. + */ +export type PluginSetting = SettingBase & + ( + | { + readonly type: "switch"; + readonly default: boolean; + } + | { + readonly type: "input"; + readonly default: string; + readonly placeholder?: string; + } + | { + /** + * `radio` shows every item at once. `select` shows the items in a + * dropdown, which suits longer lists. + */ + readonly type: "radio" | "select"; + + /** + * The {@linkcode ChoiceItem.value} of the item selected by default. + */ + readonly default: string; + readonly items: ChoiceItem[]; + } + | { + readonly type: "slider"; + readonly default: number; + readonly min?: number; + readonly max?: number; + readonly step?: number; + + /** + * Shows a tick mark at each step along the track. + */ + readonly showSteps?: boolean; + + /** + * Formats the value that the slider displays, for example to add a + * unit. + */ + readonly formatValue?: (value: number) => string; + } + ); + +/** + * A plugin's settings, keyed by a name that is unique in the plugin. The app + * stores each value as `plugins..`, so renaming a key resets + * that setting for every user. The key `enabled` is reserved for the switch + * that turns the plugin on and off. + */ +export type PluginSettings = Record; + +type SettingValue = T["default"] extends boolean + ? boolean + : T["default"] extends number + ? number + : string; + +/** + * The current value of each of the plugin's settings, or its default if the + * user has not changed it. When you read a value in a reactive context, the + * context runs again after the user changes that setting. + */ +export type SettingValues = { + readonly [K in keyof S]: SettingValue; +}; + +export interface RequestOptions { + /** + * @default "GET" + */ + readonly method?: "GET" | "POST"; + readonly headers?: HeadersInit; + + /** + * Sent as a JSON request body. + */ + readonly body?: Record; + + /** + * Cancels the request. When this signal aborts, the promise rejects with + * the signal's reason, not with a timeout error. + */ + readonly signal?: AbortSignal; + + /** + * The value to resolve with when the server responds with 404. Without it, + * a 404 rejects like any other error status. + */ + readonly notFound?: T; +} + +export interface PluginHttp { + /** + * Fetches a URL and parses the response as JSON. The request uses the + * app's timeout, and an error status or timeout rejects with the app's API + * error, so failures look the same as the app's own requests. + */ + json(url: string, options?: RequestOptions): Promise; +} + +/** + * Writes to the app's log. Each message starts with the plugin id in + * brackets, so you do not need to add it. + */ +export interface PluginLogger { + debug(message: string): void; + info(message: string): void; + warn(message: string, cause?: unknown): void; + error(message: string, cause?: unknown): void; +} + +/** + * Registers providers of one kind. Each call registers one provider and + * returns a function that removes it. + */ +interface Provider { + provide(options: T): Dispose; +} + +/** + * Removes what a call registered. + * + * This only has an effect during the plugin's lifetime since the app removes + * everything that the plugin registered when it's disabled. + */ +export type Dispose = () => void; + +/** + * The plugin's access to the app. The app creates a new context each time + * the plugin is enabled. + */ +export interface PluginContext { + /** + * The plugin's {@linkcode PluginManifest.id}. + */ + readonly id: string; + readonly settings: SettingValues; + readonly log: PluginLogger; + readonly http: PluginHttp; + + /** + * Registers emote providers. A plugin can register more than one, but each + * one needs a unique name. + */ + readonly emotes: Provider; + + /** + * Registers the plugin's badge provider. The app stores badges under the + * plugin id, so a plugin can register only one badge provider at a time. + * Attempting to register more than one will throw an error. + */ + readonly badges: Provider; + + /** + * Adds a function that runs when the plugin is disabled. Cleanup functions + * run in the reverse order of registration. If one throws, the app logs + * the error and continues with the next. + */ + onDispose(cleanup: Dispose): void; +} + +/** + * The behavior of a plugin. Its name and other details are in its + * {@linkcode PluginManifest}. + */ +export interface PluginDefinition { + /** + * The settings shown for the plugin on the settings page. + */ + readonly settings?: S; + + /** + * Runs inside an [`$effect.root`](https://svelte.dev/docs/svelte/$effect#$effect.root) + * each time the plugin is enabled. Effects created here stop when the + * plugin is disabled. The returned function runs before the app removes + * what the plugin registered. If `setup` throws, the app logs the error and + * removes everything that it registered before it threw. + */ + setup(ctx: PluginContext): Dispose | void; +} + +export function definePlugin( + definition: PluginDefinition, +): PluginDefinition { + return definition; +} diff --git a/packages/plugin/src/vite.ts b/packages/plugin/src/vite.ts new file mode 100644 index 00000000..49c06a68 --- /dev/null +++ b/packages/plugin/src/vite.ts @@ -0,0 +1,149 @@ +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; + +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import type { Plugin, PluginOption } from "vite"; + +import type { BuiltManifest } from "./index"; + +export interface HyperionOptions { + /** + * The path of the module that default exports the plugin definition, + * relative to the Vite root. The default is `src/index.ts`. + */ + entry?: string; +} + +interface PackageJson { + version?: string; + hyperion?: Record; + dependencies?: Record; + devDependencies?: Record; + peerDependencies?: Record; +} + +const API_PACKAGE = "@usehyperion/plugin"; +const ENTRY_FILE = "index.js"; +const ID_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + +/** + * Modules that the build leaves as imports because the app supplies them at + * runtime. Svelte must come from the app, because reactivity and context only + * work inside one copy of the Svelte runtime. + */ +const SHARED = /^svelte(?:\/|$)/; + +/** + * Returns the Vite plugins that build a Hyperion plugin in library mode. + * + * The build reads the manifest from the `hyperion` field in package.json and + * fails if a field is missing or the id is not valid. Svelte imports stay + * external, and component styles are inlined into the JavaScript. + */ +export function hyperion(options: HyperionOptions = {}): PluginOption[] { + let root = process.cwd(); + let manifest: BuiltManifest; + + const plugin: Plugin = { + name: "hyperion:plugin", + config(config) { + root = resolve(config.root ?? process.cwd()); + + return { + build: { + target: "esnext", + minify: true, + lib: { + entry: resolve(root, options.entry ?? "src/index.ts"), + formats: ["es"], + fileName: () => ENTRY_FILE, + }, + rolldownOptions: { + external: (id) => SHARED.test(id), + }, + }, + }; + }, + buildStart() { + manifest = readManifest(root, (message) => this.error(message)); + }, + generateBundle() { + this.emitFile({ + type: "asset", + fileName: "manifest.json", + source: `${JSON.stringify(manifest, null, "\t")}\n`, + }); + }, + }; + + return [ + // Each component injects its own styles, so the build emits no CSS file + // and the plugin stays one module. + svelte({ + emitCss: false, + compilerOptions: { css: "injected" }, + }), + plugin, + ]; +} + +function readManifest(root: string, fail: (message: string) => never): BuiltManifest { + const pkgPath = resolve(root, "package.json"); + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as PackageJson; + const meta = pkg.hyperion ?? fail(`${pkgPath} has no "hyperion" field`); + + function field(key: string) { + const value = meta[key]; + + return typeof value === "string" && value.trim() + ? value.trim() + : fail(`"hyperion.${key}" in ${pkgPath} must be a non-empty string`); + } + + const id = field("id"); + + if (!ID_REGEX.test(id)) { + fail(`"hyperion.id" must be lowercase letters, digits, and dashes, got "${id}"`); + } + + const range = + pkg.peerDependencies?.[API_PACKAGE] ?? + pkg.dependencies?.[API_PACKAGE] ?? + pkg.devDependencies?.[API_PACKAGE] ?? + fail(`${pkgPath} must depend on ${API_PACKAGE}`); + + const require = createRequire(pkgPath); + const installed = (name: string) => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + (require(`${name}/package.json`) as { version: string }).version; + + return { + id, + name: field("name"), + description: field("description"), + version: pkg.version ?? fail(`${pkgPath} has no "version"`), + api: resolveRange(range, () => installed(API_PACKAGE)), + svelte: installed("svelte"), + entry: ENTRY_FILE, + }; +} + +function resolveRange(range: string, version: () => string) { + if (!range.startsWith("workspace:")) { + return range; + } + + const spec = range.slice("workspace:".length); + + switch (spec) { + case "*": + return version(); + case "^": + case "~": + return spec + version(); + default: + return spec; + } +} diff --git a/packages/plugin/tsconfig.base.json b/packages/plugin/tsconfig.base.json new file mode 100644 index 00000000..1b41eac7 --- /dev/null +++ b/packages/plugin/tsconfig.base.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["esnext", "DOM", "DOM.Iterable"], + "types": ["vite/client"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "resolveJsonModule": true, + "skipLibCheck": true + } +} diff --git a/packages/plugin/tsconfig.json b/packages/plugin/tsconfig.json new file mode 100644 index 00000000..c3a8b021 --- /dev/null +++ b/packages/plugin/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.base.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["src"] +} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index cf2f3936..078489e3 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,3 +1,5 @@ +packages: + - packages/* allowBuilds: esbuild: false catalog: From e4722d9e2528f9cac8dc6252e18977af56e33306 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Sat, 28 Nov 2026 11:19:47 -0500 Subject: [PATCH 02/22] add plugin api, make bttv and ffz internal plugins --- package.json | 5 +- packages/plugin-bttv/package.json | 24 ++ packages/plugin-bttv/src/Icon.svelte | 23 ++ packages/plugin-bttv/src/index.ts | 113 ++++++++ .../plugin-bttv/src/logo.svg | 0 packages/plugin-bttv/tsconfig.json | 4 + packages/plugin-ffz/package.json | 24 ++ packages/plugin-ffz/src/Icon.svelte | 19 ++ packages/plugin-ffz/src/index.ts | 121 +++++++++ .../plugin-ffz/src/logo.svg | 0 packages/plugin-ffz/tsconfig.json | 4 + packages/plugin/README.md | 4 +- pnpm-lock.yaml | 194 ++++++++------ src/hooks.client.ts | 3 + src/lib/commands/built-in/reload-badges.ts | 15 +- .../emote-picker/EmotePicker.svelte | 32 +-- src/lib/components/emote/EmoteTooltip.svelte | 8 +- .../settings/schema/categories/chat.ts | 26 -- .../settings/schema/categories/plugins.ts | 62 +++++ src/lib/emotes.ts | 202 +++----------- src/lib/icons.ts | 1 + src/lib/managers/badge-manager.ts | 253 ++++++++++-------- src/lib/managers/base-emote-manager.ts | 187 +++++-------- src/lib/managers/channel-emote-manager.ts | 101 +------ src/lib/managers/emote-manager.ts | 54 +--- src/lib/models/badge.ts | 16 -- src/lib/models/message/user-message.svelte.ts | 12 +- src/lib/plugins/host.svelte.ts | 170 ++++++++++++ src/lib/plugins/internal.ts | 53 ++++ src/lib/plugins/registry.ts | 85 ++++++ src/lib/plugins/settings.ts | 29 ++ src/lib/providers/seventv.ts | 190 +++++++++++++ src/lib/settings.ts | 18 +- src/routes/(main)/+layout.svelte | 11 +- 34 files changed, 1344 insertions(+), 719 deletions(-) create mode 100644 packages/plugin-bttv/package.json create mode 100644 packages/plugin-bttv/src/Icon.svelte create mode 100644 packages/plugin-bttv/src/index.ts rename src/assets/logos/bttv.svg => packages/plugin-bttv/src/logo.svg (100%) create mode 100644 packages/plugin-bttv/tsconfig.json create mode 100644 packages/plugin-ffz/package.json create mode 100644 packages/plugin-ffz/src/Icon.svelte create mode 100644 packages/plugin-ffz/src/index.ts rename src/assets/logos/ffz.svg => packages/plugin-ffz/src/logo.svg (100%) create mode 100644 packages/plugin-ffz/tsconfig.json create mode 100644 src/lib/components/settings/schema/categories/plugins.ts create mode 100644 src/lib/plugins/host.svelte.ts create mode 100644 src/lib/plugins/internal.ts create mode 100644 src/lib/plugins/registry.ts create mode 100644 src/lib/plugins/settings.ts create mode 100644 src/lib/providers/seventv.ts diff --git a/package.json b/package.json index c0a998ba..03171362 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,10 @@ "@tauri-store/svelte": "^3.2.1", "@ui-sdk/core": "0.1.0-beta.24", "@ui-sdk/svelte": "0.1.0-beta.24", - "colord": "^2.14.1", + "@usehyperion/plugin": "workspace:^", + "@usehyperion/plugin-bttv": "workspace:^", + "@usehyperion/plugin-ffz": "workspace:^", + "colord": "^2.14.0", "dayjs": "^1.11.23", "gql.tada": "^1.11.6", "graphql-web-lite": "16.6.0-4", diff --git a/packages/plugin-bttv/package.json b/packages/plugin-bttv/package.json new file mode 100644 index 00000000..dea12c25 --- /dev/null +++ b/packages/plugin-bttv/package.json @@ -0,0 +1,24 @@ +{ + "name": "@usehyperion/plugin-bttv", + "version": "0.1.0", + "private": true, + "description": "BetterTTV emotes and badges for Hyperion", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "devDependencies": { + "@usehyperion/plugin": "workspace:^", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "svelte": "^5.57.3" + }, + "hyperion": { + "id": "bttv", + "name": "BetterTTV", + "description": "Emotes and badges from [BetterTTV](https://betterttv.com/)." + } +} diff --git a/packages/plugin-bttv/src/Icon.svelte b/packages/plugin-bttv/src/Icon.svelte new file mode 100644 index 00000000..672672f2 --- /dev/null +++ b/packages/plugin-bttv/src/Icon.svelte @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/packages/plugin-bttv/src/index.ts b/packages/plugin-bttv/src/index.ts new file mode 100644 index 00000000..22c285be --- /dev/null +++ b/packages/plugin-bttv/src/index.ts @@ -0,0 +1,113 @@ +import { definePlugin, type BadgeData, type EmoteData } from "@usehyperion/plugin"; + +import Icon from "./Icon.svelte"; +import logo from "./logo.svg"; + +const NAME = "BetterTTV"; +const API = "https://api.betterttv.net/3"; + +interface BttvEmote { + id: string; + code: string; + width?: number; + height?: number; +} + +interface BttvUser { + channelEmotes: BttvEmote[]; + sharedEmotes: BttvEmote[]; +} + +interface BttvBadgeOwner { + providerId: string; + badge: { + type: number; + description: string; + svg: string; + }; +} + +function toEmote(emote: BttvEmote): EmoteData { + const width = emote.width ?? 28; + const height = emote.height ?? 28; + + return { + id: emote.id, + name: emote.code, + displayName: emote.code, + width, + height, + displayWidth: width, + displayHeight: height, + srcset: [1, 2, 3].map((n) => `https://cdn.betterttv.net/emote/${emote.id}/${n}x ${n}x`), + }; +} + +export default definePlugin({ + settings: { + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from BetterTTV.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from BetterTTV.", + default: true, + }, + }, + setup(ctx) { + ctx.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => ctx.settings.emotes, + async global({ signal }) { + const emotes = await ctx.http.json(`${API}/cached/emotes/global`, { + signal, + }); + + return emotes.map(toEmote); + }, + async channel(channel, { signal }) { + const user = await ctx.http.json( + `${API}/cached/users/twitch/${channel.id}`, + { notFound: null, signal }, + ); + + return user ? [...user.channelEmotes, ...user.sharedEmotes].map(toEmote) : []; + }, + }); + + ctx.badges.provide({ + name: NAME, + enabled: () => ctx.settings.badges, + async load({ signal }) { + const owners = await ctx.http.json(`${API}/cached/badges`, { + signal, + }); + + const badges = new Map(); + const users: Record = {}; + + for (const { providerId, badge } of owners) { + const version = badge.type.toString(); + + if (!badges.has(version)) { + badges.set(version, { + version, + title: badge.description, + imageUrl: badge.svg, + }); + } + + (users[version] ??= []).push(providerId); + } + + return { badges: [...badges.values()], users }; + }, + }); + }, +}); diff --git a/src/assets/logos/bttv.svg b/packages/plugin-bttv/src/logo.svg similarity index 100% rename from src/assets/logos/bttv.svg rename to packages/plugin-bttv/src/logo.svg diff --git a/packages/plugin-bttv/tsconfig.json b/packages/plugin-bttv/tsconfig.json new file mode 100644 index 00000000..678520af --- /dev/null +++ b/packages/plugin-bttv/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "include": ["src"] +} diff --git a/packages/plugin-ffz/package.json b/packages/plugin-ffz/package.json new file mode 100644 index 00000000..70e131c2 --- /dev/null +++ b/packages/plugin-ffz/package.json @@ -0,0 +1,24 @@ +{ + "name": "@usehyperion/plugin-ffz", + "version": "0.1.0", + "private": true, + "description": "FrankerFaceZ emotes and badges for Hyperion", + "type": "module", + "exports": { + ".": "./src/index.ts", + "./package.json": "./package.json" + }, + "devDependencies": { + "@usehyperion/plugin": "workspace:^", + "svelte": "^5.57.3", + "vite": "catalog:" + }, + "peerDependencies": { + "svelte": "^5.57.3" + }, + "hyperion": { + "id": "ffz", + "name": "FrankerFaceZ", + "description": "Emotes and badges from [FrankerFaceZ](https://www.frankerfacez.com/)." + } +} diff --git a/packages/plugin-ffz/src/Icon.svelte b/packages/plugin-ffz/src/Icon.svelte new file mode 100644 index 00000000..a34deeac --- /dev/null +++ b/packages/plugin-ffz/src/Icon.svelte @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/plugin-ffz/src/index.ts b/packages/plugin-ffz/src/index.ts new file mode 100644 index 00000000..324b9c74 --- /dev/null +++ b/packages/plugin-ffz/src/index.ts @@ -0,0 +1,121 @@ +import { definePlugin, type BadgeData, type EmoteData } from "@usehyperion/plugin"; + +import Icon from "./Icon.svelte"; +import logo from "./logo.svg"; + +const NAME = "FrankerFaceZ"; +const API = "https://api.frankerfacez.com/v1"; + +const GLOBAL_SET = 3; + +// Twitch already has a bot badge so we don't need the FFZ one +const BOT_BADGE = 2; + +interface FfzEmote { + id: number; + name: string; + height: number; + width: number; + urls: Record; +} + +interface FfzEmoteSet { + emoticons: FfzEmote[]; +} + +interface GlobalSets { + sets: Record; +} + +interface Room { + room: { set: number }; + sets: Record; +} + +interface FfzBadge { + id: number; + title: string; + color: string; + urls: Record; +} + +interface Badges { + badges: FfzBadge[]; + users: Record; +} + +function toEmote(emote: FfzEmote): EmoteData { + return { + id: emote.id.toString(), + name: emote.name, + displayName: emote.name, + width: emote.width, + height: emote.height, + displayWidth: emote.width, + displayHeight: emote.height, + srcset: Object.entries(emote.urls).map(([n, url]) => `${url} ${n}x`), + }; +} + +export default definePlugin({ + settings: { + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from FrankerFaceZ.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from FrankerFaceZ.", + default: true, + }, + }, + setup(ctx) { + ctx.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => ctx.settings.emotes, + async global({ signal }) { + const data = await ctx.http.json(`${API}/set/global`, { signal }); + return data.sets[GLOBAL_SET].emoticons.map(toEmote); + }, + async channel(channel, { signal }) { + const data = await ctx.http.json(`${API}/room/id/${channel.id}`, { + notFound: null, + signal, + }); + + return data?.sets[data.room.set].emoticons.map(toEmote) ?? []; + }, + }); + + ctx.badges.provide({ + name: NAME, + enabled: () => ctx.settings.badges, + async load({ signal }) { + const data = await ctx.http.json(`${API}/badges/ids`, { signal }); + + const badges: BadgeData[] = data.badges + .filter((badge) => badge.id !== BOT_BADGE) + .map((badge) => ({ + version: badge.id.toString(), + title: badge.title, + color: badge.color, + imageUrl: badge.urls["4"], + })); + + const users = Object.fromEntries( + Object.entries(data.users).map(([version, ids]) => [ + version, + ids.map((id) => id.toString()), + ]), + ); + + return { badges, users }; + }, + }); + }, +}); diff --git a/src/assets/logos/ffz.svg b/packages/plugin-ffz/src/logo.svg similarity index 100% rename from src/assets/logos/ffz.svg rename to packages/plugin-ffz/src/logo.svg diff --git a/packages/plugin-ffz/tsconfig.json b/packages/plugin-ffz/tsconfig.json new file mode 100644 index 00000000..678520af --- /dev/null +++ b/packages/plugin-ffz/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "include": ["src"] +} diff --git a/packages/plugin/README.md b/packages/plugin/README.md index 9d24725f..befc3271 100644 --- a/packages/plugin/README.md +++ b/packages/plugin/README.md @@ -1,12 +1,12 @@ # `@usehyperion/plugin` ```ts +import { hyperion } from "@usehyperion/plugin/vite"; // vite.config.ts import { defineConfig } from "vite"; -import { hyperion } from "@usehyperion/plugin/vite"; export default defineConfig({ - plugins: [hyperion()], + plugins: [hyperion()], }); ``` diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ecc0780e..be6fb1e4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -232,8 +232,17 @@ importers: '@ui-sdk/svelte': specifier: 0.1.0-beta.24 version: 0.1.0-beta.24(@ui-sdk/core@0.1.0-beta.24)(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@usehyperion/plugin': + specifier: workspace:^ + version: link:packages/plugin + '@usehyperion/plugin-bttv': + specifier: workspace:^ + version: link:packages/plugin-bttv + '@usehyperion/plugin-ffz': + specifier: workspace:^ + version: link:packages/plugin-ffz colord: - specifier: ^2.14.1 + specifier: ^2.14.0 version: 2.14.1 dayjs: specifier: ^1.11.23 @@ -264,7 +273,7 @@ importers: version: 7.6.4 valibot: specifier: ^1.5.0 - version: 1.5.0(typescript@6.0.3) + version: 1.6.0(typescript@6.0.3) virtua: specifier: ^0.56.0 version: 0.56.0(svelte@5.60.2(@typescript-eslint/types@8.74.0)) @@ -280,10 +289,10 @@ importers: version: 3.12.4 '@sveltejs/adapter-static': specifier: ^4.0.1 - version: 4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)) + version: 4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)) '@sveltejs/kit': specifier: ^3.5.0 - version: 3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + version: 3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) '@tauri-apps/cli': specifier: ^2.13.0 version: 2.13.0 @@ -321,6 +330,46 @@ importers: specifier: 'catalog:' version: 1.9.0(@types/node@26.6.11)(@vitest/ui@5.1.2)(jiti@2.7.0)(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + packages/plugin: + dependencies: + vite: + specifier: npm:@voidzero-dev/vite-plus-core@8.4.0 + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + devDependencies: + '@sveltejs/vite-plugin-svelte': + specifier: ^7.0.0 + version: 7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@types/node': + specifier: ^26.6.6 + version: 26.6.11 + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + + packages/plugin-bttv: + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + + packages/plugin-ffz: + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.60.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + packages: '@0no-co/graphql.web@1.3.4': @@ -343,16 +392,16 @@ packages: '@antfu/install-pkg@2.1.0': resolution: {integrity: sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==} - '@babel/code-frame@7.29.7': - resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + '@babel/code-frame@7.29.17': + resolution: {integrity: sha512-IdlVpcDeoDATtN2cfmnVk0A4XJKhu7SlpGuSaiOFdko09YC1MD07WokWUSEdw5R2o4o8VObX2LzViQW6VXnzkA==} engines: {node: '>=6.9.0'} - '@babel/helper-validator-identifier@7.29.7': - resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + '@babel/helper-validator-identifier@7.29.17': + resolution: {integrity: sha512-AG+olLB+teKhkQ2WYJeaZqJwNLjtWTz1waQIP/tEYITzVzpdHLP7IXx2c/bH2JTsNCgvWlkqdCv91xcb8lul8Q==} engines: {node: '>=6.9.0'} - '@babel/runtime@7.29.16': - resolution: {integrity: sha512-LKBjGopxrQE0aFucNL69OyyyF143MOWUULEOftU3oCgyD35Sy84UUpVnt/sNvTb7ZmCyALSt7om+fojlW35zYQ==} + '@babel/runtime@7.29.17': + resolution: {integrity: sha512-CvlZdpED5dsu21yK0DfpXksJWt1zeW09lY49hp7P9cA5Qedx/QkwEs1PfluSJjijH9i94oT9LmtgGWlPY8ISzw==} engines: {node: '>=6.9.0'} '@blazediff/core@1.10.0': @@ -804,8 +853,8 @@ packages: resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} engines: {node: '>= 18.0.0'} - '@sveltejs/vite-plugin-svelte@7.3.2': - resolution: {integrity: sha512-86J4nBLeTqYYIx/paBIRqYJMFYlpTS2sepUdQ6tUyU1jxqRV72ejOrIV2wsqlOsKlkM+h0G1SgwoHI30N+n9CA==} + '@sveltejs/vite-plugin-svelte@7.3.3': + resolution: {integrity: sha512-DRlbdAR4JPByiz+9MIUCS101Mx5xLHRAdj85qc0QJurwjsaS+0wt+pyDPqi7iN957mo+LqVqgKeN/F9iv7vqeQ==} engines: {node: ^20.19 || ^22.12 || >=24} peerDependencies: svelte: ^5.46.4 @@ -1027,8 +1076,8 @@ packages: resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==} engines: {node: '>=18'} - '@testing-library/user-event@14.6.13': - resolution: {integrity: sha512-2LVZGptuB5un1Cu/u31o9adkCwbsUTMp4B4p04xupI7uobvTIpgKidSdShqZiReo/mQmvR9xjgdgTgge4oAbYA==} + '@testing-library/user-event@14.6.14': + resolution: {integrity: sha512-N2IuJHrFLa4uEpVzOqMjwoFJ26PLjbEZnX+8ogaDKRcKyKGb5WviZW4IZ1zOQZJzIZGpB0ESkG4QTjJ4ViiYtA==} engines: {node: '>=12', npm: '>=6'} peerDependencies: '@testing-library/dom': '>=7.21.4' @@ -1385,8 +1434,8 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - brace-expansion@5.1.0: - resolution: {integrity: sha512-aa11Dv491GKnYqxaul3aRJ0szew7yMJMfZPnqD44NjGrZXoj62l41OEDDpdpC4eE2P88vBFfLuSyRhpG91NUvg==} + brace-expansion@5.1.2: + resolution: {integrity: sha512-ELhY3JEerIBbhgW+rh0/8glkZAaMqn1x3BAvp3yTULSEGozMK/5PT6WTdBgsdvJqwwmv7MAQNOydfYbvK1Vgfw==} engines: {node: 20 || >=22} cacheable@2.5.0: @@ -1420,8 +1469,8 @@ packages: resolution: {integrity: sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw==} engines: {node: '>=22'} - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + cross-spawn@7.1.2: + resolution: {integrity: sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==} engines: {node: '>= 8'} dayjs@1.11.23: @@ -1442,10 +1491,6 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - deepmerge@4.3.1: - resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} - engines: {node: '>=0.10.0'} - dequal@2.0.3: resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} engines: {node: '>=6'} @@ -1464,8 +1509,8 @@ packages: dom-accessibility-api@0.5.16: resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} - enhanced-resolve@5.27.0: - resolution: {integrity: sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==} + enhanced-resolve@5.27.2: + resolution: {integrity: sha512-Cpp3nuaI7ZdgEsvVP6zzk08uxrfGTSUnDwijv6PZfe8qHjcUYv5X9bJF71WTt5HwOeaeVandf9zACK4jcWroNw==} engines: {node: '>=10.13.0'} es-module-lexer@2.3.2: @@ -1581,8 +1626,8 @@ packages: flat-cache@6.1.23: resolution: {integrity: sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==} - flatted@3.4.4: - resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + flatted@3.6.0: + resolution: {integrity: sha512-1Szo+c/GCm/cKBovrfT0Wpqw7fiqZg/xzlZtLtvWlYyvT4zUGZTS8Qo3sXPQ0nWqMg3N4nEFL2Ukzrjnsopwbg==} fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} @@ -1766,8 +1811,8 @@ packages: magic-string@1.4.5: resolution: {integrity: sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==} - minimatch@11.0.9: - resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} + minimatch@11.0.10: + resolution: {integrity: sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==} engines: {node: 20 || >=22} mlly@1.8.2: @@ -1865,8 +1910,8 @@ packages: resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} engines: {node: '>=10'} - package-manager-detector@1.9.0: - resolution: {integrity: sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==} + package-manager-detector@1.10.0: + resolution: {integrity: sha512-FlC7wr4YYRfVyk1E3u3qwi7Vh6qVvPowYkHQSDEoSKCN0o0F7w0TzNfJSBb/1rwEQbU3c96Exx/2vMYiCIx+wQ==} paneforge@1.0.2: resolution: {integrity: sha512-KzmIXQH1wCfwZ4RsMohD/IUtEjVhteR+c+ulb/CHYJHX8SuDXoJmChtsc/Xs5Wl8NHS4L5Q7cxL8MG40gSU1bA==} @@ -1973,8 +2018,8 @@ packages: resolution: {integrity: sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==} engines: {node: '>=18'} - source-map-js@1.2.4: - resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} + source-map-js@1.3.0: + resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} engines: {node: '>=6.0.0'} std-env@4.3.0: @@ -2003,11 +2048,11 @@ packages: peerDependencies: svelte: ^5.30.2 - svelte2tsx@0.7.63: - resolution: {integrity: sha512-gRgz/V6wOx0NDZhm6OMD2VIh+/HrgZc3k6ibX93rkNPEkWNn/P3Uhb1fYCqOrimEUpQd8r65dhiHZIJXSQBeow==} + svelte2tsx@0.7.64: + resolution: {integrity: sha512-/aPUIr0+kyVtiPr+HGl88YMR4DQdpjskiw5/90FWgek3W0lL1DPkdeMAFdhZ4bVui5M1UEhdfyqY+/iWmyqNvg==} peerDependencies: - svelte: ^3.55 || ^4.0.0-next.0 || ^4.0 || ^5.0.0-next.0 - typescript: ^4.9.4 || ^5.0.0 || ^6.0.0 + svelte: ^3.55 || ^4.0.0 || ^5.0.0 + typescript: ^4.9.4 || ^5.0.0 || ^6.0.0 || ^7.1.0-0 svelte@5.60.2: resolution: {integrity: sha512-AlsscDbX17QNh1MV4ZO/7a8XpjDrWTDX8Wv3QjHzFATvC7NL+z/PRvu0poBAkVZe8dvpvieGBqcJio7aopkh0A==} @@ -2150,8 +2195,8 @@ packages: resolution: {integrity: sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==} hasBin: true - valibot@1.5.0: - resolution: {integrity: sha512-nil6AkP2TChWL43Z5uJ6GTxX01CUA+g8LWUM+N/rB9NBbkUMaUsi9PUNzlUPgoKASgmx9f7eGOYpJ04/fSa6FQ==} + valibot@1.6.0: + resolution: {integrity: sha512-r8Cpu38zehdfONp8KbtWDDAFR3S3sklmSm0hAn61yC5WUKJvMr4LTds+c3kQqkjw4bKliHlo29doqZk0mbiTXQ==} peerDependencies: typescript: '>=5' peerDependenciesMeta: @@ -2319,23 +2364,23 @@ snapshots: '@antfu/install-pkg@1.1.0': dependencies: - package-manager-detector: 1.9.0 + package-manager-detector: 1.10.0 tinyexec: 1.4.0 '@antfu/install-pkg@2.1.0': dependencies: - package-manager-detector: 1.9.0 + package-manager-detector: 1.10.0 tinyexec: 1.4.0 - '@babel/code-frame@7.29.7': + '@babel/code-frame@7.29.17': dependencies: - '@babel/helper-validator-identifier': 7.29.7 + '@babel/helper-validator-identifier': 7.29.17 js-tokens: 4.0.0 picocolors: 1.1.1 - '@babel/helper-validator-identifier@7.29.7': {} + '@babel/helper-validator-identifier@7.29.17': {} - '@babel/runtime@7.29.16': {} + '@babel/runtime@7.29.17': {} '@blazediff/core@1.10.0': {} @@ -2405,7 +2450,7 @@ snapshots: dependencies: '@eslint/object-schema': 3.0.5 debug: 4.4.3 - minimatch: 11.0.9 + minimatch: 11.0.10 transitivePeerDependencies: - supports-color @@ -2443,7 +2488,7 @@ snapshots: '@gql.tada/svelte-support@1.0.3(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': dependencies: '@jridgewell/sourcemap-codec': 1.6.0 - svelte2tsx: 0.7.63(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + svelte2tsx: 0.7.64(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) typescript: 6.0.3 vscode-languageserver-textdocument: 1.0.16 transitivePeerDependencies: @@ -2648,16 +2693,16 @@ snapshots: dependencies: acorn: 8.19.0 - '@sveltejs/adapter-static@4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))': + '@sveltejs/adapter-static@4.0.1(@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))': dependencies: - '@sveltejs/kit': 3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) + '@sveltejs/kit': 3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3) - '@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': + '@sveltejs/kit@3.5.0(@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)))(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3)': dependencies: '@jridgewell/trace-mapping': 0.3.31 '@rolldown/pluginutils': 1.1.1 '@standard-schema/spec': 1.1.0 - '@sveltejs/vite-plugin-svelte': 7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) + '@sveltejs/vite-plugin-svelte': 7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0)) cookie: 2.0.2 devalue: 6.0.4 esm-env: 1.2.2 @@ -2671,9 +2716,8 @@ snapshots: '@sveltejs/load-config@0.2.3': {} - '@sveltejs/vite-plugin-svelte@7.3.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))': + '@sveltejs/vite-plugin-svelte@7.3.3(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(svelte@5.60.2(@typescript-eslint/types@8.74.0))': dependencies: - deepmerge: 4.3.1 obug: 3.0.0 svelte: 5.60.2(@typescript-eslint/types@8.74.0) vite: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' @@ -2684,11 +2728,11 @@ snapshots: '@tailwindcss/node@4.3.5': dependencies: '@jridgewell/remapping': 2.3.5 - enhanced-resolve: 5.27.0 + enhanced-resolve: 5.27.2 jiti: 2.7.0 lightningcss: 1.33.0 magic-string: 1.4.5 - source-map-js: 1.2.4 + source-map-js: 1.3.0 tailwindcss: 4.3.5 '@tailwindcss/oxide-android-arm64@4.3.5': @@ -2848,8 +2892,8 @@ snapshots: '@testing-library/dom@10.4.2': dependencies: - '@babel/code-frame': 7.29.7 - '@babel/runtime': 7.29.16 + '@babel/code-frame': 7.29.17 + '@babel/runtime': 7.29.17 '@types/aria-query': 5.0.4 aria-query: 5.3.0 dom-accessibility-api: 0.5.16 @@ -2857,7 +2901,7 @@ snapshots: picocolors: 1.1.1 pretty-format: 27.5.1 - '@testing-library/user-event@14.6.13(@testing-library/dom@10.4.2)': + '@testing-library/user-event@14.6.14(@testing-library/dom@10.4.2)': dependencies: '@testing-library/dom': 10.4.2 @@ -2931,7 +2975,7 @@ snapshots: '@typescript-eslint/types': 8.74.0 '@typescript-eslint/visitor-keys': 8.74.0 debug: 4.4.3 - minimatch: 11.0.9 + minimatch: 11.0.10 semver: 7.8.6 tinyglobby: 0.2.17 ts-api-utils: 2.5.0(typescript@6.0.3) @@ -2966,7 +3010,7 @@ snapshots: '@vitest/browser-preview@5.1.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(vitest@5.1.2)': dependencies: '@testing-library/dom': 10.4.2 - '@testing-library/user-event': 14.6.13(@testing-library/dom@10.4.2) + '@testing-library/user-event': 14.6.14(@testing-library/dom@10.4.2) '@vitest/browser': 5.1.2(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3))(vitest@5.1.2) vitest: 5.1.2(@types/node@26.6.11)(@vitest/browser-preview@5.1.2)(@vitest/ui@5.1.2)(@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)) transitivePeerDependencies: @@ -3019,7 +3063,7 @@ snapshots: dependencies: '@vitest/utils': 5.1.2 fflate: 0.8.3 - flatted: 3.4.4 + flatted: 3.6.0 pathe: 2.0.3 sirv: 3.0.2 tinyrainbow: 3.2.0 @@ -3127,7 +3171,7 @@ snapshots: balanced-match@4.0.4: {} - brace-expansion@5.1.0: + brace-expansion@5.1.2: dependencies: balanced-match: 4.0.4 @@ -3157,7 +3201,7 @@ snapshots: cookie@2.0.2: {} - cross-spawn@7.0.6: + cross-spawn@7.1.2: dependencies: path-key: 3.1.1 shebang-command: 2.0.0 @@ -3173,8 +3217,6 @@ snapshots: deep-is@0.1.4: {} - deepmerge@4.3.1: {} - dequal@2.0.3: {} destr@2.0.5: {} @@ -3185,7 +3227,7 @@ snapshots: dom-accessibility-api@0.5.16: {} - enhanced-resolve@5.27.0: + enhanced-resolve@5.27.2: dependencies: graceful-fs: 4.2.12 tapable: 2.3.4 @@ -3232,7 +3274,7 @@ snapshots: '@humanwhocodes/retry': 0.4.3 '@types/estree': 1.0.11 ajv: 6.15.0 - cross-spawn: 7.0.6 + cross-spawn: 7.1.2 debug: 4.4.3 escape-string-regexp: 4.0.0 eslint-scope: 9.1.2 @@ -3248,7 +3290,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 json-stable-stringify-without-jsonify: 1.0.1 - minimatch: 11.0.9 + minimatch: 11.0.10 natural-compare: 1.4.0 optionator: 0.9.4 optionalDependencies: @@ -3314,10 +3356,10 @@ snapshots: flat-cache@6.1.23: dependencies: cacheable: 2.5.0 - flatted: 3.4.4 + flatted: 3.6.0 hookified: 1.15.1 - flatted@3.4.4: {} + flatted@3.6.0: {} fsevents@2.3.3: optional: true @@ -3466,10 +3508,10 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.6.0 - minimatch@11.0.9: + minimatch@11.0.10: dependencies: '@isaacs/nonrecursive-glob-match': 1.1.0 - brace-expansion: 5.1.0 + brace-expansion: 5.1.2 mlly@1.8.2: dependencies: @@ -3581,7 +3623,7 @@ snapshots: dependencies: p-limit: 3.1.0 - package-manager-detector@1.9.0: {} + package-manager-detector@1.10.0: {} paneforge@1.0.2(svelte@5.60.2(@typescript-eslint/types@8.74.0)): dependencies: @@ -3617,7 +3659,7 @@ snapshots: dependencies: nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.4 + source-map-js: 1.3.0 prelude-ls@1.2.1: {} @@ -3676,7 +3718,7 @@ snapshots: mrmime: 2.0.1 totalist: 3.0.1 - source-map-js@1.2.4: {} + source-map-js@1.3.0: {} std-env@4.3.0: {} @@ -3711,7 +3753,7 @@ snapshots: style-to-object: 1.0.14 svelte: 5.60.2(@typescript-eslint/types@8.74.0) - svelte2tsx@0.7.63(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3): + svelte2tsx@0.7.64(svelte@5.60.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3): dependencies: dedent-js: 1.0.1 scule: 1.3.0 @@ -3830,7 +3872,7 @@ snapshots: uuid@14.0.3: {} - valibot@1.5.0(typescript@6.0.3): + valibot@1.6.0(typescript@6.0.3): optionalDependencies: typescript: 6.0.3 diff --git a/src/hooks.client.ts b/src/hooks.client.ts index 00fc06f1..e2f3ea2d 100644 --- a/src/hooks.client.ts +++ b/src/hooks.client.ts @@ -4,6 +4,7 @@ import localizedFormat from "dayjs/plugin/localizedFormat"; import relativeTime from "dayjs/plugin/relativeTime"; import { log } from "#lib/log.js"; +import { startPlugins } from "#lib/plugins/host.svelte.js"; import { loadThemes } from "#lib/themes.js"; dayjs.extend(duration); @@ -11,6 +12,8 @@ dayjs.extend(localizedFormat); dayjs.extend(relativeTime); export async function init() { + startPlugins(); + // Themes are optional, so errors shouldn't block the app from starting await loadThemes().catch(log.swallow("Failed to load themes")); } diff --git a/src/lib/commands/built-in/reload-badges.ts b/src/lib/commands/built-in/reload-badges.ts index f447e804..987d0616 100644 --- a/src/lib/commands/built-in/reload-badges.ts +++ b/src/lib/commands/built-in/reload-badges.ts @@ -1,13 +1,8 @@ import { app } from "#lib/app.svelte.js"; import { CommandError } from "#lib/errors/command-error.js"; -import { BADGE_PROVIDERS, type BadgeProvider } from "#lib/managers/badge-manager.js"; import { command } from "../define"; -function isProvider(name: string): name is BadgeProvider { - return (BADGE_PROVIDERS as readonly string[]).includes(name); -} - export default command({ name: "reload-badges", description: @@ -20,21 +15,19 @@ export default command({ }, ], async exec(args, channel) { + const providers = app.badges.providers; const names = args.providers?.toLowerCase().split(",").filter(Boolean) ?? []; - const unknown = names.filter((name) => name !== "all" && !isProvider(name)); + const unknown = names.filter((name) => name !== "all" && !providers.includes(name)); if (unknown.length) { - const valid = [...BADGE_PROVIDERS, "all"].join(", "); + const valid = [...providers, "all"].join(", "); throw new CommandError(`Unknown badge provider: ${unknown.join(", ")}. Use ${valid}.`); } await Promise.all([ channel.badges.fetch(true), - app.badges.fetch( - names.includes("all") ? BADGE_PROVIDERS : names.filter(isProvider), - true, - ), + app.badges.fetch(names.includes("all") ? providers : names, true), ]); channel.chat.notice("Reloaded badges."); diff --git a/src/lib/components/emote-picker/EmotePicker.svelte b/src/lib/components/emote-picker/EmotePicker.svelte index c1140c49..8cf925df 100644 --- a/src/lib/components/emote-picker/EmotePicker.svelte +++ b/src/lib/components/emote-picker/EmotePicker.svelte @@ -1,10 +1,13 @@ + +{#await data.fetch(data.id) then emote} + {#if emote} + + {#snippet media()} +
+ {emote.displayName} +
+ + {#if !emote.listed && blurred} + + {/if} + {/snippet} + +
+ + {emote.displayName} + + + {#if !emote.listed} + + unlisted + + {/if} +
+ +
+ by {emote.owner ?? "Unknown"} +
+
+ {/if} +{/await} diff --git a/src/lib/components/message/events/EmoteSetChange.svelte b/packages/plugin-7tv/src/components/EmoteSetChange.svelte similarity index 50% rename from src/lib/components/message/events/EmoteSetChange.svelte rename to packages/plugin-7tv/src/components/EmoteSetChange.svelte index 0ab46ca0..9d2a37d7 100644 --- a/src/lib/components/message/events/EmoteSetChange.svelte +++ b/packages/plugin-7tv/src/components/EmoteSetChange.svelte @@ -1,17 +1,16 @@ - + {#if name} changed the active emote set to diff --git a/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte b/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte new file mode 100644 index 00000000..4352cc69 --- /dev/null +++ b/packages/plugin-7tv/src/components/EmoteSetUpdate.svelte @@ -0,0 +1,25 @@ + + + + +{#if action === "renamed"} + renamed {oldName} to + {emote.displayName} +{:else} + {action} an emote: + {emote.displayName} +{/if} + + diff --git a/packages/plugin-7tv/src/components/HiddenIcon.svelte b/packages/plugin-7tv/src/components/HiddenIcon.svelte new file mode 100644 index 00000000..1b9cd8cd --- /dev/null +++ b/packages/plugin-7tv/src/components/HiddenIcon.svelte @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/packages/plugin-7tv/src/components/Icon.svelte b/packages/plugin-7tv/src/components/Icon.svelte new file mode 100644 index 00000000..3ca122cf --- /dev/null +++ b/packages/plugin-7tv/src/components/Icon.svelte @@ -0,0 +1,19 @@ + + + + + + diff --git a/packages/plugin-7tv/src/cosmetics.ts b/packages/plugin-7tv/src/cosmetics.ts new file mode 100644 index 00000000..7ba2b6ab --- /dev/null +++ b/packages/plugin-7tv/src/cosmetics.ts @@ -0,0 +1,101 @@ +import type { EmoteData } from "@usehyperion/plugin"; +import { SvelteMap } from "svelte/reactivity"; + +import type { PaintObject } from "./types"; + +export interface Paint { + name: string; + css: string; +} + +/** + * Paints and personal emotes, learned from live events. + */ +export class Cosmetics { + /** + * Paints keyed by their id. + */ + public readonly paints = new Map(); + + /** + * The emotes of personal emote sets keyed by set id. + */ + public readonly personalSets = new SvelteMap(); + + /** + * The paint each user has equipped keyed by Twitch user id. + */ + public readonly userPaints = new SvelteMap(); + + /** + * The personal emote set each user has keyed by Twitch user id. + */ + public readonly userPersonalSets = new SvelteMap(); + + /** + * The emote with the given name in the user's personal emote set. + */ + public personalEmote(userId: string, name: string) { + const setId = this.userPersonalSets.get(userId); + + return setId + ? this.personalSets.get(setId)?.find((emote) => emote.displayName === name) + : undefined; + } +} + +function toRgb(decimal: number) { + const r = (decimal >>> 24) & 255; + const g = (decimal >>> 16) & 255; + const b = (decimal >>> 8) & 255; + const a = (decimal & 255) / 255; + + return `rgb(${r} ${g} ${b} / ${a.toFixed(2)})`; +} + +/** + * The CSS that paints text with the given paint. + */ +export function paintCss(paint: PaintObject) { + const args: string[] = []; + + switch (paint.function) { + case "LINEAR_GRADIENT": { + args.push(`${paint.angle}deg`); + break; + } + + case "RADIAL_GRADIENT": { + args.push(paint.shape); + break; + } + + case "URL": { + args.push(paint.image_url); + break; + } + } + + if (paint.function !== "URL") { + for (const stop of paint.stops) { + args.push(`${toRgb(stop.color)} ${stop.at * 100}%`); + } + } + + const cssFunction = + (paint.repeat ? "repeating-" : "") + paint.function.toLowerCase().replace(/_/g, "-"); + + const shadows = paint.shadows.map( + (shadow) => + `drop-shadow(${shadow.x_offset}px ${shadow.y_offset}px ${shadow.radius}px ${toRgb(shadow.color)})`, + ); + + return [ + `background-color: currentcolor`, + `background-image: ${cssFunction}(${args.join(", ")})`, + `background-size: 100% 100%`, + `background-clip: text`, + `filter: ${shadows.join(" ")}`, + `-webkit-text-fill-color: transparent`, + ].join(";"); +} diff --git a/packages/plugin-7tv/src/emotes.ts b/packages/plugin-7tv/src/emotes.ts new file mode 100644 index 00000000..3b1fce5b --- /dev/null +++ b/packages/plugin-7tv/src/emotes.ts @@ -0,0 +1,102 @@ +import type { EmoteData } from "@usehyperion/plugin"; + +import type { Emote } from "./graphql"; +import type { EmoteChange } from "./types"; + +import { fileUrl } from "./types"; + +const ZERO_WIDTH_FLAG = 256; + +interface Image { + url: string; + format: string; + width: number; + height: number; + scale: number; +} + +function toEmote( + emote: { id: string; name: string; alias?: string | null; zeroWidth: boolean }, + images: Image[], +): EmoteData { + const format = ["webp", "gif", "png"].find((f) => images.some((img) => img.format === f)); + + const candidates = images + .filter((img) => img.format === format) + .toSorted((a, b) => b.width - a.width); + + const largest = candidates.at(0); + const scale = largest?.scale || 1; + const alias = emote.alias && emote.alias !== emote.name ? emote.alias : undefined; + + return { + id: emote.id, + name: emote.name, + alias, + displayName: alias ?? emote.name, + width: largest?.width ?? 28, + height: largest?.height ?? 28, + displayWidth: (largest?.width ?? 28) / scale, + displayHeight: (largest?.height ?? 28) / scale, + srcset: candidates.map((img) => `${img.url} ${img.scale}x`), + zeroWidth: emote.zeroWidth, + }; +} + +/** + * A copy of the emote typed as the given name, so messages that already show + * the emote keep its old name. + */ +export function rename(emote: T, name: string): T { + return { + ...emote, + alias: name === emote.name ? undefined : name, + displayName: name, + }; +} + +/** + * Converts an emote from the GraphQL API. + */ +export function fromGql(emote: Emote, alias?: string | null): EmoteData { + return toEmote( + { + id: emote.id, + name: emote.defaultName, + alias, + zeroWidth: emote.flags.defaultZeroWidth, + }, + emote.images + .filter((img) => !img.url.includes("static")) + .map((img) => ({ + url: img.url, + format: img.mime.split("/").at(-1) ?? "", + width: img.width, + height: img.height, + scale: img.scale, + })), + ); +} + +/** + * Converts an emote from a live event. + */ +export function fromEvent(emote: EmoteChange): EmoteData { + const { host } = emote.data; + + return toEmote( + { + id: emote.id, + name: emote.data.name, + alias: emote.name, + zeroWidth: (emote.data.flags & ZERO_WIDTH_FLAG) === ZERO_WIDTH_FLAG, + }, + host.files.map((file) => ({ + url: fileUrl(host, file), + format: file.format.toLowerCase(), + width: file.width, + height: file.height, + scale: Number(file.name[0]) || 1, + })), + ); +} diff --git a/src/lib/graphql/7tv.ts b/packages/plugin-7tv/src/graphql/index.ts similarity index 65% rename from src/lib/graphql/7tv.ts rename to packages/plugin-7tv/src/graphql/index.ts index e51d4058..20a4d68f 100644 --- a/src/lib/graphql/7tv.ts +++ b/packages/plugin-7tv/src/graphql/index.ts @@ -1,7 +1,9 @@ +import type { PluginHttp } from "@usehyperion/plugin"; import { initGraphQLTada } from "gql.tada"; import type { FragmentOf, ResultOf, TadaDocumentNode } from "gql.tada"; +import { print } from "graphql-web-lite"; -import { request, type GqlRequestOptions, type NonNullableDeep } from "."; +const ENDPOINT = "https://7tv.io/v4/gql"; const gql = initGraphQLTada<{ disableMasking: true; @@ -12,12 +14,49 @@ const gql = initGraphQLTada<{ }; }>(); -export function execute7tvQuery( - query: TadaDocumentNode, - variables?: U, - { signal }: Pick = {}, -) { - return request("https://7tv.io/v4/gql", query, variables, { signal }); +type GqlResponse = { data: T; errors?: never } | { data?: never; errors: { message: string }[] }; + +type NonNullableDeep = P extends `${infer K}.${infer R}` + ? K extends keyof T + ? NonNullableDeep, R> + : never + : P extends keyof T + ? NonNullable + : never; + +export type Query = ( + document: TadaDocumentNode, + variables?: V, + signal?: AbortSignal, +) => Promise; + +/** + * Runs queries against 7TV's GraphQL API. + */ +export function createQuery(http: PluginHttp): Query { + return async function query( + document: TadaDocumentNode, + variables?: V, + signal?: AbortSignal, + ) { + // @ts-expect-error - outdated types + const source: string = print(document); + + const response = await http.json>(ENDPOINT, { + method: "POST", + body: { query: source, variables }, + signal, + }); + + if (response.errors) { + throw new AggregateError( + response.errors.map((error) => new Error(error.message)), + "7TV GraphQL request failed", + ); + } + + return response.data; + }; } const emoteDetailsFragment = gql(` diff --git a/packages/plugin-7tv/src/index.ts b/packages/plugin-7tv/src/index.ts new file mode 100644 index 00000000..78e5b6bb --- /dev/null +++ b/packages/plugin-7tv/src/index.ts @@ -0,0 +1,600 @@ +import { + definePlugin, + type EmoteData, + type EmoteLoadContext, + type EmoteSetData, + type User, +} from "@usehyperion/plugin"; +import type { ComponentProps } from "svelte"; + +import type { ActiveEmoteSet } from "./graphql"; +import type { EmbeddedEmote, EmoteEmbedData, EventMap, SevenTvUser } from "./types"; + +import EmoteEmbed from "./components/EmoteEmbed.svelte"; +import EmoteSetChange from "./components/EmoteSetChange.svelte"; +import EmoteSetUpdate from "./components/EmoteSetUpdate.svelte"; +import Icon from "./components/Icon.svelte"; +import { Cosmetics, paintCss } from "./cosmetics"; +import { fromEvent, fromGql, rename } from "./emotes"; +import { + activeEmoteSetQuery, + createQuery, + emoteQuery, + globalEmoteSetQuery, + globalEmoteSetVersionQuery, + userEmoteSetsQuery, +} from "./graphql"; +import logo from "./logo.svg"; +import { EventSocket, type Condition } from "./socket"; +import { fileUrl, twitchConnection } from "./types"; + +const NAME = "7TV"; + +interface SetVersion { + setId: string; + updatedAt: string; +} + +interface VersionedEmotes { + emotes: EmoteData[]; + version: SetVersion | null; +} + +/** + * A channel's 7TV account and its active emote set. + */ +interface Account { + userId: string | null; + setId: string | null; +} + +type UpdateProps = Omit, "actor" | "ui">; + +export default definePlugin({ + settings: { + emotes: { + type: "switch", + label: "Enable emotes", + description: "Show and autocomplete emotes from 7TV, including personal emotes.", + default: true, + }, + badges: { + type: "switch", + label: "Enable badges", + description: "Show badges from 7TV.", + default: true, + }, + paints: { + type: "switch", + label: "Paint usernames", + description: "Style usernames with 7TV paints if the user has one.", + default: true, + }, + }, + setup(ctx) { + const query = createQuery(ctx.http); + const cosmetics = new Cosmetics(); + + /** + * The 7TV account of each channel keyed by Twitch channel id, once + * it's been looked up. + */ + const accounts = new Map(); + + /** + * The ids of the channels whose events are followed. + */ + const joined = new Set(); + + /** + * The 7TV user id of each signed in Twitch user, for presences. + */ + const selves = new Map>(); + + const socket = new EventSocket({ + log: ctx.log, + onDispatch: (type, body) => { + dispatch(type, body).catch((error) => { + ctx.log.error(`Failed to handle ${type}`, error); + }); + }, + }); + + socket.connect(); + ctx.onDispose(() => socket.close()); + + function follow(channelId: string) { + if (!joined.has(channelId)) { + socket.removeChannel(channelId); + return; + } + + const channel: Condition = { ctx: "channel", platform: "TWITCH", id: channelId }; + + const events: [string, Condition][] = [ + ["cosmetic.create", channel], + ["entitlement.create", channel], + ]; + + const account = accounts.get(channelId); + + if (account?.setId) events.push(["emote_set.*", { object_id: account.setId }]); + if (account?.userId) events.push(["user.update", { object_id: account.userId }]); + + socket.setChannel(channelId, events); + } + + function setAccount(channelId: string, userId: string | null, setId: string | null) { + const current = accounts.get(channelId); + if (current && current.userId === userId && current.setId === setId) return; + + accounts.set(channelId, { userId, setId }); + follow(channelId); + } + + function findChannel(matches: (account: Account) => boolean) { + for (const [channelId, account] of accounts) { + if (matches(account)) return channelId; + } + + return undefined; + } + + /** + * Resolves the channel's 7TV account and active emote set, following + * their events. + */ + async function activeSet( + channelId: string, + details: D, + signal?: AbortSignal, + ) { + const { users } = await query(activeEmoteSetQuery, { id: channelId, details }, signal); + + const user = users.userByConnection; + const set = user?.style.activeEmoteSet ?? null; + + setAccount(channelId, user?.id ?? null, set?.id ?? null); + + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + return set as ActiveEmoteSet | null; + } + + /** + * Looks up the channel's active emote set and reloads its emotes if it + * changed while the channel wasn't followed. + */ + async function syncAccount(channelId: string) { + try { + const previous = accounts.get(channelId)?.setId ?? null; + const set = await activeSet(channelId, false); + const scope = emotes.channel(channelId); + + if (scope?.loaded && (set?.id ?? null) !== previous) { + await scope.reload(); + } + } catch (error) { + // The channel still works without knowing its 7TV account. + ctx.log.warn(`Failed to sync the emote set of ${channelId}`, error); + } + } + + /** + * Returns cached emotes immediately and checks whether their set has + * changed since in the background, applying the new emotes if it has. + */ + async function loadVersioned( + key: string, + load: EmoteLoadContext, + fetchSet: (signal: AbortSignal) => Promise, + fetchVersion: (signal: AbortSignal) => Promise, + isCurrent: (setId: string | null) => boolean, + ) { + const entry = load.force ? null : await ctx.cache.get(key); + + if (entry && isCurrent(entry.version?.setId ?? null)) { + revalidate(key, load, entry.version, fetchSet, fetchVersion).catch((error) => { + if (!load.signal.aborted) ctx.log.warn(`Failed to revalidate ${key}`, error); + }); + + return entry.emotes; + } + + const fetched = await fetchSet(load.signal); + void ctx.cache.set(key, fetched); + + return fetched.emotes; + } + + async function revalidate( + key: string, + load: EmoteLoadContext, + cached: SetVersion | null, + fetchSet: (signal: AbortSignal) => Promise, + fetchVersion: (signal: AbortSignal) => Promise, + ) { + const version = await fetchVersion(load.signal); + + if (version?.setId === cached?.setId && version?.updatedAt === cached?.updatedAt) { + return; + } + + const fetched = await fetchSet(load.signal); + void ctx.cache.set(key, fetched); + + load.update(fetched.emotes); + } + + async function fetchGlobal(signal: AbortSignal): Promise { + const { emoteSets } = await query(globalEmoteSetQuery, undefined, signal); + const set = emoteSets.global!; + + return { + emotes: set.emotes.items.map((item) => fromGql(item.emote, item.alias)), + version: { setId: set.id, updatedAt: set.updatedAt }, + }; + } + + async function fetchGlobalVersion(signal: AbortSignal) { + const { emoteSets } = await query(globalEmoteSetVersionQuery, undefined, signal); + const set = emoteSets.global; + + return set ? { setId: set.id, updatedAt: set.updatedAt } : null; + } + + async function fetchUserSets(user: User, signal: AbortSignal) { + const { users } = await query(userEmoteSetsQuery, { id: user.id }, signal); + const account = users.userByConnection; + + selves.set(user.id, Promise.resolve(account?.id ?? null)); + + const sets: EmoteSetData[] = []; + + if (account?.personalEmoteSet) { + sets.push({ + id: account.personalEmoteSet.id, + name: `${user.displayName}: 7TV Personal Emotes`, + emotes: account.personalEmoteSet.emotes.items.map((item) => + fromGql(item.emote, item.alias), + ), + }); + } + + for (const set of account?.specialEmoteSets ?? []) { + sets.push({ + id: set.id, + name: set.name, + emotes: set.emotes.items.map((item) => fromGql(item.emote, item.alias)), + }); + } + + return sets; + } + + const emotes = ctx.emotes.provide({ + name: NAME, + icon: Icon, + logo, + enabled: () => ctx.settings.emotes, + // Cached by set version rather than age, see loadVersioned. + fresh: false, + global: (load) => + loadVersioned("emotes:global", load, fetchGlobal, fetchGlobalVersion, () => true), + channel: (channel, load) => + loadVersioned( + `emotes:${channel.id}`, + load, + async (signal) => { + const set = await activeSet(channel.id, true, signal); + + return { + emotes: + set?.emotes.items.map((item) => fromGql(item.emote, item.alias)) ?? + [], + version: set && { setId: set.id, updatedAt: set.updatedAt }, + }; + }, + async (signal) => { + const set = await activeSet(channel.id, false, signal); + return set && { setId: set.id, updatedAt: set.updatedAt }; + }, + // Unknown until the channel's account has been resolved, + // which happens while revalidating. + (setId) => { + const account = accounts.get(channel.id); + return account?.userId == null || setId === account.setId; + }, + ), + personal: (userId, name) => cosmetics.personalEmote(userId, name), + userSets: (user, { signal }) => fetchUserSets(user, signal), + }); + + const badges = ctx.badges.provide({ + name: NAME, + enabled: () => ctx.settings.badges, + }); + + ctx.users.decorate((userId) => + ctx.settings.paints ? cosmetics.userPaints.get(userId)?.css : undefined, + ); + + async function fetchEmbeddedEmote(id: string): Promise { + try { + const { emotes } = await query(emoteQuery, { id }); + const emote = emotes.emote; + if (!emote) return null; + + return { + ...fromGql(emote), + listed: emote.flags.publicListed, + owner: emote.owner?.mainConnection?.platformDisplayName ?? null, + }; + } catch (error) { + ctx.log.warn("Failed to fetch emote embed", error); + return null; + } + } + + ctx.embeds.provide({ + match(url) { + const official = url.hostname === "7tv.app" || url.hostname.endsWith(".7tv.app"); + const [, section, id] = url.pathname.split("/"); + + return official && section === "emotes" && id + ? { id, fetch: fetchEmbeddedEmote } + : null; + }, + component: EmoteEmbed, + }); + + function selfId() { + const user = ctx.users.current; + if (!user) return Promise.resolve(null); + + let id = selves.get(user.id); + + if (!id) { + id = query(activeEmoteSetQuery, { id: user.id, details: false }).then( + ({ users }) => users.userByConnection?.id ?? null, + ); + + selves.set(user.id, id); + + // Try again next time. + id.catch(() => selves.delete(user.id)); + } + + return id; + } + + /** + * Tells 7TV the user is active in the channel so others see their + * cosmetics. + */ + async function sendPresence(channelId: string) { + try { + const id = await selfId(); + if (!id) return; + + await ctx.http.json(`https://7tv.io/v3/users/${id}/presences`, { + method: "POST", + body: { + kind: 1, + passive: false, + session_id: null, + data: { platform: "TWITCH", id: channelId }, + }, + }); + + ctx.log.debug(`Presence sent in ${channelId}`); + } catch (error) { + ctx.log.warn("Failed to send presence", error); + } + } + + ctx.channels.onJoin((channel) => { + joined.add(channel.id); + follow(channel.id); + + void sendPresence(channel.id); + + // Loading the channel's emotes resolves its account already. + if (ctx.settings.emotes && !emotes.channel(channel.id)?.loaded) return; + + void syncAccount(channel.id); + }); + + ctx.channels.onLeave((channel) => { + joined.delete(channel.id); + socket.removeChannel(channel.id); + }); + + ctx.channels.onMessageSent((channel) => { + void sendPresence(channel.id); + }); + + /** + * Resolves who made a change, as a viewer of the channel. + */ + async function actorIn(channelId: string, actor: SevenTvUser) { + const twitch = twitchConnection(actor); + const channel = ctx.channels.get(channelId); + + const user = + twitch && channel ? await ctx.channels.fetchUser(channel, twitch.id) : null; + + return user && channel ? { channel, user } : null; + } + + const handlers: { [K in keyof EventMap]: (data: EventMap[K]) => unknown } = { + "cosmetic.create": onCosmetic, + "entitlement.create": onEntitlement, + "emote_set.create": (data) => cosmetics.personalSets.set(data.id, []), + "emote_set.update": onEmoteSetUpdate, + "user.update": onUserUpdate, + }; + + async function dispatch(type: string, body: unknown) { + if (!Object.hasOwn(handlers, type)) return; + + // The payload's shape is 7TV's to keep; it isn't validated. + // oxlint-disable-next-line typescript/no-unsafe-type-assertion + const handle = handlers[type as keyof EventMap] as (data: unknown) => unknown; + + await handle(body); + } + + function onCosmetic(cosmetic: EventMap["cosmetic.create"]) { + if (cosmetic.kind === "BADGE") { + const { host } = cosmetic.data; + const file = host.files.find((f) => f.name.startsWith("4x")); + if (!file) return; + + badges.set({ + version: cosmetic.id, + title: cosmetic.data.name, + description: cosmetic.data.tooltip, + imageUrl: fileUrl(host, file), + }); + + return; + } + + cosmetics.paints.set(cosmetic.id, { + name: cosmetic.data.name, + css: paintCss(cosmetic.data), + }); + } + + function onEntitlement(entitlement: EventMap["entitlement.create"]) { + const twitch = twitchConnection(entitlement.user); + if (!twitch) return; + + switch (entitlement.kind) { + case "BADGE": { + badges.give(twitch.id, entitlement.ref_id); + break; + } + + case "PAINT": { + cosmetics.userPaints.set(twitch.id, cosmetics.paints.get(entitlement.ref_id)); + break; + } + + case "EMOTE_SET": { + cosmetics.userPersonalSets.set(twitch.id, entitlement.ref_id); + break; + } + } + } + + async function onEmoteSetUpdate(data: EventMap["emote_set.update"]) { + const channelId = findChannel((account) => account.setId === data.id); + + if (!channelId) { + updatePersonalSet(data); + return; + } + + const scope = emotes.channel(channelId); + if (!scope?.loaded) return; + + let last: UpdateProps | null = null; + + for (const change of data.pushed ?? []) { + const emote = fromEvent(change.value); + scope.set(emote); + + const added = scope.get(emote.displayName); + if (added) last = { action: "added", emote: added }; + } + + for (const change of data.pulled ?? []) { + const emote = scope.get(change.old_value.name); + if (!emote) continue; + + scope.delete(change.old_value.name); + last = { action: "removed", emote }; + } + + for (const change of data.updated ?? []) { + const emote = scope.get(change.old_value.name); + if (!emote) continue; + + const renamed = rename(emote, change.value.name); + + scope.delete(change.old_value.name); + scope.set(renamed); + + last = { action: "renamed", oldName: emote.displayName, emote: renamed }; + } + + if (!last) return; + + const props = last; + const found = await actorIn(channelId, data.actor); + + if (!found) return; + + ctx.channels.event( + found.channel, + EmoteSetUpdate, + { ...props, actor: found.user, ui: ctx.ui }, + { type: "emote-set-update" }, + ); + } + + function updatePersonalSet(data: EventMap["emote_set.update"]) { + const current = cosmetics.personalSets.get(data.id); + if (!current) return; + + const pulled = new Set(data.pulled?.map((change) => change.old_value.id)); + + const kept = current + .filter((emote) => !pulled.has(emote.id)) + .map((emote) => { + const update = data.updated?.find((change) => change.value.id === emote.id); + return update ? rename(emote, update.value.name) : emote; + }); + + const pushed = data.pushed?.map((change) => fromEvent(change.value)) ?? []; + + cosmetics.personalSets.set(data.id, [...kept, ...pushed]); + } + + async function onUserUpdate(data: EventMap["user.update"]) { + const channelId = findChannel((account) => account.userId === data.id); + if (!channelId) return; + + const account = accounts.get(channelId)!; + + const root = data.updated?.find((change) => change.key === "connections"); + if (!root) return; + + const child = root.value.find( + (change) => change.key === "emote_set" && change.value?.id !== account.setId, + ); + if (!child) return; + + const scope = emotes.channel(channelId); + scope?.clear(); + + // Follow the new set before fetching its emotes so its updates + // aren't missed if the fetch fails. + setAccount(channelId, account.userId, child.value?.id ?? null); + + const found = await actorIn(channelId, data.actor); + + if (found) { + ctx.channels.event( + found.channel, + EmoteSetChange, + { name: child.value?.name, actor: found.user, ui: ctx.ui }, + { type: "emote-set-change" }, + ); + } + + await scope?.reload(); + } + }, +}); diff --git a/src/assets/logos/7tv.svg b/packages/plugin-7tv/src/logo.svg similarity index 100% rename from src/assets/logos/7tv.svg rename to packages/plugin-7tv/src/logo.svg diff --git a/packages/plugin-7tv/src/socket.ts b/packages/plugin-7tv/src/socket.ts new file mode 100644 index 00000000..b886387c --- /dev/null +++ b/packages/plugin-7tv/src/socket.ts @@ -0,0 +1,345 @@ +import type { PluginLogger } from "@usehyperion/plugin"; + +const URL = "wss://events.7tv.io/v3"; + +/** + * Assumed until the server's hello says otherwise. + */ +const DEFAULT_HEARTBEAT_INTERVAL = 25_000; + +/** + * How late a heartbeat may be before the connection counts as dead. + */ +const HEARTBEAT_GRACE = 10_000; + +const INITIAL_BACKOFF = 1000; +const MAX_BACKOFF = 120_000; + +const Op = { + Dispatch: 0, + Hello: 1, + Heartbeat: 2, + Reconnect: 4, + Ack: 5, + Error: 6, + EndOfStream: 7, + Resume: 34, + Subscribe: 35, + Unsubscribe: 36, +} as const; + +interface Envelope { + op: number; + d?: any; +} + +export type Condition = Record; + +interface Subscription { + type: string; + condition: Condition; +} + +export interface EventSocketOptions { + log: PluginLogger; + onDispatch(type: string, body: unknown): void; +} + +/** + * A connection to the 7TV EventAPI that reconnects with backoff, resumes the + * previous session to replay missed events, and keeps the server's + * subscriptions in sync with what each channel needs. + */ +export class EventSocket { + /** + * What should be subscribed to, keyed by owner and event type. + */ + readonly #wanted = new Map(); + + /** + * What the server was told. + */ + readonly #synced = new Map(); + + #socket: WebSocket | null = null; + + /** + * The last session that became ready. Resuming it after a drop keeps its + * subscriptions and replays the events missed in between. + */ + #sessionId: string | null = null; + + #closed = false; + #ready = false; + + /** + * This connection's session, while waiting to hear whether resuming + * `#sessionId` worked. + */ + #resuming: string | null = null; + + #heartbeatTimeout = DEFAULT_HEARTBEAT_INTERVAL + HEARTBEAT_GRACE; + #backoff = INITIAL_BACKOFF; + + #watchdog: ReturnType | undefined; + #retry: ReturnType | undefined; + + public constructor(private readonly options: EventSocketOptions) {} + + public connect() { + if (this.#closed || this.#socket) return; + + const socket = new WebSocket(URL); + this.#socket = socket; + + socket.addEventListener("open", () => { + this.#resuming = null; + this.#expect(); + }); + + socket.addEventListener("message", (event) => { + if (typeof event.data === "string") this.#received(event.data); + }); + + socket.addEventListener("close", () => { + if (this.#socket === socket) this.#dropped(); + }); + } + + public close() { + this.#closed = true; + clearTimeout(this.#retry); + this.#disconnect(); + } + + /** + * Replaces the subscriptions kept for a channel. + */ + public setChannel(channelId: string, events: [type: string, condition: Condition][]) { + this.#removeOwned(channelId); + + for (const [type, condition] of events) { + this.#wanted.set(`${channelId}\n${type}`, { type, condition }); + } + + this.#sync(); + } + + public removeChannel(channelId: string) { + this.#removeOwned(channelId); + this.#sync(); + } + + #removeOwned(channelId: string) { + for (const key of this.#wanted.keys()) { + if (key.startsWith(`${channelId}\n`)) this.#wanted.delete(key); + } + } + + #received(text: string) { + let envelope: Envelope; + + try { + envelope = JSON.parse(text); + } catch (error) { + this.options.log.warn("Failed to parse 7TV message", error); + return; + } + + // Heartbeats are what the server promises, but anything it sends shows + // the connection is alive. + this.#expect(); + + const { op, d } = envelope; + + switch (op) { + case Op.Dispatch: { + const body = d?.body; + const payload = + body && typeof body === "object" && "object" in body ? body.object : body; + + try { + this.options.onDispatch(d?.type, payload); + } catch (error) { + this.options.log.error(`Failed to handle ${d?.type}`, error); + } + + break; + } + + case Op.Hello: { + this.#hello(d); + break; + } + + case Op.Heartbeat: { + break; + } + + case Op.Reconnect: { + this.options.log.warn("Server requested a reconnect"); + this.#reconnect(); + break; + } + + case Op.Ack: { + // Nothing is subscribed while resuming, so this acknowledges it. + const sessionId = this.#resuming; + + if (sessionId) { + this.#resuming = null; + this.#resumed(sessionId, d?.data?.success === true); + } + + break; + } + + case Op.Error: { + this.options.log.error(`Server returned an error: ${JSON.stringify(d)}`); + + // In place of the resume's ack, it means resuming failed. + const sessionId = this.#resuming; + + if (sessionId) { + this.#resuming = null; + this.#resumed(sessionId, false); + } + + break; + } + + case Op.EndOfStream: { + this.options.log.warn(`End of stream: ${JSON.stringify(d)}`); + this.#reconnect(); + break; + } + } + } + + #hello(hello: { session_id?: string; heartbeat_interval?: number } | undefined) { + if (!hello?.session_id) { + this.options.log.error("Malformed hello"); + this.#reconnect(); + + return; + } + + if (hello.heartbeat_interval) { + this.#heartbeatTimeout = hello.heartbeat_interval + HEARTBEAT_GRACE; + this.#expect(); + } + + const previous = this.#sessionId; + + if (!previous) { + this.options.log.info(`Session ${hello.session_id} established`); + + this.#sessionId = hello.session_id; + this.#becomeReady(false); + + return; + } + + this.options.log.info(`Resuming session ${previous}`); + + this.#resuming = hello.session_id; + this.#send(Op.Resume, { session_id: previous }); + } + + #resumed(sessionId: string, restored: boolean) { + if (restored) { + this.options.log.info(`Session ${sessionId} resumed`); + } else { + this.options.log.warn(`Resuming failed, resubscribing in session ${sessionId}`); + } + + this.#sessionId = sessionId; + this.#becomeReady(restored); + } + + #becomeReady(restored: boolean) { + if (!restored) this.#synced.clear(); + + this.#ready = true; + this.#backoff = INITIAL_BACKOFF; + this.#sync(); + } + + /** + * Sends the subscription changes made since the last sync. Changes made + * while not ready are sent once the session is. + */ + #sync() { + if (!this.#ready) return; + + for (const [key, subscription] of this.#synced) { + if (!same(this.#wanted.get(key), subscription)) { + this.#send(Op.Unsubscribe, subscription); + this.#synced.delete(key); + } + } + + for (const [key, subscription] of this.#wanted) { + if (!same(this.#synced.get(key), subscription)) { + this.#send(Op.Subscribe, subscription); + this.#synced.set(key, subscription); + } + } + } + + #send(op: number, d: unknown) { + if (this.#socket?.readyState === WebSocket.OPEN) { + this.#socket.send(JSON.stringify({ op, d })); + } + } + + /** + * Restarts the countdown after which the connection counts as dead. + */ + #expect() { + clearTimeout(this.#watchdog); + + this.#watchdog = setTimeout(() => { + this.options.log.warn("Server stopped responding"); + this.#reconnect(); + }, this.#heartbeatTimeout); + } + + #reconnect() { + this.#disconnect(); + this.#dropped(); + } + + /** + * Closes the socket without waiting for the server, which may never answer + * on a dead connection. + */ + #disconnect() { + const socket = this.#socket; + this.#socket = null; + + clearTimeout(this.#watchdog); + this.#ready = false; + + if (socket && socket.readyState < WebSocket.CLOSING) { + socket.close(); + } + } + + #dropped() { + this.#disconnect(); + if (this.#closed) return; + + const delay = this.#backoff; + this.#backoff = Math.min(this.#backoff * 2, MAX_BACKOFF); + + this.options.log.info(`Reconnecting in ${delay / 1000}s`); + + clearTimeout(this.#retry); + this.#retry = setTimeout(() => this.connect(), delay); + } +} + +function same(a: Subscription | undefined, b: Subscription) { + return a?.type === b.type && JSON.stringify(a.condition) === JSON.stringify(b.condition); +} diff --git a/src/lib/seventv.ts b/packages/plugin-7tv/src/types.ts similarity index 59% rename from src/lib/seventv.ts rename to packages/plugin-7tv/src/types.ts index e271bfd4..61165bdd 100644 --- a/src/lib/seventv.ts +++ b/packages/plugin-7tv/src/types.ts @@ -1,6 +1,19 @@ -import { SvelteMap } from "svelte/reactivity"; +import type { EmoteData } from "@usehyperion/plugin"; -import type { Emote as ChatEmote } from "./emotes"; +/** + * An emote linked in chat, with what its embed shows. + */ +export interface EmbeddedEmote extends EmoteData { + listed: boolean; + owner: string | null; +} + +export interface EmoteEmbedData { + id: string; + fetch: (id: string) => Promise; +} + +// The payloads of the 7TV EventAPI events the plugin subscribes to. interface EventObject { id: string; @@ -21,7 +34,7 @@ export interface Host { files: HostFile[]; } -interface Emote { +interface EmoteObject { name: string; listed: boolean; flags: number; @@ -30,12 +43,7 @@ interface Emote { } export interface EmoteChange extends EventObject { - data: Emote; -} - -export interface Paint { - name: string; - css: string; + data: EmoteObject; } interface Connection { @@ -61,7 +69,7 @@ export interface SevenTvUser { style: UserStyle; } -interface BadgeData extends EventObject { +interface BadgeObject extends EventObject { host: Host; tooltip: string; } @@ -69,7 +77,7 @@ interface BadgeData extends EventObject { interface BadgeCosmetic { id: string; kind: "BADGE"; - data: BadgeData; + data: BadgeObject; } interface PaintShadow { @@ -84,7 +92,7 @@ interface PaintStop { at: number; } -interface PaintData extends EventObject { +export interface PaintObject extends EventObject { angle: number; color: number | null; function: "LINEAR_GRADIENT" | "RADIAL_GRADIENT" | "URL"; @@ -98,11 +106,9 @@ interface PaintData extends EventObject { interface PaintCosmetic { id: string; kind: "PAINT"; - data: PaintData; + data: PaintObject; } -type CosmeticCreate = BadgeCosmetic | PaintCosmetic; - interface EmoteSetCreate extends EventObject { capacity: number; flags: number; @@ -134,13 +140,8 @@ interface ChangeMap { updated?: ChangeField<"updated", T, N>[]; } -export interface DispatchPayload { - type: string; - body: { object: unknown } | ChangeMap; -} - -export interface SevenTvEventMap { - "cosmetic.create": CosmeticCreate; +export interface EventMap { + "cosmetic.create": BadgeCosmetic | PaintCosmetic; "emote_set.create": EmoteSetCreate; "emote_set.update": ChangeMap; "entitlement.create": EntitlementCreate; @@ -151,46 +152,6 @@ export function twitchConnection(user: SevenTvUser) { return user.connections.find((c) => c.platform === "TWITCH"); } -export function sevenTvFileUrl(host: Host, file: HostFile) { +export function fileUrl(host: Host, file: HostFile) { return `https:${host.url}/${file.name}`; } - -export class SevenTvCosmetics { - /** - * Paints keyed by their id. - */ - public readonly paints = new Map(); - - /** - * The emotes of personal emote sets keyed by set id. - */ - public readonly personalSets = new SvelteMap(); - - /** - * The paint each user has equipped keyed by user id. - */ - public readonly userPaints = new SvelteMap(); - - /** - * The personal emote set each user has keyed by user id. - */ - public readonly userPersonalSets = new SvelteMap(); - - /** - * The emote with the given name in the user's personal emote set. - */ - public personalEmote(userId: string, name: string) { - const setId = this.userPersonalSets.get(userId); - - return setId - ? this.personalSets.get(setId)?.find((emote) => emote.displayName === name) - : undefined; - } - - public clear() { - this.paints.clear(); - this.userPaints.clear(); - this.personalSets.clear(); - this.userPersonalSets.clear(); - } -} diff --git a/packages/plugin-7tv/tsconfig.json b/packages/plugin-7tv/tsconfig.json new file mode 100644 index 00000000..63b76eb2 --- /dev/null +++ b/packages/plugin-7tv/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "@usehyperion/plugin/tsconfig.json", + "compilerOptions": { + "plugins": [ + { + "name": "gql.tada/ts-plugin", + "shouldCheckForColocatedFragments": false, + "trackFieldUsage": false, + "schema": "https://7tv.io/v4/gql", + "tadaOutputLocation": "./src/graphql/7tv-env.d.ts", + "tadaTurboLocation": "./src/graphql/7tv-cache.d.ts" + } + ] + }, + "include": ["src"] +} diff --git a/packages/plugin-bttv/package.json b/packages/plugin-bttv/package.json index dea12c25..b3a54331 100644 --- a/packages/plugin-bttv/package.json +++ b/packages/plugin-bttv/package.json @@ -2,7 +2,6 @@ "name": "@usehyperion/plugin-bttv", "version": "0.1.0", "private": true, - "description": "BetterTTV emotes and badges for Hyperion", "type": "module", "exports": { ".": "./src/index.ts", diff --git a/packages/plugin-ffz/package.json b/packages/plugin-ffz/package.json index 70e131c2..a3522880 100644 --- a/packages/plugin-ffz/package.json +++ b/packages/plugin-ffz/package.json @@ -2,7 +2,6 @@ "name": "@usehyperion/plugin-ffz", "version": "0.1.0", "private": true, - "description": "FrankerFaceZ emotes and badges for Hyperion", "type": "module", "exports": { ".": "./src/index.ts", diff --git a/packages/plugin/package.json b/packages/plugin/package.json index 298edcf1..6116c518 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -10,6 +10,9 @@ "./tsconfig.json": "./tsconfig.base.json", "./package.json": "./package.json" }, + "dependencies": { + "@usehyperion/types": "workspace:^" + }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.0.0", "@types/node": "^26.6.6", diff --git a/packages/plugin/src/index.ts b/packages/plugin/src/index.ts index b7973f47..eef2ea23 100644 --- a/packages/plugin/src/index.ts +++ b/packages/plugin/src/index.ts @@ -1,15 +1,7 @@ -/** - * The Hyperion plugin API. - * - * Every export in this module is public, so keep the surface small. Describe - * data with plain interfaces, not with the app's own classes. The app - * implements these types, and this module never imports from the app. - * - * The only runtime code here is {@linkcode definePlugin}, which returns its - * argument unchanged. A plugin reaches the app through the - * {@linkcode PluginContext} that it gets in {@linkcode PluginDefinition.setup}. - */ -import type { Component } from "svelte"; +import type { Channel, Emote, User } from "@usehyperion/types"; +import type { Component, ComponentProps, Snippet } from "svelte"; + +export type { Channel, Emote, User } from "@usehyperion/types"; export interface PluginManifest { /** @@ -54,83 +46,28 @@ export interface BuiltManifest extends PluginManifest { readonly entry: string; } -export interface Emote { - /** - * The {@linkcode EmoteProviderOptions.name} of the provider that supplied - * the emote. - */ - readonly provider: string; - - /** - * The emote's id at its provider. - */ - readonly id: string; - - /** - * The name the provider gives the emote. - */ - readonly name: string; - - /** - * A different name the emote has in one channel, if the channel renamed it. - */ - alias?: string; - - /** - * The name that users see and type. Set it to the alias if there is one, - * and to the name if there is not. - */ - displayName: string; - - /** - * The width of the source image in pixels. - */ - readonly width: number; - - /** - * The height of the source image in pixels. - */ - readonly height: number; - - /** - * The width in pixels that the emote takes up in a chat message. It can be - * different from the image width. - */ - readonly displayWidth: number; - - /** - * The height in pixels that the emote takes up in a chat message. - */ - readonly displayHeight: number; - - /** - * The image candidates for the `srcset` attribute. Each entry has the - * format ` x`, for example `https://cdn.example/1x 1x`. - */ - readonly srcset: string[]; - - /** - * When true, the emote has no width of its own and the app draws it on top - * of the emote before it. - */ - readonly zeroWidth?: boolean; -} - export type EmoteData = Omit; /** - * The channel fields that the app guarantees to plugins. + * Emotes that the current user can use in every channel, such as a + * subscription to the provider. Shown as one group in the emote picker. */ -export interface PluginChannel { +export interface EmoteSetData { /** - * The Twitch user id of the channel owner. + * Unique among the sets of every provider. */ readonly id: string; + readonly name: string; + readonly emotes: EmoteData[]; +} +export interface ChannelEventOptions { /** - * The lowercase Twitch login name of the channel owner. + * Set as the event's `data-type` attribute so themes can style it. The + * plugin id is set as `data-plugin`, so types only need to be unique + * within the plugin. */ - readonly login: string; + readonly type?: string; } export interface LoadContext { @@ -142,6 +79,23 @@ export interface LoadContext { readonly signal: AbortSignal; } +export interface EmoteLoadContext extends LoadContext { + /** + * Whether the user asked for a reload, so cached emotes shouldn't be used. + * Only relevant when the provider caches emotes itself, see + * {@linkcode EmoteProviderOptions.fresh}. + */ + readonly force: boolean; + + /** + * Replaces the emotes that the load resolved with, for example after a + * provider that caches emotes itself finds that they changed. Returns + * whether the emotes were applied, which they aren't once + * {@linkcode signal} has aborted. + */ + update(emotes: EmoteData[]): boolean; +} + /** * Registers a source of emotes with {@linkcode PluginContext.emotes}. */ @@ -175,7 +129,7 @@ export interface EmoteProviderOptions { /** * Loads the emotes that users can use in every channel. */ - readonly global?: (ctx: LoadContext) => Promise; + readonly global?: (ctx: EmoteLoadContext) => Promise; /** * Loads the emotes of one channel. Resolve to an empty array when the @@ -183,13 +137,77 @@ export interface EmoteProviderOptions { * with 404 for such a channel, pass {@linkcode RequestOptions.notFound} to * {@linkcode PluginHttp.json}. */ - readonly channel?: (channel: PluginChannel, ctx: LoadContext) => Promise; + readonly channel?: (channel: Channel, ctx: EmoteLoadContext) => Promise; + + /** + * Finds an emote that only the given user can use, in any channel, by the + * name it's typed as. The app calls it for every word of the user's + * messages and prefers its result over other emotes, so it must be + * synchronous and cheap. + */ + readonly personal?: (userId: string, name: string) => EmoteData | undefined; + + /** + * Loads the sets of emotes that the current user can use in every + * channel, for the emote picker and autocompletion. + */ + readonly userSets?: (user: User, ctx: LoadContext) => Promise; /** * How many seconds the app uses cached emotes before it fetches them again. - * The default is 5 minutes. + * The default is 5 minutes. Pass `false` to cache emotes yourself with + * {@linkcode PluginContext.cache}, for example to check whether they + * changed rather than refetching them after a fixed time. + */ + readonly fresh?: number | false; +} + +/** + * A provider's emotes in one place, either globally or in one channel. + */ +export interface EmoteScope { + /** + * Whether the provider's emotes have loaded here. + */ + readonly loaded: boolean; + + /** + * Finds one of the provider's emotes by the name it's typed as. + */ + get(name: string): Emote | undefined; + + /** + * Adds an emote or replaces the one with the same + * {@linkcode Emote.displayName}, for example after a live update. + */ + set(emote: EmoteData): void; + + /** + * Removes one of the provider's emotes by the name it's typed as. + */ + delete(name: string): void; + + /** + * Loads the provider's emotes again if it's enabled. With `force`, the + * load skips the cache. */ - readonly fresh?: number; + reload(force?: boolean): Promise; + + /** + * Removes the provider's emotes until they're loaded again. + */ + clear(): void; +} + +export interface EmoteProviderHandle { + readonly global: EmoteScope; + + /** + * The provider's emotes in a channel, or `undefined` if the app doesn't + * know the channel. + */ + channel(id: string): EmoteScope | undefined; + readonly dispose: Dispose; } export interface BadgeData { @@ -247,9 +265,100 @@ export interface BadgeProviderOptions { readonly enabled?: () => boolean; /** - * Loads all of the provider's badges and the users who have them. + * Loads all of the provider's badges and the users who have them. Omit it + * if the badges arrive some other way, and add them with + * {@linkcode BadgeProviderHandle}. + */ + readonly load?: (ctx: LoadContext) => Promise; +} + +export interface BadgeProviderHandle { + /** + * Adds a badge or replaces the one with the same version. + */ + set(badge: BadgeData): void; + + /** + * Gives a badge that was added with {@linkcode set} or loaded to a user. + * Does nothing if the provider has no badge with that version. + */ + give(userId: string, version: string): void; + readonly dispose: Dispose; +} + +export interface EmbedCardProps { + /** + * Where clicking the card leads. + */ + readonly href: string; + + /** + * The accessible name of the card's link. + */ + readonly label: string; + + /** + * Set as the card's `data-type` attribute so themes can style it. + */ + readonly type: string; + + /** + * The square area at the start of the card, usually an image. + */ + readonly media: Snippet; + + /** + * The text next to the media. + */ + readonly children: Snippet; +} + +/** + * Components from the app for plugins to render, so plugin UI looks like the + * rest of the app. + */ +export interface PluginUi { + /** + * A user's name in their color and decorations. + */ + readonly Username: Component<{ user: User }>; + + /** + * An emote at its chat size, with its tooltip. + */ + readonly Emote: Component<{ emote: Emote }>; + + /** + * The card that link embeds use. + */ + readonly EmbedCard: Component; +} + +export interface EmbedProps { + readonly url: URL; + + /** + * What {@linkcode EmbedProviderOptions.match} returned for the URL. + */ + readonly data: T; + readonly ui: PluginUi; +} + +/** + * Registers a kind of link embed with {@linkcode PluginContext.embeds}. + */ +export interface EmbedProviderOptions { + /** + * Returns what the component needs to embed the URL, or `null` if the + * provider doesn't embed it. The app calls it for every link in chat, so + * it must be synchronous and cheap. + */ + match(url: URL): T | null; + + /** + * Renders the embed. It can load more data itself. */ - readonly load: (ctx: LoadContext) => Promise; + readonly component: Component>; } interface SettingBase { @@ -383,6 +492,75 @@ export interface PluginHttp { json(url: string, options?: RequestOptions): Promise; } +/** + * Stores data across launches in the app's cache. Keys are scoped to the + * plugin, and the user can clear the cache at any time. + */ +export interface PluginCache { + get(key: string): Promise; + + /** + * @param ttl Seconds until the entry is removed. The default is 30 days. + */ + set(key: string, value: unknown, ttl?: number): Promise; +} + +export interface PluginChannels { + /** + * A channel that the app knows, or `undefined`. + */ + get(id: string): Channel | undefined; + + /** + * Runs whenever the current user joins a channel's chat, including after a + * reconnect. + */ + onJoin(callback: (channel: Channel) => void): Dispose; + + /** + * Runs when the current user leaves a channel's chat. + */ + onLeave(callback: (channel: Channel) => void): Dispose; + + /** + * Runs after the current user sent a message in a channel. + */ + onMessageSent(callback: (channel: Channel) => void): Dispose; + + /** + * Adds an event to the channel's chat, rendered by the given component + * with the event chrome around it. Does nothing if the app no longer knows + * the channel. + */ + event>( + channel: Channel, + component: C, + props: ComponentProps, + options?: ChannelEventOptions, + ): void; + + /** + * Resolves a user as a viewer of the channel, fetching them if the app + * hasn't seen them yet. Resolves to `null` if the user doesn't exist or + * the app no longer knows the channel. + */ + fetchUser(channel: Channel, userId: string): Promise; +} + +export interface PluginUsers { + /** + * The signed in user, or `null` while nobody is signed in. Reactive. + */ + readonly current: User | null; + + /** + * Adds CSS that styles a user's name, for example a gradient. The app + * reads it in a reactive context and uses the first decoration that + * returns a value, after the user's color. + */ + decorate(style: (userId: string) => string | undefined): Dispose; +} + /** * Writes to the app's log. Each message starts with the plugin id in * brackets, so you do not need to add it. @@ -396,10 +574,10 @@ export interface PluginLogger { /** * Registers providers of one kind. Each call registers one provider and - * returns a function that removes it. + * returns a way to remove it. */ -interface Provider { - provide(options: T): Dispose; +interface Provider { + provide(options: T): R; } /** @@ -422,19 +600,30 @@ export interface PluginContext { readonly settings: SettingValues; readonly log: PluginLogger; readonly http: PluginHttp; + readonly cache: PluginCache; + readonly channels: PluginChannels; + readonly users: PluginUsers; + readonly ui: PluginUi; /** * Registers emote providers. A plugin can register more than one, but each * one needs a unique name. */ - readonly emotes: Provider; + readonly emotes: Provider; /** * Registers the plugin's badge provider. The app stores badges under the * plugin id, so a plugin can register only one badge provider at a time. * Attempting to register more than one will throw an error. */ - readonly badges: Provider; + readonly badges: Provider; + + /** + * Registers link embeds. The first provider that matches a link embeds it. + */ + readonly embeds: { + provide(options: EmbedProviderOptions): Dispose; + }; /** * Adds a function that runs when the plugin is disabled. Cleanup functions diff --git a/packages/types/package.json b/packages/types/package.json new file mode 100644 index 00000000..fe54d60c --- /dev/null +++ b/packages/types/package.json @@ -0,0 +1,9 @@ +{ + "name": "@usehyperion/types", + "version": "0.1.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + } +} diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts new file mode 100644 index 00000000..9be92fd0 --- /dev/null +++ b/packages/types/src/index.ts @@ -0,0 +1,96 @@ +export interface User { + /** + * The Twitch user id. + */ + readonly id: string; + + /** + * The lowercase Twitch login name. + */ + readonly username: string; + + /** + * The name shown in chat. The capitalization may differ from the username, + * and it may include a localized name if the user enabled those. + */ + readonly displayName: string; + + /** + * The CSS color of the user's name, after the app's readability + * adjustments. + */ + readonly color: string; +} + +export interface Channel { + /** + * The Twitch user id of the channel owner. + */ + readonly id: string; + + /** + * The channel owner. + */ + readonly user: User; +} + +export interface Emote { + /** + * The name of the provider that supplied the emote, e.g. `Twitch`. + */ + readonly provider: string; + + /** + * The emote's id from its provider. + */ + readonly id: string; + + /** + * The name the provider gives the emote. + */ + readonly name: string; + + /** + * A different name the emote has in one channel, if the channel renamed it. + */ + alias?: string; + + /** + * The name that users see and type. Set it to the alias if there is one, + * and to the name if there is not. + */ + displayName: string; + + /** + * The width of the source image in pixels. + */ + readonly width: number; + + /** + * The height of the source image in pixels. + */ + readonly height: number; + + /** + * The width in pixels that the emote takes up in a chat message. It can be + * different from the image width. + */ + readonly displayWidth: number; + + /** + * The height in pixels that the emote takes up in a chat message. + */ + readonly displayHeight: number; + + /** + * The image candidates for the `srcset` attribute. Each entry has the + * format ` x`, for example `https://cdn.example/1x 1x`. + */ + readonly srcset: string[]; + + /** + * When true, the emote has no width of its own and the app draws it on top + * of the emote before it. + */ + readonly zeroWidth?: boolean; +} diff --git a/packages/types/tsconfig.json b/packages/types/tsconfig.json new file mode 100644 index 00000000..fa8fb83c --- /dev/null +++ b/packages/types/tsconfig.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "esnext", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["esnext"], + "strict": true, + "noEmit": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be6fb1e4..d80c8a18 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -235,12 +235,18 @@ importers: '@usehyperion/plugin': specifier: workspace:^ version: link:packages/plugin + '@usehyperion/plugin-7tv': + specifier: workspace:^ + version: link:packages/plugin-7tv '@usehyperion/plugin-bttv': specifier: workspace:^ version: link:packages/plugin-bttv '@usehyperion/plugin-ffz': specifier: workspace:^ version: link:packages/plugin-ffz + '@usehyperion/types': + specifier: workspace:^ + version: link:packages/types colord: specifier: ^2.14.0 version: 2.14.1 @@ -332,6 +338,9 @@ importers: packages/plugin: dependencies: + '@usehyperion/types': + specifier: workspace:^ + version: link:../types vite: specifier: npm:@voidzero-dev/vite-plus-core@8.4.0 version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' @@ -346,6 +355,25 @@ importers: specifier: ^5.57.3 version: 5.60.2(@typescript-eslint/types@8.74.0) + packages/plugin-7tv: + dependencies: + gql.tada: + specifier: ^1.11.4 + version: 1.11.5(@gql.tada/svelte-support@1.0.3(svelte@5.59.2(@typescript-eslint/types@8.74.0))(typescript@6.0.3))(graphql@17.1.0)(typescript@6.0.3) + graphql-web-lite: + specifier: 16.6.0-4 + version: 16.6.0-4(graphql@17.1.0) + devDependencies: + '@usehyperion/plugin': + specifier: workspace:^ + version: link:../plugin + svelte: + specifier: ^5.57.3 + version: 5.59.2(@typescript-eslint/types@8.74.0) + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.7)(jiti@2.7.0)(typescript@6.0.3)' + packages/plugin-bttv: devDependencies: '@usehyperion/plugin': @@ -370,6 +398,8 @@ importers: specifier: 'catalog:' version: '@voidzero-dev/vite-plus-core@8.4.0(@types/node@26.6.11)(jiti@2.7.0)(tsrs@7.1.0-beta.tsrs7)(typescript@6.0.3)' + packages/types: {} + packages: '@0no-co/graphql.web@1.3.4': diff --git a/src-tauri/src/api.rs b/src-tauri/src/api.rs index ca42fae4..26789f00 100644 --- a/src-tauri/src/api.rs +++ b/src-tauri/src/api.rs @@ -19,8 +19,6 @@ pub fn ensure_login(login: &str) -> Result<(), Error> { pub async fn join( state: State<'_, Mutex>, id: String, - stv_id: Option, - set_id: Option, login: String, is_mod: bool, ) -> Result<(), Error> { @@ -30,12 +28,6 @@ pub async fn join( let state = state.lock().await; let irc = irc::client(&state)?; - if let Some(seventv) = &state.seventv { - seventv - .client() - .join(&login, &id, stv_id.as_deref(), set_id.as_deref()); - } - if let Some(pubsub) = &state.pubsub { pubsub.client().listen(&login, &id, is_mod); } @@ -53,10 +45,6 @@ pub async fn leave(state: State<'_, Mutex>, login: String) -> Result<( let state = state.lock().await; let irc = irc::client(&state)?; - if let Some(seventv) = &state.seventv { - seventv.client().leave(&login); - } - if let Some(pubsub) = &state.pubsub { pubsub.client().unlisten(&login); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 58b446c1..b4502f59 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -5,7 +5,6 @@ use cache::Cache; use connection::Connection; use irc::IrcClient; use pubsub::PubSubClient; -use seventv::SeventTvClient; use tauri::Manager; use tauri::async_runtime::{self, Mutex}; use tauri::ipc::Invoke; @@ -23,7 +22,6 @@ mod log; mod notify; mod popout; mod pubsub; -mod seventv; mod theme; mod ws; @@ -41,7 +39,6 @@ pub struct AppState { unverified: PendingToken, integrity: IntegrityState, irc: Option>, - seventv: Option>, pubsub: Option>, } @@ -53,7 +50,6 @@ impl AppState { unverified: PendingToken::default(), integrity: IntegrityState::default(), irc: None, - seventv: None, pubsub: None, } } @@ -61,7 +57,6 @@ impl AppState { fn close_connections(&mut self) { connection::close(&mut self.irc); connection::close(&mut self.pubsub); - connection::close(&mut self.seventv); } } @@ -182,8 +177,6 @@ fn get_handler() -> impl Fn(Invoke) -> bool { log::log, log::update_log_level, pubsub::connect_pubsub, - seventv::connect_seventv, - seventv::sync_seventv, notify::notify, ] } diff --git a/src-tauri/src/seventv/client.rs b/src-tauri/src/seventv/client.rs deleted file mode 100644 index 642e7a7d..00000000 --- a/src-tauri/src/seventv/client.rs +++ /dev/null @@ -1,228 +0,0 @@ -use std::sync::Arc; -use std::time::Duration; - -use futures::FutureExt; -use serde::Deserialize; -use serde_json::json; -use tokio::sync::mpsc; - -use crate::connection::Started; -use crate::ws::{self, Changes, Flow, Link, Protocol, SubscriptionStore, WsError}; - -/// Assumed until the server's hello says otherwise. -const DEFAULT_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(25); - -/// How late a heartbeat may be before the connection counts as dead. -const HEARTBEAT_GRACE: Duration = Duration::from_secs(10); - -mod op { - pub const DISPATCH: u8 = 0; - pub const HELLO: u8 = 1; - pub const HEARTBEAT: u8 = 2; - pub const RECONNECT: u8 = 4; - pub const ACK: u8 = 5; - pub const ERROR: u8 = 6; - pub const END_OF_STREAM: u8 = 7; - pub const RESUME: u8 = 34; - pub const SUBSCRIBE: u8 = 35; - pub const UNSUBSCRIBE: u8 = 36; -} - -#[derive(Deserialize)] -struct Envelope { - op: u8, - #[serde(default)] - d: serde_json::Value, -} - -#[derive(Deserialize)] -struct Hello { - session_id: String, - heartbeat_interval: Option, -} - -pub struct SeventTvClient { - subscriptions: SubscriptionStore, -} - -impl SeventTvClient { - pub fn start() -> Started { - let client = Arc::new(Self { - subscriptions: SubscriptionStore::default(), - }); - - let (events_tx, events) = mpsc::unbounded_channel(); - - let driver = SeventTvDriver { - client: Arc::clone(&client), - events: events_tx, - session_id: None, - resuming: None, - heartbeat_timeout: DEFAULT_HEARTBEAT_INTERVAL + HEARTBEAT_GRACE, - }; - - Started { - client, - events, - run: Some(ws::run(driver).boxed()), - } - } - - /// Replaces the events subscribed to for `channel`. - pub fn set_channel(&self, channel: &str, events: Vec<(String, serde_json::Value)>) { - self.subscriptions.set_channel(channel, events); - } - - pub fn leave(&self, channel: &str) { - self.subscriptions.remove_channel(channel); - } -} - -struct SeventTvDriver { - client: Arc, - events: mpsc::UnboundedSender, - /// The last session that became ready. Resuming it after a drop keeps its - /// subscriptions and replays the events missed in between. - session_id: Option, - /// This connection's session, while waiting to hear whether resuming - /// `session_id` worked. - resuming: Option, - heartbeat_timeout: Duration, -} - -impl SeventTvDriver { - async fn hello(&mut self, hello: Hello, link: &mut Link) -> Result { - if let Some(interval) = hello.heartbeat_interval { - self.heartbeat_timeout = Duration::from_millis(interval) + HEARTBEAT_GRACE; - link.expect_within(self.heartbeat_timeout); - } - - let Some(previous) = &self.session_id else { - tracing::info!(id = %hello.session_id, "Session established"); - self.session_id = Some(hello.session_id); - - return Ok(Flow::Ready { restored: false }); - }; - - tracing::info!(%previous, "Resuming session"); - - link.send(&json!({ - "op": op::RESUME, - "d": { "session_id": previous } - })) - .await?; - - self.resuming = Some(hello.session_id); - - Ok(Flow::Continue) - } - - fn resumed(&mut self, session_id: String, restored: bool) -> Flow { - if restored { - tracing::info!(id = %session_id, "Session resumed"); - } else { - tracing::warn!(id = %session_id, "Resume unsuccessful, resubscribing"); - } - - self.session_id = Some(session_id); - - Flow::Ready { restored } - } -} - -impl Protocol for SeventTvDriver { - type Subscription = serde_json::Value; - - const NAME: &'static str = "7TV"; - const URI: &'static str = "wss://events.7tv.io/v3"; - - fn subscriptions(&self) -> &SubscriptionStore { - &self.client.subscriptions - } - - fn opened(&mut self, link: &mut Link) -> Flow { - self.resuming = None; - link.expect_within(self.heartbeat_timeout); - - Flow::Continue - } - - async fn received(&mut self, text: &str, link: &mut Link) -> Result { - let Envelope { op, d } = match serde_json::from_str(text) { - Ok(envelope) => envelope, - Err(err) => { - tracing::warn!(%err, "Failed to deserialize 7TV message"); - return Ok(Flow::Continue); - } - }; - - // Heartbeats are what the server promises, but anything it sends shows - // the connection is alive - link.expect_within(self.heartbeat_timeout); - - match op { - op::DISPATCH => { - if self.events.send(d).is_err() { - tracing::warn!("7TV event receiver dropped"); - } - } - op::HELLO => match serde_json::from_value(d) { - Ok(hello) => return self.hello(hello, link).await, - Err(err) => { - tracing::error!(%err, "Malformed hello"); - return Ok(Flow::Reconnect); - } - }, - op::HEARTBEAT => tracing::trace!("Heartbeat received"), - op::RECONNECT => { - tracing::warn!("7TV server requested reconnect"); - return Ok(Flow::Reconnect); - } - op::ACK => match self.resuming.take() { - // Nothing is subscribed while resuming, so this acknowledges it - Some(session_id) => { - let restored = d["data"]["success"].as_bool().unwrap_or(false); - return Ok(self.resumed(session_id, restored)); - } - None => tracing::debug!(payload = %d, "Opcode acknowledged"), - }, - op::ERROR => { - tracing::error!(payload = %d, "7TV returned an error"); - - // In place of the resume's ack, it means resuming failed - if let Some(session_id) = self.resuming.take() { - return Ok(self.resumed(session_id, false)); - } - } - op::END_OF_STREAM => { - tracing::warn!(payload = %d, "End of stream reached"); - return Ok(Flow::Reconnect); - } - _ => tracing::debug!(op, "Unhandled 7TV opcode"), - } - - Ok(Flow::Continue) - } - - async fn sync( - &mut self, - changes: &Changes, - link: &mut Link, - ) -> Result<(), WsError> { - let removed = changes.removed.iter().map(|entry| (op::UNSUBSCRIBE, entry)); - let added = changes.added.iter().map(|entry| (op::SUBSCRIBE, entry)); - - for (op, (key, condition)) in removed.chain(added) { - link.send(&json!({ - "op": op, - "d": { - "type": key.event, - "condition": condition - } - })) - .await?; - } - - Ok(()) - } -} diff --git a/src-tauri/src/seventv/mod.rs b/src-tauri/src/seventv/mod.rs deleted file mode 100644 index f3232f90..00000000 --- a/src-tauri/src/seventv/mod.rs +++ /dev/null @@ -1,86 +0,0 @@ -mod client; - -pub use client::SeventTvClient; -use serde_json::json; -use tauri::ipc::Channel; -use tauri::{AppHandle, State}; -use tokio::sync::Mutex; - -use crate::AppState; -use crate::api::ensure_login; -use crate::connection::{self, Client, Connection}; -use crate::error::Error; - -impl SeventTvClient { - pub fn join( - &self, - login: &str, - channel_id: &str, - user_id: Option<&str>, - emote_set_id: Option<&str>, - ) { - let channel = json!({ - "ctx": "channel", - "platform": "TWITCH", - "id": channel_id - }); - - let mut events = vec![ - ("cosmetic.create".to_owned(), channel.clone()), - ("entitlement.create".to_owned(), channel), - ]; - - if let Some(emote_set_id) = emote_set_id { - events.push(( - "emote_set.*".to_owned(), - json!({ "object_id": emote_set_id }), - )); - } - - if let Some(user_id) = user_id { - events.push(("user.update".to_owned(), json!({ "object_id": user_id }))); - } - - self.set_channel(login, events); - } -} - -impl Client for SeventTvClient { - type Message = serde_json::Value; - - const NAME: &'static str = "7TV"; - - fn slot(state: &mut AppState) -> &mut Option> { - &mut state.seventv - } -} - -#[tauri::command] -pub async fn connect_seventv( - app_handle: AppHandle, - channel: Channel, -) -> Result<(), Error> { - connection::connect(app_handle, channel, |_| Ok(SeventTvClient::start())).await -} - -/// Recomputes the 7TV subscriptions for a joined channel after its 7TV user or -/// active emote set changed. -#[tracing::instrument(skip(state))] -#[tauri::command] -pub async fn sync_seventv( - state: State<'_, Mutex>, - login: String, - id: String, - stv_id: Option, - set_id: Option, -) -> Result<(), Error> { - ensure_login(&login)?; - - if let Some(seventv) = &state.lock().await.seventv { - seventv - .client() - .join(&login, &id, stv_id.as_deref(), set_id.as_deref()); - } - - Ok(()) -} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3a758cef..eff4c803 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -25,7 +25,7 @@ } ], "security": { - "csp": "default-src 'self' https: ipc: http://ipc.localhost; style-src 'self' 'unsafe-inline' theme: http://theme.localhost; font-src 'self' data: theme: http://theme.localhost https:; img-src 'self' data: https: theme: http://theme.localhost", + "csp": "default-src 'self' https: ipc: http://ipc.localhost; connect-src 'self' https: wss: ipc: http://ipc.localhost; style-src 'self' 'unsafe-inline' theme: http://theme.localhost; font-src 'self' data: theme: http://theme.localhost https:; img-src 'self' data: https: theme: http://theme.localhost", "dangerousDisableAssetCspModification": ["style-src"] } }, diff --git a/src/lib/app.svelte.ts b/src/lib/app.svelte.ts index 54a1e800..2cf5a8b4 100644 --- a/src/lib/app.svelte.ts +++ b/src/lib/app.svelte.ts @@ -7,7 +7,6 @@ import { page } from "$app/state"; import type { Channel } from "./models/channel.svelte"; import type { Followed } from "./models/current-user.svelte"; import type { NotificationOptions, NotificationResponse } from "./notifications"; -import type { DispatchPayload } from "./seventv"; import type { IrcMessage } from "./twitch/irc"; import type { PubSubMessage } from "./twitch/pubsub"; @@ -18,7 +17,6 @@ import { ChannelManager } from "./managers/channel-manager"; import { EmoteManager } from "./managers/emote-manager"; import { CurrentUser } from "./models/current-user.svelte"; import { settings } from "./settings"; -import { SevenTvCosmetics } from "./seventv"; import { SplitController } from "./splits/controller.svelte"; import { firstLeaf } from "./splits/tree"; import { storage } from "./stores"; @@ -57,7 +55,6 @@ class App { * Provider-specific global emotes. */ public readonly emotes = new EmoteManager(); - public readonly cosmetics = new SevenTvCosmetics(); /** * Provider-specific global badges. @@ -333,18 +330,9 @@ class App { }); }); - const seventv = new IpcChannel(async (message) => { - await dispatch( - "seventv", - message.type, - "object" in message.body ? message.body.object : message.body, - ); - }); - await Promise.all([ invoke("connect_irc", { channel: irc }), invoke("connect_pubsub", { channel: pubsub }), - invoke("connect_seventv", { channel: seventv }), ]); this.#connected = true; @@ -367,7 +355,6 @@ class App { this.channels.clear(); this.emotes.clear(); - this.cosmetics.clear(); this.badges.clear(); } diff --git a/src/lib/components/message/Embed.svelte b/src/lib/components/message/Embed.svelte index a0c4c0e7..d65b9ed4 100644 --- a/src/lib/components/message/Embed.svelte +++ b/src/lib/components/message/Embed.svelte @@ -1,18 +1,25 @@ -{#if target.type === "emote"} - {#await fetchEmote(target.id) then emote} - {#if emote} - {#snippet emoteMedia()} -
- {emote.displayName} -
- - {#if !emote.listed && blurred} - - {/if} - {/snippet} - - {#snippet emoteBody()} -
- - {emote.displayName} - - - {#if !emote.listed} - - unlisted - - {/if} -
- - {#snippet emoteMeta()} - - by {emote.owner?.mainConnection?.platformDisplayName ?? "Unknown"} - - {/snippet} - - {@render meta(emoteMeta)} - {/snippet} - - {@render card(url.href, emote.displayName, emoteMedia, emoteBody)} - {/if} - {/await} +{#if target.type === "plugin"} + {:else if target.type === "spotify"}
+ {@render clipBody()} + {/if} {/await} {/if} -{#snippet card(href: string, label: string, media: Snippet, body: Snippet)} -
- - -
- {@render media()} -
- -
- {@render body()} -
-
-{/snippet} - {#snippet meta(children: Snippet)}
{@render children()} diff --git a/src/lib/components/message/EmbedCard.svelte b/src/lib/components/message/EmbedCard.svelte new file mode 100644 index 00000000..39ee3950 --- /dev/null +++ b/src/lib/components/message/EmbedCard.svelte @@ -0,0 +1,23 @@ + + +
+ + +
+ {@render media()} +
+ +
+ {@render children()} +
+
diff --git a/src/lib/components/message/Event.svelte b/src/lib/components/message/Event.svelte index 75a3946b..bbaae094 100644 --- a/src/lib/components/message/Event.svelte +++ b/src/lib/components/message/Event.svelte @@ -7,8 +7,6 @@ import BlockStatus from "./events/BlockStatus.svelte"; import Clear from "./events/Clear.svelte"; import Delete from "./events/Delete.svelte"; - import EmoteSetChange from "./events/EmoteSetChange.svelte"; - import EmoteSetUpdate from "./events/EmoteSetUpdate.svelte"; import Join from "./events/Join.svelte"; import Mode from "./events/Mode.svelte"; import Notice from "./events/Notice.svelte"; @@ -31,8 +29,6 @@ [BlockStatus, "block-status"], [Clear, "clear"], [Delete, "delete"], - [EmoteSetChange, "emote-set-change"], - [EmoteSetUpdate, "emote-set-update"], [Join, "join"], [Mode, "mode"], [Notice, "notice"], @@ -68,7 +64,8 @@
diff --git a/src/lib/components/message/events/EmoteSetUpdate.svelte b/src/lib/components/message/events/EmoteSetUpdate.svelte deleted file mode 100644 index fdfcd3d2..00000000 --- a/src/lib/components/message/events/EmoteSetUpdate.svelte +++ /dev/null @@ -1,28 +0,0 @@ - - - - -{#if action === "renamed"} - renamed {oldName} to - {emote.displayName} -{:else} - {action} an emote: - {emote.displayName} -{/if} - - diff --git a/src/lib/components/settings/schema/categories/chat.ts b/src/lib/components/settings/schema/categories/chat.ts index e3e0c627..62b2d6aa 100644 --- a/src/lib/components/settings/schema/categories/chat.ts +++ b/src/lib/components/settings/schema/categories/chat.ts @@ -38,18 +38,6 @@ export default { }, ], }, - { - type: "group", - label: "Badges", - fields: [ - { - id: "chat.badges.seventv", - type: "switch", - label: "Enable 7TV badges", - description: "Show badges from [7TV](https://7tv.app/).", - }, - ], - }, { type: "group", label: "Usernames", @@ -66,7 +54,7 @@ export default { type: "switch", label: "Readable name colors", description: - "Lightens or darkens the color of usernames based on the current theme. This does not apply to 7TV paints.", + "Lightens or darkens the color of usernames based on the current theme. This does not apply to paints from plugins such as 7TV.", }, { id: "chat.usernames.randomColor", @@ -75,18 +63,12 @@ export default { description: "Assign a random Twitch color to usernames that do not have a color set.", }, - { - id: "chat.usernames.paint", - type: "switch", - label: "Paint usernames", - description: "Style usernames with 7TV paints if the user has one.", - }, { id: "chat.usernames.mentionStyle", type: "radio", label: "Mention style", description: - "Choose how mentions in messages are displayed. Painted mentions will fallback to the user's color if they have no 7TV paint.", + "Choose how mentions in messages are displayed. Painted mentions use paints from plugins such as 7TV, and fall back to the user's color if they have none.", items: [ { label: "None", value: "none" }, { label: "Colored", value: "colored" }, @@ -99,12 +81,6 @@ export default { type: "group", label: "Emotes", fields: [ - { - id: "chat.emotes.seventv", - type: "switch", - label: "Enable 7TV emotes", - description: "Show and autocomplete emotes from [7TV](https://7tv.app/).", - }, { id: "chat.emotes.padding", type: "slider", diff --git a/src/lib/components/user/Username.svelte b/src/lib/components/user/Username.svelte index 8df7d229..e1ad22cd 100644 --- a/src/lib/components/user/Username.svelte +++ b/src/lib/components/user/Username.svelte @@ -1,5 +1,5 @@ -{#snippet markdown(text: string)} - {@html parseDescription(text)} -{/snippet} - {#if field.type === "group"}
{#each field.fields as subField (subField)} @@ -45,13 +30,15 @@ {:else} {#snippet description()} {#if field.description} - {@render markdown(field.description)} + {@html parseMarkdown(field.description)} {/if} {/snippet} {@const described = field.description ? description : undefined} - {#if field.type === "custom"} + {#if field.type === "plugin"} + + {:else if field.type === "custom"}
@@ -75,7 +62,9 @@ > {#each field.items as option (option.value)} {#snippet optionDescription()} - {#if option.description}{@render markdown(option.description)}{/if} + {#if option.description} + {@html parseMarkdown(option.description)} + {/if} {/snippet} {#each results as category (category.label)} - + {/each} diff --git a/src/lib/components/settings/custom/plugins/PluginCard.svelte b/src/lib/components/settings/custom/plugins/PluginCard.svelte new file mode 100644 index 00000000..c6c48061 --- /dev/null +++ b/src/lib/components/settings/custom/plugins/PluginCard.svelte @@ -0,0 +1,80 @@ + + +
+
+
+
+ +
+
+

+ {manifest.name} +

+ + + v{manifest.version} + +
+ +

+ {@html parseMarkdown(manifest.description)} +

+
+ + +
+ + {#if count > 0} +
+ + {#snippet render({ props })} + + {/snippet} + +
+ + + {/if} +
diff --git a/src/lib/components/settings/custom/plugins/PluginDialog.svelte b/src/lib/components/settings/custom/plugins/PluginDialog.svelte new file mode 100644 index 00000000..fa1d0d34 --- /dev/null +++ b/src/lib/components/settings/custom/plugins/PluginDialog.svelte @@ -0,0 +1,63 @@ + + + + {#snippet header()} +
+ {manifest.name} + + v{manifest.version} +
+ + + {@html parseMarkdown(manifest.description)} + + {/snippet} + + {#if !enabled} +

+ Turn on {manifest.name} to change its settings. +

+ {/if} + +
+ {#each field.fields as subField (subField)} + + {/each} +
+ + {#snippet footer()} + + + + + + {#snippet render({ props })} + + {/snippet} + + {/snippet} +
diff --git a/src/lib/components/settings/schema/categories/plugins.ts b/src/lib/components/settings/schema/categories/plugins.ts index 968f959e..1038629f 100644 --- a/src/lib/components/settings/schema/categories/plugins.ts +++ b/src/lib/components/settings/schema/categories/plugins.ts @@ -54,20 +54,20 @@ export default { order: 50, label: "Plugins", icon: IconPlugins, - fields: plugins.map((plugin) => ({ - type: "group", - label: plugin.manifest.name, - fields: [ - { + fields: [ + { + type: "group", + fields: plugins.map((plugin) => ({ id: enabledKey(plugin.manifest.id), - type: "switch", - label: `Enable ${plugin.manifest.name}`, + type: "plugin", + label: plugin.manifest.name, description: plugin.manifest.description, keywords: ["plugin", plugin.manifest.id], - }, - ...Object.entries(plugin.settings).map(([key, setting]) => - toField(plugin, key, setting), - ), - ], - })), + plugin, + fields: Object.entries(plugin.settings).map(([key, setting]) => + toField(plugin, key, setting), + ), + })), + }, + ], } satisfies SettingsCategory; diff --git a/src/lib/components/settings/schema/search.ts b/src/lib/components/settings/schema/search.ts index d1bba80f..1056b13f 100644 --- a/src/lib/components/settings/schema/search.ts +++ b/src/lib/components/settings/schema/search.ts @@ -21,6 +21,10 @@ function fieldText(field: SettingsField): string { parts.push(item.label, item.description ?? ""); } } + + if (field.type === "plugin") { + parts.push(...field.fields.map(fieldText)); + } } return parts.join(" ").toLowerCase(); diff --git a/src/lib/components/settings/schema/types.ts b/src/lib/components/settings/schema/types.ts index 21b4a385..7ffa8a26 100644 --- a/src/lib/components/settings/schema/types.ts +++ b/src/lib/components/settings/schema/types.ts @@ -1,5 +1,7 @@ import type { Component } from "svelte"; +import type { InstalledPlugin } from "#lib/plugins/internal.js"; +import type { PluginSettingKey } from "#lib/plugins/settings.js"; import type { Settings } from "#lib/settings.js"; type SettingKey = keyof Settings; @@ -37,6 +39,12 @@ interface CustomField extends BaseField { component: Component; } +export interface PluginField extends BaseField { + type: "plugin"; + plugin: InstalledPlugin; + fields: SettingsField[]; +} + interface InputField extends BaseField> { type: "input"; placeholder?: string; @@ -76,6 +84,7 @@ interface SwitchField extends BaseField> { export type SettingsField = | GroupField | CustomField + | PluginField | InputField | ChoiceField | SliderField diff --git a/src/lib/dialog.ts b/src/lib/dialog.ts index 789deafc..fd74758d 100644 --- a/src/lib/dialog.ts +++ b/src/lib/dialog.ts @@ -4,6 +4,7 @@ export const dialogs = { about: "about-dialog", join: "join-dialog", settings: "settings-dialog", + plugin: (pluginId: string) => `plugin-dialog-${pluginId}`, poll: (channelId: string) => `poll-dialog-${channelId}`, prediction: (channelId: string) => `prediction-dialog-${channelId}`, pinDuration: (messageId: string) => `pin-duration-dialog-${messageId}`, diff --git a/src/lib/util/index.ts b/src/lib/util/index.ts index 55f3390e..73556b94 100644 --- a/src/lib/util/index.ts +++ b/src/lib/util/index.ts @@ -44,3 +44,14 @@ export async function openMenu(event: MouseEvent, menufn: () => Promise) { export function mentions(text: string, username: string | undefined) { return !!username && new RegExp(`@${RegExp.escape(username)}\\b`, "i").test(text); } + +export function parseMarkdown(text: string) { + return text + .replace(/`([^`]+)`/g, "$1") + .replace( + /\[([^\]]+)\]\(([^)]+)\)/g, + '$1', + ) + .replace(/(\*\*)(.*?)\1/g, "$2") + .replace(/(\*)(.*?)\1/g, "$2"); +} From 8ef8e0d8ada99e67085d71d71fd672f92bbb7b3c Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Tue, 1 Dec 2026 14:37:04 -0500 Subject: [PATCH 06/22] load settings before plugins --- src/hooks.client.ts | 5 +++++ src/lib/settings.ts | 1 - 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/hooks.client.ts b/src/hooks.client.ts index e2f3ea2d..32cb5da1 100644 --- a/src/hooks.client.ts +++ b/src/hooks.client.ts @@ -5,6 +5,7 @@ import relativeTime from "dayjs/plugin/relativeTime"; import { log } from "#lib/log.js"; import { startPlugins } from "#lib/plugins/host.svelte.js"; +import { settings } from "#lib/settings.js"; import { loadThemes } from "#lib/themes.js"; dayjs.extend(duration); @@ -12,6 +13,10 @@ dayjs.extend(localizedFormat); dayjs.extend(relativeTime); export async function init() { + // Settings need to be started before plugins so their settings are loaded + // before they start. + await settings.start().catch(log.swallow("Failed to load settings")); + startPlugins(); // Themes are optional, so errors shouldn't block the app from starting diff --git a/src/lib/settings.ts b/src/lib/settings.ts index 354c75e3..1620a529 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -87,7 +87,6 @@ const defaults: Settings = { }; export const settings = new RuneStore("settings", defaults, { - autoStart: true, hooks: { beforeFrontendSync: (state) => { // Highlight kinds added since the settings were saved get defaults. From 581e1ceac023dec75b4e3db5fe5df77f66ecff21 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Tue, 1 Dec 2026 14:40:28 -0500 Subject: [PATCH 07/22] reserve twitch id --- src/lib/plugins/internal.ts | 5 +++++ src/lib/plugins/registry.ts | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/lib/plugins/internal.ts b/src/lib/plugins/internal.ts index aad754d4..885eaf0d 100644 --- a/src/lib/plugins/internal.ts +++ b/src/lib/plugins/internal.ts @@ -24,6 +24,7 @@ interface PluginPackage { const ID_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; const RESERVED_SETTINGS = new Set(["enabled"]); +const RESERVED_IDS = new Set(["twitch"]); function bundled(pkg: PluginPackage, module: PluginModule): InstalledPlugin { const manifest = { @@ -35,6 +36,10 @@ function bundled(pkg: PluginPackage, module: PluginModule): InstalledPlugin { throw new Error(`Plugin id "${manifest.id}" must be lowercase letters, digits, and dashes`); } + if (RESERVED_IDS.has(manifest.id)) { + throw new Error(`Plugin id "${manifest.id}" is reserved`); + } + const settings = module.default.settings ?? {}; for (const key of Object.keys(settings)) { diff --git a/src/lib/plugins/registry.ts b/src/lib/plugins/registry.ts index 1371eee9..5ca8a17d 100644 --- a/src/lib/plugins/registry.ts +++ b/src/lib/plugins/registry.ts @@ -97,6 +97,9 @@ const channelListeners: Record> = { messageSent: new Set(), }; +const RESERVED_EMOTE_PROVIDERS = new Set(["Twitch"]); +const RESERVED_BADGE_SETS = new Set(["twitch"]); + function register(map: SvelteMap, key: string, value: T, kind: string): Dispose { if (map.has(key)) { throw new Error(`A ${kind} named "${key}" is already registered`); @@ -112,10 +115,18 @@ function register(map: SvelteMap, key: string, value: T, kind: str } export function registerEmoteProvider(provider: EmoteProvider) { + if (RESERVED_EMOTE_PROVIDERS.has(provider.name)) { + throw new Error(`The emote provider name "${provider.name}" is reserved`); + } + return register(emoteProviders, provider.name, provider, "emote provider"); } export function registerBadgeProvider(provider: BadgeProvider) { + if (RESERVED_BADGE_SETS.has(provider.setId)) { + throw new Error(`The badge set "${provider.setId}" is reserved`); + } + return register(badgeProviders, provider.setId, provider, "badge provider"); } From 5becaf7629bcf89e0cf8845e6eb66f52cfc49755 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Tue, 1 Dec 2026 14:48:28 -0500 Subject: [PATCH 08/22] catch root effect errors --- src/lib/plugins/host.svelte.ts | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/lib/plugins/host.svelte.ts b/src/lib/plugins/host.svelte.ts index d30bc5f5..bf3e199b 100644 --- a/src/lib/plugins/host.svelte.ts +++ b/src/lib/plugins/host.svelte.ts @@ -89,23 +89,31 @@ function activate(plugin: InstalledPlugin): Dispose | undefined { log.info(`Disabled plugin "${id}"`); } - try { - // Run the constructor inside the root too so field initializers can - // create effects. - const destroy = $effect.root(() => { + // Stored as an object to prevent any value from passing + let failure: { error: unknown } | undefined; + + // Run the constructor inside the root too so field initializers can create + // effects. Errors are caught inside so the root is still returned and the + // effects created before the error can be destroyed. + const destroy = $effect.root(() => { + try { const instance = new plugin.main(ctx); instance.onload(); // First so it runs last, after what the plugin registered is // removed. disposers.unshift(() => instance.onunload()); - }); + } catch (error) { + failure = { error }; + } + }); + + // Registered last so it runs first, before what the plugin registered is + // removed. + disposers.push(destroy); - // Registered last so it runs first, before what the plugin registered - // is removed. - disposers.push(destroy); - } catch (error) { - log.error(`Failed to enable plugin "${id}"`, error); + if (failure) { + log.error(`Failed to enable plugin "${id}"`, failure.error); dispose(); return undefined; From e078baad61d1185d8c8b875c43b2911112f50646 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Tue, 1 Dec 2026 14:51:49 -0500 Subject: [PATCH 09/22] track provider badges --- src/lib/managers/badge-manager.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/lib/managers/badge-manager.ts b/src/lib/managers/badge-manager.ts index 177b5afd..7d49e61b 100644 --- a/src/lib/managers/badge-manager.ts +++ b/src/lib/managers/badge-manager.ts @@ -23,6 +23,11 @@ export class BadgeManager extends SvelteMap { */ readonly #forced = new Set(); + /** + * The set ids of providers that have added badges. + */ + readonly #providerSets = new Set(); + readonly #loads = new Map>(); readonly #requests = new Map(); @@ -48,6 +53,7 @@ export class BadgeManager extends SvelteMap { this.#reset(name); } + this.#providerSets.clear(); this.users.clear(); super.clear(); } @@ -95,6 +101,7 @@ export class BadgeManager extends SvelteMap { }); this.set(badge.id, badge); + this.#providerSets.add(setId); return badge; } @@ -183,11 +190,12 @@ export class BadgeManager extends SvelteMap { * their plugin was disabled. */ #prune() { - for (const name of this.#loads.keys()) { + for (const name of new Set([...this.#loads.keys(), ...this.#providerSets])) { if (name === TWITCH || badgeProviders.has(name)) continue; this.#reset(name); this.#loads.delete(name); + this.#providerSets.delete(name); for (const [id, badge] of this) { if (badge.setId === name) this.delete(id); From 023637e03fa1a6b7f760e0b276320e71fb139f3b Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Thu, 3 Dec 2026 12:35:28 -0500 Subject: [PATCH 10/22] update 7tv gql imports --- packages/plugin-7tv/.gitignore | 1 + packages/plugin-7tv/src/emotes.ts | 2 +- .../plugin-7tv/src/{graphql/index.ts => gql.ts} | 15 ++++++++++----- packages/plugin-7tv/src/index.ts | 4 ++-- packages/plugin-7tv/tsconfig.json | 4 ++-- 5 files changed, 16 insertions(+), 10 deletions(-) create mode 100644 packages/plugin-7tv/.gitignore rename packages/plugin-7tv/src/{graphql/index.ts => gql.ts} (94%) diff --git a/packages/plugin-7tv/.gitignore b/packages/plugin-7tv/.gitignore new file mode 100644 index 00000000..cc06060c --- /dev/null +++ b/packages/plugin-7tv/.gitignore @@ -0,0 +1 @@ +gql-*.d.ts diff --git a/packages/plugin-7tv/src/emotes.ts b/packages/plugin-7tv/src/emotes.ts index 3b1fce5b..0f38265f 100644 --- a/packages/plugin-7tv/src/emotes.ts +++ b/packages/plugin-7tv/src/emotes.ts @@ -1,6 +1,6 @@ import type { EmoteData } from "@usehyperion/plugin"; -import type { Emote } from "./graphql"; +import type { Emote } from "./gql"; import type { EmoteChange } from "./types"; import { fileUrl } from "./types"; diff --git a/packages/plugin-7tv/src/graphql/index.ts b/packages/plugin-7tv/src/gql.ts similarity index 94% rename from packages/plugin-7tv/src/graphql/index.ts rename to packages/plugin-7tv/src/gql.ts index 20a4d68f..350bddde 100644 --- a/packages/plugin-7tv/src/graphql/index.ts +++ b/packages/plugin-7tv/src/gql.ts @@ -7,14 +7,22 @@ const ENDPOINT = "https://7tv.io/v4/gql"; const gql = initGraphQLTada<{ disableMasking: true; - introspection: import("./7tv-env").introspection; + introspection: import("./gql-env").introspection; scalars: { Id: string; DateTime: string; }; }>(); -type GqlResponse = { data: T; errors?: never } | { data?: never; errors: { message: string }[] }; +type GqlResponse = + | { + data: T; + errors?: never; + } + | { + data?: never; + errors: { message: string }[]; + }; type NonNullableDeep = P extends `${infer K}.${infer R}` ? K extends keyof T @@ -30,9 +38,6 @@ export type Query = ( signal?: AbortSignal, ) => Promise; -/** - * Runs queries against 7TV's GraphQL API. - */ export function createQuery(http: PluginHttp): Query { return async function query( document: TadaDocumentNode, diff --git a/packages/plugin-7tv/src/index.ts b/packages/plugin-7tv/src/index.ts index 61862d47..87649c88 100644 --- a/packages/plugin-7tv/src/index.ts +++ b/packages/plugin-7tv/src/index.ts @@ -10,7 +10,7 @@ import { } from "@usehyperion/plugin"; import type { ComponentProps } from "svelte"; -import type { ActiveEmoteSet } from "./graphql"; +import type { ActiveEmoteSet } from "./gql"; import type { EmbeddedEmote, EmoteEmbedData, EventMap, SevenTvUser } from "./types"; import EmoteEmbed from "./components/EmoteEmbed.svelte"; @@ -26,7 +26,7 @@ import { globalEmoteSetQuery, globalEmoteSetVersionQuery, userEmoteSetsQuery, -} from "./graphql"; +} from "./gql"; import logo from "./logo.svg"; import { EventSocket, type Condition } from "./socket"; import { fileUrl, twitchConnection } from "./types"; diff --git a/packages/plugin-7tv/tsconfig.json b/packages/plugin-7tv/tsconfig.json index 63b76eb2..1abc3ce3 100644 --- a/packages/plugin-7tv/tsconfig.json +++ b/packages/plugin-7tv/tsconfig.json @@ -7,8 +7,8 @@ "shouldCheckForColocatedFragments": false, "trackFieldUsage": false, "schema": "https://7tv.io/v4/gql", - "tadaOutputLocation": "./src/graphql/7tv-env.d.ts", - "tadaTurboLocation": "./src/graphql/7tv-cache.d.ts" + "tadaOutputLocation": "./src/gql-env.d.ts", + "tadaTurboLocation": "./src/gql-cache.d.ts" } ] }, From 13840557d6b035396693968980f895fad4b91674 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Thu, 3 Dec 2026 12:46:22 -0500 Subject: [PATCH 11/22] remove redundant plugin toggle --- .../components/settings/custom/plugins/PluginDialog.svelte | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/lib/components/settings/custom/plugins/PluginDialog.svelte b/src/lib/components/settings/custom/plugins/PluginDialog.svelte index fa1d0d34..886f0bc2 100644 --- a/src/lib/components/settings/custom/plugins/PluginDialog.svelte +++ b/src/lib/components/settings/custom/plugins/PluginDialog.svelte @@ -6,8 +6,6 @@ import FieldControl from "#lib/components/settings/FieldControl.svelte"; import Button from "#lib/components/ui/Button.svelte"; import Dialog from "#lib/components/ui/Dialog.svelte"; - import Field from "#lib/components/ui/Field.svelte"; - import Switch from "#lib/components/ui/Switch.svelte"; import { dialogs } from "#lib/dialog.js"; import { settings } from "#lib/settings.js"; import { parseMarkdown } from "#lib/util/index.js"; @@ -50,10 +48,6 @@
{#snippet footer()} - - - - {#snippet render({ props })} From 4c3a1d5e23b46f877a003fc8829ca2b57c7a07f3 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Thu, 3 Dec 2026 12:55:10 -0500 Subject: [PATCH 12/22] nit --- src/hooks.client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks.client.ts b/src/hooks.client.ts index 32cb5da1..63157d00 100644 --- a/src/hooks.client.ts +++ b/src/hooks.client.ts @@ -14,7 +14,7 @@ dayjs.extend(relativeTime); export async function init() { // Settings need to be started before plugins so their settings are loaded - // before they start. + // before they're read. await settings.start().catch(log.swallow("Failed to load settings")); startPlugins(); From 768609ec28700d0ce42a370d7d469b4e4277d186 Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Thu, 3 Dec 2026 13:58:21 -0500 Subject: [PATCH 13/22] nit --- src/lib/managers/base-emote-manager.ts | 2 +- src/lib/models/message/parse.ts | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/lib/managers/base-emote-manager.ts b/src/lib/managers/base-emote-manager.ts index 23d44cd3..2e7c57da 100644 --- a/src/lib/managers/base-emote-manager.ts +++ b/src/lib/managers/base-emote-manager.ts @@ -12,7 +12,7 @@ import { latest, type Latest } from "#lib/util/resource.js"; export type ScopedSource = (ctx: EmoteSourceContext) => Promise; /** - * Emotes from the registered providers keyed by the name they're typed as. + * Emotes from the registered providers keyed by their name. */ export abstract class BaseEmoteManager extends SvelteMap { /** diff --git a/src/lib/models/message/parse.ts b/src/lib/models/message/parse.ts index c6453ef4..26139366 100644 --- a/src/lib/models/message/parse.ts +++ b/src/lib/models/message/parse.ts @@ -236,7 +236,10 @@ function personalEmote(userId: string, name: string): Emote | undefined { if (!provider.personal || !provider.enabled()) continue; const emote = provider.personal(userId, name); - if (emote) return { ...emote, provider: provider.name }; + + if (emote) { + return { ...emote, provider: provider.name }; + } } return undefined; From d8cff16eac0fa810ea50deb3319bc93a777ac11f Mon Sep 17 00:00:00 2001 From: Oliver Rose Date: Thu, 3 Dec 2026 14:10:38 -0500 Subject: [PATCH 14/22] remove useless type alias --- .../components/emote-picker/EmotePicker.svelte | 6 +++--- src/lib/emotes.ts | 16 +++++----------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/src/lib/components/emote-picker/EmotePicker.svelte b/src/lib/components/emote-picker/EmotePicker.svelte index 8cf925df..5640f344 100644 --- a/src/lib/components/emote-picker/EmotePicker.svelte +++ b/src/lib/components/emote-picker/EmotePicker.svelte @@ -1,7 +1,7 @@