@vocalstack/payload 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/api.d.ts +171 -0
  4. package/dist/api.js +178 -0
  5. package/dist/components/Brand.d.ts +13 -0
  6. package/dist/components/Brand.js +19 -0
  7. package/dist/components/ConnectionPanel.d.ts +3 -0
  8. package/dist/components/ConnectionPanel.js +41 -0
  9. package/dist/components/SpeechField.d.ts +7 -0
  10. package/dist/components/SpeechField.js +177 -0
  11. package/dist/components/TranscribeButton.d.ts +8 -0
  12. package/dist/components/TranscribeButton.js +197 -0
  13. package/dist/components/TranscriptField.d.ts +3 -0
  14. package/dist/components/TranscriptField.js +167 -0
  15. package/dist/components/VoiceField.d.ts +1 -0
  16. package/dist/components/VoiceField.js +226 -0
  17. package/dist/components/brandAssets.d.ts +11 -0
  18. package/dist/components/brandAssets.js +6 -0
  19. package/dist/components/useConnection.d.ts +11 -0
  20. package/dist/components/useConnection.js +59 -0
  21. package/dist/endpoints/connection.d.ts +14 -0
  22. package/dist/endpoints/connection.js +132 -0
  23. package/dist/endpoints/speech.d.ts +12 -0
  24. package/dist/endpoints/speech.js +392 -0
  25. package/dist/endpoints/stream.d.ts +14 -0
  26. package/dist/endpoints/stream.js +180 -0
  27. package/dist/endpoints/transcribe.d.ts +33 -0
  28. package/dist/endpoints/transcribe.js +268 -0
  29. package/dist/endpoints/voices.d.ts +20 -0
  30. package/dist/endpoints/voices.js +275 -0
  31. package/dist/exports/client.d.ts +5 -0
  32. package/dist/exports/client.js +6 -0
  33. package/dist/fileSource.d.ts +12 -0
  34. package/dist/fileSource.js +40 -0
  35. package/dist/index.d.ts +7 -0
  36. package/dist/index.js +184 -0
  37. package/dist/readings.d.ts +6 -0
  38. package/dist/readings.js +24 -0
  39. package/dist/settings.d.ts +20 -0
  40. package/dist/settings.js +47 -0
  41. package/dist/text.d.ts +29 -0
  42. package/dist/text.js +78 -0
  43. package/dist/types.d.ts +218 -0
  44. package/dist/types.js +1 -0
  45. package/package.json +47 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VocalStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ # @vocalstack/payload
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ VocalStack for [Payload CMS](https://payloadcms.com) 3: a **Transcribe** button on every audio upload. The transcript is saved on the document as text plus timed sentences.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @vocalstack/payload
9
+ ```
10
+
11
+ ```ts
12
+ // payload.config.ts
13
+ import { vocalstackPlugin } from '@vocalstack/payload'
14
+
15
+ export default buildConfig({
16
+ plugins: [
17
+ vocalstackPlugin({
18
+ // Optional. Without it, connect from Admin → Settings → VocalStack.
19
+ apiKey: process.env.VOCALSTACK_API_KEY,
20
+ }),
21
+ ],
22
+ })
23
+ ```
24
+
25
+ Then run `payload generate:importmap`. The plugin adds fields to the targeted collections and a `vocalstack` global, so with Postgres also run `payload migrate:create`.
26
+
27
+ ## What it adds
28
+
29
+ - **Every upload collection that accepts audio** (`audio/*`, a wildcard, or no restriction), or the ones in `collections`, gets:
30
+ - a sidebar **Transcribe** button, shown on `audio/*` documents only. It shows progress and survives a reload mid-job, and **Stop** ends a job you no longer want: the document goes back to how it was (an earlier transcript stays), and VocalStack keeps what it transcribed before the stop.
31
+ - a `vocalstack` group:
32
+ - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
33
+ - `sentences`: `[{ start, end, speaker, text }]` in seconds.
34
+ - `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
35
+ - `POST /api/{collection}/:id/vocalstack/transcribe`, `POST …/vocalstack/stop`, `GET …/vocalstack/status` and `GET …/vocalstack/stream` (live progress as Server-Sent Events).
36
+ - **Translations and readings**, under every finished transcript: translate it into any of 100 languages, and have the translation read aloud (in a cloned voice, or one of VocalStack's). Saved in the `vocalstack` group as:
37
+ - `translations`: `{ [lang]: { translatedAt, sentences } }`, the transcript's sentences (same ids and times) translated.
38
+ - `speech`: `{ [lang]: { voice, state, error, durationS, requestedAt, renderedAt, sentences } }`. `state` is `queued`, `running`, `failed` or `sealed`; once sealed, `sentences` are the translation in the reading's own timing, with words, for a read-along player.
39
+ - `POST …/vocalstack/translate { langs }` (answers `more: true` when it stopped for time; call again), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs, voice? }`, `GET …/vocalstack/speak`, and the public `GET …/vocalstack/audio?lang=`, which redirects to the reading's MP3 (or, with no `lang` or the spoken one, the recording's audio) for anyone who may read the document.
40
+ - **Voices** (opt in with `voices`): documents of a collection of people get a sidebar panel to clone that person's voice from a minute of a recording they speak in, or from an uploaded sample, with their permission. Kept in a hidden `vocalstackVoice` group (`voiceId`, `state`: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/voice`, `…/voice/sources` and `…/voice/preview`.
41
+ - **Settings → VocalStack** (a global), where an editor connects an account. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
42
+
43
+ ## Options
44
+
45
+ | Option | Default | |
46
+ |---|---|---|
47
+ | `apiKey` | none | A `vs_key_…` key with Read and Write. It wins over a key connected in the admin. |
48
+ | `collections` | every upload collection that accepts audio | Which upload collections get the button. |
49
+ | `audioFields` | none | Audio that isn't an upload document; see below. |
50
+ | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
51
+ | `fileURL` | the doc's `url`, made absolute | `({ doc, collection, req }) => string`: the address VocalStack fetches. Point it at your bucket's public URL to skip the Payload file proxy. |
52
+ | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, voices and the admin lookups, and for changing the connection. |
53
+ | `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
54
+ | `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
55
+ | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
56
+ | `voices` | none | Collections of people who get a cloned voice; see below. |
57
+ | `readings` | `{ slug: 'vocalstack-readings' }` | The upload collection finished readings are kept in, added by the plugin; `overrides: (collection) => collection` adjusts it. `false` streams readings from VocalStack instead. See below for bringing your own. |
58
+ | `speechVoice` | VocalStack's default | `({ collection, doc, row, req }) => voice`: the voice a transcript's translations are read in, e.g. its speaker's (`clonedVoiceKey(person.vocalstackVoice)`). |
59
+
60
+ ### Audio that isn't an upload
61
+
62
+ Imported content often points at files by name or link instead of upload documents. `audioFields` gives each row of an array field its own button and `vocalstack` transcript:
63
+
64
+ ```ts
65
+ vocalstackPlugin({
66
+ audioFields: [
67
+ {
68
+ collection: 'episodes',
69
+ field: 'attachments', // a top-level array (tabs, rows and collapsibles are looked through)
70
+ condition: (row) => row.type === 'file',
71
+ audioURL: ({ row }) => (row.filename ? `https://cdn.example.com/episodes/${encodeURIComponent(String(row.filename))}` : undefined),
72
+ },
73
+ ],
74
+ })
75
+ ```
76
+
77
+ Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
78
+
79
+ ### Voices
80
+
81
+ ```ts
82
+ import { clonedVoiceKey, vocalstackPlugin } from '@vocalstack/payload'
83
+
84
+ vocalstackPlugin({
85
+ voices: [
86
+ {
87
+ collection: 'speakers',
88
+ // Recordings this speaker is in, offered as the sample to clone from.
89
+ recordings: async ({ doc, req }) => {
90
+ const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
91
+ return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences }] : []))
92
+ },
93
+ },
94
+ ],
95
+ // Read each episode's translations in its speaker's voice, once there is one.
96
+ speechVoice: async ({ doc, req }) => {
97
+ const speaker = await req.payload.findByID({ collection: 'speakers', id: doc.speaker as number, req })
98
+ return clonedVoiceKey(speaker.vocalstackVoice)
99
+ },
100
+ })
101
+ ```
102
+
103
+ A sample from a recording can only come from the recordings `recordings` returns for that document: cloning, and hearing a stretch first (`GET /:id/vocalstack/voice/clip`), refuse any other.
104
+
105
+ Cloning needs at least 30 seconds of the person speaking alone (a minute is better, at most two), and the editor confirms they have the person's permission. From a recording, the editor clicks where the stretch starts and hears it before cloning; the plugin takes it from VocalStack. An uploaded sample is sent through your server, so on hosts that cap request bodies (Vercel: 4.5 MB) keep it to a minute or two of MP3 or M4A. Training takes a few minutes; the panel follows it. Deleting the voice deletes it in VocalStack too.
106
+
107
+ ### Translations and readings
108
+
109
+ Translating an hour-long transcript takes a few minutes; the admin keeps calling until it is done, and what is translated is saved as it goes. A reading is rendered by VocalStack (a few languages at a time per recording) and saved once ready. The reading keeps each sentence where it was said, unless the one before still runs, so a player can follow along with `speech[lang].sentences` (`timedTokens()` works on them as on the transcript).
110
+
111
+ **Everything is asked for once and kept.** The transcript (text, sentences, word times) and each translation are saved on the document. Translating again only asks for sentences that have none, and reads ones VocalStack already translated back from `/transcript?lang=` rather than translating them again. A finished reading's MP3 is downloaded once and saved as an upload in the `vocalstack-readings` collection (option `readings`), so listeners are served from your storage: `GET …/vocalstack/audio` redirects to that file, or for the spoken language to your own audio file, and only falls back to VocalStack while a reading isn't kept yet. Point your storage adapter at the readings collection, e.g. `s3Storage({ collections: { 'vocalstack-readings': { prefix: 'readings', disablePayloadAccessControl: true } } })` for direct public URLs.
112
+
113
+ **The readings collection.** By default the plugin adds `vocalstack-readings`: public read, and create, update and delete for signed-in users. Change it with `readings: { overrides: (collection) => ({ ...collection, access: { ... } }) }`, or define an upload collection with that slug (or `readings.slug`) yourself; the plugin then uses yours as it is. It needs to accept `audio/mpeg` and to have text fields `lang`, `recordingId` and `voice`.
114
+
115
+ When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
116
+
117
+ **How the audio reaches VocalStack.** If the file has a public address, VocalStack fetches it (`POST /v1/transcriptions { url }`). Otherwise (localhost, a private network) the plugin uploads the bytes. Either way the job runs on VocalStack, and the admin polls every 3 s. The account is billed per second, with a 5-minute minimum per transcription.
118
+
119
+ ## One-click connect (protocol)
120
+
121
+ The alternative to pasting a key: **Connect VocalStack** opens the dashboard in a new tab, the person clicks **Authenticate**, and the tab closes. This is OAuth 2.0 authorization code + PKCE (RFC 7636) with an API key as the access token. There is no client registration: the consent screen shows the `redirect_uri` host instead.
122
+
123
+ ```
124
+ CMS admin CMS server app.vocalstack.com / api.vocalstack.com
125
+ ────────── ────────── ───────────────────────────────────────
126
+ click Connect ── POST /api/vocalstack/connect ─▶ state, verifier (10 min)
127
+ ◀──────────── { url } ──────────────
128
+ new tab ─▶ GET app/connect?response_type=code&client_name=…&redirect_uri=…&state=…
129
+ &code_challenge=…&code_challenge_method=S256&scope=read write
130
+ (sign in if needed; pick the organization; "example.com wants to transcribe with VocalStack")
131
+ click Authenticate ─▶ API stores a single-use grant (code hash, challenge, redirect, scopes, principal; 2 min)
132
+ ◀── 302 redirect_uri?code=…&state=…
133
+ tab ─────── GET /api/vocalstack/callback ─▶ check state (+ admin session)
134
+ POST api/v1/connect/token (form) ─▶ grant_type=authorization_code, code,
135
+ code_verifier, redirect_uri
136
+ verify, burn the code, create the key
137
+ ◀── { access_token: "vs_key_…", token_type: "api_key", key_id, account: { name } }
138
+ stores the key (never sent to a browser)
139
+ tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab closes
140
+ ```
141
+
142
+ Cancel redirects with `?error=access_denied&state=…`. The key appears in the dashboard's API keys list as `example.com (Payload CMS)`, where it can be revoked.
package/dist/api.d.ts ADDED
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
+ * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
+ */
5
+ export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
6
+ export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
+ export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
8
+ export type Job = {
9
+ error?: null | string;
10
+ /** Why a failed job failed; `stopped` when its owner stopped it. */
11
+ errorCode?: null | string;
12
+ progress: {
13
+ pct: number;
14
+ phase?: null | string;
15
+ phasePct?: null | number;
16
+ processedS?: number;
17
+ totalS?: null | number;
18
+ };
19
+ recordingId: string;
20
+ state: JobState;
21
+ transcriptionId: string;
22
+ };
23
+ export type Transcription = {
24
+ id: string;
25
+ job?: Job | null;
26
+ name: string;
27
+ };
28
+ export type Transcript = {
29
+ lang?: null | string;
30
+ segments: {
31
+ end: number;
32
+ seq: number;
33
+ start: number;
34
+ suppressed?: boolean;
35
+ words?: {
36
+ end: number;
37
+ start: number;
38
+ text: string;
39
+ }[] | null;
40
+ }[];
41
+ sentences: {
42
+ end: number;
43
+ language?: null | string;
44
+ sentenceId: number;
45
+ speaker: number;
46
+ start: number;
47
+ suppressed?: boolean;
48
+ text: string;
49
+ }[];
50
+ };
51
+ export type Voice = {
52
+ createdAt: string;
53
+ error?: null | string;
54
+ id: string;
55
+ name: string;
56
+ progress: number;
57
+ sampleS: number;
58
+ /** `training`, `ready` or `failed`. */
59
+ state: string;
60
+ };
61
+ export type VoiceOption = {
62
+ cloned: boolean;
63
+ default: boolean;
64
+ gender?: null | string;
65
+ id: string;
66
+ name: string;
67
+ quality: number;
68
+ ready?: boolean;
69
+ };
70
+ /** A recording's spoken translation in one language and voice (`voiceKey` is `''` for the default voice). */
71
+ export type VoiceTrack = {
72
+ /** Seconds each sentence's clip lasts, by sentence id. */
73
+ clipDur?: Record<string, number>;
74
+ clips: number[];
75
+ durationS?: null | number;
76
+ error?: null | string;
77
+ lang: string;
78
+ /** `queued`, `running`, `failed`, `sealed` (the track is ready), or `clips` (sentences only). */
79
+ state: string;
80
+ voice?: null | string;
81
+ voiceKey: string;
82
+ /** Each sentence's words as [start, end] within its clip, by sentence id. */
83
+ wordTimes?: Record<string, [number, number][]>;
84
+ };
85
+ export type Languages = {
86
+ languages: {
87
+ code: string;
88
+ name: string;
89
+ native: string;
90
+ translation: boolean;
91
+ voice: boolean;
92
+ }[];
93
+ translation: string[];
94
+ voice: string[];
95
+ };
96
+ export declare const UNAVAILABLE = "VocalStack is unavailable, try again shortly.";
97
+ export declare class VocalStackAPIError extends Error {
98
+ code: string;
99
+ status: number;
100
+ constructor(status: number, code: string, message: string);
101
+ }
102
+ export declare class VocalStackAPI {
103
+ private apiKey;
104
+ private baseURL;
105
+ constructor(apiKey: string, baseURL?: string);
106
+ /**
107
+ * The raw answer. An engine that is down or does not answer in time (an upgrade, an
108
+ * outage) is one error, `unavailable`, so the admin says so instead of hanging.
109
+ */
110
+ fetch(method: string, path: string, opts?: {
111
+ body?: BodyInit | object;
112
+ headers?: Record<string, string>;
113
+ redirect?: RequestRedirect;
114
+ timeoutMs?: number;
115
+ }): Promise<Response>;
116
+ private request;
117
+ me(): Promise<Record<string, unknown>>;
118
+ transcribeURL(url: string, opts: {
119
+ idempotencyKey: string;
120
+ name: string;
121
+ spokenLanguage?: string;
122
+ }): Promise<Transcription>;
123
+ transcribeFile(file: Blob, fileName: string, opts: {
124
+ idempotencyKey: string;
125
+ name: string;
126
+ spokenLanguage?: string;
127
+ }): Promise<Transcription>;
128
+ job(recordingId: string): Promise<Job>;
129
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
130
+ stop(recordingId: string, reason?: string): Promise<unknown>;
131
+ transcript(recordingId: string): Promise<Transcript>;
132
+ /**
133
+ * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
134
+ * answers only the sentences it translates in that call, so stored ones are read here.
135
+ */
136
+ storedTranslations(recordingId: string, lang: string): Promise<Record<string, string>>;
137
+ languages(): Promise<Languages>;
138
+ /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
139
+ translation(recordingId: string, lang: string, sentenceIds: number[]): Promise<{
140
+ lang: string;
141
+ translations: Record<string, string>;
142
+ }>;
143
+ /** Render spoken translations, one job per language, in `voice` (the default voice when left out). */
144
+ speak(recordingId: string, langs: string[], voice?: string): Promise<VoiceTrack[]>;
145
+ voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
146
+ /** A freshly signed address (an hour) of the recording's audio, or of a spoken translation's. */
147
+ audioURL(recordingId: string, opts: {
148
+ format?: 'caf' | 'mp3' | 'ogg';
149
+ kind: 'delivery' | 'voice';
150
+ lang?: string;
151
+ voice?: string;
152
+ }): Promise<string>;
153
+ /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
154
+ clip(recordingId: string, startS: number, endS: number): Promise<Response>;
155
+ voice(id: string): Promise<Voice>;
156
+ /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
157
+ createVoice(sample: Blob, fileName: string, meta: {
158
+ consent: boolean;
159
+ name: string;
160
+ }, idempotencyKey: string): Promise<Voice>;
161
+ deleteVoice(id: string): Promise<unknown>;
162
+ availableVoices(lang: string, recordingId?: string): Promise<{
163
+ lang: string;
164
+ voices: VoiceOption[];
165
+ }>;
166
+ /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
167
+ voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
168
+ private raise;
169
+ }
170
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
171
+ export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
+ * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
+ */
5
+ export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
+ export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
7
+ export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
8
+ export class VocalStackAPIError extends Error {
9
+ code;
10
+ status;
11
+ constructor(status, code, message) {
12
+ super(message);
13
+ this.code = code;
14
+ this.status = status;
15
+ }
16
+ }
17
+ export class VocalStackAPI {
18
+ apiKey;
19
+ baseURL;
20
+ constructor(apiKey, baseURL = DEFAULT_API_URL) {
21
+ this.apiKey = apiKey;
22
+ this.baseURL = baseURL;
23
+ }
24
+ /**
25
+ * The raw answer. An engine that is down or does not answer in time (an upgrade, an
26
+ * outage) is one error, `unavailable`, so the admin says so instead of hanging.
27
+ */
28
+ async fetch(method, path, opts = {}) {
29
+ const init = {
30
+ headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...opts.headers },
31
+ method,
32
+ redirect: opts.redirect,
33
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
34
+ };
35
+ if (opts.body instanceof FormData)
36
+ init.body = opts.body;
37
+ else if (opts.body !== undefined) {
38
+ init.body = JSON.stringify(opts.body);
39
+ init.headers['content-type'] = 'application/json';
40
+ }
41
+ let res;
42
+ try {
43
+ res = await fetch(`${this.baseURL}${path}`, init);
44
+ }
45
+ catch {
46
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
47
+ }
48
+ if (res.status === 502 || res.status === 504 || (res.status === 503 && !res.headers.get('content-type')?.includes('json'))) {
49
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
50
+ }
51
+ return res;
52
+ }
53
+ async request(method, path, body, headers = {}, timeoutMs) {
54
+ const res = await this.fetch(method, path, { body, headers, timeoutMs });
55
+ const data = await res.json().catch(() => undefined);
56
+ if (!res.ok) {
57
+ const err = (data?.error ?? data);
58
+ throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
59
+ }
60
+ return data;
61
+ }
62
+ me() {
63
+ return this.request('GET', '/v1/me');
64
+ }
65
+ transcribeURL(url, opts) {
66
+ return this.request('POST', '/v1/transcriptions', { name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { 'idempotency-key': opts.idempotencyKey });
67
+ }
68
+ transcribeFile(file, fileName, opts) {
69
+ const form = new FormData();
70
+ form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
71
+ form.append('file', file, fileName);
72
+ return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
73
+ }
74
+ job(recordingId) {
75
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
76
+ }
77
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
78
+ stop(recordingId, reason) {
79
+ return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/stop`, { reason: reason ?? null });
80
+ }
81
+ transcript(recordingId) {
82
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
83
+ }
84
+ /**
85
+ * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
86
+ * answers only the sentences it translates in that call, so stored ones are read here.
87
+ */
88
+ async storedTranslations(recordingId, lang) {
89
+ const t = await this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript?lang=${encodeURIComponent(lang)}`);
90
+ const out = {};
91
+ for (const s of t.sentences ?? []) {
92
+ const text = s.translations?.[lang];
93
+ if (text?.trim())
94
+ out[String(s.sentenceId)] = text;
95
+ }
96
+ return out;
97
+ }
98
+ languages() {
99
+ return this.request('GET', '/v1/languages');
100
+ }
101
+ /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
102
+ translation(recordingId, lang, sentenceIds) {
103
+ const q = new URLSearchParams({ lang, sentences: sentenceIds.join(',') });
104
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/translation?${q}`, undefined, {}, 180_000);
105
+ }
106
+ /** Render spoken translations, one job per language, in `voice` (the default voice when left out). */
107
+ speak(recordingId, langs, voice) {
108
+ return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/voice`, voice ? { langs, voice } : { langs });
109
+ }
110
+ voiceTracks(recordingId, lang) {
111
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/voice${lang ? `?lang=${encodeURIComponent(lang)}` : ''}`);
112
+ }
113
+ /** A freshly signed address (an hour) of the recording's audio, or of a spoken translation's. */
114
+ async audioURL(recordingId, opts) {
115
+ const q = new URLSearchParams({ format: opts.format ?? 'mp3', kind: opts.kind });
116
+ if (opts.lang)
117
+ q.set('lang', opts.lang);
118
+ if (opts.voice)
119
+ q.set('voice', opts.voice);
120
+ const res = await this.fetch('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/audio?${q}`, { redirect: 'manual' });
121
+ const location = res.headers.get('location');
122
+ if (res.status >= 300 && res.status < 400 && location)
123
+ return new URL(location, this.baseURL).toString();
124
+ const data = (await res.json().catch(() => undefined));
125
+ throw new VocalStackAPIError(res.ok ? 502 : res.status, data?.code ?? 'http_error', data?.message ?? `VocalStack answered ${res.status}`);
126
+ }
127
+ /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
128
+ async clip(recordingId, startS, endS) {
129
+ const res = await this.fetch('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/audio/clip?startS=${startS}&endS=${endS}`, { timeoutMs: 60_000 });
130
+ if (!res.ok)
131
+ await this.raise(res);
132
+ return res;
133
+ }
134
+ voice(id) {
135
+ return this.request('GET', `/v1/voices/${encodeURIComponent(id)}`);
136
+ }
137
+ /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
138
+ createVoice(sample, fileName, meta, idempotencyKey) {
139
+ const form = new FormData();
140
+ form.append('meta', JSON.stringify(meta));
141
+ form.append('sample', sample, fileName);
142
+ return this.request('POST', '/v1/voices', form, { 'idempotency-key': idempotencyKey }, 120_000);
143
+ }
144
+ deleteVoice(id) {
145
+ return this.request('DELETE', `/v1/voices/${encodeURIComponent(id)}`);
146
+ }
147
+ availableVoices(lang, recordingId) {
148
+ const q = new URLSearchParams({ lang });
149
+ if (recordingId)
150
+ q.set('recording', recordingId);
151
+ return this.request('GET', `/v1/voices/available?${q}`);
152
+ }
153
+ /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
154
+ voicePreview(id, lang, format = 'ogg') {
155
+ const q = new URLSearchParams({ format });
156
+ if (lang)
157
+ q.set('lang', lang);
158
+ return this.fetch('GET', `/v1/voices/${encodeURIComponent(id)}/preview?${q}`, { timeoutMs: 60_000 });
159
+ }
160
+ async raise(res) {
161
+ const data = (await res.json().catch(() => undefined));
162
+ const err = data?.error ?? data;
163
+ throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
164
+ }
165
+ }
166
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
167
+ export function accountLabel(me) {
168
+ const pick = (o, ...keys) => {
169
+ if (!o || typeof o !== 'object')
170
+ return undefined;
171
+ for (const k of keys) {
172
+ const v = o[k];
173
+ if (typeof v === 'string' && v)
174
+ return v;
175
+ }
176
+ };
177
+ return pick(me.principal, 'name', 'displayName') ?? pick(me.organization, 'name') ?? pick(me.user, 'email', 'name') ?? pick(me, 'email', 'name', 'displayName');
178
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Brand colors as CSS variables, and the light/dark artwork swap, following
3
+ * Payload's theme (`html[data-theme]`). Rendered once per component tree; repeats are harmless.
4
+ */
5
+ export declare const BrandStyles: () => import("react").JSX.Element;
6
+ /** The VocalStack wordmark. */
7
+ export declare const Logo: React.FC<{
8
+ height?: number;
9
+ }>;
10
+ /** The V on its own, for small spaces. */
11
+ export declare const Mark: React.FC<{
12
+ height?: number;
13
+ }>;
@@ -0,0 +1,19 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { BRAND, LOGO_DARK, LOGO_LIGHT, MARK_DARK, MARK_LIGHT } from './brandAssets.js';
4
+ /**
5
+ * Brand colors as CSS variables, and the light/dark artwork swap, following
6
+ * Payload's theme (`html[data-theme]`). Rendered once per component tree; repeats are harmless.
7
+ */
8
+ export const BrandStyles = () => (_jsx("style", { children: `
9
+ .vs-brand { --vs-accent: ${BRAND.blue}; --vs-coral: ${BRAND.coral}; }
10
+ html[data-theme='dark'] .vs-brand { --vs-accent: ${BRAND.lightBlue}; --vs-coral: ${BRAND.lightCoral}; }
11
+ .vs-art { display: inline-flex; line-height: 0; }
12
+ .vs-art svg { height: 100%; width: auto; }
13
+ html[data-theme='dark'] .vs-art--light, html:not([data-theme='dark']) .vs-art--dark { display: none; }
14
+ ` }));
15
+ const Art = ({ dark, height, label, light }) => (_jsxs("span", { "aria-label": label, role: label ? 'img' : undefined, style: { display: 'inline-flex', verticalAlign: 'middle' }, children: [_jsx("span", { className: "vs-art vs-art--light", dangerouslySetInnerHTML: { __html: light }, style: { height } }), _jsx("span", { className: "vs-art vs-art--dark", dangerouslySetInnerHTML: { __html: dark }, style: { height } })] }));
16
+ /** The VocalStack wordmark. */
17
+ export const Logo = ({ height = 16 }) => _jsx(Art, { dark: LOGO_DARK, height: height, label: "VocalStack", light: LOGO_LIGHT });
18
+ /** The V on its own, for small spaces. */
19
+ export const Mark = ({ height = 14 }) => _jsx(Art, { dark: MARK_DARK, height: height, light: MARK_LIGHT });
@@ -0,0 +1,3 @@
1
+ export declare const ConnectionPanel: React.FC<{
2
+ oneClickConnect?: boolean;
3
+ }>;
@@ -0,0 +1,41 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, TextInput, toast } from '@payloadcms/ui';
4
+ import { useState } from 'react';
5
+ import { BrandStyles, Logo } from './Brand.js';
6
+ import { useConnection } from './useConnection.js';
7
+ const KEYS_URL = 'https://app.vocalstack.com/developers/keys';
8
+ export const ConnectionPanel = ({ oneClickConnect }) => {
9
+ const { call, connect, connecting, connection, setConnection } = useConnection();
10
+ const [apiKey, setAPIKey] = useState('');
11
+ const [saving, setSaving] = useState(false);
12
+ const [error, setError] = useState();
13
+ const run = async (fn, done) => {
14
+ setSaving(true);
15
+ setError(undefined);
16
+ try {
17
+ setConnection(await fn());
18
+ setAPIKey('');
19
+ toast.success(done);
20
+ }
21
+ catch (err) {
22
+ setError(err.message);
23
+ }
24
+ finally {
25
+ setSaving(false);
26
+ }
27
+ };
28
+ const save = () => void run(() => call('/vocalstack/key', { body: JSON.stringify({ apiKey }), method: 'POST' }), 'Connected to VocalStack.');
29
+ const muted = { color: 'var(--theme-elevation-500)' };
30
+ if (!connection)
31
+ return _jsx("p", { style: muted, children: "Checking the VocalStack connection\u2026" });
32
+ if (connection.source === 'options') {
33
+ return _jsx("p", { style: muted, children: "Connected with the API key from the plugin config. Change it there." });
34
+ }
35
+ return (_jsxs("div", { className: "vs-brand", style: { display: 'grid', gap: 'var(--base)', marginBottom: 'calc(var(--base) * 2)', maxWidth: 560 }, children: [_jsx(BrandStyles, {}), _jsx(Logo, { height: 24 }), connection.connected ? (_jsxs(_Fragment, { children: [_jsxs("p", { style: { margin: 0 }, children: ["Connected to VocalStack", connection.account ? ` as ${connection.account}` : '', ". Audio uploads now have a Transcribe button."] }), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: saving, margin: false, onClick: () => run(() => call('/vocalstack/key', { method: 'DELETE' }), 'Disconnected.'), children: "Disconnect" }) })] })) : (_jsxs(_Fragment, { children: [_jsx("p", { style: { margin: 0 }, children: "Connect a VocalStack account to transcribe audio uploads. Transcriptions use that account's credit." }), oneClickConnect && (_jsxs("div", { children: [_jsx(Button, { disabled: connecting, margin: false, onClick: () => connect().catch((e) => setError(e.message)), children: connecting ? 'Waiting for VocalStack…' : 'Connect VocalStack' }), _jsx("p", { style: { ...muted, fontSize: 13, marginBottom: 0 }, children: "Opens VocalStack in a new tab; click Authenticate there." })] })), _jsxs("div", { onKeyDown: (e) => {
36
+ if (e.key === 'Enter' && apiKey.trim()) {
37
+ e.preventDefault();
38
+ save();
39
+ }
40
+ }, style: { display: 'grid', gap: 'calc(var(--base) / 2)' }, children: [_jsx(TextInput, { label: oneClickConnect ? 'Or paste an API key' : 'API key', onChange: (e) => setAPIKey(e.target.value), path: "vocalstack-api-key", placeholder: "vs_key_\u2026", value: apiKey }), _jsxs("p", { style: { ...muted, fontSize: 13, margin: 0 }, children: ["Create one with Read and Write permissions under", ' ', _jsx("a", { href: KEYS_URL, rel: "noreferrer", target: "_blank", children: "Developers \u2192 API keys" }), ". It is stored on the server and never shown again."] }), _jsx("div", { children: _jsx(Button, { disabled: saving || !apiKey.trim(), margin: false, onClick: save, children: "Save key" }) })] })] })), error && _jsx("p", { style: { color: 'var(--theme-error-500)', margin: 0 }, children: error })] }));
41
+ };
@@ -0,0 +1,7 @@
1
+ type Props = {
2
+ field?: string;
3
+ path?: string;
4
+ };
5
+ /** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
6
+ export declare const SpeechField: React.FC<Props>;
7
+ export {};