-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackground.js
More file actions
255 lines (211 loc) · 8 KB
/
Copy pathbackground.js
File metadata and controls
255 lines (211 loc) · 8 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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/**
* Graphic Density — Background Service Worker (Phase 4)
*
* Handles:
* - Popup ↔ content script message routing
* - Native messaging bridge ↔ content script API routing
* - Tab-aware message targeting (not just active tab)
* - Navigation control
* - Tab state tracking
*/
// ── State ────────────────────────────────────────────────────────
let nativePort = null;
let bridgeReady = false;
const tabStates = new Map();
// ── Native Messaging Connection ──────────────────────────────────
function connectNativeBridge() {
try {
nativePort = chrome.runtime.connectNative('com.graphicdensity.bridge');
nativePort.onMessage.addListener((msg) => {
if (msg.type === 'BRIDGE_READY') {
bridgeReady = true;
nativePort.postMessage({ type: 'CONNECTED' });
console.log('[GD] Bridge connected. API available at http://127.0.0.1:7080');
return;
}
// API request from bridge — route to content script
if (msg.requestId !== undefined) {
handleApiRequest(msg).then((response) => {
nativePort.postMessage({ requestId: msg.requestId, response });
}).catch((err) => {
nativePort.postMessage({ requestId: msg.requestId, response: { error: err.message } });
});
}
});
nativePort.onDisconnect.addListener(() => {
const err = chrome.runtime.lastError?.message || 'unknown';
console.log(`[GD] Bridge disconnected: ${err}`);
nativePort = null;
bridgeReady = false;
setTimeout(connectNativeBridge, 5000);
});
console.log('[GD] Connecting to native bridge...');
} catch (err) {
console.log(`[GD] Native bridge not available: ${err.message}`);
console.log('[GD] Run bridge/install.sh to set up the API layer.');
setTimeout(connectNativeBridge, 15000);
}
}
// ── API Request Router ───────────────────────────────────────────
async function handleApiRequest(msg) {
switch (msg.type) {
case 'API_GET_STATE':
return await sendToTab(msg.tabId, {
type: 'GET_STATE',
mode: msg.mode || 'numbered',
});
case 'API_GET_ENVIRONMENT':
return await sendToTab(msg.tabId, { type: 'GET_ENVIRONMENT' });
case 'API_EXECUTE_ACTION':
return await sendToTab(msg.tabId, {
type: 'EXECUTE_ACTION',
action: msg.action,
});
case 'API_EXECUTE_BATCH':
return await sendToTab(msg.tabId, {
type: 'EXECUTE_BATCH',
actions: msg.actions,
});
case 'API_GET_HISTORY':
return await sendToTab(msg.tabId, { type: 'GET_HISTORY' });
case 'API_CLEAR_HISTORY':
return await sendToTab(msg.tabId, { type: 'CLEAR_HISTORY' });
case 'API_NAVIGATE':
return await navigateTab(msg.url, msg.tabId);
case 'API_GET_TABS':
return await getTabList();
default:
return { error: `Unknown API request type: ${msg.type}` };
}
}
// ── Tab-Aware Message Sending ────────────────────────────────────
async function sendToTab(targetTabId, message) {
const tabId = targetTabId || await getActiveTabId();
if (!tabId) {
return { error: 'No active tab found.' };
}
await ensureContentScript(tabId);
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, message, (response) => {
if (chrome.runtime.lastError) {
resolve({ error: chrome.runtime.lastError.message });
} else {
resolve(response || { error: 'Empty response from content script.' });
}
});
});
}
async function ensureContentScript(tabId) {
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, { type: 'PING' }, (response) => {
if (chrome.runtime.lastError) {
chrome.scripting.executeScript(
{ target: { tabId }, files: ['renderer.js'] },
() => {
if (chrome.runtime.lastError) {
console.log(`[GD] Cannot inject into tab ${tabId}: ${chrome.runtime.lastError.message}`);
}
setTimeout(resolve, 200);
}
);
} else {
resolve();
}
});
});
}
async function getActiveTabId() {
return new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
resolve(tabs[0]?.id || null);
});
});
}
// ── Navigation ───────────────────────────────────────────────────
async function navigateTab(url, tabId) {
const targetTabId = tabId || await getActiveTabId();
if (!targetTabId) {
return { error: 'No active tab found.' };
}
return new Promise((resolve) => {
chrome.tabs.update(targetTabId, { url }, () => {
if (chrome.runtime.lastError) {
resolve({ error: chrome.runtime.lastError.message });
return;
}
const listener = (updatedTabId, changeInfo) => {
if (updatedTabId === targetTabId && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
setTimeout(async () => {
const state = await sendToTab(targetTabId, {
type: 'GET_STATE',
mode: 'numbered',
});
resolve({
success: true,
tabId: targetTabId,
url,
state,
});
}, 500);
}
};
chrome.tabs.onUpdated.addListener(listener);
// Timeout failsafe
setTimeout(() => {
chrome.tabs.onUpdated.removeListener(listener);
resolve({ success: true, tabId: targetTabId, url, state: null, note: 'Page load timeout.' });
}, 15000);
});
});
}
// ── Tab Listing ──────────────────────────────────────────────────
async function getTabList() {
return new Promise((resolve) => {
chrome.tabs.query({}, (tabs) => {
const tabList = tabs.map(tab => ({
id: tab.id,
url: tab.url,
title: tab.title,
active: tab.active,
windowId: tab.windowId,
index: tab.index,
lastAccessed: tabStates.get(tab.id)?.lastUpdate || null,
}));
resolve({ tabs: tabList, count: tabList.length });
});
});
}
// ── Popup Message Routing ────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.target === 'content') {
sendToTab(null, msg.payload).then((response) => {
sendResponse(response);
});
return true;
}
});
// ── External Connection Handler ──────────────────────────────────
chrome.runtime.onConnectExternal?.addListener((port) => {
console.log('[GD] External connection from:', port.sender?.origin);
port.onMessage.addListener(async (msg) => {
const response = await handleApiRequest(msg);
port.postMessage(response);
});
});
// ── Tab State Tracking ───────────────────────────────────────────
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
tabStates.set(tabId, {
url: tab.url,
title: tab.title,
lastUpdate: Date.now(),
});
}
});
chrome.tabs.onRemoved.addListener((tabId) => {
tabStates.delete(tabId);
});
// ── Startup ──────────────────────────────────────────────────────
connectNativeBridge();
console.log('[Graphic Density] Phase 4 service worker started.');