Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

device-stream-document.ts

43 lines1.7 KB

1import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
2import type { DevicePlatform } from "@t3tools/contracts";
3​
4export interface DeviceStreamConfiguration {
5 readonly access: DeviceHubAccess;
6 readonly platform: DevicePlatform;
7 readonly deviceId: string;
8 readonly colors: {
9 readonly background: string;
10 readonly foreground: string;
11 readonly muted: string;
12 readonly buttonBackground: string;
13 readonly buttonForeground: string;
14 readonly buttonBorder: string;
15 };
17​
18export function deviceStreamDocument(configuration: string, script: string) {
19 // Tickets and device names are data, including any HTML delimiter characters.
20 const safeConfiguration = configuration.replace(/</g, "\\u003c");
21 const safeScript = script.replace(/<\/script/gi, "<\\/script");
22 return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>${safeScript}\nT3DeviceStream.start(${safeConfiguration});</script></body></html>`;
24​
25export function deviceStreamMessage(data: string) {
26 try {
27 const message: unknown = JSON.parse(data);
28 if (typeof message !== "object" || message === null || !("type" in message)) return null;
29 if (message.type === "unauthorized" || message.type === "retry") {
30 return { type: message.type } as const;
31 }
32 if (
33 message.type === "input" &&
34 "connected" in message &&
35 typeof message.connected === "boolean"
36 ) {
37 return { type: message.type, connected: message.connected } as const;
38 }
39 } catch {
40 // Ignore messages that are not part of the stream bridge.
41 }
42 return null;