@vocalstack/payload 0.7.0 → 0.8.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.
- package/README.md +16 -7
- package/dist/api.d.ts +2 -0
- package/dist/api.js +17 -2
- package/dist/components/ConnectionPanel.js +8 -2
- package/dist/components/WorkspaceMark.d.ts +11 -0
- package/dist/components/WorkspaceMark.js +30 -0
- package/dist/components/useConnection.d.ts +1 -0
- package/dist/components/useConnection.js +7 -1
- package/dist/endpoints/connection.d.ts +2 -0
- package/dist/endpoints/connection.js +77 -8
- package/dist/endpoints/transcribe.js +12 -2
- package/dist/types.d.ts +5 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workspace.d.ts +20 -0
- package/dist/workspace.js +22 -0
- package/dist/workspaceMark.d.ts +8 -0
- package/dist/workspaceMark.js +24 -0
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
|
|
|
41
41
|
- `POST …/vocalstack/voices { voices: 'synthetic' | 'cloned' }`, `POST …/vocalstack/request { langs, speak? }` (translate, and read aloud unless `speak: false`; carried on by the server), `POST …/vocalstack/translate { langs }` (one step; answers `more: true` when it stopped for time), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs }`, `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.
|
|
42
42
|
- **Languages for listeners** (opt in with `listeners`): visitors pick any language VocalStack offers, and it is made for them and kept for everyone after. `GET /api/vocalstack/languages` is public, `POST …/vocalstack/listen { lang }` asks for a language and `GET …/vocalstack/listen?lang=` says where it stands; see below.
|
|
43
43
|
- **Speakers** (opt in with `speakers`): documents of a collection of people get a sidebar panel that saves that person as a VocalStack speaker and clones their voice, from a minute of a recording they speak in or from an uploaded sample, with their permission. Kept in a hidden `vocalstackSpeaker` group (`speakerId`, `cloneId`, `state` of the voice: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/speaker`, `…/speaker/sources` and `…/speaker/preview`.
|
|
44
|
-
- **Settings → VocalStack** (a global), where an editor connects
|
|
44
|
+
- **Settings → VocalStack** (a global), where an editor connects a VocalStack workspace. It shows the workspace the site works in, with its name and icon, and **Change** picks another. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
|
|
45
45
|
|
|
46
46
|
## Options
|
|
47
47
|
|
|
@@ -176,11 +176,19 @@ The translation is saved on the document, and where VocalStack can read the lang
|
|
|
176
176
|
|
|
177
177
|
When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
|
|
178
178
|
|
|
179
|
-
**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
|
|
179
|
+
**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 connected workspace is billed per second, with a 5-minute minimum per transcription.
|
|
180
|
+
|
|
181
|
+
## The workspace
|
|
182
|
+
|
|
183
|
+
A VocalStack API key belongs to one workspace: what the site transcribes is kept in that workspace and uses its credit. **Settings → VocalStack** shows it under **Workspace**, with its name and its mark as the VocalStack Dashboard draws it (its own icon; a person for the personal workspace; otherwise its initials on its colour). The name and icon are read from `GET /v1/me` whenever the connection is checked (at most once a minute), so a rename or a new icon in VocalStack shows up here, and a pasted key or a key from the plugin config shows its workspace too. `GET /api/vocalstack/connection` answers `{ connected, source, account, workspace: { id, name, personal, iconUrl } }`, with `iconUrl` an absolute link the browser can load as it is.
|
|
184
|
+
|
|
185
|
+
A key never moves to another workspace. With `oneClickConnect`, **Change** next to the workspace runs the connect flow again: pick another workspace on VocalStack's consent screen and click Authenticate, and the site swaps to the new key. Cancelling, in VocalStack or with **Cancel** in the admin, leaves the connection as it was. Connecting again makes a new key; the old one keeps working until it is revoked in VocalStack under **Developers → API keys**. Without `oneClickConnect`, disconnect and paste a key made in the other workspace. A key from the plugin config is changed there.
|
|
186
|
+
|
|
187
|
+
Transcripts stay in the workspace that made them. After a change, the transcripts, translations and readings already saved on your documents are still there and still served, but asking VocalStack for more of one made in the old workspace (another language, a reading, a speaker's sample) answers *This transcript is not in the connected VocalStack workspace…*; transcribe the file again to work with it in the new workspace. A transcription that was still running when the workspace changed ends as failed with the same sentence.
|
|
180
188
|
|
|
181
189
|
## One-click connect (protocol)
|
|
182
190
|
|
|
183
|
-
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.
|
|
191
|
+
The alternative to pasting a key: **Connect VocalStack** opens the dashboard in a new tab, the person chooses a workspace and clicks **Authenticate**, and the tab closes. **Change** runs the same flow while connected; the stored key is replaced only once the new one has been issued. 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.
|
|
184
192
|
|
|
185
193
|
```
|
|
186
194
|
CMS admin CMS server app.vocalstack.com / api.vocalstack.com
|
|
@@ -189,20 +197,21 @@ click Connect ── POST /api/vocalstack/connect ─▶ state, verifier (10 min
|
|
|
189
197
|
◀──────────── { url } ──────────────
|
|
190
198
|
new tab ─▶ GET app/connect?response_type=code&client_name=…&redirect_uri=…&state=…
|
|
191
199
|
&code_challenge=…&code_challenge_method=S256&scope=read write
|
|
192
|
-
(sign in if needed; pick the
|
|
200
|
+
(sign in if needed; pick the workspace; "example.com wants to transcribe with VocalStack")
|
|
193
201
|
click Authenticate ─▶ API stores a single-use grant (code hash, challenge, redirect, scopes, principal; 2 min)
|
|
194
202
|
◀── 302 redirect_uri?code=…&state=…
|
|
195
203
|
tab ─────── GET /api/vocalstack/callback ─▶ check state (+ admin session)
|
|
196
204
|
POST api/v1/connect/token (form) ─▶ grant_type=authorization_code, code,
|
|
197
205
|
code_verifier, redirect_uri
|
|
198
206
|
verify, burn the code, create the key
|
|
199
|
-
◀── { access_token: "vs_key_…", token_type: "api_key", key_id, account: { name }
|
|
207
|
+
◀── { access_token: "vs_key_…", token_type: "api_key", key_id, account: { name },
|
|
208
|
+
workspace: { id, name, personal, iconUrl } }
|
|
200
209
|
stores the key (never sent to a browser)
|
|
201
210
|
tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab closes
|
|
202
211
|
```
|
|
203
212
|
|
|
204
|
-
Cancel redirects with `?error=access_denied&state
|
|
213
|
+
Cancel redirects with `?error=access_denied&state=…`; `DELETE /api/vocalstack/connect` drops a pending connect from the admin side. The key appears in the dashboard's API keys list as `example.com (Payload CMS)`, where it can be revoked.
|
|
205
214
|
|
|
206
215
|
## Releasing
|
|
207
216
|
|
|
208
|
-
Bump `version` in `package.json` and push to `main`. The `publish` workflow publishes that version to npm (trusted publishing, with provenance), tags `v<version>` and creates the GitHub release. A version npm already has is skipped. A prerelease (`0.5.0-beta.1`) goes to the `next` dist-tag. Nobody publishes from a laptop.
|
|
217
|
+
Bump `version` in `package.json` and push to `main`. The `publish` workflow runs the tests (`pnpm test`: a build, then `node --test` over `test/`), publishes that version to npm (trusted publishing, with provenance), tags `v<version>` and creates the GitHub release. A version npm already has is skipped. A prerelease (`0.5.0-beta.1`) goes to the `next` dist-tag. Nobody publishes from a laptop.
|
package/dist/api.d.ts
CHANGED
|
@@ -107,6 +107,8 @@ export type Languages = {
|
|
|
107
107
|
voice: string[];
|
|
108
108
|
};
|
|
109
109
|
export declare const UNAVAILABLE = "VocalStack is unavailable, try again shortly.";
|
|
110
|
+
/** A stored recording the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
|
|
111
|
+
export declare const NOT_IN_WORKSPACE = "This transcript is not in the connected VocalStack workspace: it was made in another workspace, or deleted in VocalStack. Transcribe the file again to work with it here.";
|
|
110
112
|
export declare class VocalStackAPIError extends Error {
|
|
111
113
|
code: string;
|
|
112
114
|
status: number;
|
package/dist/api.js
CHANGED
|
@@ -24,6 +24,9 @@ function savedSpeakerOf(raw) {
|
|
|
24
24
|
const speakerRoutes = new Map();
|
|
25
25
|
const both = (rest) => ({ speakers: `/v1/speakers${rest}`, voices: `/v1/voices${rest}` });
|
|
26
26
|
export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
|
|
27
|
+
/** A stored recording the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
|
|
28
|
+
export const NOT_IN_WORKSPACE = 'This transcript is not in the connected VocalStack workspace: it was made in another workspace, or deleted in VocalStack. Transcribe the file again to work with it here.';
|
|
29
|
+
const isGone = (status, message) => status === 404 && /^no such (recording|transcription|job)\b/i.test(message.trim());
|
|
27
30
|
export class VocalStackAPIError extends Error {
|
|
28
31
|
code;
|
|
29
32
|
status;
|
|
@@ -52,6 +55,8 @@ function toAPIError(err) {
|
|
|
52
55
|
const down = err.code === 'unavailable' || (err.code === 'internal' && (err.status === 502 || err.status === 503 || err.status === 504));
|
|
53
56
|
if (down)
|
|
54
57
|
return new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
|
|
58
|
+
if (isGone(err.status, err.message))
|
|
59
|
+
return new VocalStackAPIError(404, 'not_found', NOT_IN_WORKSPACE);
|
|
55
60
|
return new VocalStackAPIError(err.status ?? 500, err.code, err.message);
|
|
56
61
|
}
|
|
57
62
|
if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError'))
|
|
@@ -90,8 +95,16 @@ export class VocalStackAPI {
|
|
|
90
95
|
transcribeFile(file, fileName, opts) {
|
|
91
96
|
return call(() => this.sdk.transcriptions.create({ file, fileName, name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }, { idempotencyKey: opts.idempotencyKey }));
|
|
92
97
|
}
|
|
93
|
-
job(recordingId) {
|
|
94
|
-
|
|
98
|
+
async job(recordingId) {
|
|
99
|
+
try {
|
|
100
|
+
return await call(() => this.sdk.jobs.get(recordingId));
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
// Any "not found" for a job that was started here means this key cannot see it (a wrong address says "no route").
|
|
104
|
+
if (err instanceof VocalStackAPIError && err.status === 404 && !/^no route\b/i.test(err.message))
|
|
105
|
+
throw new VocalStackAPIError(404, 'not_found', NOT_IN_WORKSPACE);
|
|
106
|
+
throw err;
|
|
107
|
+
}
|
|
95
108
|
}
|
|
96
109
|
/** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
|
|
97
110
|
stop(recordingId, reason) {
|
|
@@ -142,6 +155,8 @@ export class VocalStackAPI {
|
|
|
142
155
|
return body;
|
|
143
156
|
if (res.status === 502 || res.status === 503 || res.status === 504)
|
|
144
157
|
throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
|
|
158
|
+
if (isGone(res.status, body?.message ?? ''))
|
|
159
|
+
throw new VocalStackAPIError(404, 'not_found', NOT_IN_WORKSPACE);
|
|
145
160
|
throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
|
|
146
161
|
}
|
|
147
162
|
voiceTracks(recordingId, lang) {
|
|
@@ -5,6 +5,7 @@ import { useState } from 'react';
|
|
|
5
5
|
import { BrandStyles, Logo } from './Brand.js';
|
|
6
6
|
import { useConnection } from './useConnection.js';
|
|
7
7
|
import { useVersion } from './useVersion.js';
|
|
8
|
+
import { WorkspaceMark, WorkspaceMarkStyles } from './WorkspaceMark.js';
|
|
8
9
|
const KEYS_URL = 'https://app.vocalstack.com/developers/keys';
|
|
9
10
|
const muted = { color: 'var(--theme-elevation-500)' };
|
|
10
11
|
/** The installed version, and the newer one when there is one. */
|
|
@@ -16,8 +17,10 @@ const VersionLine = () => {
|
|
|
16
17
|
return _jsxs("p", { style: { ...muted, fontSize: 13, margin: 0 }, children: ["@vocalstack/payload ", version.current] });
|
|
17
18
|
return (_jsxs("div", { style: { background: 'var(--theme-warning-100)', borderRadius: 'var(--style-radius-s, 4px)', fontSize: 13, padding: '10px 12px' }, children: [_jsxs("strong", { children: ["@vocalstack/payload ", version.latest, " is out."] }), " This site runs ", version.current, ".", ' ', version.releaseURL && (_jsx("a", { href: version.releaseURL, rel: "noreferrer", target: "_blank", children: "What's new" })), _jsxs("p", { style: { margin: '6px 0 0' }, children: ["Update it in the site's code (", _jsx("code", { children: "pnpm up @vocalstack/payload" }), "), then run ", _jsx("code", { children: "payload generate:importmap" }), " and, with Postgres or SQLite,", ' ', _jsx("code", { children: "payload migrate:create" }), " before deploying."] })] }));
|
|
18
19
|
};
|
|
20
|
+
/** The workspace the key works in: its mark and name under a "Workspace" label, with room for a button beside it. */
|
|
21
|
+
const WorkspaceRow = ({ children, workspace }) => (_jsxs("div", { style: { alignItems: 'center', display: 'flex', gap: 12 }, children: [_jsx(WorkspaceMarkStyles, {}), _jsx(WorkspaceMark, { size: 40, workspace: workspace }), _jsxs("div", { "aria-label": `Workspace: ${workspace.name}`, role: "group", style: { flex: 1, minWidth: 0 }, children: [_jsx("div", { style: { ...muted, fontSize: 11, fontWeight: 600, letterSpacing: '.08em', lineHeight: 1.4, textTransform: 'uppercase' }, children: "Workspace" }), _jsx("div", { style: { fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, children: workspace.name })] }), children] }));
|
|
19
22
|
export const ConnectionPanel = ({ oneClickConnect }) => {
|
|
20
|
-
const { call, connect, connecting, connection, setConnection } = useConnection();
|
|
23
|
+
const { call, cancel, connect, connecting, connection, setConnection } = useConnection();
|
|
21
24
|
const [apiKey, setAPIKey] = useState('');
|
|
22
25
|
const [saving, setSaving] = useState(false);
|
|
23
26
|
const [error, setError] = useState();
|
|
@@ -39,7 +42,10 @@ export const ConnectionPanel = ({ oneClickConnect }) => {
|
|
|
39
42
|
const save = () => void run(() => call('/vocalstack/key', { body: JSON.stringify({ apiKey }), method: 'POST' }), 'Connected to VocalStack.');
|
|
40
43
|
if (!connection)
|
|
41
44
|
return _jsx("p", { style: muted, children: "Checking the VocalStack connection\u2026" });
|
|
42
|
-
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.source === 'options' ? (_jsx("p", { style: { margin: 0 }, children: "Connected with the API key from the plugin config. Change it there." })) : connection.connected ? (_jsxs(_Fragment, { children: [
|
|
45
|
+
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.source === 'options' ? (_jsxs(_Fragment, { children: [connection.workspace && _jsx(WorkspaceRow, { workspace: connection.workspace }), _jsx("p", { style: { margin: 0 }, children: "Connected with the API key from the plugin config. Change it there." })] })) : connection.connected ? (_jsxs(_Fragment, { children: [connection.workspace ? (_jsxs(_Fragment, { children: [_jsx(WorkspaceRow, { workspace: connection.workspace, children: oneClickConnect && (_jsx(Button, { "aria-label": connecting ? 'Cancel changing the workspace' : 'Change workspace', buttonStyle: "secondary", disabled: saving, margin: false, onClick: () => {
|
|
46
|
+
setError(undefined);
|
|
47
|
+
void (connecting ? cancel() : connect().catch((e) => setError(e.message)));
|
|
48
|
+
}, size: "small", children: connecting ? 'Cancel' : 'Change' })) }), _jsx("p", { style: { margin: 0 }, children: "Connected to VocalStack. Audio uploads have a Transcribe button, and what is transcribed here is kept in this workspace and uses its credit." }), oneClickConnect && (_jsx("p", { style: { ...muted, fontSize: 13, margin: 0 }, children: connecting ? ('Choose a workspace in the VocalStack tab, then click Authenticate. Until then this workspace stays connected.') : (_jsxs(_Fragment, { children: ["Change connects again, to the workspace you pick in VocalStack. That makes a new API key; the old one keeps working until it is revoked in VocalStack under", ' ', _jsx("a", { href: KEYS_URL, rel: "noreferrer", target: "_blank", children: "Developers \u2192 API keys" }), ". Transcripts made in another workspace stay in it."] })) }))] })) : (_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 || connecting, margin: false, onClick: () => run(() => call('/vocalstack/key', { method: 'DELETE' }), 'Disconnected.'), children: "Disconnect" }) })] })) : (_jsxs(_Fragment, { children: [_jsx("p", { style: { margin: 0 }, children: "Connect a VocalStack workspace to transcribe audio uploads. Transcriptions are kept in that workspace and use its 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; choose a workspace and click Authenticate there." })] })), _jsxs("div", { onKeyDown: (e) => {
|
|
43
49
|
if (e.key === 'Enter' && apiKey.trim()) {
|
|
44
50
|
e.preventDefault();
|
|
45
51
|
save();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Workspace } from '../workspace.js';
|
|
2
|
+
/** The mark's looks, as in the VocalStack Dashboard, on Payload's theme colours. */
|
|
3
|
+
export declare const WorkspaceMarkStyles: () => import("react").JSX.Element;
|
|
4
|
+
/**
|
|
5
|
+
* A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
|
|
6
|
+
* one, a person for the personal workspace, else its initials on its colour.
|
|
7
|
+
*/
|
|
8
|
+
export declare const WorkspaceMark: React.FC<{
|
|
9
|
+
size?: number;
|
|
10
|
+
workspace: Workspace;
|
|
11
|
+
}>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { useState } from 'react';
|
|
4
|
+
import { workspaceHue, workspaceInitials } from '../workspaceMark.js';
|
|
5
|
+
const PERSON = 'M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z';
|
|
6
|
+
/** The mark's looks, as in the VocalStack Dashboard, on Payload's theme colours. */
|
|
7
|
+
export const WorkspaceMarkStyles = () => (_jsx("style", { children: `
|
|
8
|
+
.vs-wsmark { flex: none; display: grid; place-items: center; font-weight: 600; letter-spacing: .02em; line-height: 1; --ws-c: oklch(.66 .13 var(--ws-h, 252)); background: color-mix(in oklab, var(--ws-c) 22%, transparent); color: color-mix(in oklab, var(--ws-c) 72%, var(--theme-text)); box-shadow: inset 0 0 0 1px color-mix(in oklab, var(--ws-c) 30%, transparent); }
|
|
9
|
+
.vs-wsmark--me { background: var(--theme-elevation-100); color: var(--theme-elevation-650); box-shadow: inset 0 0 0 1px var(--theme-elevation-150); }
|
|
10
|
+
.vs-wsmark--img { overflow: hidden; background: var(--theme-elevation-50); box-shadow: inset 0 0 0 1px var(--theme-elevation-150); }
|
|
11
|
+
.vs-wsmark--img img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
|
12
|
+
` }));
|
|
13
|
+
/**
|
|
14
|
+
* A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
|
|
15
|
+
* one, a person for the personal workspace, else its initials on its colour.
|
|
16
|
+
*/
|
|
17
|
+
export const WorkspaceMark = ({ size = 28, workspace }) => {
|
|
18
|
+
// An icon that does not load (its link ran out, the network) gives way to the drawn mark.
|
|
19
|
+
const [broken, setBroken] = useState();
|
|
20
|
+
const style = { borderRadius: Math.round(size * 0.29), fontSize: Math.round(size * 0.39), height: size, width: size };
|
|
21
|
+
const icon = workspace.iconUrl && workspace.iconUrl !== broken ? workspace.iconUrl : undefined;
|
|
22
|
+
if (icon) {
|
|
23
|
+
return (_jsx("span", { "aria-hidden": "true", className: "vs-wsmark vs-wsmark--img", style: style, children: _jsx("img", { alt: "", draggable: false, onError: () => setBroken(icon), src: icon }) }));
|
|
24
|
+
}
|
|
25
|
+
if (workspace.personal) {
|
|
26
|
+
const glyph = Math.round(size * 0.55);
|
|
27
|
+
return (_jsx("span", { "aria-hidden": "true", className: "vs-wsmark vs-wsmark--me", style: style, children: _jsx("svg", { fill: "none", height: glyph, stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 1.6, viewBox: "0 0 24 24", width: glyph, children: _jsx("path", { d: PERSON }) }) }));
|
|
28
|
+
}
|
|
29
|
+
return (_jsx("span", { "aria-hidden": "true", className: "vs-wsmark", style: { ...style, '--ws-h': workspaceHue(workspace.id) }, children: workspaceInitials(workspace.name) }));
|
|
30
|
+
};
|
|
@@ -3,6 +3,7 @@ export declare function useAPI(): <T>(path: string, init?: RequestInit) => Promi
|
|
|
3
3
|
/** The VocalStack connection, and the one-click flow that opens the dashboard in a new tab. */
|
|
4
4
|
export declare function useConnection(): {
|
|
5
5
|
call: <T>(path: string, init?: RequestInit) => Promise<T>;
|
|
6
|
+
cancel: () => Promise<void>;
|
|
6
7
|
connect: () => Promise<void>;
|
|
7
8
|
connecting: boolean;
|
|
8
9
|
connection: ConnectionResponse | undefined;
|
|
@@ -55,5 +55,11 @@ export function useConnection() {
|
|
|
55
55
|
throw err;
|
|
56
56
|
}
|
|
57
57
|
}, [call]);
|
|
58
|
-
|
|
58
|
+
/** Give up a connect that is waiting: its link stops working, and the connection in use stays. */
|
|
59
|
+
const cancel = useCallback(async () => {
|
|
60
|
+
setConnecting(false);
|
|
61
|
+
await call('/vocalstack/connect', { method: 'DELETE' }).catch(() => undefined);
|
|
62
|
+
await refresh();
|
|
63
|
+
}, [call, refresh]);
|
|
64
|
+
return { call, cancel, connect, connecting, connection, refresh, setConnection };
|
|
59
65
|
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Endpoint } from 'payload';
|
|
2
2
|
import type { VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
/** Forget what was read from `/v1/me` (tests). */
|
|
4
|
+
export declare const forgetOwners: () => void;
|
|
3
5
|
/**
|
|
4
6
|
* One-click connect, as OAuth 2.0 authorization code + PKCE (RFC 7636) whose
|
|
5
7
|
* token is a VocalStack API key:
|
|
@@ -1,9 +1,47 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { accountLabel, DEFAULT_API_URL, DEFAULT_DASHBOARD_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
3
3
|
import { readSettings, writeSettings } from '../settings.js';
|
|
4
|
+
import { workspaceOf } from '../workspace.js';
|
|
4
5
|
const json = (body, status = 200) => Response.json(body, { status });
|
|
5
6
|
const base64url = (b) => b.toString('base64url');
|
|
6
7
|
const CONNECT_TTL_MS = 10 * 60 * 1000;
|
|
8
|
+
const OWNER_FRESH_MS = 60_000;
|
|
9
|
+
const OWNER_RETRY_MS = 15_000;
|
|
10
|
+
const OWNER_TIMEOUT_MS = 6_000;
|
|
11
|
+
const owners = new Map();
|
|
12
|
+
const ownerKey = (apiKey, apiURL) => createHash('sha256').update(`${apiURL}\n${apiKey}`).digest('hex');
|
|
13
|
+
/** Forget what was read from `/v1/me` (tests). */
|
|
14
|
+
export const forgetOwners = () => owners.clear();
|
|
15
|
+
const ownerOf = (me, apiURL) => {
|
|
16
|
+
const workspace = workspaceOf(me.workspace, apiURL);
|
|
17
|
+
return { account: workspace?.name ?? accountLabel(me), workspace };
|
|
18
|
+
};
|
|
19
|
+
function remember(apiKey, apiURL, owner, ms = OWNER_FRESH_MS) {
|
|
20
|
+
if (owners.size > 50)
|
|
21
|
+
owners.clear();
|
|
22
|
+
owners.set(ownerKey(apiKey, apiURL), { owner, until: Date.now() + ms });
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The key's workspace as `/v1/me` has it now, so a new name or icon set in the VocalStack
|
|
26
|
+
* Dashboard reaches the admin. Asked at most once a minute per key; `undefined` when
|
|
27
|
+
* VocalStack did not answer in time.
|
|
28
|
+
*/
|
|
29
|
+
async function lookUpOwner(apiKey, apiURL) {
|
|
30
|
+
const hit = owners.get(ownerKey(apiKey, apiURL));
|
|
31
|
+
if (hit && Date.now() < hit.until)
|
|
32
|
+
return hit.owner;
|
|
33
|
+
const owner = await Promise.race([
|
|
34
|
+
new VocalStackAPI(apiKey, apiURL).me().then((me) => ownerOf(me, apiURL), () => undefined),
|
|
35
|
+
new Promise((resolve) => {
|
|
36
|
+
const timer = setTimeout(resolve, OWNER_TIMEOUT_MS);
|
|
37
|
+
timer.unref?.();
|
|
38
|
+
}),
|
|
39
|
+
]);
|
|
40
|
+
// Through a blip the last good answer stays, and VocalStack is asked again sooner.
|
|
41
|
+
const last = owner ?? hit?.owner;
|
|
42
|
+
remember(apiKey, apiURL, last, owner ? OWNER_FRESH_MS : OWNER_RETRY_MS);
|
|
43
|
+
return last;
|
|
44
|
+
}
|
|
7
45
|
/**
|
|
8
46
|
* One-click connect, as OAuth 2.0 authorization code + PKCE (RFC 7636) whose
|
|
9
47
|
* token is a VocalStack API key:
|
|
@@ -27,10 +65,18 @@ export function connectionEndpoints(options) {
|
|
|
27
65
|
handler: async (req) => {
|
|
28
66
|
if (!req.user)
|
|
29
67
|
return json({ error: 'Sign in first.' }, 401);
|
|
30
|
-
if (options.apiKey)
|
|
31
|
-
|
|
68
|
+
if (options.apiKey) {
|
|
69
|
+
const owner = await lookUpOwner(options.apiKey, apiURL);
|
|
70
|
+
return json({ account: owner?.account, connected: true, source: 'options', workspace: owner?.workspace });
|
|
71
|
+
}
|
|
32
72
|
const settings = await readSettings(req);
|
|
33
|
-
|
|
73
|
+
if (!settings.apiKey)
|
|
74
|
+
return json({ account: settings.account ?? undefined, connected: false });
|
|
75
|
+
const owner = await lookUpOwner(settings.apiKey, apiURL);
|
|
76
|
+
// The stored label follows a rename, so it is still right when VocalStack cannot be asked.
|
|
77
|
+
if (owner?.account && owner.account !== settings.account)
|
|
78
|
+
await writeSettings(req, { account: owner.account }).catch(() => undefined);
|
|
79
|
+
return json({ account: owner?.account ?? settings.account ?? undefined, connected: true, source: 'admin', workspace: owner?.workspace });
|
|
34
80
|
},
|
|
35
81
|
},
|
|
36
82
|
{
|
|
@@ -45,9 +91,10 @@ export function connectionEndpoints(options) {
|
|
|
45
91
|
if (!apiKey?.startsWith('vs_key_'))
|
|
46
92
|
return json({ error: 'A VocalStack API key starts with vs_key_.' }, 400);
|
|
47
93
|
try {
|
|
48
|
-
const
|
|
49
|
-
await writeSettings(req, { account, apiKey });
|
|
50
|
-
|
|
94
|
+
const owner = ownerOf(await new VocalStackAPI(apiKey, apiURL).me(), apiURL);
|
|
95
|
+
await writeSettings(req, { account: owner.account ?? null, apiKey });
|
|
96
|
+
remember(apiKey, apiURL, owner);
|
|
97
|
+
return json({ account: owner.account, connected: true, source: 'admin', workspace: owner.workspace });
|
|
51
98
|
}
|
|
52
99
|
catch (err) {
|
|
53
100
|
const message = err instanceof VocalStackAPIError && err.status === 401 ? 'VocalStack refused that key.' : String(err.message);
|
|
@@ -65,6 +112,17 @@ export function connectionEndpoints(options) {
|
|
|
65
112
|
return json({ connected: Boolean(options.apiKey), source: options.apiKey ? 'options' : undefined });
|
|
66
113
|
},
|
|
67
114
|
},
|
|
115
|
+
{
|
|
116
|
+
// Give up a connect that was started: its link stops working, and the key in use stays.
|
|
117
|
+
method: 'delete',
|
|
118
|
+
path: '/vocalstack/connect',
|
|
119
|
+
handler: async (req) => {
|
|
120
|
+
if (!(await canManage(req)))
|
|
121
|
+
return json({ error: 'You may not change the VocalStack connection.' }, 403);
|
|
122
|
+
await writeSettings(req, { connectExpiresAt: null, connectState: null, connectVerifier: null });
|
|
123
|
+
return json({ ok: true });
|
|
124
|
+
},
|
|
125
|
+
},
|
|
68
126
|
{
|
|
69
127
|
method: 'post',
|
|
70
128
|
path: '/vocalstack/connect',
|
|
@@ -112,10 +170,21 @@ export function connectionEndpoints(options) {
|
|
|
112
170
|
method: 'POST',
|
|
113
171
|
});
|
|
114
172
|
const token = (await res.json().catch(() => ({})));
|
|
173
|
+
// Nothing was stored yet: a refused or cancelled connect leaves the key in use as it was.
|
|
115
174
|
if (!res.ok || !token.access_token)
|
|
116
175
|
return page(`VocalStack did not issue a key: ${token.error_description ?? res.status}`, false);
|
|
117
|
-
|
|
118
|
-
|
|
176
|
+
let workspace = workspaceOf(token.workspace, apiURL);
|
|
177
|
+
let account = workspace?.name ?? token.account?.name;
|
|
178
|
+
if (!workspace) {
|
|
179
|
+
// An API from before workspaces were named on this answer: ask /v1/me.
|
|
180
|
+
const owner = ownerOf(await new VocalStackAPI(token.access_token, apiURL).me().catch(() => ({})), apiURL);
|
|
181
|
+
workspace = owner.workspace;
|
|
182
|
+
account = workspace?.name ?? account ?? owner.account;
|
|
183
|
+
}
|
|
184
|
+
await writeSettings(req, { account: account ?? null, apiKey: token.access_token });
|
|
185
|
+
remember(token.access_token, apiURL, { account, workspace });
|
|
186
|
+
if (workspace)
|
|
187
|
+
return page(`Connected to the VocalStack workspace ${workspace.name}.`, true);
|
|
119
188
|
return page(account ? `Connected to VocalStack as ${account}.` : 'Connected to VocalStack.', true);
|
|
120
189
|
},
|
|
121
190
|
},
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
2
|
+
import { DEFAULT_API_URL, NOT_IN_WORKSPACE, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
3
3
|
import { fetchFile, isPublicURL, resolveFileURL } from '../fileSource.js';
|
|
4
4
|
import { attachWords, transcriptText } from '../text.js';
|
|
5
5
|
import { resolveAPIKey } from '../settings.js';
|
|
@@ -118,7 +118,17 @@ export function apiError(err) {
|
|
|
118
118
|
* whole transcript when done, the reason when it failed.
|
|
119
119
|
*/
|
|
120
120
|
export async function checkJob(api, target, recordingId) {
|
|
121
|
-
|
|
121
|
+
let job;
|
|
122
|
+
try {
|
|
123
|
+
job = await api.job(recordingId);
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
if (!(err instanceof VocalStackAPIError && err.message === NOT_IN_WORKSPACE))
|
|
127
|
+
throw err;
|
|
128
|
+
// The job is not this key's to see (the workspace was changed while it ran, or it was deleted):
|
|
129
|
+
// it would otherwise stay "processing" for ever. An earlier transcript stays; the file can be transcribed again.
|
|
130
|
+
return { error: NOT_IN_WORKSPACE, status: 'failed', vocalstack: await target.save({ error: NOT_IN_WORKSPACE, status: 'failed' }) };
|
|
131
|
+
}
|
|
122
132
|
if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
|
|
123
133
|
return restore(target);
|
|
124
134
|
if (job.state === 'failed' || job.state === 'cropping') {
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { CollectionConfig, CollectionSlug, PayloadRequest, TypeWithID } from 'payload';
|
|
2
|
+
import type { Workspace } from './workspace.js';
|
|
3
|
+
export type { Workspace } from './workspace.js';
|
|
2
4
|
export type VocalStackPluginOptions = {
|
|
3
5
|
/**
|
|
4
6
|
* Where finished spoken readings are kept: the plugin downloads each one's MP3
|
|
@@ -285,10 +287,13 @@ export type VersionResponse = {
|
|
|
285
287
|
state: 'current' | 'outdated' | 'unknown';
|
|
286
288
|
};
|
|
287
289
|
export type ConnectionResponse = {
|
|
290
|
+
/** A label for what the key belongs to: the workspace's name when VocalStack says which workspace it is. */
|
|
288
291
|
account?: string;
|
|
289
292
|
connected: boolean;
|
|
290
293
|
/** `options`: the key is in the plugin config; `admin`: connected from the admin panel. */
|
|
291
294
|
source?: 'admin' | 'options';
|
|
295
|
+
/** The VocalStack workspace the key works in. Missing when VocalStack did not say (an older API, or unreachable just now). */
|
|
296
|
+
workspace?: Workspace;
|
|
292
297
|
};
|
|
293
298
|
/** Where one language of a transcript stands, for a listener: what the listen endpoint answers. */
|
|
294
299
|
export type ListenStatus = {
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const PACKAGE_NAME = "@vocalstack/payload";
|
|
2
|
-
export declare const VERSION = "0.
|
|
2
|
+
export declare const VERSION = "0.8.0";
|
package/dist/version.js
CHANGED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The VocalStack workspace an API key belongs to. Everything the key makes lands
|
|
3
|
+
* there and is billed there, and a key never changes workspace: working in another
|
|
4
|
+
* one takes a new key, from connecting again.
|
|
5
|
+
*/
|
|
6
|
+
export type Workspace = {
|
|
7
|
+
/** The workspace's own icon (a PNG that needs no key to load), or `null` when it has none. */
|
|
8
|
+
iconUrl: null | string;
|
|
9
|
+
id: string;
|
|
10
|
+
/** As the VocalStack Dashboard shows it (`Personal workspace` for an unnamed personal one). */
|
|
11
|
+
name: string;
|
|
12
|
+
/** The workspace every person starts with. */
|
|
13
|
+
personal: boolean;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The `workspace` of `GET /v1/me` or of the `POST /v1/connect/token` answer, with its
|
|
17
|
+
* icon's address made absolute (the API sends it relative to its own address).
|
|
18
|
+
* `undefined` when there is none: an older API leaves it out.
|
|
19
|
+
*/
|
|
20
|
+
export declare function workspaceOf(raw: unknown, apiURL: string): undefined | Workspace;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `workspace` of `GET /v1/me` or of the `POST /v1/connect/token` answer, with its
|
|
3
|
+
* icon's address made absolute (the API sends it relative to its own address).
|
|
4
|
+
* `undefined` when there is none: an older API leaves it out.
|
|
5
|
+
*/
|
|
6
|
+
export function workspaceOf(raw, apiURL) {
|
|
7
|
+
if (!raw || typeof raw !== 'object')
|
|
8
|
+
return undefined;
|
|
9
|
+
const { iconUrl, id, name, personal } = raw;
|
|
10
|
+
if (typeof id !== 'string' || !id || typeof name !== 'string' || !name.trim())
|
|
11
|
+
return undefined;
|
|
12
|
+
let icon = null;
|
|
13
|
+
if (typeof iconUrl === 'string' && iconUrl) {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(iconUrl, `${apiURL.replace(/\/+$/, '')}/`);
|
|
16
|
+
if (url.protocol === 'https:' || url.protocol === 'http:')
|
|
17
|
+
icon = url.toString();
|
|
18
|
+
}
|
|
19
|
+
catch { }
|
|
20
|
+
}
|
|
21
|
+
return { iconUrl: icon, id, name: name.trim(), personal: personal === true };
|
|
22
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A workspace's mark when it has no icon of its own, exactly as the VocalStack
|
|
3
|
+
* Dashboard draws it: one or two letters, on a tile tinted with the workspace's colour.
|
|
4
|
+
*/
|
|
5
|
+
/** The first letter of the first two words, or the first two letters of a single word. */
|
|
6
|
+
export declare function workspaceInitials(name: string): string;
|
|
7
|
+
/** The tile's hue in degrees (`oklch(.66 .13 <hue>)`), always the same for one workspace id. */
|
|
8
|
+
export declare function workspaceHue(id: string): number;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A workspace's mark when it has no icon of its own, exactly as the VocalStack
|
|
3
|
+
* Dashboard draws it: one or two letters, on a tile tinted with the workspace's colour.
|
|
4
|
+
*/
|
|
5
|
+
/** The first letter of the first two words, or the first two letters of a single word. */
|
|
6
|
+
export function workspaceInitials(name) {
|
|
7
|
+
const words = name.trim().split(/\s+/).filter((w) => /[\p{L}\p{N}]/u.test(w));
|
|
8
|
+
const first = (w) => Array.from(w.replace(/^[^\p{L}\p{N}]+/u, ''))[0] ?? '';
|
|
9
|
+
if (words.length === 0)
|
|
10
|
+
return '?';
|
|
11
|
+
if (words.length === 1)
|
|
12
|
+
return Array.from(words[0].replace(/[^\p{L}\p{N}]/gu, '')).slice(0, 2).join('').toUpperCase() || '?';
|
|
13
|
+
return (first(words[0]) + first(words[1])).toUpperCase();
|
|
14
|
+
}
|
|
15
|
+
const HUES = [252, 200, 160, 128, 85, 40, 12, 330, 296];
|
|
16
|
+
/** The tile's hue in degrees (`oklch(.66 .13 <hue>)`), always the same for one workspace id. */
|
|
17
|
+
export function workspaceHue(id) {
|
|
18
|
+
let h = 2166136261;
|
|
19
|
+
for (let i = 0; i < id.length; i++) {
|
|
20
|
+
h ^= id.charCodeAt(i);
|
|
21
|
+
h = Math.imul(h, 16777619);
|
|
22
|
+
}
|
|
23
|
+
return HUES[(h >>> 0) % HUES.length];
|
|
24
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vocalstack/payload",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "VocalStack for Payload CMS: transcribe audio, translate it into other languages and read it aloud, kept in your own database and storage.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"version": "node scripts/version.mjs && git add src/version.ts",
|
|
24
24
|
"build": "node scripts/version.mjs && tsc -p tsconfig.json",
|
|
25
|
-
"typecheck": "node scripts/version.mjs && tsc -p tsconfig.json --noEmit"
|
|
25
|
+
"typecheck": "node scripts/version.mjs && tsc -p tsconfig.json --noEmit",
|
|
26
|
+
"test": "pnpm build && node --test \"test/*.test.*\""
|
|
26
27
|
},
|
|
27
28
|
"peerDependencies": {
|
|
28
29
|
"@payloadcms/ui": "^3.0.0",
|