@vocalstack/sanity 0.1.0 → 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.
package/README.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  VocalStack for [Sanity](https://www.sanity.io) Studio 3 and later: a **Transcribe** button next to every audio file. The transcript is saved on the document as text plus timed sentences.
4
4
 
5
- ## Install
5
+ Read more about the [VocalStack transcription plugin for Sanity](https://vocalstack.com/sanity-transcription-plugin/) on the [VocalStack website](https://vocalstack.com/).
6
6
 
7
- Not on npm. Install from this repo; `dist/` is committed, so nothing builds on install (run `pnpm build` and commit `dist/` with every change):
7
+ ## Install
8
8
 
9
9
  ```sh
10
- npm i github:vocalstack/sanity-plugin
10
+ npm i @vocalstack/sanity
11
11
  ```
12
12
 
13
13
  VocalStack API keys are for servers: the API refuses a key sent from a web page. So the plugin has two halves, the Studio plugin and a small server handler that holds the key.
@@ -65,13 +65,14 @@ defineType({
65
65
  ## What it adds
66
66
 
67
67
  - **A `vocalstack.transcript` field type**, to put next to a `file` field (at the top level of a document, or inside an object). Its input has:
68
+ - the **workspace** the Studio is connected to, with its icon, at the top of the field (see [Workspace](#workspace));
68
69
  - a **Transcribe** button, shown when the sibling file is `audio/*`. It shows progress and survives a reload mid-job, because `recordingId` and `status` are saved on the document. **Stop** ends a job you no longer want: the field goes back to how it was (an earlier transcript stays), and VocalStack keeps what it transcribed before the stop.
69
70
  - the stored value:
70
71
  - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
71
72
  - `sentences`: `[{ start, end, speaker, text }]` in seconds.
72
73
  - `status` (`idle`, `processing`, `done` or `failed`), `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
73
74
  - **A "Transcribe audio" document action** on every document type with a transcript field. It starts a job for each transcript field next to an audio file; the field follows the job from there.
74
- - **The handler** (`@vocalstack/sanity/server`): `GET …/connection`, `POST …/transcriptions`, `GET …/recordings/:id/job` and `POST …/recordings/:id/stop`.
75
+ - **The handler** (`@vocalstack/sanity/server`): `GET …/connection` (`{ connected, account, workspace: { id, name, personal, iconUrl } }`), `POST …/transcriptions`, `GET …/recordings/:id/job` and `POST …/recordings/:id/stop`.
75
76
 
76
77
  Like any edit in the Studio, the transcript lands in the draft; publish to make it public. Transcripts are plain fields, so GROQ reads them like any other:
77
78
 
@@ -104,7 +105,7 @@ The handler, `createVocalStackHandler({ … })`:
104
105
  | `allowedOrigins` | any | The Studio origins allowed to call the handler (CORS), e.g. `['https://example.sanity.studio']`. |
105
106
  | `apiURL` | `https://api.vocalstack.com` | |
106
107
 
107
- **How the audio reaches VocalStack.** The Studio sends the handler the file's asset id; the handler reads the asset from your dataset, checks that it is `audio/*`, and VocalStack fetches it from Sanity's CDN (`POST /v1/transcriptions { url }`). VocalStack does not fetch loopback or private addresses, so for those the handler reads the file and uploads it. The job runs on VocalStack, and the Studio polls the handler every 3 s. The account is billed per second, with a 5-minute minimum per transcription.
108
+ **How the audio reaches VocalStack.** The Studio sends the handler the file's asset id; the handler reads the asset from your dataset, checks that it is `audio/*`, and VocalStack fetches it from Sanity's CDN (`POST /v1/transcriptions { url }`). VocalStack does not fetch loopback or private addresses, so for those the handler reads the file and uploads it. The job runs on VocalStack, and the Studio polls the handler every 3 s. The key's workspace is billed per second, with a 5-minute minimum per transcription.
108
109
 
109
110
  ## How the handler knows the caller
110
111
 
@@ -115,11 +116,19 @@ The handler only answers someone signed in to the Studio with permission to edit
115
116
 
116
117
  Only someone who can write to the dataset can create a session. The id has a dot in it, so Sanity never serves it to unauthenticated requests, even from a public dataset; project members who can read the dataset see the hash, never the secret. Expired sessions are swept by the Studio. The handler keeps no cookies, so CORS from any origin is safe; `allowedOrigins` narrows it further.
117
118
 
118
- The VocalStack key never reaches a browser: it lives in the handler's environment only. Anyone who can edit the dataset can start, follow and stop transcriptions on that key's account.
119
+ The VocalStack key never reaches a browser: it lives in the handler's environment only. Anyone who can edit the dataset can start, follow and stop transcriptions in that key's workspace.
120
+
121
+ ## Workspace
122
+
123
+ A VocalStack API key belongs to one workspace: every transcription the plugin makes lands in that workspace and is billed there. The transcript field shows which one, as the VocalStack Dashboard does: **Workspace**, its icon (its own picture, a person for the personal workspace, or its initials on its colour) and its name. The handler reads it from `GET /v1/me` and keeps it for five minutes, so a new name or icon shows up in the Studio without a redeploy.
124
+
125
+ There is no workspace switch in the Studio, because the key lives in the handler's environment. To use another workspace, set `VOCALSTACK_API_KEY` where the handler runs to a key made in that workspace: in the [Dashboard](https://app.vocalstack.com), switch to the workspace, then Developers → API keys. **Change**, next to the workspace's name, says the same.
126
+
127
+ After the key moves to another workspace, transcripts already saved on documents stay as they are. A job that was still running under the old key cannot be followed any more: its field says that the transcription is not in the connected workspace and offers **Transcribe again**, which makes a new one in the new workspace.
119
128
 
120
129
  ## Testing
121
130
 
122
- `e2e/run.sh` runs a real Studio on a fake Content Lake against the handler and a real VocalStack, in Chromium; see [e2e/README.md](e2e/README.md).
131
+ `pnpm test` builds `dist/` and runs the unit tests in `test/` (the workspace mark, the handler's `…/connection` answer). `e2e/run.sh` runs a real Studio on a fake Content Lake against the handler and a real VocalStack, in Chromium; see [e2e/README.md](e2e/README.md).
123
132
 
124
133
  ## One-click connect
125
134
 
package/dist/api.d.ts CHANGED
@@ -2,7 +2,12 @@
2
2
  * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
3
  * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
4
  */
5
+ import type { ConnectionWorkspace } from './wire.js';
5
6
  export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
7
+ /** Sent as the User-Agent of every call to VocalStack (they run in the
8
+ * handler, on the server): VocalStack lists the transcriptions it makes
9
+ * as made in Sanity. Keep it to package.json's version. */
10
+ export declare const PLUGIN_VERSION = "0.2.0";
6
11
  export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
12
  export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
8
13
  export type Job = {
@@ -76,3 +81,9 @@ export declare class VocalStackAPI {
76
81
  }
77
82
  /** A short label for the connected account, from whatever `/v1/me` carries. */
78
83
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
84
+ /**
85
+ * The workspace the key belongs to, from `/v1/me` (`workspace: { id, name, personal,
86
+ * iconUrl }`), with the icon's link made absolute against the API's address. Undefined
87
+ * when the API does not say (an older VocalStack).
88
+ */
89
+ export declare function workspaceOf(me: Record<string, unknown>, baseURL?: string): ConnectionWorkspace | undefined;
package/dist/api.js CHANGED
@@ -3,6 +3,10 @@
3
3
  * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
4
  */
5
5
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
+ /** Sent as the User-Agent of every call to VocalStack (they run in the
7
+ * handler, on the server): VocalStack lists the transcriptions it makes
8
+ * as made in Sanity. Keep it to package.json's version. */
9
+ export const PLUGIN_VERSION = '0.2.0';
6
10
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
7
11
  export class VocalStackAPIError extends Error {
8
12
  code;
@@ -21,7 +25,7 @@ export class VocalStackAPI {
21
25
  this.baseURL = baseURL;
22
26
  }
23
27
  async request(method, path, body, headers = {}) {
24
- const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...headers }, method };
28
+ const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, 'user-agent': `VocalStack-Sanity/${PLUGIN_VERSION}`, ...headers }, method };
25
29
  if (body instanceof FormData)
26
30
  init.body = body;
27
31
  else if (body !== undefined) {
@@ -72,3 +76,23 @@ export function accountLabel(me) {
72
76
  };
73
77
  return pick(me.principal, 'name', 'displayName') ?? pick(me.organization, 'name') ?? pick(me.user, 'email', 'name') ?? pick(me, 'email', 'name', 'displayName');
74
78
  }
79
+ /**
80
+ * The workspace the key belongs to, from `/v1/me` (`workspace: { id, name, personal,
81
+ * iconUrl }`), with the icon's link made absolute against the API's address. Undefined
82
+ * when the API does not say (an older VocalStack).
83
+ */
84
+ export function workspaceOf(me, baseURL = DEFAULT_API_URL) {
85
+ const w = me.workspace;
86
+ if (!w || typeof w !== 'object' || typeof w.id !== 'string' || !w.id || typeof w.name !== 'string' || !w.name.trim())
87
+ return undefined;
88
+ let iconUrl = null;
89
+ if (typeof w.iconUrl === 'string' && w.iconUrl) {
90
+ try {
91
+ const url = new URL(w.iconUrl, baseURL);
92
+ if (url.protocol === 'https:' || url.protocol === 'http:')
93
+ iconUrl = url.href;
94
+ }
95
+ catch { }
96
+ }
97
+ return { iconUrl, id: w.id, name: w.name, personal: w.personal === true };
98
+ }
@@ -5,7 +5,9 @@ import { set, setIfMissing, unset, useFormValue } from 'sanity';
5
5
  import { findAudio, jobName, POLL_MS, restored, siblingFileRefs, TRANSCRIPT_TYPE } from '../core.js';
6
6
  import { HandlerError, useConnection, useHandler } from '../handler.js';
7
7
  import { transcriptText } from '../text.js';
8
+ import { NOT_IN_WORKSPACE } from '../wire.js';
8
9
  import { Logo, useAccent } from './Brand.js';
10
+ import { WorkspaceMark } from './WorkspaceMark.js';
9
11
  /** 2433.0 → "40:33", 4000 → "1:06:40". */
10
12
  const clock = (s) => {
11
13
  const t = Math.floor(s);
@@ -46,6 +48,10 @@ export function TranscriptInput(props) {
46
48
  const [stopping, setStopping] = useState(false);
47
49
  const [progress, setProgress] = useState({});
48
50
  const [error, setError] = useState();
51
+ // The recording this field was following, when the connected workspace does not have it:
52
+ // VOCALSTACK_API_KEY now belongs to another workspace. The field offers Transcribe again.
53
+ const [lost, setLost] = useState();
54
+ const [changing, setChanging] = useState(false);
49
55
  // A short note after a job ends. Inline rather than a toast: Sanity UI moved its toasts between versions.
50
56
  const [notice, setNotice] = useState();
51
57
  useEffect(() => {
@@ -98,6 +104,8 @@ export function TranscriptInput(props) {
98
104
  catch (err) {
99
105
  if (cancelled)
100
106
  return;
107
+ if (err instanceof HandlerError && err.code === NOT_IN_WORKSPACE)
108
+ setLost(recordingId);
101
109
  // A network blip or a server hiccup should not end the wait; anything refused should.
102
110
  if (err instanceof HandlerError && err.status && err.status < 500)
103
111
  return setError(err.message);
@@ -143,13 +151,17 @@ export function TranscriptInput(props) {
143
151
  finish(outcome);
144
152
  }
145
153
  catch (err) {
154
+ if (err instanceof HandlerError && err.code === NOT_IN_WORKSPACE)
155
+ setLost(recordingId);
146
156
  setError(err.message);
147
157
  }
148
158
  finally {
149
159
  setStopping(false);
150
160
  }
151
161
  };
152
- const busy = status === 'processing';
162
+ const isLost = status === 'processing' && Boolean(recordingId) && lost === recordingId;
163
+ const busy = status === 'processing' && !isLost;
164
+ const workspace = connection?.connected ? connection.workspace : undefined;
153
165
  const shownError = error ?? (status === 'failed' ? (value?.error ?? undefined) : undefined);
154
166
  const partialText = useMemo(() => (busy && progress.partial?.length ? transcriptText(progress.partial) : undefined), [busy, progress.partial]);
155
167
  const muted = { muted: true, size: 1 };
@@ -164,9 +176,9 @@ export function TranscriptInput(props) {
164
176
  else if (!asset && !busy)
165
177
  action = _jsx(Text, { ...muted, children: refs.length ? 'Only audio files can be transcribed.' : 'Add an audio file, then transcribe.' });
166
178
  else {
167
- action = (_jsxs(Flex, { gap: 2, wrap: "wrap", children: [_jsx(Button, { disabled: busy || starting || readOnly || !asset, onClick: transcribe, text: busy || starting ? 'Transcribing…' : status === 'done' ? 'Transcribe again' : 'Transcribe', tone: "primary" }), busy && _jsx(Button, { disabled: stopping || readOnly, mode: "ghost", onClick: stop, text: stopping ? 'Stopping…' : 'Stop' })] }));
179
+ action = (_jsxs(Flex, { gap: 2, wrap: "wrap", children: [_jsx(Button, { disabled: busy || starting || readOnly || !asset, onClick: transcribe, text: busy || starting ? 'Transcribing…' : status === 'done' || isLost ? 'Transcribe again' : 'Transcribe', tone: "primary" }), busy && _jsx(Button, { disabled: stopping || readOnly, mode: "ghost", onClick: stop, text: stopping ? 'Stopping…' : 'Stop' })] }));
168
180
  }
169
- return (_jsx(Card, { border: true, padding: 3, radius: 2, children: _jsxs(Stack, { space: 3, children: [_jsx(Logo, { height: 14 }), action, busy && (_jsxs(Stack, { space: 2, children: [_jsxs(Text, { ...muted, children: [PHASES[progress.phase ?? 'queued'] ?? progress.phase, progress.progress ? ` · ${progress.progress}%` : '…', progress.audio?.totalS ? ` · ${clock(progress.audio.processedS)} of ${clock(progress.audio.totalS)}` : ''] }), _jsx(Card, { radius: 1, style: { height: 4, overflow: 'hidden' }, tone: "transparent", children: _jsx("div", { style: { background: accent, height: '100%', transition: 'width .4s', width: `${progress.progress || 2}%` } }) })] })), notice && (_jsx(Card, { padding: 2, radius: 2, tone: "positive", children: _jsx(Text, { size: 1, children: notice }) })), !busy && status === 'done' && !shownError && (_jsxs(Text, { ...muted, children: ["Transcribed", value?.language ? ` (${value.language})` : '', value?.sentences?.length ? ` · ${value.sentences.length} sentences with timings` : '', "."] })), shownError && (_jsx(Card, { padding: 2, radius: 2, tone: "critical", children: _jsx(Text, { size: 1, children: shownError }) })), (partialText || value?.transcript) && (_jsx(Box, { children: _jsx(TextArea, { onChange: (e) => {
181
+ return (_jsx(Card, { border: true, padding: 3, radius: 2, children: _jsxs(Stack, { space: 3, children: [_jsxs(Flex, { align: "center", gap: 3, justify: "space-between", wrap: "wrap", children: [_jsx(Logo, { height: 14 }), workspace && (_jsxs(Flex, { align: "center", "data-testid": "vocalstack-workspace", gap: 2, style: { minWidth: 0 }, children: [_jsx(Text, { ...muted, children: "Workspace" }), _jsx(WorkspaceMark, { size: 18, workspace: workspace }), _jsx(Text, { size: 1, textOverflow: "ellipsis", weight: "medium", children: workspace.name }), _jsx(Button, { "aria-expanded": changing, fontSize: 1, mode: "bleed", onClick: () => setChanging((c) => !c), padding: 2, text: "Change" })] }))] }), workspace && changing && (_jsx(Card, { border: true, padding: 2, radius: 2, children: _jsxs(Text, { ...muted, children: ["Transcriptions made here go to the workspace this Studio\u2019s VocalStack API key was made in. To use another workspace, set ", _jsx("code", { children: "VOCALSTACK_API_KEY" }), ' ', "where the VocalStack handler runs to a key made in that workspace: in the VocalStack Dashboard, switch to the workspace, then Developers \u2192 API keys."] }) })), action, busy && (_jsxs(Stack, { space: 2, children: [_jsxs(Text, { ...muted, children: [PHASES[progress.phase ?? 'queued'] ?? progress.phase, progress.progress ? ` · ${progress.progress}%` : '…', progress.audio?.totalS ? ` · ${clock(progress.audio.processedS)} of ${clock(progress.audio.totalS)}` : ''] }), _jsx(Card, { radius: 1, style: { height: 4, overflow: 'hidden' }, tone: "transparent", children: _jsx("div", { style: { background: accent, height: '100%', transition: 'width .4s', width: `${progress.progress || 2}%` } }) })] })), notice && (_jsx(Card, { padding: 2, radius: 2, tone: "positive", children: _jsx(Text, { size: 1, children: notice }) })), !busy && status === 'done' && !shownError && (_jsxs(Text, { ...muted, children: ["Transcribed", value?.language ? ` (${value.language})` : '', value?.sentences?.length ? ` · ${value.sentences.length} sentences with timings` : '', "."] })), shownError && (_jsx(Card, { padding: 2, radius: 2, tone: "critical", children: _jsx(Text, { size: 1, children: shownError }) })), (partialText || value?.transcript) && (_jsx(Box, { children: _jsx(TextArea, { onChange: (e) => {
170
182
  const text = e.currentTarget.value;
171
183
  onChange([setIfMissing({ _type: TRANSCRIPT_TYPE }), text ? set(text, ['transcript']) : unset(['transcript'])]);
172
184
  }, readOnly: readOnly || Boolean(partialText), rows: 10, value: partialText ?? value?.transcript ?? '' }) }))] }) }));
@@ -0,0 +1,9 @@
1
+ import type { ConnectionWorkspace } from '../wire.js';
2
+ /**
3
+ * A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
4
+ * one; else a person for the personal workspace; else its initials on its colour.
5
+ */
6
+ export declare function WorkspaceMark({ size, workspace }: {
7
+ size?: number;
8
+ workspace: ConnectionWorkspace;
9
+ }): import("react").JSX.Element;
@@ -0,0 +1,45 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { useEffect, useState } from 'react';
3
+ import { workspaceHue, workspaceInitials } from '../workspaceMark.js';
4
+ import { useDark } from './Brand.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
+ /**
7
+ * A workspace's mark, as the VocalStack Dashboard draws it: its own icon when it has
8
+ * one; else a person for the personal workspace; else its initials on its colour.
9
+ */
10
+ export function WorkspaceMark({ size = 20, workspace }) {
11
+ const dark = useDark();
12
+ const { iconUrl } = workspace;
13
+ // An icon that does not load (a link signed long ago, a network that blocks it) gives way to the drawn mark.
14
+ const [broken, setBroken] = useState();
15
+ useEffect(() => setBroken(undefined), [iconUrl]);
16
+ const ink = dark ? '#fff' : '#101112';
17
+ const hair = `inset 0 0 0 1px color-mix(in oklab, ${ink} 14%, transparent)`;
18
+ const tile = {
19
+ alignItems: 'center',
20
+ borderRadius: Math.round(size * 0.29),
21
+ display: 'inline-flex',
22
+ flex: 'none',
23
+ fontSize: Math.round(size * 0.39),
24
+ fontWeight: 600,
25
+ height: size,
26
+ justifyContent: 'center',
27
+ letterSpacing: '.02em',
28
+ lineHeight: 1,
29
+ width: size,
30
+ };
31
+ if (iconUrl && broken !== iconUrl) {
32
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "icon", style: { ...tile, background: `color-mix(in oklab, ${ink} 6%, transparent)`, boxShadow: hair, overflow: 'hidden' }, children: _jsx("img", { alt: "", draggable: false, onError: () => setBroken(iconUrl), src: iconUrl, style: { display: 'block', height: '100%', objectFit: 'cover', width: '100%' } }) }));
33
+ }
34
+ if (workspace.personal) {
35
+ const glyph = Math.round(size * 0.55);
36
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "personal", style: { ...tile, background: `color-mix(in oklab, ${ink} 9%, transparent)`, boxShadow: hair, color: `color-mix(in oklab, ${ink} 70%, transparent)` }, 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 }) }) }));
37
+ }
38
+ const colour = `oklch(.66 .13 ${workspaceHue(workspace.id)})`;
39
+ return (_jsx("span", { "aria-hidden": "true", "data-mark": "initials", style: {
40
+ ...tile,
41
+ background: `color-mix(in oklab, ${colour} 22%, transparent)`,
42
+ boxShadow: `inset 0 0 0 1px color-mix(in oklab, ${colour} 30%, transparent)`,
43
+ color: `color-mix(in oklab, ${colour} 72%, ${ink})`,
44
+ }, children: workspaceInitials(workspace.name) }));
45
+ }
@@ -1,4 +1,4 @@
1
- export type { ConnectionResponse, JobOutcome, StartRequest, StartResponse } from '../wire.js';
1
+ export type { ConnectionResponse, ConnectionWorkspace, JobOutcome, StartRequest, StartResponse } from '../wire.js';
2
2
  export type VocalStackHandlerOptions = {
3
3
  /** A VocalStack API key (`vs_key_…`, Read + Write). Default: `process.env.VOCALSTACK_API_KEY`. */
4
4
  apiKey?: string;
@@ -38,4 +38,9 @@ export type SanityFileAsset = {
38
38
  url?: string;
39
39
  };
40
40
  type Handler = (request: Request) => Promise<Response>;
41
+ /**
42
+ * The connection answer, briefly: a rename or a new icon in the Dashboard, and the
43
+ * icon's re-signed link, reach the Studio within minutes, without a redeploy.
44
+ */
45
+ export declare const CONNECTION_CACHE_MS: number;
41
46
  export declare function createVocalStackHandler(options: VocalStackHandlerOptions): Handler;
@@ -1,5 +1,5 @@
1
- import { accountLabel, DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
2
- import { SESSION_MAX_AGE_MS, SESSION_PREFIX, SESSION_TYPE, sha256Hex } from '../wire.js';
1
+ import { accountLabel, DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError, workspaceOf } from '../api.js';
2
+ import { NOT_IN_WORKSPACE, SESSION_MAX_AGE_MS, SESSION_PREFIX, SESSION_TYPE, sha256Hex } from '../wire.js';
3
3
  import { checkJob, stopJob } from './jobs.js';
4
4
  /** `https://<projectId>.api.sanity.io`, or the custom API host, as `@sanity/client` builds it. */
5
5
  function sanityHost({ apiHost = 'https://api.sanity.io', projectId, useProjectHostname = true }) {
@@ -36,12 +36,17 @@ async function fetchFile(url) {
36
36
  }
37
37
  /** Verified sessions, briefly, so a poll every 3 s is not a Sanity query every 3 s. */
38
38
  const SESSION_CACHE_MS = 60_000;
39
+ /**
40
+ * The connection answer, briefly: a rename or a new icon in the Dashboard, and the
41
+ * icon's re-signed link, reach the Studio within minutes, without a redeploy.
42
+ */
43
+ export const CONNECTION_CACHE_MS = 5 * 60_000;
39
44
  export function createVocalStackHandler(options) {
40
45
  const apiKey = options.apiKey ?? globalThis.process?.env?.VOCALSTACK_API_KEY;
41
46
  const { dataset, projectId, token } = options.sanity;
42
47
  const sanityBase = `${sanityHost(options.sanity)}/v${(options.sanity.apiVersion ?? '2024-01-01').replace(/^v/, '')}`;
43
48
  const sessions = new Map();
44
- let account;
49
+ let connection;
45
50
  async function query(groq, params) {
46
51
  const url = new URL(`${sanityBase}/data/query/${encodeURIComponent(dataset)}`);
47
52
  url.searchParams.set('query', groq);
@@ -106,11 +111,17 @@ export function createVocalStackHandler(options) {
106
111
  }
107
112
  if (!apiKey)
108
113
  return fail(503, 'VOCALSTACK_API_KEY is not set where the VocalStack handler runs.', 'not_connected');
109
- const api = new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL);
114
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
115
+ const api = new VocalStackAPI(apiKey, apiURL);
116
+ const recordingRoute = route !== 'connection' && route !== 'transcriptions';
110
117
  try {
111
118
  if (route === 'connection' && request.method === 'GET') {
112
- account ??= accountLabel(await api.me());
113
- return json({ account, connected: true });
119
+ if (!connection || connection.until <= Date.now()) {
120
+ const me = await api.me();
121
+ const workspace = workspaceOf(me, apiURL);
122
+ connection = { answer: { account: workspace?.name ?? accountLabel(me), connected: true, workspace }, until: Date.now() + CONNECTION_CACHE_MS };
123
+ }
124
+ return json(connection.answer);
114
125
  }
115
126
  if (route === 'transcriptions' && request.method === 'POST') {
116
127
  const body = (await request.json().catch(() => ({})));
@@ -146,6 +157,11 @@ export function createVocalStackHandler(options) {
146
157
  if (err instanceof VocalStackAPIError) {
147
158
  if (err.status === 401)
148
159
  return fail(502, 'VocalStack refused the API key in VOCALSTACK_API_KEY.', 'not_connected');
160
+ // A key sees only its own workspace: after VOCALSTACK_API_KEY moved to another one, a
161
+ // recording made with the old key is not found (as is one deleted in VocalStack).
162
+ if (err.status === 404 && recordingRoute) {
163
+ return fail(404, 'This transcription is not in the workspace VocalStack is connected to now: it was made in another workspace, or deleted. Transcribe the audio again to make it here.', NOT_IN_WORKSPACE);
164
+ }
149
165
  return fail(err.status >= 500 ? 502 : err.status, err.message, err.code);
150
166
  }
151
167
  return fail(500, err instanceof Error ? err.message : String(err));
package/dist/wire.d.ts CHANGED
@@ -35,9 +35,24 @@ export type StartRequest = {
35
35
  export type StartResponse = Required<Pick<VocalStackTranscript, 'recordingId' | 'status' | 'transcriptionId'>>;
36
36
  /** `GET {handlerURL}/connection` */
37
37
  export type ConnectionResponse = {
38
+ /** The workspace's name; against an older VocalStack, the key's label. */
38
39
  account?: string;
39
40
  connected: boolean;
41
+ /** The workspace the handler's API key belongs to. Absent against a VocalStack that does not say. */
42
+ workspace?: ConnectionWorkspace;
40
43
  };
44
+ /**
45
+ * A VocalStack workspace. `iconUrl` is its own icon as an absolute link that needs no
46
+ * key (re-signed from time to time, so not for keeping), or null when it has none.
47
+ */
48
+ export type ConnectionWorkspace = {
49
+ iconUrl: null | string;
50
+ id: string;
51
+ name: string;
52
+ personal: boolean;
53
+ };
54
+ /** The handler's `code` when a recording is not in the workspace its key belongs to. */
55
+ export declare const NOT_IN_WORKSPACE = "not_in_workspace";
41
56
  /** Every error: `{ code?, error }`. `session` means the Studio should prove itself again. */
42
57
  export type ErrorResponse = {
43
58
  code?: string;
package/dist/wire.js CHANGED
@@ -1,3 +1,5 @@
1
+ /** The handler's `code` when a recording is not in the workspace its key belongs to. */
2
+ export const NOT_IN_WORKSPACE = 'not_in_workspace';
1
3
  /** The document type of a Studio session (see `SESSION_PREFIX`). */
2
4
  export const SESSION_TYPE = 'vocalstack.session';
3
5
  /** Session ids are `vocalstack-session.<sha256 hex of the secret>`: dotted, so never public. */
@@ -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: its initials, on a tile tinted with its colour.
4
+ */
5
+ /** "Acme studio" → "AS", "Podcast" → "PO"; words with no letter or digit are skipped. */
6
+ export declare function workspaceInitials(name: string): string;
7
+ /** The hue of a workspace's colour, `oklch(.66 .13 <hue>)`: always the same for one id. */
8
+ export declare function workspaceHue(id: string): number;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * A workspace's mark when it has no icon of its own, exactly as the VocalStack
3
+ * Dashboard draws it: its initials, on a tile tinted with its colour.
4
+ */
5
+ /** "Acme studio" → "AS", "Podcast" → "PO"; words with no letter or digit are skipped. */
6
+ export function workspaceInitials(name) {
7
+ const words = name
8
+ .trim()
9
+ .split(/\s+/)
10
+ .filter((w) => /[\p{L}\p{N}]/u.test(w));
11
+ const first = (w) => Array.from(w.replace(/^[^\p{L}\p{N}]+/u, ''))[0] ?? '';
12
+ if (words.length === 0)
13
+ return '?';
14
+ if (words.length === 1)
15
+ return Array.from(words[0].replace(/[^\p{L}\p{N}]/gu, '')).slice(0, 2).join('').toUpperCase() || '?';
16
+ return (first(words[0]) + first(words[1])).toUpperCase();
17
+ }
18
+ const HUES = [252, 200, 160, 128, 85, 40, 12, 330, 296];
19
+ /** The hue of a workspace's colour, `oklch(.66 .13 <hue>)`: always the same for one id. */
20
+ export function workspaceHue(id) {
21
+ let h = 2166136261;
22
+ for (let i = 0; i < id.length; i++) {
23
+ h ^= id.charCodeAt(i);
24
+ h = Math.imul(h, 16777619);
25
+ }
26
+ return HUES[(h >>> 0) % HUES.length];
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vocalstack/sanity",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "VocalStack for Sanity Studio: a Transcribe button next to every audio file.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,7 +22,8 @@
22
22
  "sideEffects": false,
23
23
  "scripts": {
24
24
  "build": "rm -rf dist && tsc -p tsconfig.json",
25
- "typecheck": "tsc -p tsconfig.json --noEmit"
25
+ "typecheck": "tsc -p tsconfig.json --noEmit",
26
+ "test": "npm run build && node --test test/*.test.mjs"
26
27
  },
27
28
  "peerDependencies": {
28
29
  "@sanity/ui": "^2.0.0 || ^3.0.0 || ^4.0.0",