@vocalstack/payload 0.0.0-stage → 0.1.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.
@@ -0,0 +1,180 @@
1
+ import { DEFAULT_API_URL, VocalStackAPI } from '../api.js';
2
+ import { resolveAPIKey } from '../settings.js';
3
+ import { attachWords } from '../text.js';
4
+ import { apiError, checkJob, locate, toSentences } from './transcribe.js';
5
+ const OVER = new Set(['done', 'failed', 'cropping', 'ended', 'finalized']);
6
+ /**
7
+ * GET /:id/vocalstack/stream: the job live, as Server-Sent Events. The server holds
8
+ * the VocalStack subscribe socket (the API key never reaches the browser) and sends
9
+ * progress { progress, phase, audio } as it changes
10
+ * snapshot { sentences } everything so far, once caught up
11
+ * sentence { sentence } | { id, removed } a settled sentence, new or rewritten
12
+ * draft { words } words heard after the last settled sentence
13
+ * done | failed | stopped (StatusResponse) once, saved on the document; then it closes
14
+ * Sentences carry their words as [start, end, text]. A dropped stream is resumed by
15
+ * EventSource: it reconnects and gets a fresh snapshot.
16
+ */
17
+ export function streamEndpoint(collection, options, rowFields) {
18
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
19
+ return {
20
+ method: 'get',
21
+ path: '/:id/vocalstack/stream',
22
+ handler: async (req) => {
23
+ if (!req.user)
24
+ return Response.json({ error: 'Sign in first.' }, { status: 401 });
25
+ const target = await locate(req, collection, options, rowFields, 'user');
26
+ if (target instanceof Response)
27
+ return target;
28
+ const recordingId = target.data.recordingId;
29
+ if (target.data.status !== 'processing' || !recordingId)
30
+ return Response.json({ status: target.data.status ?? 'idle', vocalstack: target.data });
31
+ const apiKey = await resolveAPIKey(req, options);
32
+ if (!apiKey)
33
+ return Response.json({ code: 'not_connected', error: 'Connect VocalStack first.' }, { status: 409 });
34
+ const api = new VocalStackAPI(apiKey, apiURL);
35
+ const encoder = new TextEncoder();
36
+ let socket;
37
+ let heartbeat;
38
+ let draftTimer;
39
+ let closed = false;
40
+ const stream = new ReadableStream({
41
+ cancel() {
42
+ closed = true;
43
+ cleanup();
44
+ },
45
+ start(controller) {
46
+ const send = (event, data) => {
47
+ if (!closed)
48
+ controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
49
+ };
50
+ const finish = (result) => {
51
+ if (closed)
52
+ return;
53
+ send(result.stopped ? 'stopped' : result.status === 'processing' ? 'progress' : result.status, result);
54
+ closed = true;
55
+ cleanup();
56
+ controller.close();
57
+ };
58
+ // VocalStack signals the end several ways (progress, state, socket close); check once at a time.
59
+ let settling;
60
+ const settle = () => (settling ??= checkJob(api, target, recordingId)
61
+ .then((r) => (r.status === 'processing' ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
62
+ .finally(() => (settling = undefined)));
63
+ // What the page has been told: settled sentences by id, the words of committed
64
+ // segments (sentences take theirs by time), and the words heard since.
65
+ const sentences = new Map();
66
+ const segmentWords = new Map();
67
+ let draft = [];
68
+ let caughtUp = false;
69
+ let lastProgress = '';
70
+ const withWords = (s, seqs) => {
71
+ const pool = seqs?.length ? seqs.flatMap((q) => segmentWords.get(q) ?? []) : [...segmentWords.values()].flat();
72
+ return attachWords([s], pool)[0];
73
+ };
74
+ const sendDraft = () => {
75
+ draftTimer = undefined;
76
+ const settledTo = Math.max(0, ...[...sentences.values()].map((s) => s.end));
77
+ draft = draft.filter((w) => w.end > settledTo);
78
+ send('draft', { words: draft.map((w) => [w.start, w.end, w.text.trim()]) });
79
+ };
80
+ const scheduleDraft = () => {
81
+ if (caughtUp)
82
+ draftTimer ??= setTimeout(sendDraft, 200);
83
+ };
84
+ controller.enqueue(encoder.encode('retry: 2000\n\n'));
85
+ heartbeat = setInterval(() => !closed && controller.enqueue(encoder.encode(': ping\n\n')), 15000);
86
+ const wsURL = `${apiURL.replace(/^http/, 'ws')}/v1/recordings/${encodeURIComponent(recordingId)}/subscribe`;
87
+ // Node's WebSocket (undici) takes headers, which the DOM type does not know about.
88
+ socket = new WebSocket(wsURL, { headers: { authorization: `Bearer ${apiKey}` } });
89
+ socket.onmessage = (message) => {
90
+ let frame;
91
+ try {
92
+ frame = JSON.parse(String(message.data));
93
+ }
94
+ catch {
95
+ return;
96
+ }
97
+ switch (frame.type) {
98
+ case 'job.progress': {
99
+ if (frame.state && OVER.has(frame.state))
100
+ return void settle();
101
+ const progress = frame.state === 'fetching' ? (frame.phasePct ?? 0) : (frame.pct ?? 0);
102
+ const audio = frame.processedS !== undefined ? { processedS: frame.processedS, totalS: frame.totalS ?? undefined } : undefined;
103
+ const update = { audio, phase: frame.state === 'fetching' ? (frame.phase ?? 'fetching') : frame.state, progress, status: 'processing' };
104
+ // VocalStack repeats progress frames; pass on only what changed.
105
+ const key = JSON.stringify(update);
106
+ if (key === lastProgress)
107
+ return;
108
+ lastProgress = key;
109
+ return send('progress', update);
110
+ }
111
+ case 'recording.state':
112
+ case 'subscribe.ready':
113
+ if (frame.state && OVER.has(frame.state))
114
+ return void settle();
115
+ if (frame.type === 'subscribe.ready') {
116
+ // Catch up on everything said before the socket opened. Live frames that
117
+ // arrive meanwhile update the same maps by id, so the overlap is harmless.
118
+ void api.transcript(recordingId).then((t) => {
119
+ for (const g of t.segments ?? [])
120
+ if (!g.suppressed && g.words)
121
+ segmentWords.set(g.seq, g.words);
122
+ for (const s of toSentences(t))
123
+ if (s.id !== undefined && !sentences.has(s.id))
124
+ sentences.set(s.id, s);
125
+ caughtUp = true;
126
+ send('snapshot', { sentences: [...sentences.values()].sort((a, b) => a.start - b.start) });
127
+ scheduleDraft();
128
+ }, () => undefined);
129
+ }
130
+ return;
131
+ case 'transcript.committed':
132
+ if (frame.segment && !frame.segment.suppressed && frame.segment.words)
133
+ segmentWords.set(frame.segment.seq, frame.segment.words);
134
+ return;
135
+ case 'transcript.sentence': {
136
+ const s = frame.sentence;
137
+ if (!s)
138
+ return;
139
+ if (s.suppressed || !s.text.trim()) {
140
+ sentences.delete(s.sentenceId);
141
+ if (caughtUp)
142
+ send('sentence', { id: s.sentenceId, removed: true });
143
+ }
144
+ else {
145
+ const sentence = withWords({ id: s.sentenceId, end: s.end, speaker: s.speaker, start: s.start, text: s.text.trim() }, s.seqs);
146
+ sentences.set(s.sentenceId, sentence);
147
+ if (caughtUp)
148
+ send('sentence', { sentence });
149
+ }
150
+ return scheduleDraft();
151
+ }
152
+ case 'transcript.words':
153
+ draft.push(...(frame.words ?? []));
154
+ return scheduleDraft();
155
+ }
156
+ };
157
+ // The socket ended without the job ending: say where it stands, then let EventSource reconnect.
158
+ socket.onclose = () => {
159
+ if (!closed)
160
+ void settle().then(() => !closed && (closed = true, cleanup(), controller.close()));
161
+ };
162
+ },
163
+ });
164
+ function cleanup() {
165
+ clearInterval(heartbeat);
166
+ clearTimeout(draftTimer);
167
+ if (socket && socket.readyState <= 1)
168
+ socket.close();
169
+ }
170
+ try {
171
+ return new Response(stream, {
172
+ headers: { 'cache-control': 'no-cache, no-transform', connection: 'keep-alive', 'content-type': 'text/event-stream; charset=utf-8', 'x-accel-buffering': 'no' },
173
+ });
174
+ }
175
+ catch (err) {
176
+ return apiError(err);
177
+ }
178
+ },
179
+ };
180
+ }
@@ -0,0 +1,25 @@
1
+ import type { CollectionSlug, Endpoint, PayloadRequest } from 'payload';
2
+ import type { AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
3
+ import { type Transcript, VocalStackAPI } from '../api.js';
4
+ /** One transcribable thing: an upload document, or one row of an array field. */
5
+ export type Target = {
6
+ data: VocalStackFieldData;
7
+ fileName: string;
8
+ name: string;
9
+ save: (patch: VocalStackFieldData) => Promise<VocalStackFieldData>;
10
+ url: () => Promise<string | undefined>;
11
+ };
12
+ export declare function locate(req: PayloadRequest, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], readAs: 'admin' | 'user'): Promise<Response | Target>;
13
+ /** A transcript's sentences, each with its words. */
14
+ export declare function toSentences(t: Pick<Transcript, 'segments' | 'sentences'>): TranscriptSentence[];
15
+ export declare function apiError(err: unknown): Response;
16
+ /**
17
+ * Where a job stands, saving the outcome on the document once it is over: the
18
+ * whole transcript when done, the reason when it failed.
19
+ */
20
+ export declare function checkJob(api: VocalStackAPI, target: Target, recordingId: string): Promise<StatusResponse>;
21
+ /**
22
+ * POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
23
+ * they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
24
+ */
25
+ export declare function transcribeEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint[];
@@ -0,0 +1,257 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
3
+ import { fetchFile, isPublicURL, resolveFileURL } from '../fileSource.js';
4
+ import { attachWords, transcriptText } from '../text.js';
5
+ import { resolveAPIKey } from '../settings.js';
6
+ const json = (body, status = 200) => Response.json(body, { status });
7
+ /**
8
+ * Saves to one document, one at a time. Payload writes array fields by deleting and
9
+ * re-inserting every row (of every array), so two overlapping saves collide in the database.
10
+ */
11
+ const queues = new Map();
12
+ function serially(key, run) {
13
+ const next = (queues.get(key) ?? Promise.resolve()).then(run, run);
14
+ const settled = next.catch(() => undefined);
15
+ queues.set(key, settled);
16
+ void settled.then(() => queues.get(key) === settled && queues.delete(key));
17
+ return next;
18
+ }
19
+ /** Finished jobs being saved, so that every "done" signal for one job shares a single save. */
20
+ const finishing = new Map();
21
+ /** Whether the signed-in user may update this document, by the collection's own `access.update`. */
22
+ async function canUpdate(req, collection, id) {
23
+ if (!req.user)
24
+ return false;
25
+ const access = req.payload.collections[collection]?.config.access.update;
26
+ if (!access)
27
+ return true;
28
+ const result = await access({ id, req });
29
+ if (typeof result !== 'object')
30
+ return Boolean(result);
31
+ const { totalDocs } = await req.payload.count({ collection, overrideAccess: true, req, where: { and: [{ id: { equals: id } }, result] } });
32
+ return totalDocs > 0;
33
+ }
34
+ export async function locate(req, collection, options, rowFields, readAs) {
35
+ const id = req.routeParams?.id;
36
+ const find = (overrideAccess) => req.payload.findByID({ id, collection, depth: 0, overrideAccess, req, user: req.user }).catch(() => null);
37
+ const doc = await find(readAs === 'admin');
38
+ if (!doc)
39
+ return json({ error: 'Not found.' }, 404);
40
+ const field = req.searchParams.get('field');
41
+ if (!field) {
42
+ const upload = doc;
43
+ if (!req.payload.collections[collection]?.config.upload)
44
+ return json({ error: 'Not an upload collection.' }, 400);
45
+ if (!upload.mimeType?.startsWith('audio/'))
46
+ return json({ error: 'Only audio files can be transcribed.' }, 400);
47
+ return {
48
+ data: upload.vocalstack ?? {},
49
+ fileName: upload.filename ?? 'audio',
50
+ name: upload.filename ?? `${collection} ${id}`,
51
+ save: (patch) => serially(`${collection}:${id}`, async () => {
52
+ const vocalstack = { ...upload.vocalstack, ...patch };
53
+ await req.payload.update({ id, collection, data: { vocalstack }, depth: 0, overrideAccess: true, req });
54
+ return vocalstack;
55
+ }),
56
+ url: () => resolveFileURL(req, collection, upload, options),
57
+ };
58
+ }
59
+ const config = rowFields.find((f) => f.field === field);
60
+ if (!config)
61
+ return json({ error: `${field} is not a VocalStack audio field.` }, 400);
62
+ const rowId = req.searchParams.get('row');
63
+ const row = (doc[field] ?? []).find((r) => r.id === rowId);
64
+ if (!row)
65
+ return json({ error: 'Save the document first, then transcribe.' }, 404);
66
+ const base = req.payload.config.serverURL || req.origin;
67
+ return {
68
+ data: row.vocalstack ?? {},
69
+ fileName: 'audio',
70
+ name: config.name?.({ doc, row }) ?? (typeof doc.title === 'string' && doc.title ? doc.title : `${collection} ${id}`),
71
+ save: (patch) => serially(`${collection}:${id}`, async () => {
72
+ // Re-read so edits saved to other rows meanwhile are kept; arrays are written whole.
73
+ const fresh = (await find(true)) ?? doc;
74
+ let saved;
75
+ const rows = (fresh[field] ?? []).map((r) => {
76
+ if (r.id !== rowId)
77
+ return r;
78
+ saved = { ...r.vocalstack, ...patch };
79
+ return { ...r, vocalstack: saved };
80
+ });
81
+ if (!saved)
82
+ throw new Error('That row was removed.');
83
+ await req.payload.update({ id, collection, data: { [field]: rows }, depth: 0, overrideAccess: true, req });
84
+ return saved;
85
+ }),
86
+ url: async () => {
87
+ const url = await config.audioURL({ doc, req, row });
88
+ return url ? new URL(url, base).toString() : undefined;
89
+ },
90
+ };
91
+ }
92
+ /** A transcript's sentences, each with its words. */
93
+ export function toSentences(t) {
94
+ const sentences = t.sentences
95
+ .filter((s) => !s.suppressed && s.text.trim())
96
+ .map(({ end, sentenceId, speaker, start, text }) => ({ id: sentenceId, end, speaker, start, text: text.trim() }));
97
+ return attachWords(sentences, (t.segments ?? []).filter((g) => !g.suppressed).flatMap((g) => g.words ?? []));
98
+ }
99
+ export function apiError(err) {
100
+ if (err instanceof VocalStackAPIError) {
101
+ const status = err.status === 401 ? 409 : err.status >= 500 ? 502 : err.status;
102
+ const code = err.status === 401 ? 'not_connected' : err.code;
103
+ const message = err.status === 401 ? 'The VocalStack API key was refused. Reconnect VocalStack.' : err.message;
104
+ return json({ code, error: message }, status);
105
+ }
106
+ return json({ error: err instanceof Error ? err.message : String(err) }, 500);
107
+ }
108
+ /**
109
+ * Where a job stands, saving the outcome on the document once it is over: the
110
+ * whole transcript when done, the reason when it failed.
111
+ */
112
+ export async function checkJob(api, target, recordingId) {
113
+ const job = await api.job(recordingId);
114
+ if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
115
+ return restore(target);
116
+ if (job.state === 'failed' || job.state === 'cropping') {
117
+ const error = job.state === 'cropping' ? 'VocalStack is waiting for a crop window; open the transcription in VocalStack.' : (job.error ?? 'The transcription failed.');
118
+ return { error, status: 'failed', vocalstack: await target.save({ error, status: 'failed' }) };
119
+ }
120
+ if (job.state !== 'done') {
121
+ const progress = job.state === 'fetching' ? (job.progress.phasePct ?? 0) : job.progress.pct;
122
+ if (job.state !== 'transcribing')
123
+ return { phase: job.progress.phase ?? job.state, progress, status: 'processing' };
124
+ // Sentences are readable while the job runs; send what is there so far.
125
+ const partial = await api.transcript(recordingId).then(toSentences, () => undefined);
126
+ return { audio: { processedS: job.progress.processedS ?? 0, totalS: job.progress.totalS ?? undefined }, partial, phase: 'transcribing', progress, status: 'processing' };
127
+ }
128
+ let saving = finishing.get(recordingId);
129
+ if (!saving) {
130
+ saving = saveTranscript(api, target, recordingId);
131
+ finishing.set(recordingId, saving);
132
+ void saving.catch(() => undefined).then(() => finishing.delete(recordingId));
133
+ }
134
+ return saving;
135
+ }
136
+ /**
137
+ * A stopped job leaves the field as it was before Transcribe: the earlier transcript, if
138
+ * there was one (a new job only replaces it once done), or none. The job's partial
139
+ * transcript stays in VocalStack.
140
+ */
141
+ async function restore(target) {
142
+ const status = target.data.transcript ? 'done' : 'idle';
143
+ return { status, stopped: true, vocalstack: await target.save({ error: null, status }) };
144
+ }
145
+ async function saveTranscript(api, target, recordingId) {
146
+ const transcript = await api.transcript(recordingId);
147
+ const sentences = toSentences(transcript);
148
+ const vocalstack = await target.save({
149
+ error: null,
150
+ language: transcript.lang ?? transcript.sentences.find((s) => s.language)?.language ?? null,
151
+ sentences,
152
+ status: 'done',
153
+ transcribedAt: new Date().toISOString(),
154
+ transcript: transcriptText(sentences),
155
+ });
156
+ return { progress: 100, status: 'done', vocalstack };
157
+ }
158
+ /**
159
+ * POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
160
+ * they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
161
+ */
162
+ export function transcribeEndpoints(collection, options, rowFields) {
163
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
164
+ return [
165
+ {
166
+ method: 'post',
167
+ path: '/:id/vocalstack/transcribe',
168
+ handler: async (req) => {
169
+ const id = req.routeParams?.id;
170
+ if (!(await canUpdate(req, collection, id)))
171
+ return json({ error: 'You may not transcribe this file.' }, 403);
172
+ if (options.access && !(await options.access({ req })))
173
+ return json({ error: 'You may not transcribe this file.' }, 403);
174
+ const apiKey = await resolveAPIKey(req, options);
175
+ if (!apiKey)
176
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
177
+ const target = await locate(req, collection, options, rowFields, 'admin');
178
+ if (target instanceof Response)
179
+ return target;
180
+ if (target.data.status === 'processing')
181
+ return json({ status: 'processing', vocalstack: target.data });
182
+ const url = await target.url();
183
+ if (!url)
184
+ return json({ error: 'There is no audio file here.' }, 400);
185
+ const api = new VocalStackAPI(apiKey, apiURL);
186
+ const call = { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage: options.spokenLanguage };
187
+ try {
188
+ const tx = isPublicURL(url)
189
+ ? await api.transcribeURL(url, call)
190
+ : await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
191
+ if (!tx.job)
192
+ throw new Error('VocalStack did not start a job for this file.');
193
+ const vocalstack = await target.save({ error: null, recordingId: tx.job.recordingId, status: 'processing', transcriptionId: tx.id });
194
+ return json({ phase: tx.job.state, progress: 0, status: 'processing', vocalstack }, 202);
195
+ }
196
+ catch (err) {
197
+ return apiError(err);
198
+ }
199
+ },
200
+ },
201
+ {
202
+ method: 'get',
203
+ path: '/:id/vocalstack/status',
204
+ handler: async (req) => {
205
+ if (!req.user)
206
+ return json({ error: 'Sign in first.' }, 401);
207
+ // Read through access control: only someone who can see the document sees its status.
208
+ const target = await locate(req, collection, options, rowFields, 'user');
209
+ if (target instanceof Response)
210
+ return target;
211
+ const field = target.data;
212
+ if (field.status !== 'processing' || !field.recordingId)
213
+ return json({ status: field.status ?? 'idle', vocalstack: field });
214
+ const apiKey = await resolveAPIKey(req, options);
215
+ if (!apiKey)
216
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
217
+ try {
218
+ return json(await checkJob(new VocalStackAPI(apiKey, apiURL), target, field.recordingId));
219
+ }
220
+ catch (err) {
221
+ return apiError(err);
222
+ }
223
+ },
224
+ },
225
+ {
226
+ method: 'post',
227
+ path: '/:id/vocalstack/stop',
228
+ handler: async (req) => {
229
+ const id = req.routeParams?.id;
230
+ if (!(await canUpdate(req, collection, id)))
231
+ return json({ error: 'You may not stop this transcription.' }, 403);
232
+ if (options.access && !(await options.access({ req })))
233
+ return json({ error: 'You may not stop this transcription.' }, 403);
234
+ const apiKey = await resolveAPIKey(req, options);
235
+ if (!apiKey)
236
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
237
+ const target = await locate(req, collection, options, rowFields, 'admin');
238
+ if (target instanceof Response)
239
+ return target;
240
+ const { recordingId, status } = target.data;
241
+ if (status !== 'processing' || !recordingId)
242
+ return json({ status: status ?? 'idle', vocalstack: target.data });
243
+ const api = new VocalStackAPI(apiKey, apiURL);
244
+ try {
245
+ await api.stop(recordingId, 'Stopped from Payload');
246
+ return json(await restore(target));
247
+ }
248
+ catch (err) {
249
+ // Too late to stop: the job ended meanwhile, so take its outcome instead.
250
+ if (err instanceof VocalStackAPIError && err.status === 409)
251
+ return json(await checkJob(api, target, recordingId).catch(() => restore(target)));
252
+ return apiError(err);
253
+ }
254
+ },
255
+ },
256
+ ];
257
+ }
@@ -0,0 +1,3 @@
1
+ export { ConnectionPanel } from '../components/ConnectionPanel.js';
2
+ export { TranscribeButton } from '../components/TranscribeButton.js';
3
+ export { TranscriptField } from '../components/TranscriptField.js';
@@ -0,0 +1,4 @@
1
+ 'use client';
2
+ export { ConnectionPanel } from '../components/ConnectionPanel.js';
3
+ export { TranscribeButton } from '../components/TranscribeButton.js';
4
+ export { TranscriptField } from '../components/TranscriptField.js';
@@ -0,0 +1,12 @@
1
+ import type { CollectionSlug, PayloadRequest } from 'payload';
2
+ import type { UploadDoc, VocalStackPluginOptions } from './types.js';
3
+ /** The absolute address of an upload's file. */
4
+ export declare function resolveFileURL(req: PayloadRequest, collection: CollectionSlug, doc: UploadDoc, options: VocalStackPluginOptions): Promise<string | undefined>;
5
+ /**
6
+ * Whether VocalStack can fetch this address itself. The API refuses loopback,
7
+ * private and link-local hosts, so for those (local development, an intranet)
8
+ * the plugin sends the bytes instead.
9
+ */
10
+ export declare function isPublicURL(url: string): boolean;
11
+ /** The file's bytes, for an upload VocalStack cannot reach by link. */
12
+ export declare function fetchFile(req: PayloadRequest, url: string): Promise<Blob>;
@@ -0,0 +1,40 @@
1
+ /** The absolute address of an upload's file. */
2
+ export async function resolveFileURL(req, collection, doc, options) {
3
+ const custom = await options.fileURL?.({ collection, doc, req });
4
+ const url = custom ?? doc.url;
5
+ if (!url)
6
+ return undefined;
7
+ const base = req.payload.config.serverURL || req.origin;
8
+ return new URL(url, base).toString();
9
+ }
10
+ /**
11
+ * Whether VocalStack can fetch this address itself. The API refuses loopback,
12
+ * private and link-local hosts, so for those (local development, an intranet)
13
+ * the plugin sends the bytes instead.
14
+ */
15
+ export function isPublicURL(url) {
16
+ const { hostname, protocol } = new URL(url);
17
+ if (protocol !== 'https:' && protocol !== 'http:')
18
+ return false;
19
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
20
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal'))
21
+ return false;
22
+ const v4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
23
+ if (v4) {
24
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
25
+ return !(a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127));
26
+ }
27
+ if (host.includes(':'))
28
+ return !(host === '::1' || host.startsWith('fc') || host.startsWith('fd') || host.startsWith('fe80'));
29
+ return true;
30
+ }
31
+ /** The file's bytes, for an upload VocalStack cannot reach by link. */
32
+ export async function fetchFile(req, url) {
33
+ // Same-origin files go through Payload's access control: pass the editor's cookie along.
34
+ const sameOrigin = new URL(url).origin === req.origin;
35
+ const cookie = req.headers.get('cookie');
36
+ const res = await fetch(url, { headers: sameOrigin && cookie ? { cookie } : {} });
37
+ if (!res.ok)
38
+ throw new Error(`Could not read the file (${res.status} from ${url})`);
39
+ return res.blob();
40
+ }
@@ -0,0 +1,5 @@
1
+ import type { Plugin } from 'payload';
2
+ import type { VocalStackPluginOptions } from './types.js';
3
+ export type * from './types.js';
4
+ export { timedTokens, transcriptText } from './text.js';
5
+ export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,113 @@
1
+ import { connectionEndpoints } from './endpoints/connection.js';
2
+ import { streamEndpoint } from './endpoints/stream.js';
3
+ import { transcribeEndpoints } from './endpoints/transcribe.js';
4
+ import { settingsGlobal } from './settings.js';
5
+ export { timedTokens, transcriptText } from './text.js';
6
+ const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
7
+ /** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
8
+ function acceptsAudio(collection) {
9
+ if (!collection.upload)
10
+ return false;
11
+ const mimeTypes = collection.upload === true ? undefined : collection.upload.mimeTypes;
12
+ return !mimeTypes?.length || mimeTypes.some((m) => m.startsWith('audio') || m === '*' || m === '*/*');
13
+ }
14
+ const hidden = { admin: { hidden: true, readOnly: true } };
15
+ /** The Transcribe button and the `vocalstack` group, for an upload document or for each row of an array. */
16
+ function transcriptionFields(enabled, options, target) {
17
+ return [
18
+ ...(enabled
19
+ ? [
20
+ {
21
+ name: 'vocalstackTranscribe',
22
+ type: 'ui',
23
+ admin: {
24
+ components: {
25
+ Field: {
26
+ clientProps: { field: target.field, oneClickConnect: Boolean(options.oneClickConnect) },
27
+ path: '@vocalstack/payload/client#TranscribeButton',
28
+ },
29
+ },
30
+ condition: target.condition,
31
+ ...(target.sidebar ? { position: 'sidebar' } : {}),
32
+ },
33
+ },
34
+ ]
35
+ : []),
36
+ {
37
+ name: 'vocalstack',
38
+ type: 'group',
39
+ label: 'Transcript',
40
+ admin: { condition: target.condition },
41
+ fields: [
42
+ {
43
+ name: 'transcript',
44
+ type: 'textarea',
45
+ label: false,
46
+ admin: { components: { Field: '@vocalstack/payload/client#TranscriptField' } },
47
+ },
48
+ {
49
+ name: 'status',
50
+ type: 'select',
51
+ defaultValue: 'idle',
52
+ options: ['idle', 'processing', 'done', 'failed'],
53
+ ...hidden,
54
+ },
55
+ { name: 'error', type: 'text', ...hidden },
56
+ { name: 'language', type: 'text', ...hidden },
57
+ { name: 'recordingId', type: 'text', ...hidden },
58
+ { name: 'transcriptionId', type: 'text', ...hidden },
59
+ { name: 'transcribedAt', type: 'date', ...hidden },
60
+ // [{ start, end, speaker, text }] in seconds, for captions or a synced player.
61
+ { name: 'sentences', type: 'json', ...hidden },
62
+ ],
63
+ },
64
+ ];
65
+ }
66
+ /** Add fields to the named array, looking through unnamed containers (rows, collapsibles, unnamed tabs). */
67
+ function addToArray(fields, name, extra) {
68
+ let found = false;
69
+ const visit = (list) => list.map((f) => {
70
+ if (found)
71
+ return f;
72
+ if (f.type === 'array' && f.name === name) {
73
+ found = true;
74
+ return { ...f, fields: [...f.fields, ...extra] };
75
+ }
76
+ if ((f.type === 'row' || f.type === 'collapsible') && !('name' in f && f.name))
77
+ return { ...f, fields: visit(f.fields) };
78
+ if (f.type === 'tabs')
79
+ return { ...f, tabs: f.tabs.map((t) => ('name' in t && t.name ? t : { ...t, fields: visit(t.fields) })) };
80
+ return f;
81
+ });
82
+ return { fields: visit(fields), found };
83
+ }
84
+ export const vocalstackPlugin = (options = {}) => (config) => {
85
+ const enabled = options.enabled !== false;
86
+ const collections = config.collections ?? [];
87
+ const uploads = new Set(options.collections ?? collections.filter(acceptsAudio).map((c) => c.slug));
88
+ const audioFields = options.audioFields ?? [];
89
+ return {
90
+ ...config,
91
+ collections: collections.map((collection) => {
92
+ const rowFields = audioFields.filter((f) => f.collection === collection.slug);
93
+ const isUpload = uploads.has(collection.slug);
94
+ if (!isUpload && !rowFields.length)
95
+ return collection;
96
+ let fields = isUpload ? [...collection.fields, ...transcriptionFields(enabled, options, { condition: isAudioDoc, sidebar: true })] : collection.fields;
97
+ for (const row of rowFields) {
98
+ const condition = (_, siblingData) => (row.condition ? row.condition(siblingData) : true);
99
+ const result = addToArray(fields, row.field, transcriptionFields(enabled, options, { condition, field: row.field, sidebar: false }));
100
+ if (!result.found)
101
+ throw new Error(`vocalstackPlugin: no array field "${row.field}" in collection "${collection.slug}"`);
102
+ fields = result.fields;
103
+ }
104
+ return {
105
+ ...collection,
106
+ endpoints: enabled ? [...(collection.endpoints || []), ...transcribeEndpoints(collection.slug, options, rowFields), streamEndpoint(collection.slug, options, rowFields)] : collection.endpoints,
107
+ fields,
108
+ };
109
+ }),
110
+ endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options)] : config.endpoints,
111
+ globals: [...(config.globals ?? []), settingsGlobal(options)],
112
+ };
113
+ };