Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
fix(admin): surface plugin registry install errors
Gabe Kangasd2ad6601b7a2
diff --git a/web/pages/admin/plugins.tsx b/web/pages/admin/plugins.tsxindex 04591c977a..ae85f50026 100644--- a/web/pages/admin/plugins.tsx+++ b/web/pages/admin/plugins.tsx@@ -250,20 +250,25 @@ const Plugins = () => {// surface the same post-install confirmation flow.const installFromRegistry = useCallback(async (slug: string, version: string) => {- const entry = (await fetchData(PLUGIN_REGISTRY_INSTALL, {- method: 'POST',- data: { slug, version },- })) as Plugin;- message.success(t(Localization.Admin.Plugins.uploadSuccess, { name: entry.name }));- await loadPlugins();- await loadRegistry();- // Only prompt to enable for plugins that aren't already- // running. Updates of enabled plugins keep their enabled state- // unless the new manifest expanded permissions (in which case- // the host marks them auto-disabled and the modal shows the- // new perms).- if (!entry.enabled) {- setPendingEnable(entry);+ try {+ const entry = (await fetchData(PLUGIN_REGISTRY_INSTALL, {+ method: 'POST',+ data: { slug, version },+ })) as Plugin;+ setError(null);+ message.success(t(Localization.Admin.Plugins.uploadSuccess, { name: entry.name }));+ await loadPlugins();+ await loadRegistry();+ // Only prompt to enable for plugins that aren't already+ // running. Updates of enabled plugins keep their enabled state+ // unless the new manifest expanded permissions (in which case+ // the host marks them auto-disabled and the modal shows the+ // new perms).+ if (!entry.enabled) {+ setPendingEnable(entry);+ }+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e));}},[loadPlugins, loadRegistry, t],diff --git a/web/tests/apis.test.ts b/web/tests/apis.test.tsnew file mode 100644index 0000000000..590278e7e7--- /dev/null+++ b/web/tests/apis.test.ts@@ -0,0 +1,26 @@+import { extractAPIErrorMessage } from '../utils/apis';++describe('extractAPIErrorMessage', () => {+ test('prefers backend error field when present', () => {+ expect(+ extractAPIErrorMessage(400, {+ error: 'manifest.scripts requires the "http.serve" permission',+ message: 'generic message',+ }),+ ).toBe('manifest.scripts requires the "http.serve" permission');+ });++ test('falls back to backend message when error is absent', () => {+ expect(extractAPIErrorMessage(502, { message: 'registry unavailable' })).toBe(+ 'registry unavailable',+ );+ });++ test('falls back to response text when body is not structured json', () => {+ expect(extractAPIErrorMessage(500, null, 'plain text failure')).toBe('plain text failure');+ });++ test('falls back to generic status when no detail exists', () => {+ expect(extractAPIErrorMessage(418, null, '')).toBe('An error has occurred: 418');+ });+});diff --git a/web/tests/plugins-page.test.tsx b/web/tests/plugins-page.test.tsxnew file mode 100644index 0000000000..817027a366--- /dev/null+++ b/web/tests/plugins-page.test.tsx@@ -0,0 +1,98 @@+import React from 'react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import Plugins from '../pages/admin/plugins';+import {+ fetchData,+ PLUGINS_LIST,+ PLUGIN_REGISTRY_INSTALL,+ PLUGIN_REGISTRY_LIST,+} from '../utils/apis';++jest.mock('../pages/admin/plugins.module.scss', () => ({+ errorAlert: 'errorAlert',+}));++jest.mock('next/router', () => ({+ useRouter: () => ({+ push: jest.fn(),+ }),+}));++jest.mock('next-export-i18n', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++jest.mock('../components/layouts/AdminLayout', () => ({+ AdminLayout: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}));++jest.mock('../components/admin/plugins/PluginsList', () => ({+ PluginsList: ({+ onUpdate,+ }: {+ onUpdate?: (plugin: any, version: string) => Promise<void> | void;+ }) => (+ <button+ type="button"+ onClick={() =>+ onUpdate?.(+ { slug: 'scripts-demo', name: 'Example Scripts Demo', version: '0.1.0' },+ '0.2.0',+ )+ }+ >+ trigger update+ </button>+ ),+}));++jest.mock('../components/admin/plugins/BrowseRegistry', () => ({+ BrowseRegistry: () => <div>browse registry</div>,+}));++jest.mock('../components/admin/plugins/InstallConfirmModal', () => ({+ InstallConfirmModal: () => null,+}));++jest.mock('../utils/apis', () => {+ const actual = jest.requireActual('../utils/apis');+ return {+ ...actual,+ fetchData: jest.fn(),+ };+});++const mockedFetchData = fetchData as jest.MockedFunction<typeof fetchData>;++describe('Plugins admin page', () => {+ beforeEach(() => {+ mockedFetchData.mockReset();+ });++ test('surfaces registry install errors to the admin page', async () => {+ mockedFetchData.mockImplementation(async url => {+ if (url === PLUGINS_LIST) {+ return [];+ }+ if (url === PLUGIN_REGISTRY_LIST) {+ return [];+ }+ if (url === PLUGIN_REGISTRY_INSTALL) {+ throw new Error('invalid manifest: manifest.scripts requires the "http.serve" permission');+ }+ throw new Error(`unexpected fetchData call: ${url}`);+ });++ render(<Plugins />);++ fireEvent.click(await screen.findByText('trigger update'));++ await waitFor(() => {+ expect(+ screen.getByText('invalid manifest: manifest.scripts requires the "http.serve" permission'),+ ).toBeInTheDocument();+ });+ });+});diff --git a/web/utils/apis.ts b/web/utils/apis.tsindex 0674f19581..31e4fb84b4 100644--- a/web/utils/apis.ts+++ b/web/utils/apis.ts@@ -134,6 +134,23 @@ interface FetchOptions {auth?: boolean;}+export function extractAPIErrorMessage(status: number, body?: any, fallbackText = '') {+ if (body && typeof body === 'object') {+ if (typeof body.error === 'string' && body.error.trim() !== '') {+ return body.error;+ }+ if (typeof body.message === 'string' && body.message.trim() !== '') {+ return body.message;+ }+ }++ if (fallbackText.trim() !== '') {+ return fallbackText;+ }++ return `An error has occurred: ${status}`;+}+export async function fetchData(url: string, options?: FetchOptions) {const { data, method = 'GET', auth = true } = options || {};@@ -156,11 +173,18 @@ export async function fetchData(url: string, options?: FetchOptions) {}const response = await fetch(url, requestOptions);- const json = await response.json();+ const text = await response.text();+ let json = {};+ if (text) {+ try {+ json = JSON.parse(text);+ } catch {+ json = {};+ }+ }if (!response.ok) {- const message = json.message || `An error has occurred: ${response.status}`;- throw new Error(message);+ throw new Error(extractAPIErrorMessage(response.status, json, text));}return json;}