Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions ui/src/applet-core/hooks/useAppletExtensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useMemo } from 'react';
import { useAppletContext } from '../context/AppletContext';

export function useAppletExtensions<
TExtensions extends Record<string, unknown> = Record<string, unknown>,
>(): TExtensions {
const { extensions } = useAppletContext();

return useMemo(
() => ((extensions ?? {}) as TExtensions),
[extensions],
);
}
43 changes: 43 additions & 0 deletions ui/src/applet-core/hooks/useAppletRPCClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useMemo } from 'react';
import { createAppletRPCClient, type AppletRPCSchema } from '../../applet-host/rpc';
import { useAppletContext } from '../context/AppletContext';

export interface UseAppletRPCClientOptions {
endpoint?: string
timeoutMs?: number
fetcher?: typeof fetch
}

export function useAppletRPCClient<
TRouter extends AppletRPCSchema = AppletRPCSchema,
>(options: UseAppletRPCClientOptions = {}) {
const { config, session } = useAppletContext();
const endpoint = options.endpoint ?? config.rpcUIEndpoint ?? '/rpc';
const baseFetcher = options.fetcher ?? fetch;
const csrfToken = session.csrfToken;

return useMemo(() => {
const fetcher: typeof fetch = async (input, init) => {
const headers = new Headers(init?.headers ?? undefined);
if (csrfToken !== '' && !headers.has('X-CSRF-Token')) {
headers.set('X-CSRF-Token', csrfToken);
}

return baseFetcher(input, {
...init,
headers,
});
};

return createAppletRPCClient({
endpoint,
timeoutMs: options.timeoutMs,
fetcher,
}) as ReturnType<typeof createAppletRPCClient> & {
callTyped<TMethod extends keyof TRouter & string>(
method: TMethod,
params: TRouter[TMethod]['params']
): Promise<TRouter[TMethod]['result']>
};
}, [baseFetcher, csrfToken, endpoint, options.timeoutMs]);
}
2 changes: 2 additions & 0 deletions ui/src/applet-core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export { ConfigProvider, useConfigContext } from './context/ConfigProvider';

// Hooks
export { useAppletContext as useAppletContextDirect } from './hooks/useAppletContext';
export { useAppletExtensions } from './hooks/useAppletExtensions';
export { useAppletRPCClient, type UseAppletRPCClientOptions } from './hooks/useAppletRPCClient';
export { useConfig } from './hooks/useConfig';
export { useUser } from './hooks/useUser';
export { usePermissions } from './hooks/usePermissions';
Expand Down
Loading