π¬ A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots π
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
feat(export): add a text-to-speech provider registry
davbio500d10d038b4
diff --git a/src/core/capture/ai/validate.ts b/src/core/capture/ai/validate.tsindex c720424..b94ac59 100644--- a/src/core/capture/ai/validate.ts+++ b/src/core/capture/ai/validate.ts@@ -25,11 +25,15 @@ const PROTOCOL_HEADERS: Record<AIProtocol, (key: string) => Record<string, strin}),};-const VOICE_ENDPOINTS: Record<string, { url: string; headers: (key: string) => Record<string, string> }> = {+const DIRECT_ENDPOINTS: Record<string, { url: string; headers: (key: string) => Record<string, string> }> = {groq: {url: 'https://api.groq.com/openai/v1/models',headers: (key) => ({ Authorization: `Bearer ${key}` }),},+ elevenlabs: {+ url: 'https://api.elevenlabs.io/v1/user',+ headers: (key) => ({ 'xi-api-key': key }),+ },};function parseModelIds(body: unknown): string[] | undefined {@@ -150,7 +154,7 @@ export async function validateApiKey(const config = findProvider(provider);if (!config) {- const endpoint = VOICE_ENDPOINTS[provider];+ const endpoint = DIRECT_ENDPOINTS[provider];if (!endpoint) {logger.error('No API key validation endpoint for provider', provider);return { valid: false, reason: 'network' };diff --git a/src/core/export/voiceover/__tests__/client.test.ts b/src/core/export/voiceover/__tests__/client.test.tsnew file mode 100644index 0000000..79bc4d3--- /dev/null+++ b/src/core/export/voiceover/__tests__/client.test.ts@@ -0,0 +1,109 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { fetchVoices, parseVoices, speechRequest, synthesizeSpeech } from '@/core/export/voiceover/client';+import type { VoiceoverConfig } from '@/core/export/voiceover/config';++const openai: VoiceoverConfig = {+ provider: 'openai',+ apiKey: 'sk-test',+ voiceId: 'alloy',+ modelId: 'gpt-4o-mini-tts',+ source: 'voiceover',+};++const eleven: VoiceoverConfig = {+ provider: 'elevenlabs',+ apiKey: 'sk_test',+ voiceId: '21m00Tcm4TlvDq8ikWAM',+ modelId: 'eleven_turbo_v2_5',+ source: 'voiceover',+};++afterEach(() => vi.unstubAllGlobals());++describe('speechRequest', () => {+ it('posts OpenAI the text as input, with the voice in the body', () => {+ const request = speechRequest(openai, 'Click Save');+ expect(request.url).toBe('https://api.openai.com/v1/audio/speech');+ expect(request.headers.Authorization).toBe('Bearer sk-test');+ expect(JSON.parse(request.body)).toEqual({+ model: 'gpt-4o-mini-tts',+ voice: 'alloy',+ input: 'Click Save',+ response_format: 'mp3',+ });+ });++ it('puts the ElevenLabs voice in the path and the key in its own header', () => {+ const request = speechRequest(eleven, 'Click Save');+ expect(request.url).toBe(+ 'https://api.elevenlabs.io/v1/text-to-speech/21m00Tcm4TlvDq8ikWAM?output_format=mp3_44100_128',+ );+ expect(request.headers['xi-api-key']).toBe('sk_test');+ expect(request.headers.Authorization).toBeUndefined();+ expect(JSON.parse(request.body)).toEqual({ text: 'Click Save', model_id: 'eleven_turbo_v2_5' });+ });++ it('escapes a voice id rather than splicing it into the path raw', () => {+ expect(speechRequest({ ...eleven, voiceId: 'a/../b' }, 'x').url).toContain('a%2F..%2Fb');+ });+});++describe('synthesizeSpeech', () => {+ const respond = (init: { ok: boolean; status?: number; body?: string }) => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => ({+ ok: init.ok,+ status: init.status ?? 200,+ text: async () => init.body ?? '',+ arrayBuffer: async () => new ArrayBuffer(8),+ })),+ );+ };++ it('returns the audio bytes on success', async () => {+ respond({ ok: true });+ expect((await synthesizeSpeech(openai, 'Click Save')).byteLength).toBe(8);+ });++ it('never repeats the response body for a rejected key, which can echo it back', async () => {+ respond({ ok: false, status: 401, body: '{"error":{"message":"Incorrect API key provided: sk-test123"}}' });++ await expect(synthesizeSpeech(openai, 'Click Save')).rejects.toThrow(/rejected the API key \(401\)/);+ await expect(synthesizeSpeech(openai, 'Click Save')).rejects.not.toThrow(/sk-test123/);+ });++ it('keeps the body for an error that explains something useful', async () => {+ respond({ ok: false, status: 422, body: 'voice_not_found' });+ await expect(synthesizeSpeech(eleven, 'Click Save')).rejects.toThrow(/ElevenLabs returned 422: voice_not_found/);+ });+});++describe('fetchVoices', () => {+ it('serves OpenAI the shipped list without a request', async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal('fetch', fetchSpy);++ expect((await fetchVoices('openai', 'sk-test')).map((voice) => voice.id)).toContain('alloy');+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});++describe('parseVoices', () => {+ it('keeps the entries that carry an id and drops the rest', () => {+ expect(+ parseVoices({+ voices: [{ voice_id: 'v1', name: 'Rachel' }, { voice_id: 'v2' }, { name: 'no id' }, null, 'nonsense'],+ }),+ ).toEqual([+ { id: 'v1', name: 'Rachel' },+ { id: 'v2', name: 'v2' },+ ]);+ });++ it('is empty for anything that is not a voice list', () => {+ expect(parseVoices(null)).toEqual([]);+ expect(parseVoices({ voices: 'nope' })).toEqual([]);+ expect(parseVoices({ detail: 'unauthorized' })).toEqual([]);+ });+});diff --git a/src/core/export/voiceover/__tests__/config.test.ts b/src/core/export/voiceover/__tests__/config.test.tsnew file mode 100644index 0000000..8e3a141--- /dev/null+++ b/src/core/export/voiceover/__tests__/config.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from 'vitest';+import {+ hasVoiceoverKey,+ parseVoiceoverKeys,+ resolveVoiceoverConfig,+ withVoiceoverKey,+} from '@/core/export/voiceover/config';+import { VOICEOVER_PROVIDERS } from '@/core/export/voiceover/providers';++describe('resolveVoiceoverConfig', () => {+ it('defaults to OpenAI, the key most users already hold', () => {+ expect(resolveVoiceoverConfig({}).provider).toBe('openai');+ });++ it('prefers a voice-over key of its own over the AI key', () => {+ const config = resolveVoiceoverConfig({+ voiceoverApiKeys: { openai: 'sk-own' },+ aiProvider: 'openai',+ aiApiKeys: { openai: 'sk-ai' },+ });+ expect(config).toMatchObject({ apiKey: 'sk-own', source: 'voiceover' });+ });++ it('borrows the OpenAI key already set for descriptions', () => {+ const config = resolveVoiceoverConfig({ aiProvider: 'openai', aiApiKeys: { openai: 'sk-ai' } });+ expect(config).toMatchObject({ apiKey: 'sk-ai', source: 'ai' });+ });++ it('never borrows across vendors', () => {+ expect(+ resolveVoiceoverConfig({+ voiceoverProvider: 'elevenlabs',+ aiProvider: 'openai',+ aiApiKeys: { openai: 'sk-ai' },+ }),+ ).toMatchObject({ apiKey: '', source: 'none' });++ expect(resolveVoiceoverConfig({ aiProvider: 'anthropic', aiApiKeys: { anthropic: 'sk-ant' } })).toMatchObject({+ apiKey: '',+ source: 'none',+ });+ });++ it('drops a voice id belonging to the other provider rather than sending it', () => {+ expect(+ resolveVoiceoverConfig({ voiceoverProvider: 'openai', voiceoverVoiceId: '21m00Tcm4TlvDq8ikWAM' }).voiceId,+ ).toBe(VOICEOVER_PROVIDERS.openai.defaultVoice);+ });++ it('keeps an ElevenLabs id it cannot verify, because the account catalog is larger than ours', () => {+ expect(+ resolveVoiceoverConfig({ voiceoverProvider: 'elevenlabs', voiceoverVoiceId: 'cloned-voice-42' }).voiceId,+ ).toBe('cloned-voice-42');+ });++ it('falls back to the provider default for a model it does not offer', () => {+ expect(resolveVoiceoverConfig({ voiceoverProvider: 'openai', voiceoverModelId: 'eleven_turbo_v2_5' }).modelId).toBe(+ VOICEOVER_PROVIDERS.openai.defaultModel,+ );+ });+});++describe('voice-over key storage', () => {+ it('keeps each provider key, so switching back does not lose one', () => {+ const keys = withVoiceoverKey({ openai: 'sk-a' }, 'elevenlabs', 'sk_b');+ expect(keys).toEqual({ openai: 'sk-a', elevenlabs: 'sk_b' });+ });++ it('clears a key when the field is emptied', () => {+ expect(withVoiceoverKey({ openai: 'sk-a' }, 'openai', ' ')).toEqual({});+ });++ it('ignores junk and unknown providers in storage', () => {+ expect(parseVoiceoverKeys({ openai: 'sk-a', bogus: 'x', elevenlabs: 42 })).toEqual({ openai: 'sk-a' });+ expect(parseVoiceoverKeys(null)).toEqual({});+ });++ it('reports no key when nothing is set anywhere', () => {+ expect(hasVoiceoverKey({})).toBe(false);+ expect(hasVoiceoverKey({ voiceoverApiKeys: { openai: 'sk-a' } })).toBe(true);+ });+});diff --git a/src/core/export/voiceover/client.ts b/src/core/export/voiceover/client.tsnew file mode 100644index 0000000..6b107e1--- /dev/null+++ b/src/core/export/voiceover/client.ts@@ -0,0 +1,94 @@+import type { VoiceoverConfig } from './config';+import { type VoiceoverProviderKey, type VoiceoverVoice, voiceoverProvider } from './providers';++const ERROR_BODY_LIMIT = 200;+const REQUEST_TIMEOUT_MS = 60_000;++export interface SpeechRequest {+ url: string;+ headers: Record<string, string>;+ body: string;+}++function authHeaders(provider: VoiceoverProviderKey, apiKey: string): Record<string, string> {+ return provider === 'elevenlabs' ? { 'xi-api-key': apiKey } : { Authorization: `Bearer ${apiKey}` };+}++export function speechRequest(config: VoiceoverConfig, text: string): SpeechRequest {+ const base = voiceoverProvider(config.provider).defaultBaseUrl;+ const headers = { ...authHeaders(config.provider, config.apiKey), 'Content-Type': 'application/json' };++ if (config.provider === 'elevenlabs') {+ return {+ url: `${base}/text-to-speech/${encodeURIComponent(config.voiceId)}?output_format=mp3_44100_128`,+ headers,+ body: JSON.stringify({ text, model_id: config.modelId }),+ };+ }++ return {+ url: `${base}/audio/speech`,+ headers,+ body: JSON.stringify({ model: config.modelId, voice: config.voiceId, input: text, response_format: 'mp3' }),+ };+}++function timeout(signal?: AbortSignal): AbortSignal {+ const limit = AbortSignal.timeout(REQUEST_TIMEOUT_MS);+ return signal ? AbortSignal.any([signal, limit]) : limit;+}++export async function synthesizeSpeech(+ config: VoiceoverConfig,+ text: string,+ signal?: AbortSignal,+): Promise<ArrayBuffer> {+ const request = speechRequest(config, text);+ const response = await fetch(request.url, {+ method: 'POST',+ headers: request.headers,+ body: request.body,+ signal: timeout(signal),+ });++ if (!response.ok) {+ const label = voiceoverProvider(config.provider).label;+ if (response.status === 401 || response.status === 403) {+ throw new Error(`${label} rejected the API key (${response.status})`);+ }+ const body = await response.text().catch(() => '');+ throw new Error(`${label} returned ${response.status}: ${body.slice(0, ERROR_BODY_LIMIT)}`);+ }++ return response.arrayBuffer();+}++export function parseVoices(body: unknown): VoiceoverVoice[] {+ if (typeof body !== 'object' || body === null) return [];+ const list = (body as { voices?: unknown }).voices;+ if (!Array.isArray(list)) return [];+ return list+ .map((entry) => {+ if (typeof entry !== 'object' || entry === null) return null;+ const { voice_id: id, name } = entry as { voice_id?: unknown; name?: unknown };+ if (typeof id !== 'string' || !id) return null;+ return { id, name: typeof name === 'string' && name ? name : id };+ })+ .filter((voice): voice is VoiceoverVoice => voice !== null);+}++export async function fetchVoices(+ provider: VoiceoverProviderKey,+ apiKey: string,+ signal?: AbortSignal,+): Promise<VoiceoverVoice[]> {+ const config = voiceoverProvider(provider);+ if (!config.catalog) return config.voices;++ const response = await fetch(`${config.defaultBaseUrl}/voices`, {+ headers: authHeaders(provider, apiKey),+ signal: timeout(signal),+ });+ if (!response.ok) throw new Error(`${config.label} returned ${response.status}`);+ return parseVoices(await response.json().catch(() => null));+}diff --git a/src/core/export/voiceover/config.ts b/src/core/export/voiceover/config.tsnew file mode 100644index 0000000..db4e9f5--- /dev/null+++ b/src/core/export/voiceover/config.ts@@ -0,0 +1,95 @@+import { resolveAiKey } from '@/core/capture/ai/keys';+import {+ isVoiceoverProvider,+ modelForProvider,+ type VoiceoverProviderKey,+ voiceForProvider,+ voiceoverProvider,+ voiceoverProviderOrDefault,+} from './providers';++export type VoiceoverApiKeys = Partial<Record<VoiceoverProviderKey, string>>;++export const VOICEOVER_SETTINGS = [+ 'voiceoverProvider',+ 'voiceoverApiKeys',+ 'voiceoverVoiceId',+ 'voiceoverModelId',+ 'aiApiKeys',+ 'aiApiKey',+ 'aiProvider',+] as const;++export interface VoiceoverSettings {+ voiceoverProvider?: unknown;+ voiceoverApiKeys?: unknown;+ voiceoverVoiceId?: unknown;+ voiceoverModelId?: unknown;+ aiApiKeys?: unknown;+ aiApiKey?: unknown;+ aiProvider?: unknown;+}++export type VoiceoverKeySource = 'voiceover' | 'ai' | 'none';++export interface VoiceoverConfig {+ provider: VoiceoverProviderKey;+ apiKey: string;+ voiceId: string;+ modelId: string;+ source: VoiceoverKeySource;+}++function trimmed(value: unknown): string {+ return typeof value === 'string' ? value.trim() : '';+}++export function parseVoiceoverKeys(value: unknown): VoiceoverApiKeys {+ if (typeof value !== 'object' || value === null) return {};+ const keys: VoiceoverApiKeys = {};+ for (const [provider, key] of Object.entries(value as Record<string, unknown>)) {+ if (!isVoiceoverProvider(provider)) continue;+ const key_ = trimmed(key);+ if (key_) keys[provider] = key_;+ }+ return keys;+}++export function keyForVoiceoverProvider(keys: VoiceoverApiKeys, provider: VoiceoverProviderKey): string {+ return keys[provider] ?? '';+}++export function withVoiceoverKey(+ keys: VoiceoverApiKeys,+ provider: VoiceoverProviderKey,+ apiKey: string,+): VoiceoverApiKeys {+ const next = { ...keys };+ if (apiKey.trim()) next[provider] = apiKey;+ else delete next[provider];+ return next;+}++export function resolveVoiceoverConfig(stored: VoiceoverSettings): VoiceoverConfig {+ const provider = voiceoverProviderOrDefault(stored.voiceoverProvider);+ const voiceId = voiceForProvider(provider, trimmed(stored.voiceoverVoiceId));+ const modelId = modelForProvider(provider, trimmed(stored.voiceoverModelId));++ const own = keyForVoiceoverProvider(parseVoiceoverKeys(stored.voiceoverApiKeys), provider);+ if (own) return { provider, apiKey: own, voiceId, modelId, source: 'voiceover' };++ const ai = resolveAiKey(stored);+ if (provider === 'openai' && ai.provider === 'openai' && ai.apiKey) {+ return { provider, apiKey: ai.apiKey, voiceId, modelId, source: 'ai' };+ }++ return { provider, apiKey: '', voiceId, modelId, source: 'none' };+}++export function hasVoiceoverKey(stored: VoiceoverSettings): boolean {+ return resolveVoiceoverConfig(stored).apiKey.length > 0;+}++export function voiceoverKeyPlaceholder(provider: VoiceoverProviderKey): string {+ return voiceoverProvider(provider).keyPlaceholder;+}diff --git a/src/core/export/voiceover/providers.ts b/src/core/export/voiceover/providers.tsnew file mode 100644index 0000000..2da6edd--- /dev/null+++ b/src/core/export/voiceover/providers.ts@@ -0,0 +1,98 @@+export interface VoiceoverModelOption {+ id: string;+ label: string;+}++export interface VoiceoverVoice {+ id: string;+ name: string;+}++export interface VoiceoverProviderConfig {+ label: string;+ defaultBaseUrl: string;+ defaultModel: string;+ models: VoiceoverModelOption[];+ voices: VoiceoverVoice[];+ defaultVoice: string;+ catalog: boolean;+ keyPlaceholder: string;+}++export const VOICEOVER_PROVIDERS = {+ openai: {+ label: 'OpenAI',+ defaultBaseUrl: 'https://api.openai.com/v1',+ defaultModel: 'gpt-4o-mini-tts',+ models: [+ { id: 'gpt-4o-mini-tts', label: 'GPT-4o Mini TTS' },+ { id: 'tts-1', label: 'TTS-1' },+ { id: 'tts-1-hd', label: 'TTS-1 HD' },+ ],+ voices: [+ { id: 'alloy', name: 'Alloy' },+ { id: 'ash', name: 'Ash' },+ { id: 'coral', name: 'Coral' },+ { id: 'echo', name: 'Echo' },+ { id: 'fable', name: 'Fable' },+ { id: 'nova', name: 'Nova' },+ { id: 'onyx', name: 'Onyx' },+ { id: 'sage', name: 'Sage' },+ { id: 'shimmer', name: 'Shimmer' },+ ],+ defaultVoice: 'alloy',+ catalog: false,+ keyPlaceholder: 'sk-...',+ },+ elevenlabs: {+ label: 'ElevenLabs',+ defaultBaseUrl: 'https://api.elevenlabs.io/v1',+ defaultModel: 'eleven_turbo_v2_5',+ models: [+ { id: 'eleven_turbo_v2_5', label: 'Turbo v2.5' },+ { id: 'eleven_multilingual_v2', label: 'Multilingual v2' },+ { id: 'eleven_flash_v2_5', label: 'Flash v2.5' },+ ],+ voices: [+ { id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel' },+ { id: 'EXAVITQu4vr4xnSDxMaL', name: 'Sarah' },+ { id: 'onwK4e9ZLuTAKqWW03F9', name: 'Daniel' },+ { id: 'pNInz6obpgDQGcFmaJgB', name: 'Adam' },+ { id: 'ThT5KcBeYPX3keUQqHPh', name: 'Dorothy' },+ { id: 'ErXwobaYiN019PkySvjV', name: 'Antoni' },+ ],+ defaultVoice: '21m00Tcm4TlvDq8ikWAM',+ catalog: true,+ keyPlaceholder: 'sk_...',+ },+} satisfies Record<string, VoiceoverProviderConfig>;++export type VoiceoverProviderKey = keyof typeof VOICEOVER_PROVIDERS;++export const DEFAULT_VOICEOVER_PROVIDER: VoiceoverProviderKey = 'openai';++export const VOICEOVER_PROVIDER_KEYS = Object.keys(VOICEOVER_PROVIDERS) as VoiceoverProviderKey[];++export function isVoiceoverProvider(value: unknown): value is VoiceoverProviderKey {+ return typeof value === 'string' && value in VOICEOVER_PROVIDERS;+}++export function voiceoverProviderOrDefault(value: unknown): VoiceoverProviderKey {+ return isVoiceoverProvider(value) ? value : DEFAULT_VOICEOVER_PROVIDER;+}++export function voiceoverProvider(key: VoiceoverProviderKey): VoiceoverProviderConfig {+ return VOICEOVER_PROVIDERS[key];+}++export function voiceForProvider(key: VoiceoverProviderKey, voiceId: string): string {+ const config = VOICEOVER_PROVIDERS[key];+ if (!voiceId) return config.defaultVoice;+ if (config.catalog) return voiceId;+ return config.voices.some((voice) => voice.id === voiceId) ? voiceId : config.defaultVoice;+}++export function modelForProvider(key: VoiceoverProviderKey, modelId: string): string {+ const config = VOICEOVER_PROVIDERS[key];+ return config.models.some((model) => model.id === modelId) ? modelId : config.defaultModel;+}diff --git a/src/entrypoints/background/index.ts b/src/entrypoints/background/index.tsindex b8da5eb..aacc95d 100644--- a/src/entrypoints/background/index.ts+++ b/src/entrypoints/background/index.ts@@ -207,6 +207,11 @@ export default defineBackground(() => {onMessage('validateApiKey', ({ data }) => validateApiKey(data.provider, data.apiKey, data.baseUrl, data.model));+ onMessage('listVoices', async ({ data }) => {+ const { fetchVoices } = await import('@/core/export/voiceover/client');+ return { voices: await fetchVoices(data.provider, data.apiKey).catch(() => []) };+ });+onMessage('rewriteSelection', ({ data }) => rewriteSelection(data.text, data.instruction));onMessage('captureStep', async ({ data }) => {diff --git a/src/lib/messaging.ts b/src/lib/messaging.tsindex e6ef5de..dc00718 100644--- a/src/lib/messaging.ts+++ b/src/lib/messaging.ts@@ -1,6 +1,7 @@import { defineExtensionMessaging } from '@webext-core/messaging';import type { DOMContext } from '@/core/capture/dom/context';import type { CaptureStateValue, PauseReason } from '@/core/capture/machine';+import type { VoiceoverProviderKey } from '@/core/export/voiceover/providers';import type { ElementMeta } from '@/core/guides/types';export interface GetStateResponse {@@ -122,6 +123,15 @@ export interface ValidateApiKeyResponse {warning?: 'cannot-spend';}+export interface ListVoicesData {+ provider: VoiceoverProviderKey;+ apiKey: string;+}++export interface ListVoicesResponse {+ voices: { id: string; name: string }[];+}+export interface EnterBlurModeResponse {entered: boolean;}@@ -160,6 +170,7 @@ interface MimikProtocol {startNarration(): StartNarrationResponse;generateGuideDescription(data: GenerateGuideDescriptionData): GenerateGuideDescriptionResponse;validateApiKey(data: ValidateApiKeyData): ValidateApiKeyResponse;+ listVoices(data: ListVoicesData): ListVoicesResponse;rewriteSelection(data: RewriteSelectionData): RewriteSelectionResponse;}