-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
233 lines (204 loc) · 8.76 KB
/
background.js
File metadata and controls
233 lines (204 loc) · 8.76 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
// background.js - Service Worker with WASM (CSP-Immune!)
// This runs in an isolated environment, completely immune to page CSP policies
// ✅ STATIC IMPORTS at top level - Required for Service Workers!
// Dynamic import() is FORBIDDEN in ServiceWorkerGlobalScope
import init, { analyze_page, analyze_page_with_options, prune_for_api } from './pkg/sentience_core.js';
console.log('[Sentience Background] Initializing...');
// Global WASM initialization state
let wasmReady = false;
let wasmInitPromise = null;
/**
* Initialize WASM module - called once on service worker startup
* Uses static imports (not dynamic import()) which is required for Service Workers
*/
async function initWASM() {
if (wasmReady) return;
if (wasmInitPromise) return wasmInitPromise;
wasmInitPromise = (async () => {
try {
console.log('[Sentience Background] Loading WASM module...');
// Define the js_click_element function that WASM expects
// In Service Workers, use 'globalThis' instead of 'window'
// In background context, we can't actually click, so we log a warning
globalThis.js_click_element = (_id) => {
console.warn('[Sentience Background] js_click_element called in background (ignored)');
};
// Initialize WASM - this calls the init() function from the static import
// The init() function handles fetching and instantiating the .wasm file
await init();
wasmReady = true;
console.log('[Sentience Background] ✓ WASM ready!');
console.log('[Sentience Background] Available functions: analyze_page, analyze_page_with_options, prune_for_api');
} catch (error) {
console.error('[Sentience Background] WASM initialization failed:', error);
throw error;
}
})();
return wasmInitPromise;
}
// Initialize WASM on service worker startup
initWASM().catch(err => {
console.error('[Sentience Background] Failed to initialize WASM:', err);
});
/**
* Message handler for all extension communication
* Includes global error handling to prevent extension crashes
*/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Global error handler to prevent extension crashes
try {
// Handle screenshot requests (existing functionality)
if (request.action === 'captureScreenshot') {
handleScreenshotCapture(sender.tab.id, request.options)
.then(screenshot => {
sendResponse({ success: true, screenshot });
})
.catch(error => {
console.error('[Sentience Background] Screenshot capture failed:', error);
sendResponse({
success: false,
error: error.message || 'Screenshot capture failed'
});
});
return true; // Async response
}
// Handle WASM processing requests (NEW!)
if (request.action === 'processSnapshot') {
handleSnapshotProcessing(request.rawData, request.options)
.then(result => {
sendResponse({ success: true, result });
})
.catch(error => {
console.error('[Sentience Background] Snapshot processing failed:', error);
sendResponse({
success: false,
error: error.message || 'Snapshot processing failed'
});
});
return true; // Async response
}
// Unknown action
console.warn('[Sentience Background] Unknown action:', request.action);
sendResponse({ success: false, error: 'Unknown action' });
return false;
} catch (error) {
// Catch any synchronous errors that might crash the extension
console.error('[Sentience Background] Fatal error in message handler:', error);
try {
sendResponse({
success: false,
error: `Fatal error: ${error.message || 'Unknown error'}`
});
} catch (e) {
// If sendResponse already called, ignore
}
return false;
}
});
/**
* Handle screenshot capture (existing functionality)
*/
async function handleScreenshotCapture(_tabId, options = {}) {
try {
const {
format = 'png',
quality = 90
} = options;
const dataUrl = await chrome.tabs.captureVisibleTab(null, {
format: format,
quality: quality
});
console.log(`[Sentience Background] Screenshot captured: ${format}, size: ${dataUrl.length} bytes`);
return dataUrl;
} catch (error) {
console.error('[Sentience Background] Screenshot error:', error);
throw new Error(`Failed to capture screenshot: ${error.message}`);
}
}
/**
* Handle snapshot processing with WASM (NEW!)
* This is where the magic happens - completely CSP-immune!
* Includes safeguards to prevent crashes and hangs.
*
* @param {Array} rawData - Raw element data from injected_api.js
* @param {Object} options - Snapshot options (limit, filter, etc.)
* @returns {Promise<Object>} Processed snapshot result
*/
async function handleSnapshotProcessing(rawData, options = {}) {
const MAX_ELEMENTS = 10000; // Safety limit to prevent hangs
const startTime = performance.now();
try {
// Safety check: limit element count to prevent hangs
if (!Array.isArray(rawData)) {
throw new Error('rawData must be an array');
}
if (rawData.length > MAX_ELEMENTS) {
console.warn(`[Sentience Background] ⚠️ Large dataset: ${rawData.length} elements. Limiting to ${MAX_ELEMENTS} to prevent hangs.`);
rawData = rawData.slice(0, MAX_ELEMENTS);
}
// Ensure WASM is initialized
await initWASM();
if (!wasmReady) {
throw new Error('WASM module not initialized');
}
console.log(`[Sentience Background] Processing ${rawData.length} elements with options:`, options);
// Run WASM processing using the imported functions directly
// Wrap in try-catch with timeout protection
let analyzedElements;
try {
// Use a timeout wrapper to prevent infinite hangs
const wasmPromise = new Promise((resolve, reject) => {
try {
let result;
if (options.limit || options.filter) {
result = analyze_page_with_options(rawData, options);
} else {
result = analyze_page(rawData);
}
resolve(result);
} catch (e) {
reject(e);
}
});
// Add timeout protection (18 seconds - less than content.js timeout)
analyzedElements = await Promise.race([
wasmPromise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('WASM processing timeout (>18s)')), 18000)
)
]);
} catch (e) {
const errorMsg = e.message || 'Unknown WASM error';
console.error(`[Sentience Background] WASM analyze_page failed: ${errorMsg}`, e);
throw new Error(`WASM analyze_page failed: ${errorMsg}`);
}
// Prune elements for API (prevents 413 errors on large sites)
let prunedRawData;
try {
prunedRawData = prune_for_api(rawData);
} catch (e) {
console.warn('[Sentience Background] prune_for_api failed, using original data:', e);
prunedRawData = rawData;
}
const duration = performance.now() - startTime;
console.log(`[Sentience Background] ✓ Processed: ${analyzedElements.length} analyzed, ${prunedRawData.length} pruned (${duration.toFixed(1)}ms)`);
return {
elements: analyzedElements,
raw_elements: prunedRawData
};
} catch (error) {
const duration = performance.now() - startTime;
console.error(`[Sentience Background] Processing error after ${duration.toFixed(1)}ms:`, error);
throw error;
}
}
console.log('[Sentience Background] Service worker ready');
// Global error handlers to prevent extension crashes
self.addEventListener('error', (event) => {
console.error('[Sentience Background] Global error caught:', event.error);
event.preventDefault(); // Prevent extension crash
});
self.addEventListener('unhandledrejection', (event) => {
console.error('[Sentience Background] Unhandled promise rejection:', event.reason);
event.preventDefault(); // Prevent extension crash
});