@phnx-labs/artifacts-cli 0.8.3-pre.1 → 0.9.1

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,874 @@
1
+ import { mediaClock, mediaMentionMeta, mediaNormalizeSummary, mediaParseTime, mediaPromptTranscript, mediaSummarySchema, mediaTranscriptFromDeepgram, mediaViewerClient, mediaVtt, mediaVttTime, } from './media-core.js';
2
+ // The media job (PHNX-4287), injected into the generated share Worker beside
3
+ // the publish source. A video that finishes a multipart upload is transcribed
4
+ // by Deepgram (which fetches it through a single-use signed link and calls back
5
+ // with an HMAC-signed URL), summarized by OpenRouter under a zero-data-retention
6
+ // provider constraint, and its three derived files are written beside it:
7
+ //
8
+ // <path>.transcript.json [{start,end,speaker,text}]
9
+ // <path>.vtt WebVTT captions
10
+ // <path>.summary.json {title,summary,chapters,action_items,mentions}
11
+ //
12
+ // Derived files carry media-derived/media-source/media-job markers (reserved
13
+ // metadata keys, so no publish or edit can forge them). Reads gate on the
14
+ // SOURCE video's visibility, listings hide them, and nothing charges them to a
15
+ // quota ledger. The job record at __media-jobs/<id> is the authority on
16
+ // progress, and __media-videos/<path> points a video version at its current
17
+ // job. Once a job finishes, the video's own `media` metadata (ready | failed,
18
+ // plus pr/ticket mentions) mirrors it for `artifacts share list --meta`. The whole
19
+ // feature is off unless DEEPGRAM_API_KEY, OPENROUTER_API_KEY and
20
+ // MEDIA_JOB_SECRET are all bound.
21
+ export const SHARE_MEDIA_WORKER_SOURCE = `
22
+ var mediaTranscriptFromDeepgram = ${mediaTranscriptFromDeepgram};
23
+ var mediaVttTime = ${mediaVttTime};
24
+ var mediaVtt = ${mediaVtt};
25
+ var mediaClock = ${mediaClock};
26
+ var mediaSummarySchema = ${mediaSummarySchema};
27
+ var mediaNormalizeSummary = ${mediaNormalizeSummary};
28
+ var mediaMentionMeta = ${mediaMentionMeta};
29
+ var mediaPromptTranscript = ${mediaPromptTranscript};
30
+ var MEDIA_VIEWER_JS = ${JSON.stringify('var mediaParseTime = ' + mediaParseTime + ';(' + mediaViewerClient + ')();')};
31
+
32
+ var MEDIA_SUMMARY_MODEL = 'anthropic/claude-sonnet-5.5';
33
+ var MEDIA_DERIVED_SUFFIX = { transcript: '.transcript.json', captions: '.vtt', summary: '.summary.json' };
34
+ // Deepgram must fetch the source and call back within this window; a job still
35
+ // waiting after it is reported failed, so a lost callback never hangs forever.
36
+ var MEDIA_TRANSCRIBE_WINDOW_MS = 6 * 3600 * 1000;
37
+ // Cloudflare cuts ctx.waitUntil work off 30s after the response. Persist that
38
+ // deadline before starting callback work so status and listings can resolve an
39
+ // interrupted transcript/summary/listing step without a page view.
40
+ var MEDIA_WAITUNTIL_WINDOW_MS = 30 * 1000;
41
+ var MEDIA_UPSTREAM_TIMEOUT_MS = 25000;
42
+ var MEDIA_CALLBACK_MAX_BYTES = 64 * MiB;
43
+ var MEDIA_PROMPT_MAX_CHARS = 300000;
44
+ var MEDIA_ERROR_MAX_CHARS = 200;
45
+ // The metadata mirror copies the video in place; past this it would not fit
46
+ // the background budget, so the job fails with an owner-visible reason.
47
+ var MEDIA_MIRROR_MAX_BYTES = 512 * MiB;
48
+ var MEDIA_MIRROR_ATTEMPTS = 3;
49
+ var MEDIA_SUMMARY_PROMPT = 'You summarize screen recordings for a software team. You get a diarized transcript; each line starts with its time in seconds. ' +
50
+ 'Answer with JSON only. title: a short specific title. summary: 2-5 plain sentences on what was shown and decided. ' +
51
+ 'chapters: the main sections in order, each with the start time t in seconds and a short title. ' +
52
+ 'action_items: concrete follow-ups someone committed to or was asked to do, each with the time t in seconds where it came up. ' +
53
+ 'mentions.prs: pull requests named, as owner/repo#123, #123, or a GitHub pull URL. mentions.tickets: issue keys named, such as PHNX-4287. ' +
54
+ 'Use empty arrays when there are none. Never invent content that is not in the transcript.';
55
+
56
+ function mediaConfig(env) {
57
+ const read = function (name) { return typeof env[name] === 'string' ? env[name].trim() : ''; };
58
+ const deepgramKey = read('DEEPGRAM_API_KEY');
59
+ const openrouterKey = read('OPENROUTER_API_KEY');
60
+ const secret = read('MEDIA_JOB_SECRET');
61
+ if (!deepgramKey || !openrouterKey || !secret) return null;
62
+ return {
63
+ deepgramKey: deepgramKey,
64
+ openrouterKey: openrouterKey,
65
+ secret: secret,
66
+ };
67
+ }
68
+
69
+ function isMediaDerived(obj) {
70
+ return !!obj && !!obj.customMetadata && obj.customMetadata['media-derived'] === 'true';
71
+ }
72
+
73
+ function isVideoObject(obj) {
74
+ const ct = (obj && obj.httpMetadata && obj.httpMetadata.contentType) || '';
75
+ return ct.toLowerCase().indexOf('video/') === 0;
76
+ }
77
+
78
+ // The video a derived key belongs to, or '' when the marker does not describe
79
+ // a sibling of the key itself (same namespace, one of the three suffixes).
80
+ function mediaSourceOf(key, derived) {
81
+ const source = (derived.customMetadata && derived.customMetadata['media-source']) || '';
82
+ if (!source) return '';
83
+ for (const kind in MEDIA_DERIVED_SUFFIX) {
84
+ if (key === source + MEDIA_DERIVED_SUFFIX[kind]) return source;
85
+ }
86
+ return '';
87
+ }
88
+
89
+ function mediaErrorText(error) {
90
+ const message = error && typeof error.message === 'string' ? error.message : String(error || 'media job failed');
91
+ return message.replace(/[^\\x20-\\x7e]/g, '?').slice(0, MEDIA_ERROR_MAX_CHARS);
92
+ }
93
+
94
+ function mediaJobKey(id) {
95
+ return '__media-jobs/' + id;
96
+ }
97
+
98
+ async function mediaSig(cfg, purpose, id) {
99
+ return hmacHex(cfg.secret, 'media-' + purpose + ':' + id);
100
+ }
101
+
102
+ async function readMediaJob(bucket, id) {
103
+ if (!/^[0-9a-f-]{36}$/.test(id)) return null;
104
+ const object = await bucket.get(mediaJobKey(id));
105
+ if (!object) return null;
106
+ return { object: object, job: JSON.parse(await object.text()) };
107
+ }
108
+
109
+ // Compare-and-swap edit of one job record. mutate returns false to leave it
110
+ // alone; the result says whether this call changed it.
111
+ async function patchMediaJob(env, id, mutate) {
112
+ for (let attempt = 0; attempt < 6; attempt++) {
113
+ const record = await readMediaJob(env.BUCKET, id);
114
+ if (!record) return { changed: false, job: null };
115
+ const job = record.job;
116
+ if (mutate(job) === false) return { changed: false, job: job };
117
+ job.updatedAt = Date.now();
118
+ const written = await env.BUCKET.put(mediaJobKey(id), JSON.stringify(job), {
119
+ httpMetadata: { contentType: 'application/json' },
120
+ onlyIf: { etagMatches: record.object.etag },
121
+ });
122
+ if (written !== null) return { changed: true, job: job };
123
+ }
124
+ throw new Error('media job record is contended');
125
+ }
126
+
127
+ // Which video a job belongs to. The pointer at __media-videos/<path> names the
128
+ // current job and the version of the video it was started for. The version
129
+ // survives a PATCH and this job's own metadata write (both keep
130
+ // multipart-token / published-at) and changes on any republish, so a replaced
131
+ // video never inherits the old recording's transcript.
132
+ function mediaPointerKey(path) {
133
+ return '__media-videos/' + encodeURIComponent(path);
134
+ }
135
+
136
+ function mediaVideoVersion(video) {
137
+ const meta = video.customMetadata || {};
138
+ return meta['multipart-token'] || meta['published-at'] || new Date(video.uploaded).toISOString();
139
+ }
140
+
141
+ async function readMediaPointer(env, path) {
142
+ const object = await env.BUCKET.get(mediaPointerKey(path));
143
+ if (!object) return null;
144
+ return { object: object, pointer: JSON.parse(await object.text()) };
145
+ }
146
+
147
+ // The job record the video at path currently answers to, or null.
148
+ async function currentMediaJob(env, path, video) {
149
+ const record = await readMediaPointer(env, path);
150
+ if (!record || record.pointer.version !== mediaVideoVersion(video)) return null;
151
+ const job = await readMediaJob(env.BUCKET, record.pointer.jobId);
152
+ return job ? job.job : { id: record.pointer.jobId, missing: true };
153
+ }
154
+
155
+ async function isCurrentMediaJob(env, path, id) {
156
+ const video = await env.BUCKET.head(path);
157
+ if (!video) return false;
158
+ const job = await currentMediaJob(env, path, video);
159
+ return !!job && job.id === id;
160
+ }
161
+
162
+ // Point the video at a new job. replace=false (the upload trigger) declines a
163
+ // video version that already has one, so a replayed multipart complete never
164
+ // starts a second job; the conditional write lets one of two racing retries win.
165
+ async function claimMediaVideo(env, path, video, id, replace) {
166
+ const current = await readMediaPointer(env, path);
167
+ const version = mediaVideoVersion(video);
168
+ if (current && !replace && current.pointer.version === version) return false;
169
+ const written = await env.BUCKET.put(mediaPointerKey(path), JSON.stringify({ jobId: id, version: version, path: path }), {
170
+ httpMetadata: { contentType: 'application/json' },
171
+ onlyIf: current ? { etagMatches: current.object.etag } : { etagDoesNotMatch: '*' },
172
+ });
173
+ return written !== null;
174
+ }
175
+
176
+ // Mirror a finished job onto the video's own metadata (media=ready|failed plus
177
+ // pr/ticket) for 'artifacts share list --meta'. R2 has no metadata-only update,
178
+ // so this streams the stored bytes back in place under the per-path lock, like
179
+ // a PATCH. It runs once, at the end, and only for videos small enough to copy
180
+ // inside the Worker's background budget; the job record stays the authority
181
+ // for the page and the status route either way. The outcome is recorded on the
182
+ // job. A ready-state copy that is too large, busy, interrupted or rejected
183
+ // fails the job; the persisted deadline covers a Worker killed mid-stream.
184
+ // Failed-state mirrors remain best-effort and are capped across later reads.
185
+ async function mirrorMediaMeta(env, id) {
186
+ const record = await readMediaJob(env.BUCKET, id);
187
+ if (!record || (record.job.status !== 'ready' && record.job.status !== 'failed' && !(record.job.status === 'processing' && record.job.stage === 'listing')) || record.job.metaSynced || record.job.metaNote) return;
188
+ const job = record.job;
189
+ const targetStatus = job.status === 'processing' ? 'ready' : job.status;
190
+ const path = job.path;
191
+ const attempt = await patchMediaJob(env, id, function (current) {
192
+ if (current.status !== job.status || current.stage !== job.stage || current.metaSynced || current.metaNote) return false;
193
+ current.metaAttempts = (current.metaAttempts || 0) + 1;
194
+ if (current.metaAttempts > MEDIA_MIRROR_ATTEMPTS) {
195
+ current.metaNote = 'listing metadata was not rewritten after ' + MEDIA_MIRROR_ATTEMPTS + ' attempts';
196
+ }
197
+ });
198
+ if (!attempt.changed || attempt.job.metaNote) return;
199
+ let note = '';
200
+ try {
201
+ const video = await env.BUCKET.head(path);
202
+ if (!video || !(await isCurrentMediaJob(env, path, id))) return;
203
+ if (video.size > MEDIA_MIRROR_MAX_BYTES) {
204
+ throw new Error('the video is over ' + Math.round(MEDIA_MIRROR_MAX_BYTES / MiB) + ' MiB and cannot be rewritten inside the media job budget');
205
+ } else {
206
+ const version = mediaVideoVersion(video);
207
+ const summary = targetStatus === 'ready' ? await readMediaDerived(env, path, id, 'summary') : null;
208
+ const written = await updateVideoMeta(env, path, version, function (meta) {
209
+ if (summary) Object.assign(meta, mediaMentionMeta(summary, meta));
210
+ meta.media = targetStatus;
211
+ });
212
+ if (!written) return;
213
+ }
214
+ } catch (error) {
215
+ // A ready job is not complete until the in-place metadata stream lands. A
216
+ // size cap, busy path, lost lock, R2 refusal, or thrown stream must become a
217
+ // durable failure instead of disappearing into a Worker log.
218
+ if (targetStatus === 'ready') {
219
+ await failMediaJob(env, id, error, true);
220
+ return;
221
+ }
222
+ note = 'listing metadata was not rewritten: ' + mediaErrorText(error);
223
+ }
224
+ await patchMediaJob(env, id, function (current) {
225
+ if (current.status !== job.status || current.stage !== job.stage) return false;
226
+ if (note) current.metaNote = note;
227
+ else {
228
+ current.metaSynced = true;
229
+ if (targetStatus === 'ready') {
230
+ current.status = 'ready';
231
+ current.stage = 'done';
232
+ current.error = '';
233
+ delete current.deadlineAt;
234
+ }
235
+ }
236
+ });
237
+ }
238
+
239
+ async function updateVideoMeta(env, path, version, mutate) {
240
+ const holder = 'media:' + crypto.randomUUID();
241
+ let lock = null;
242
+ for (let attempt = 0; attempt < 20 && !lock; attempt++) {
243
+ lock = await acquirePathMutationLock(env.BUCKET, path, holder, 'mutation');
244
+ if (!lock) await new Promise(function (resolve) { setTimeout(resolve, 250); });
245
+ }
246
+ if (!lock) {
247
+ const busy = new Error('the video is busy with another write');
248
+ busy.mediaRetryable = true;
249
+ throw busy;
250
+ }
251
+ try {
252
+ const existing = await env.BUCKET.get(path);
253
+ if (!existing) return false;
254
+ if (mediaVideoVersion(existing) !== version) {
255
+ await existing.body.cancel();
256
+ return false;
257
+ }
258
+ const metadata = { ...(existing.customMetadata || {}) };
259
+ mutate(metadata);
260
+ if (!metadata['published-at']) metadata['published-at'] = new Date(existing.uploaded).toISOString();
261
+ const httpHeaders = new Headers();
262
+ existing.writeHttpMetadata(httpHeaders);
263
+ if (!(await pathMutationLockOwned(env.BUCKET, path, holder))) throw new Error('lost the video write lock');
264
+ const written = await env.BUCKET.put(path, existing.body, {
265
+ httpMetadata: httpHeaders,
266
+ customMetadata: metadata,
267
+ onlyIf: { etagMatches: existing.etag },
268
+ });
269
+ if (written === null) throw new Error('the video changed during the metadata write');
270
+ return true;
271
+ } finally {
272
+ await releasePathMutationLock(env.BUCKET, path, holder);
273
+ }
274
+ }
275
+
276
+ // Record a failure on the job (the authority the page and status read), then
277
+ // mirror it. If even the job record cannot be written, the Worker log is the
278
+ // last place left to say so.
279
+ async function recordMediaFailure(env, id, error) {
280
+ const message = mediaErrorText(error);
281
+ return patchMediaJob(env, id, function (job) {
282
+ if (job.status === 'ready' || job.status === 'failed') return false;
283
+ job.status = 'failed';
284
+ job.error = message;
285
+ delete job.deadlineAt;
286
+ });
287
+ }
288
+
289
+ async function failMediaJob(env, id, error, skipMirror) {
290
+ const message = mediaErrorText(error);
291
+ try {
292
+ const failed = await recordMediaFailure(env, id, message);
293
+ if (failed.changed && !skipMirror) await mirrorMediaMeta(env, id);
294
+ } catch (recordError) {
295
+ console.error('media job ' + id + ' failed (' + message + ') and the failure could not be recorded: ' + mediaErrorText(recordError));
296
+ }
297
+ }
298
+
299
+ function upstreamDetail(text) {
300
+ let detail = '';
301
+ try {
302
+ const parsed = JSON.parse(text);
303
+ const err = parsed && (parsed.error || parsed.err_msg || parsed.message);
304
+ detail = err && typeof err === 'object' ? (err.message || JSON.stringify(err)) : String(err || '');
305
+ } catch (e) {
306
+ detail = String(text || '');
307
+ }
308
+ detail = detail.trim().slice(0, 160);
309
+ return detail ? ': ' + detail : '';
310
+ }
311
+
312
+ // Create a job for the video at path and hand its single-use source link to
313
+ // Deepgram. Returns the job, or null when the claim was declined (see
314
+ // claimMediaVideo). A Deepgram refusal fails the job (recorded, never thrown).
315
+ async function startMediaJob(env, cfg, origin, path, video, replace) {
316
+ const id = crypto.randomUUID();
317
+ const now = Date.now();
318
+ const job = { id: id, path: path, status: 'transcribing', stage: 'transcribe', createdAt: now, updatedAt: now, deadlineAt: now + MEDIA_TRANSCRIBE_WINDOW_MS, requestId: '', sourceUsed: false, error: '' };
319
+ const created = await env.BUCKET.put(mediaJobKey(id), JSON.stringify(job), {
320
+ httpMetadata: { contentType: 'application/json' },
321
+ onlyIf: { etagDoesNotMatch: '*' },
322
+ });
323
+ if (created === null) throw new Error('media job id collided; retry');
324
+ if (!(await claimMediaVideo(env, path, video, id, replace))) {
325
+ await env.BUCKET.delete(mediaJobKey(id));
326
+ return null;
327
+ }
328
+ try {
329
+ const source = origin + '/__media/source?job=' + id + '&sig=' + (await mediaSig(cfg, 'source', id));
330
+ const callback = origin + '/__media/callback?job=' + id + '&sig=' + (await mediaSig(cfg, 'callback', id));
331
+ const params = new URLSearchParams({
332
+ model: 'nova-3', smart_format: 'true', utterances: 'true', paragraphs: 'true', diarize: 'true', callback: callback,
333
+ });
334
+ let res;
335
+ try {
336
+ res = await fetch('https://api.deepgram.com/v1/listen?' + params.toString(), {
337
+ method: 'POST',
338
+ headers: { authorization: 'Token ' + cfg.deepgramKey, 'content-type': 'application/json', accept: 'application/json' },
339
+ body: JSON.stringify({ url: source }),
340
+ signal: AbortSignal.timeout(MEDIA_UPSTREAM_TIMEOUT_MS),
341
+ });
342
+ } catch (error) {
343
+ throw new Error('Deepgram unreachable: ' + mediaErrorText(error));
344
+ }
345
+ const text = await res.text();
346
+ if (!res.ok) throw new Error('Deepgram answered ' + res.status + upstreamDetail(text));
347
+ let requestId = '';
348
+ try { requestId = String(JSON.parse(text).request_id || ''); } catch (e) { /* the callback still identifies itself by job */ }
349
+ await patchMediaJob(env, id, function (current) {
350
+ if (current.status !== 'transcribing' || current.requestId) return false;
351
+ current.requestId = requestId;
352
+ });
353
+ } catch (error) {
354
+ await failMediaJob(env, id, error);
355
+ }
356
+ return job;
357
+ }
358
+
359
+ // The upload trigger: a finished video upload (multipart or one request) starts its job in the
360
+ // background. Never throws into the response that already succeeded.
361
+ async function startMediaAfterUpload(env, origin, path) {
362
+ const cfg = mediaConfig(env);
363
+ if (!cfg) return;
364
+ try {
365
+ const video = await env.BUCKET.head(path);
366
+ if (!video || !isVideoObject(video)) return;
367
+ await startMediaJob(env, cfg, origin, path, video, false);
368
+ } catch (error) {
369
+ console.error('media job for ' + path + ' could not start: ' + mediaErrorText(error));
370
+ }
371
+ }
372
+
373
+ async function writeMediaDerived(env, path, id, kind, body, contentType) {
374
+ const key = path + MEDIA_DERIVED_SUFFIX[kind];
375
+ const existing = await env.BUCKET.head(key);
376
+ if (existing && !isMediaDerived(existing)) {
377
+ throw new Error(key.split('/').pop() + ' already holds a published file; move it, then retry');
378
+ }
379
+ if (!(await isCurrentMediaJob(env, path, id))) {
380
+ throw new Error('the video was replaced or deleted while it was processing');
381
+ }
382
+ await env.BUCKET.put(key, body, {
383
+ httpMetadata: { contentType: contentType },
384
+ customMetadata: { 'media-derived': 'true', 'media-source': path, 'media-job': id },
385
+ });
386
+ }
387
+
388
+ async function readMediaDerived(env, path, id, kind) {
389
+ const object = await env.BUCKET.get(path + MEDIA_DERIVED_SUFFIX[kind]);
390
+ if (!object || !isMediaDerived(object) || object.customMetadata['media-job'] !== id) {
391
+ if (object) await object.body.cancel();
392
+ return null;
393
+ }
394
+ return JSON.parse(await object.text());
395
+ }
396
+
397
+ // Remove a deleted or expired video's derived files and job pointer. Runs on
398
+ // the shared DELETE and expiry paths after their refund, best-effort: a
399
+ // leftover file is unreadable anyway once its video is gone.
400
+ async function deleteMediaDerived(env, path) {
401
+ try {
402
+ for (const kind in MEDIA_DERIVED_SUFFIX) {
403
+ const key = path + MEDIA_DERIVED_SUFFIX[kind];
404
+ const derived = await env.BUCKET.head(key);
405
+ if (derived && isMediaDerived(derived) && mediaSourceOf(key, derived) === path) await env.BUCKET.delete(key);
406
+ }
407
+ await env.BUCKET.delete(mediaPointerKey(path));
408
+ } catch (error) {
409
+ console.error('derived media files for ' + path + ' were not removed: ' + mediaErrorText(error));
410
+ }
411
+ }
412
+
413
+ async function requestMediaSummary(cfg, path, lines, duration) {
414
+ const name = path.split('/').pop();
415
+ let res;
416
+ try {
417
+ res = await fetch('https://openrouter.ai/api/v1/chat/completions', {
418
+ method: 'POST',
419
+ headers: { authorization: 'Bearer ' + cfg.openrouterKey, 'content-type': 'application/json', 'x-title': 'artifacts share' },
420
+ body: JSON.stringify({
421
+ model: MEDIA_SUMMARY_MODEL,
422
+ messages: [
423
+ { role: 'system', content: MEDIA_SUMMARY_PROMPT },
424
+ { role: 'user', content: 'Recording: ' + name + '\\nLength: ' + Math.round(duration) + ' seconds\\n\\nTranscript:\\n' + mediaPromptTranscript(lines, MEDIA_PROMPT_MAX_CHARS) },
425
+ ],
426
+ response_format: { type: 'json_schema', json_schema: { name: 'recording_summary', strict: true, schema: mediaSummarySchema() } },
427
+ // Zero data retention: only providers that neither train on nor keep
428
+ // the prompt may serve this request, and none may ignore the schema.
429
+ // No temperature: with require_parameters, no ZDR endpoint advertises it,
430
+ // and OpenRouter answers 404 "No endpoints found" (seen live, PHNX-4287).
431
+ provider: { data_collection: 'deny', zdr: true, require_parameters: true },
432
+ }),
433
+ signal: AbortSignal.timeout(MEDIA_UPSTREAM_TIMEOUT_MS),
434
+ });
435
+ } catch (error) {
436
+ throw new Error('OpenRouter unreachable: ' + mediaErrorText(error));
437
+ }
438
+ const text = await res.text();
439
+ if (!res.ok) throw new Error('OpenRouter answered ' + res.status + upstreamDetail(text));
440
+ let content;
441
+ try {
442
+ const parsed = JSON.parse(text);
443
+ content = parsed && parsed.choices && parsed.choices[0] && parsed.choices[0].message && parsed.choices[0].message.content;
444
+ } catch (e) {
445
+ throw new Error('OpenRouter answered with a body that is not JSON');
446
+ }
447
+ if (typeof content !== 'string') throw new Error('OpenRouter returned no message content' + upstreamDetail(text));
448
+ let raw;
449
+ try { raw = JSON.parse(content); } catch (e) { throw new Error('OpenRouter returned a summary that is not JSON'); }
450
+ return mediaNormalizeSummary(raw, duration);
451
+ }
452
+
453
+ async function summarizeMediaJob(env, cfg, id, path, lines) {
454
+ try {
455
+ const duration = lines.length ? lines[lines.length - 1].end : 0;
456
+ const summary = lines.length
457
+ ? await requestMediaSummary(cfg, path, lines, duration)
458
+ : { title: path.split('/').pop(), summary: 'No speech was detected in this recording.', chapters: [], action_items: [], mentions: { prs: [], tickets: [] } };
459
+ await writeMediaDerived(env, path, id, 'summary', JSON.stringify(summary), 'application/json; charset=utf-8');
460
+ const finished = await patchMediaJob(env, id, function (job) {
461
+ if (job.status !== 'processing') return false;
462
+ job.stage = 'listing';
463
+ });
464
+ if (!finished.changed) throw new Error('the media job changed while it was summarizing');
465
+ // The job remains pending until the in-place listing metadata stream lands.
466
+ // If waitUntil is cut off during that stream, its already-persisted deadline
467
+ // makes both status and listings report failure.
468
+ await mirrorMediaMeta(env, id);
469
+ } catch (error) {
470
+ await failMediaJob(env, id, error);
471
+ }
472
+ }
473
+
474
+ // GET /__media/source?job&sig — the single-use link Deepgram fetches the video
475
+ // through. Valid once, for a job still waiting on its transcript, inside the
476
+ // transcription window, for the exact video the job claimed.
477
+ async function handleMediaSource(request, env, url) {
478
+ const cfg = mediaConfig(env);
479
+ if (!cfg) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
480
+ if (request.method !== 'GET' && request.method !== 'HEAD') return json({ error: 'method not allowed' }, 405);
481
+ const id = url.searchParams.get('job') || '';
482
+ if (!id || !safeEqual(url.searchParams.get('sig') || '', await mediaSig(cfg, 'source', id))) {
483
+ return json({ error: 'invalid media source signature' }, 403);
484
+ }
485
+ const record = await readMediaJob(env.BUCKET, id);
486
+ if (!record) return json({ error: 'unknown media job' }, 404);
487
+ const job = record.job;
488
+ const gone = json({ error: 'this media source link was already used or has expired' }, 410);
489
+ if (job.status !== 'transcribing' || job.sourceUsed || Date.now() - job.createdAt > MEDIA_TRANSCRIBE_WINDOW_MS) return gone;
490
+ const video = await env.BUCKET.head(job.path);
491
+ if (!video) return gone;
492
+ const current = await currentMediaJob(env, job.path, video);
493
+ if (!current || current.id !== id) return gone;
494
+ const headers = new Headers({ 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex' });
495
+ video.writeHttpMetadata(headers);
496
+ if (request.method === 'HEAD') return new Response(null, { status: 200, headers: headers });
497
+ const used = await patchMediaJob(env, id, function (current) {
498
+ if (current.status !== 'transcribing' || current.sourceUsed) return false;
499
+ current.sourceUsed = true;
500
+ });
501
+ if (!used.changed) return gone;
502
+ const object = await env.BUCKET.get(job.path);
503
+ if (!object || object.etag !== video.etag) return gone;
504
+ return new Response(object.body, { status: 200, headers: headers });
505
+ }
506
+
507
+ // POST /__media/callback?job&sig — Deepgram's result. The HMAC over the job id
508
+ // proves it is ours; the transcribing -> processing compare-and-swap accepts
509
+ // it exactly once. Once accepted it always answers 200: whatever fails after
510
+ // that is recorded on the job and the video, where status and the page show it.
511
+ async function handleMediaCallback(request, env, url, ctx) {
512
+ const cfg = mediaConfig(env);
513
+ if (!cfg) return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain' } });
514
+ if (request.method !== 'POST') return json({ error: 'method not allowed' }, 405);
515
+ const id = url.searchParams.get('job') || '';
516
+ if (!id || !safeEqual(url.searchParams.get('sig') || '', await mediaSig(cfg, 'callback', id))) {
517
+ return json({ error: 'invalid media callback signature' }, 403);
518
+ }
519
+ const record = await readMediaJob(env.BUCKET, id);
520
+ if (!record) return json({ error: 'unknown media job' }, 404);
521
+ if (record.job.status !== 'transcribing') return json({ error: 'this media job already accepted its callback' }, 409);
522
+ const read = await readBodyBounded(request, MEDIA_CALLBACK_MAX_BYTES);
523
+ let body = null;
524
+ if (!read.oversize) {
525
+ try { body = JSON.parse(new TextDecoder().decode(read.bytes)); } catch (e) { body = null; }
526
+ }
527
+ const requestId = body && body.metadata && typeof body.metadata.request_id === 'string' ? body.metadata.request_id : '';
528
+ if (record.job.requestId && requestId && requestId !== record.job.requestId) {
529
+ return json({ error: 'callback request_id does not match this media job' }, 409);
530
+ }
531
+ const accepted = await patchMediaJob(env, id, function (job) {
532
+ if (job.status !== 'transcribing') return false;
533
+ job.status = 'processing';
534
+ job.stage = 'transcript';
535
+ job.deadlineAt = Date.now() + MEDIA_WAITUNTIL_WINDOW_MS;
536
+ });
537
+ if (!accepted.changed) return json({ error: 'this media job already accepted its callback' }, 409);
538
+ const path = accepted.job.path;
539
+ try {
540
+ if (read.oversize) throw new Error('Deepgram callback exceeded ' + MEDIA_CALLBACK_MAX_BYTES + ' bytes');
541
+ if (!body) throw new Error('Deepgram callback body is not JSON');
542
+ const lines = mediaTranscriptFromDeepgram(body);
543
+ await writeMediaDerived(env, path, id, 'transcript', JSON.stringify(lines), 'application/json; charset=utf-8');
544
+ await writeMediaDerived(env, path, id, 'captions', mediaVtt(lines), 'text/vtt; charset=utf-8');
545
+ await patchMediaJob(env, id, function (job) { job.stage = 'summary'; });
546
+ ctx.waitUntil(summarizeMediaJob(env, cfg, id, path, lines));
547
+ } catch (error) {
548
+ await failMediaJob(env, id, error);
549
+ }
550
+ return json({ ok: true, job: id }, 200);
551
+ }
552
+
553
+ // Where a video's media stands. 'pending' past its window is reported (and,
554
+ // by the caller, recorded) as failed: a job never stays pending forever.
555
+ async function mediaState(env, path, video) {
556
+ const job = await currentMediaJob(env, path, video);
557
+ if (!job) return { media: 'none', stage: '', error: '', jobId: '', updatedAt: null, stale: false, heal: false };
558
+ const id = job.id;
559
+ if (job.missing) {
560
+ return { media: 'failed', stage: '', error: 'the media job record is missing; retry', jobId: id, updatedAt: null, stale: false, heal: false };
561
+ }
562
+ let media = job.status === 'ready' ? 'ready' : job.status === 'failed' ? 'failed' : 'pending';
563
+ let error = job.error || '';
564
+ let stale = false;
565
+ const now = Date.now();
566
+ const deadlineAt = typeof job.deadlineAt === 'number'
567
+ ? job.deadlineAt
568
+ : job.updatedAt + (job.status === 'transcribing' ? MEDIA_TRANSCRIBE_WINDOW_MS : MEDIA_WAITUNTIL_WINDOW_MS);
569
+ if (job.status === 'transcribing' && now > deadlineAt) {
570
+ stale = true;
571
+ error = 'Deepgram never called back';
572
+ } else if (job.status === 'processing' && now > deadlineAt) {
573
+ stale = true;
574
+ error = 'the ' + (job.stage === 'summary' ? 'summary' : job.stage === 'listing' ? 'listing' : 'transcript') + ' step stopped before it finished';
575
+ }
576
+ if (stale) media = 'failed';
577
+ // A finished job whose metadata mirror never recorded an outcome was cut off.
578
+ const heal = !stale && (job.status === 'ready' || job.status === 'failed') && !job.metaSynced && !job.metaNote;
579
+ return {
580
+ media: media, stage: job.stage, error: error, jobId: id, updatedAt: job.updatedAt, stale: stale, heal: heal,
581
+ metaSynced: !!job.metaSynced, metaNote: job.metaNote || '',
582
+ };
583
+ }
584
+
585
+ // The listing's meta.media value is derived from the same authoritative job
586
+ // record as ?media=status, not from user metadata. Pointer keys are listed by
587
+ // namespace first so non-media videos cost no job reads. A stale deadline is
588
+ // persisted as failed while the listing is already returning that state.
589
+ async function mediaListingStates(env, user, videos) {
590
+ const prefix = mediaPointerKey(user + '/');
591
+ const pointed = {};
592
+ let cursor;
593
+ do {
594
+ const list = await env.BUCKET.list({ prefix: prefix, limit: 1000, cursor: cursor });
595
+ const pointers = list.objects || [];
596
+ for (const pointer of pointers) {
597
+ try { pointed[decodeURIComponent(pointer.key.slice('__media-videos/'.length))] = true; } catch (e) { /* ignore an invalid internal key */ }
598
+ }
599
+ cursor = list.truncated ? list.cursor : undefined;
600
+ } while (cursor);
601
+ const states = {};
602
+ await Promise.all(videos.map(async function (video) {
603
+ if (!pointed[video.key]) return;
604
+ const state = await mediaState(env, video.key, video);
605
+ if (state.stale && state.jobId) await recordMediaFailure(env, state.jobId, state.error);
606
+ if (state.media !== 'none') states[video.key] = state.media;
607
+ }));
608
+ return states;
609
+ }
610
+
611
+ // A read that finds a stale job records its failure; one that finds a finished
612
+ // job without a mirror outcome retries the mirror. Both off the response path.
613
+ function noteStaleMedia(env, ctx, state) {
614
+ if (!ctx || typeof ctx.waitUntil !== 'function') return;
615
+ if (state.stale) ctx.waitUntil(failMediaJob(env, state.jobId, state.error));
616
+ else if (state.heal) ctx.waitUntil(mirrorMediaMeta(env, state.jobId));
617
+ }
618
+
619
+ // What the video page renders: the state, plus the transcript and summary once
620
+ // ready. Files that vanished from under a ready job read as a failure. Only the
621
+ // owner sees why a job failed; the reason can quote an upstream response.
622
+ async function mediaViewData(env, ctx, video, path, isOwner) {
623
+ const state = await mediaState(env, path, video);
624
+ if (state.media === 'none') return null;
625
+ noteStaleMedia(env, ctx, state);
626
+ const view = { state: state.media, stage: state.stage, error: isOwner ? state.error : '', transcript: null, summary: null };
627
+ if (state.media !== 'ready') return view;
628
+ try {
629
+ view.transcript = await readMediaDerived(env, path, state.jobId, 'transcript');
630
+ view.summary = await readMediaDerived(env, path, state.jobId, 'summary');
631
+ } catch (error) {
632
+ view.transcript = null;
633
+ }
634
+ if (!view.transcript || !view.summary) {
635
+ return { state: 'failed', stage: state.stage, error: isOwner ? 'the transcript files are missing; retry' : '', transcript: null, summary: null };
636
+ }
637
+ return view;
638
+ }
639
+
640
+ // <video>?media=status (anyone who may watch the video) and
641
+ // <video>?media=retry (the namespace owner).
642
+ async function handleMediaRoute(request, env, url, path, action, ctx) {
643
+ const segments = path.split('/').filter(Boolean);
644
+ if (segments.length !== 2) return json({ error: 'media ' + action + ' requires /<username>/<slug>' }, 400);
645
+ if (action === 'retry') {
646
+ if (request.method !== 'POST') return json({ error: 'method not allowed' }, 405);
647
+ const auth = await authorizeWrite(request, env);
648
+ if (auth.error) return auth.error;
649
+ const notOwner = await assertNamespaceOwner(env, auth, segments);
650
+ if (notOwner) return notOwner;
651
+ const cfg = mediaConfig(env);
652
+ if (!cfg) return json({ error: 'media processing is not configured on this endpoint; bind it with artifacts share update --media-keys' }, 501);
653
+ const video = await env.BUCKET.head(path);
654
+ if (!video || isMediaDerived(video)) return json({ error: 'share not found', key: path }, 404);
655
+ if (!isVideoObject(video)) return json({ error: 'media processing needs a video' }, 415);
656
+ const state = await mediaState(env, path, video);
657
+ if (state.media === 'pending') return json({ error: 'the media job is still running', job: state.jobId, stage: state.stage }, 409);
658
+ if (state.stale) await failMediaJob(env, state.jobId, state.error);
659
+ // A summary-step failure keeps its transcript: re-run only the summary
660
+ // rather than paying for a second transcription.
661
+ const lines = state.media === 'failed' && (state.stage === 'summary' || state.stage === 'listing')
662
+ ? await readMediaDerived(env, path, state.jobId, 'transcript')
663
+ : null;
664
+ if (lines) {
665
+ const summary = state.stage === 'listing'
666
+ ? await readMediaDerived(env, path, state.jobId, 'summary')
667
+ : null;
668
+ const resumed = await patchMediaJob(env, state.jobId, function (job) {
669
+ if (job.status !== 'failed') return false;
670
+ job.status = 'processing';
671
+ job.stage = summary ? 'listing' : 'summary';
672
+ job.error = '';
673
+ job.deadlineAt = Date.now() + MEDIA_WAITUNTIL_WINDOW_MS;
674
+ delete job.metaSynced;
675
+ delete job.metaNote;
676
+ delete job.metaAttempts;
677
+ });
678
+ if (!resumed.changed) return json({ error: 'the media job changed; retry' }, 409);
679
+ if (summary) ctx.waitUntil(mirrorMediaMeta(env, state.jobId));
680
+ else ctx.waitUntil(summarizeMediaJob(env, cfg, state.jobId, path, lines));
681
+ return json({ ok: true, path: path, media: 'pending', stage: summary ? 'listing' : 'summary', job: state.jobId }, 202);
682
+ }
683
+ let job;
684
+ try {
685
+ job = await startMediaJob(env, cfg, url.origin, path, video, true);
686
+ } catch (error) {
687
+ return json({ error: 'could not start the media job: ' + mediaErrorText(error) }, 503);
688
+ }
689
+ if (!job) return json({ error: 'another media job claimed this video first; check its status' }, 409);
690
+ const started = await readMediaJob(env.BUCKET, job.id);
691
+ if (started && started.job.status === 'failed') return json({ error: started.job.error, path: path, media: 'failed', job: job.id }, 502);
692
+ return json({ ok: true, path: path, media: 'pending', stage: 'transcribe', job: job.id }, 202);
693
+ }
694
+
695
+ if (request.method !== 'GET' && request.method !== 'HEAD') return json({ error: 'method not allowed' }, 405);
696
+ const video = await env.BUCKET.head(path);
697
+ const expiresAt = video && video.customMetadata && video.customMetadata['expires-at'];
698
+ if (!video || isMediaDerived(video) || (expiresAt && Date.now() > Date.parse(expiresAt))) {
699
+ return json({ error: 'share not found', key: path }, 404);
700
+ }
701
+ const viewer = await resolveViewer(request, env, url);
702
+ if (viewer.redirect) return viewer.redirect;
703
+ const visibility = (video.customMetadata && video.customMetadata.visibility) || 'public';
704
+ if (viewer.error && isIdentityGated(visibility)) return viewer.error;
705
+ const identity = viewer.identity || null;
706
+ const denied = (await gateVisibility(url, env, video, identity)) || (await gateTokenRead(request, url, video, identity));
707
+ if (denied) {
708
+ denied.headers.set('cache-control', 'private, no-store');
709
+ return denied;
710
+ }
711
+ const bearer = (request.headers.get('authorization') || '').replace(/^Bearer\\s+/i, '');
712
+ const owner = (!!identity && handleFromEmail(identity.email) === segments[0]) ||
713
+ (!!bearer && !!env.WRITE_TOKEN && safeEqual(bearer, env.WRITE_TOKEN));
714
+ const state = await mediaState(env, path, video);
715
+ noteStaleMedia(env, ctx, state);
716
+ const base = url.origin + '/' + path;
717
+ const body = {
718
+ path: path,
719
+ media: state.media,
720
+ stage: state.stage || null,
721
+ job: state.jobId || null,
722
+ updatedAt: state.updatedAt ? new Date(state.updatedAt).toISOString() : null,
723
+ error: state.media === 'failed' ? (owner ? state.error : 'media processing failed') : null,
724
+ // Whether media=/pr=/ticket= reached the video's listing metadata (see
725
+ // mirrorMediaMeta); the reason it did not is for the owner.
726
+ listed: state.media === 'ready' || state.media === 'failed' ? state.metaSynced : null,
727
+ listedNote: owner && state.metaNote ? state.metaNote : null,
728
+ files: state.media === 'ready'
729
+ ? { transcript: base + MEDIA_DERIVED_SUFFIX.transcript, captions: base + MEDIA_DERIVED_SUFFIX.captions, summary: base + MEDIA_DERIVED_SUFFIX.summary }
730
+ : null,
731
+ };
732
+ return new Response(request.method === 'HEAD' ? null : JSON.stringify(body), {
733
+ status: 200,
734
+ headers: { 'content-type': 'application/json', 'cache-control': 'private, no-store', 'X-Robots-Tag': 'noindex' },
735
+ });
736
+ }
737
+
738
+ // GET of a derived file: the source video's gate decides, exactly as if the
739
+ // reader had asked for the video itself. Anything off (a source that is gone,
740
+ // expired, replaced, or not this key's sibling) is a plain 404.
741
+ async function serveMediaDerived(request, env, url, path, derived) {
742
+ const notFound = function () {
743
+ return new Response('not found', { status: 404, headers: { 'content-type': 'text/plain', 'cache-control': 'private, no-store' } });
744
+ };
745
+ const sourcePath = mediaSourceOf(path, derived);
746
+ const video = sourcePath ? await env.BUCKET.head(sourcePath) : null;
747
+ if (!video || isMediaDerived(video)) return notFound();
748
+ const expiresAt = video.customMetadata && video.customMetadata['expires-at'];
749
+ if (expiresAt && Date.now() > Date.parse(expiresAt)) return notFound();
750
+ // Only the current video's own job: a file left from a recording this video
751
+ // replaced must not be read under the replacement's (maybe wider) gate.
752
+ const job = await currentMediaJob(env, sourcePath, video);
753
+ if (!job || derived.customMetadata['media-job'] !== job.id) return notFound();
754
+ const visibility = (video.customMetadata && video.customMetadata.visibility) || 'public';
755
+ const gated = isIdentityGated(visibility) || visibility === 'private';
756
+ const privately = function (response) {
757
+ if (gated) {
758
+ response.headers.set('cache-control', 'private, no-store');
759
+ response.headers.set('X-Robots-Tag', 'noindex');
760
+ }
761
+ return response;
762
+ };
763
+ const viewer = await resolveViewer(request, env, url);
764
+ if (viewer.redirect) return privately(viewer.redirect);
765
+ if (viewer.error && isIdentityGated(visibility)) return privately(viewer.error);
766
+ const identity = viewer.identity || null;
767
+ const denied = (await gateVisibility(url, env, video, identity)) || (await gateTokenRead(request, url, video, identity));
768
+ if (denied) return privately(denied);
769
+ const headers = new Headers();
770
+ derived.writeHttpMetadata(headers);
771
+ if (gated) {
772
+ headers.set('cache-control', 'private, no-store');
773
+ headers.set('X-Robots-Tag', 'noindex');
774
+ } else {
775
+ headers.set('cache-control', 'public, max-age=60');
776
+ if (visibility === 'unlisted') headers.set('X-Robots-Tag', 'noindex');
777
+ }
778
+ if (request.method === 'HEAD') return new Response(null, { status: 200, headers: headers });
779
+ const object = await env.BUCKET.get(path);
780
+ if (!object) return notFound();
781
+ return new Response(object.body, { status: 200, headers: headers });
782
+ }
783
+
784
+ // The video page with its media: player + captions track, chapter ticks on a
785
+ // scrub strip, summary, action items, and the transcript rail — or the
786
+ // processing / failed state in place of the media panels.
787
+ function renderMediaPanels(pathname, media, opts) {
788
+ const seekLink = function (t) {
789
+ return '<a class="mv-ts" href="?t=' + Math.floor(t) + '" data-mv-seek="' + t + '">' + mediaClock(t) + '</a>';
790
+ };
791
+ const ready = media.state === 'ready';
792
+ const summary = media.summary || { title: '', summary: '', chapters: [], action_items: [] };
793
+ const transcript = media.transcript || [];
794
+ const track = ready ? '<track kind="captions" src="' + escapeHtml(pathname + MEDIA_DERIVED_SUFFIX.captions) + '" srclang="en" label="Transcript" default>' : '';
795
+ const player = '<video data-mv-video src="' + escapeHtml(pathname + '?raw=1') + '" controls playsinline preload="metadata">' + track + '</video>' +
796
+ '<div class="mv-strip" data-mv-strip title="Chapters"><div class="mv-fill" data-mv-fill></div>' +
797
+ summary.chapters.map(function (c) {
798
+ return '<button type="button" class="mv-tick" hidden data-mv-tick data-mv-seek="' + c.t + '" title="' + escapeHtml(mediaClock(c.t) + ' ' + c.title) + '" aria-label="' + escapeHtml('Chapter: ' + c.title) + '"></button>';
799
+ }).join('') + '</div>';
800
+
801
+ let panels = '';
802
+ if (!ready) {
803
+ const failed = media.state === 'failed';
804
+ const heading = failed
805
+ ? 'Transcript and summary failed'
806
+ : (media.stage === 'summary' ? 'Summarizing…' : media.stage === 'listing' ? 'Finalizing…' : 'Transcribing…');
807
+ const detail = failed
808
+ ? (media.error ? escapeHtml(media.error) : 'Media processing failed.')
809
+ : 'The transcript, captions and summary appear here when processing finishes. This page refreshes on its own.';
810
+ panels = '<section class="mv-card mv-status' + (failed ? ' mv-failed' : '') + '" role="status">' +
811
+ (failed ? '' : '<span class="mv-spin" aria-hidden="true"></span>') +
812
+ '<div><h2>' + heading + '</h2><p data-mv-note>' + detail + '</p>' +
813
+ (failed && opts.canRetry ? '<button type="button" class="mv-retry" data-mv-retry>Retry</button>' : '') +
814
+ '</div></section>';
815
+ } else {
816
+ panels = '<section class="mv-card"><h1>' + escapeHtml(summary.title) + '</h1><p class="mv-summary">' + escapeHtml(summary.summary) + '</p></section>' +
817
+ (summary.chapters.length ? '<section class="mv-card"><h2>Chapters</h2><ol class="mv-list">' +
818
+ summary.chapters.map(function (c) { return '<li>' + seekLink(c.t) + '<span>' + escapeHtml(c.title) + '</span></li>'; }).join('') + '</ol></section>' : '') +
819
+ '<section class="mv-card"><h2>Action items</h2>' + (summary.action_items.length
820
+ ? '<ul class="mv-list">' + summary.action_items.map(function (a) { return '<li>' + seekLink(a.t) + '<span>' + escapeHtml(a.text) + '</span></li>'; }).join('') + '</ul>'
821
+ : '<p class="mv-empty">No action items.</p>') + '</section>';
822
+ }
823
+
824
+ const rail = ready
825
+ ? '<aside class="mv-rail" aria-label="Transcript"><div class="mv-rail-head"><h2>Transcript</h2>' +
826
+ '<input type="search" data-mv-search placeholder="Search the transcript" aria-label="Search the transcript"><span class="mv-count" data-mv-count></span></div>' +
827
+ '<ol class="mv-lines" data-mv-lines>' + (transcript.length ? transcript.map(function (line) {
828
+ return '<li class="mv-line" data-mv-line data-mv-seek="' + line.start + '">' +
829
+ '<a class="mv-ts" href="?t=' + Math.floor(line.start) + '">' + mediaClock(line.start) + '</a>' +
830
+ '<span class="mv-spk mv-spk' + (line.speaker % 6) + '">Speaker ' + (line.speaker + 1) + '</span>' +
831
+ '<span class="mv-txt">' + escapeHtml(line.text) + '</span></li>';
832
+ }).join('') : '<li class="mv-empty">No speech was detected.</li>') + '</ol></aside>'
833
+ : '';
834
+
835
+ return '<main class="mv' + (ready ? '' : ' mv-solo') + '" data-mv data-mv-state="' + escapeHtml(media.state) + '">' +
836
+ '<div class="mv-main">' + player + panels + '</div>' + rail + '</main>' +
837
+ '<script>' + MEDIA_VIEWER_JS + '</script>';
838
+ }
839
+
840
+ var MEDIA_VIEWER_CSS =
841
+ 'html,body{margin:0;background:#0f0f11;color:#e8e8e8;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,system-ui,sans-serif}' +
842
+ '.mv{display:grid;grid-template-columns:minmax(0,1fr) 380px;gap:20px;max-width:1440px;margin:0 auto;padding:20px;box-sizing:border-box}' +
843
+ '.mv.mv-solo{grid-template-columns:minmax(0,1fr);max-width:1100px}' +
844
+ '@media(max-width:980px){.mv{grid-template-columns:minmax(0,1fr)}}' +
845
+ '.mv-main{min-width:0;display:flex;flex-direction:column;gap:16px}' +
846
+ '.mv video{width:100%;max-height:68vh;background:#000;border-radius:10px;display:block}' +
847
+ '.mv-strip{position:relative;height:14px;margin-top:-8px;background:#1b1b21;border-radius:7px;cursor:pointer;overflow:hidden}' +
848
+ '.mv-fill{position:absolute;left:0;top:0;bottom:0;width:0;background:rgba(91,157,255,.28)}' +
849
+ '.mv-tick{position:absolute;top:2px;bottom:2px;width:4px;margin-left:-2px;padding:0;border:0;border-radius:2px;background:#5b9dff;cursor:pointer}' +
850
+ '.mv-tick:hover,.mv-tick:focus-visible{background:#a3c6ff;outline:none}' +
851
+ '.mv-card{background:#151519;border:1px solid #24242b;border-radius:12px;padding:16px 18px}' +
852
+ '.mv-card h1{font-size:20px;margin:0 0 8px;color:#fff}.mv-card h2{font-size:12px;margin:0 0 10px;text-transform:uppercase;letter-spacing:.07em;color:#8b919c}' +
853
+ '.mv-summary{margin:0;color:#d3d7de}.mv-empty{margin:0;color:#7c8290}' +
854
+ '.mv-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}.mv-list li{display:flex;gap:10px;align-items:baseline}' +
855
+ '.mv-ts{flex:none;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;color:#7fb0ff;text-decoration:none;background:rgba(91,157,255,.1);padding:1px 6px;border-radius:5px}' +
856
+ '.mv-ts:hover{background:rgba(91,157,255,.22)}' +
857
+ '.mv-status{display:flex;gap:14px;align-items:flex-start}.mv-status h2{color:#e8e8e8;font-size:15px;text-transform:none;letter-spacing:0}.mv-status p{margin:0;color:#aab0ba}' +
858
+ '.mv-failed{border-color:#5c2b2b}.mv-failed h2{color:#ff8a8a}' +
859
+ '.mv-spin{flex:none;width:18px;height:18px;margin-top:2px;border:2px solid rgba(255,255,255,.2);border-top-color:#5b9dff;border-radius:50%;animation:mv-sp .8s linear infinite}' +
860
+ '@keyframes mv-sp{to{transform:rotate(360deg)}}' +
861
+ '.mv-retry{margin-top:12px;background:#5b9dff;color:#0b0b0c;border:0;border-radius:8px;padding:7px 16px;font:inherit;font-weight:600;cursor:pointer}.mv-retry:disabled{opacity:.5;cursor:default}' +
862
+ '.mv-rail{position:sticky;top:58px;align-self:start;height:calc(100vh - 78px);display:flex;flex-direction:column;background:#151519;border:1px solid #24242b;border-radius:12px;overflow:hidden}' +
863
+ '@media(max-width:980px){.mv-rail{position:static;height:60vh}}' +
864
+ '.mv-rail-head{padding:14px 14px 10px;border-bottom:1px solid #24242b}.mv-rail-head h2{font-size:12px;margin:0 0 8px;text-transform:uppercase;letter-spacing:.07em;color:#8b919c}' +
865
+ '.mv-rail-head input{width:100%;box-sizing:border-box;background:#0f0f11;border:1px solid #2c2c34;border-radius:8px;color:#e8e8e8;padding:7px 10px;font:inherit}' +
866
+ '.mv-count{display:block;min-height:16px;margin-top:4px;font-size:12px;color:#8b919c}' +
867
+ '.mv-lines{list-style:none;margin:0;padding:6px 0;overflow-y:auto;flex:1}' +
868
+ '.mv-line{display:grid;grid-template-columns:auto 1fr;gap:2px 10px;padding:7px 14px;border-left:3px solid transparent;cursor:pointer}' +
869
+ '.mv-line:hover{background:rgba(255,255,255,.03)}.mv-line.on{background:rgba(91,157,255,.12);border-left-color:#5b9dff}' +
870
+ '.mv-line .mv-ts{grid-row:span 2;align-self:start}.mv-spk{font-size:11px;font-weight:600}.mv-txt{grid-column:2;color:#d3d7de}' +
871
+ '.mv-spk0{color:#7fb0ff}.mv-spk1{color:#f5a54a}.mv-spk2{color:#5fd39a}.mv-spk3{color:#d58cff}.mv-spk4{color:#ff8a8a}.mv-spk5{color:#e5d36a}' +
872
+ '.mv-line mark{background:rgba(245,158,11,.4);color:#fff;border-radius:2px}';
873
+ `;
874
+ //# sourceMappingURL=worker-media-template.js.map