-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patht3-bridge.js
More file actions
99 lines (79 loc) · 2.43 KB
/
t3-bridge.js
File metadata and controls
99 lines (79 loc) · 2.43 KB
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
(() => {
const NativeWebSocket = window.WebSocket;
if (!NativeWebSocket || NativeWebSocket.__rightClickGPTT3Bridge) {
return;
}
let knownSessionId = '';
const SESSION_SCOPED_UDF = /^(account:|profiles:|threads:|messages:)/;
function visitObjects(value, callback) {
if (!value || typeof value !== 'object') {
return;
}
callback(value);
if (Array.isArray(value)) {
value.forEach((item) => visitObjects(item, callback));
return;
}
Object.values(value).forEach((item) => visitObjects(item, callback));
}
function rememberSessionId(message) {
visitObjects(message, (object) => {
if (typeof object.sessionId === 'string' && object.sessionId) {
knownSessionId = object.sessionId;
}
});
}
function shouldPatchUdf(udfPath) {
return SESSION_SCOPED_UDF.test(String(udfPath || ''));
}
function patchArg(arg) {
if (!knownSessionId || !arg || typeof arg !== 'object' || arg.sessionId) {
return false;
}
arg.sessionId = knownSessionId;
return true;
}
function patchPayload(payload) {
try {
const message = JSON.parse(payload);
let changed = false;
rememberSessionId(message);
if (Array.isArray(message.modifications)) {
message.modifications.forEach((modification) => {
if (!shouldPatchUdf(modification && modification.udfPath)) {
return;
}
const arg = Array.isArray(modification.args) ? modification.args[0] : null;
changed = patchArg(arg) || changed;
});
}
if (shouldPatchUdf(message.udfPath)) {
const arg = Array.isArray(message.args) ? message.args[0] : null;
changed = patchArg(arg) || changed;
}
rememberSessionId(message);
return changed ? JSON.stringify(message) : payload;
} catch (error) {
return payload;
}
}
class RightClickGPTWebSocket extends NativeWebSocket {
send(data) {
if (typeof data === 'string') {
data = patchPayload(data);
}
return super.send(data);
}
}
Object.getOwnPropertyNames(NativeWebSocket).forEach((key) => {
try {
RightClickGPTWebSocket[key] = NativeWebSocket[key];
} catch (error) {
// Some WebSocket properties are read-only in Chromium.
}
});
Object.defineProperty(RightClickGPTWebSocket, '__rightClickGPTT3Bridge', {
value: true,
});
window.WebSocket = RightClickGPTWebSocket;
})();