Spaces:
Running
Running
File size: 6,740 Bytes
6f5f15e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | import { randomUUID } from 'node:crypto';
import type * as T from '../../shared/api-types.js';
import type { CameraBridgeApi } from '../contracts.js';
interface TabRecord {
tabId: string;
connectedAt: string;
send: (m: T.FeedMessage) => void;
userAgent?: string;
frozen?: boolean;
deviceLabel?: string;
width?: number;
height?: number;
pendingCaptures: number;
}
interface PendingCapture {
requestId: string;
tabId: string;
timer: ReturnType<typeof setTimeout>;
resolve: (result: { mimeType: string; base64: string; dataUrl: string }) => void;
reject: (err: Error) => void;
}
export interface CameraBridgeOptions {
onTabJoined?: (tabId: string) => void;
onTabLeft?: (tabId: string) => void;
onChange?: () => void;
}
const DATA_URL_RE = /^data:([^;,]+);base64,(.+)$/s;
const ALLOWED_IMAGE_MIMES = new Set(['image/jpeg', 'image/png', 'image/webp']);
export function parseImageDataUrl(dataUrl: string): { mimeType: string; base64: string; dataUrl: string } {
const match = DATA_URL_RE.exec(dataUrl.trim());
if (!match) {
throw new Error('Invalid image data URL');
}
const mimeType = match[1].trim().toLowerCase();
const base64 = match[2].trim();
if (!ALLOWED_IMAGE_MIMES.has(mimeType) || base64.length === 0) {
throw new Error('Invalid image data URL (allowed MIME types: image/jpeg, image/png, image/webp)');
}
return { mimeType, base64, dataUrl: dataUrl.trim() };
}
export function createCameraBridge(opts: CameraBridgeOptions = {}): CameraBridgeApi {
const tabs = new Map<string, TabRecord>();
const pending = new Map<string, PendingCapture>();
let primaryTabId: string | null = null;
function ensurePrimary(): void {
if (primaryTabId !== null && tabs.has(primaryTabId)) return;
const first = tabs.keys().next();
primaryTabId = first.done ? null : first.value;
}
function getPrimaryTab(): TabRecord | undefined {
ensurePrimary();
return primaryTabId ? tabs.get(primaryTabId) : undefined;
}
function clearPendingForTab(tabId: string): void {
for (const [reqId, entry] of pending) {
if (entry.tabId === tabId) {
clearTimeout(entry.timer);
pending.delete(reqId);
entry.reject(new Error('Camera tab disconnected before completing capture'));
}
}
}
return {
addTab(tabId: string, send: (m: T.FeedMessage) => void, userAgent?: string): () => void {
const existing = tabs.get(tabId);
const record: TabRecord = {
tabId,
connectedAt: existing?.connectedAt ?? new Date().toISOString(),
send,
userAgent,
frozen: existing?.frozen,
deviceLabel: existing?.deviceLabel,
width: existing?.width,
height: existing?.height,
pendingCaptures: existing?.pendingCaptures ?? 0,
};
tabs.set(tabId, record);
if (primaryTabId === null) {
primaryTabId = tabId;
}
opts.onTabJoined?.(tabId);
opts.onChange?.();
let removed = false;
return () => {
if (removed) return;
removed = true;
// Only remove if this exact record is still active (handles reconnect with same tabId)
if (tabs.get(tabId) !== record) return;
tabs.delete(tabId);
clearPendingForTab(tabId);
if (primaryTabId === tabId) {
primaryTabId = null;
ensurePrimary();
}
opts.onTabLeft?.(tabId);
opts.onChange?.();
};
},
setPrimary(tabId: string): boolean {
if (!tabs.has(tabId)) return false;
primaryTabId = tabId;
opts.onChange?.();
return true;
},
setStatus(tabId: string, s: Partial<T.CameraTabView>): void {
const tab = tabs.get(tabId);
if (!tab) return;
if (s.frozen !== undefined) tab.frozen = s.frozen;
if (s.deviceLabel !== undefined) tab.deviceLabel = s.deviceLabel;
if (s.width !== undefined) tab.width = s.width;
if (s.height !== undefined) tab.height = s.height;
opts.onChange?.();
},
hasCamera(): boolean {
return tabs.size > 0;
},
requestCapture(
kind: 'webcam' | 'screen',
reason: string,
timeoutMs: number,
): Promise<{ mimeType: string; base64: string; dataUrl: string }> {
const tab = getPrimaryTab();
if (!tab) {
return Promise.reject(new Error('No camera tab connected'));
}
const requestId = randomUUID();
tab.pendingCaptures += 1;
opts.onChange?.();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
const entry = pending.get(requestId);
if (!entry) return;
pending.delete(requestId);
const t = tabs.get(entry.tabId);
if (t && t.pendingCaptures > 0) {
t.pendingCaptures -= 1;
}
opts.onChange?.();
reject(new Error(`Capture timed out after ${timeoutMs}ms`));
}, timeoutMs);
timer.unref?.();
pending.set(requestId, {
requestId,
tabId: tab.tabId,
timer,
resolve,
reject,
});
try {
tab.send({ type: 'capture', requestId, kind, reason });
} catch (err) {
clearTimeout(timer);
pending.delete(requestId);
if (tab.pendingCaptures > 0) tab.pendingCaptures -= 1;
opts.onChange?.();
reject(err instanceof Error ? err : new Error(String(err)));
}
});
},
resolveCapture(requestId: string, r: T.CaptureResultRequest): boolean {
const entry = pending.get(requestId);
if (!entry) return false;
clearTimeout(entry.timer);
pending.delete(requestId);
const tab = tabs.get(entry.tabId);
if (tab && tab.pendingCaptures > 0) {
tab.pendingCaptures -= 1;
}
opts.onChange?.();
if (r.error) {
entry.reject(new Error(r.error));
return true;
}
if (!r.image) {
entry.reject(new Error('Capture response missing image data'));
return true;
}
try {
const parsed = parseImageDataUrl(r.image);
entry.resolve(parsed);
} catch (err) {
entry.reject(err instanceof Error ? err : new Error(String(err)));
}
return true;
},
views(): T.CameraTabView[] {
ensurePrimary();
return Array.from(tabs.values()).map((tab) => ({
tabId: tab.tabId,
connectedAt: tab.connectedAt,
primary: tab.tabId === primaryTabId,
userAgent: tab.userAgent,
frozen: tab.frozen,
deviceLabel: tab.deviceLabel,
width: tab.width,
height: tab.height,
pendingCaptures: tab.pendingCaptures,
}));
},
};
}
|