Further simplify main.js, update documentation.

This commit is contained in:
Chad Curtis committed 2025-09-20 17:59:04 +00:00
1 parent f4f455606f
commit 53ac813eb5
3 files changed
+295 -580

No files matched your search

+84 -172
View File
@@ -64,7 +64,7 @@ All messages follow JSON-RPC 2.0 specification:
"headers": {
"Content-Type": "application/json"
},
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 of: {"name":"John","age":30}
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
}
},
"id": 124
@@ -80,7 +80,7 @@ All messages follow JSON-RPC 2.0 specification:
"Content-Type": "application/javascript",
"Cache-Control": "no-cache"
},
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7"
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
},
"id": 123
}
@@ -140,7 +140,7 @@ full request body support
### Parent Page
In this example, the parent page acts as a static file server.
The parent page acts as a static file server and console log collector:
```javascript
class FetchClientParent {
@@ -177,8 +177,8 @@ class FetchClientParent {
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(), // Parent adds timestamp when received
id: Date.now() // Unique ID for UI purposes
timestamp: Date.now(),
id: Date.now()
});
// Update UI to show new logs
@@ -189,7 +189,6 @@ class FetchClientParent {
}
updateConsoleUI() {
// This would update the parent page UI to show console logs
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
@@ -202,9 +201,6 @@ class FetchClientParent {
const url = new URL(fetchRequest.url);
const path = url.pathname;
// Decode request body if present
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
const file = this.files.get(path);
if (file) {
@@ -218,11 +214,10 @@ class FetchClientParent {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content), // base64 encode the response body
body: btoa(file.content),
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
@@ -232,7 +227,7 @@ class FetchClientParent {
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`), // base64 encode the error message
body: btoa(`File not found: ${path}`),
},
});
}
@@ -242,22 +237,15 @@ class FetchClientParent {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
### Preview Page
### iframe Client Communication
Below is a simplified RPC client that could be used inside the iframe's main
thread to test functionality of the parent. In practice, requests originate from
the ServiceWorker and the main thread acts as a relay, so multiple steps of
communication are involved.
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
```javascript
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
class JSONRPCClient {
constructor() {
this.requestId = 0;
@@ -268,7 +256,7 @@ class JSONRPCClient {
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id) {
if (message.jsonrpc === "2.0" && message.id !== undefined) {
this.handleResponse(message);
}
});
@@ -280,7 +268,6 @@ class JSONRPCClient {
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
@@ -288,7 +275,6 @@ class JSONRPCClient {
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
@@ -307,9 +293,8 @@ class JSONRPCClient {
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(error.message));
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
// Result is a serialized response
pending.resolve(result);
}
}
@@ -318,7 +303,7 @@ class JSONRPCClient {
## Base64 Encoding
All request and response bodies must be base64 encoded when not null. This ensures:
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
- **Consistent Data Handling:** Both text and binary data are handled uniformly
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
@@ -326,11 +311,16 @@ All request and response bodies must be base64 encoded when not null. This ensur
**Encoding/Decoding:**
```javascript
// Encoding (before sending)
const encodedBody = btoa(originalBody);
// Encoding text content (parent side)
const encodedBody = btoa(textContent);
// Decoding (after receiving)
const decodedBody = atob(encodedBody);
// Encoding binary content (ServiceWorker side)
const bytes = new Uint8Array(arrayBuffer);
const encodedBody = btoa(String.fromCharCode(...bytes));
// Decoding (receiver side)
const decodedText = atob(encodedBody);
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
```
## Security
@@ -356,158 +346,71 @@ const decodedBody = atob(encodedBody);
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
contentType: "text/html",
}],
["/app.js", {
content: "console.log('App loaded');",
contentType: "application/javascript",
}],
]);
// Example static file server with console logging
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Verify origin for security
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method === "console") {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { params } = message;
const { level, message: logMessage } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(), // Parent adds timestamp when received
id: Date.now() // Unique ID for UI purposes
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`);
}
updateConsoleUI() {
// This would update the parent page UI to show console logs
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
// Extract path from URL
const url = new URL(fetchRequest.url);
const path = url.pathname;
// Decode request body if present
const requestBody = fetchRequest.body ? atob(fetchRequest.body) : null;
const file = this.files.get(path);
if (file) {
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 200,
statusText: "OK",
headers: {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content), // base64 encode the response body
},
});
} else {
// Return 404 response (not a JSON-RPC error)
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 404,
statusText: "Not Found",
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`), // base64 encode the error message
},
});
}
}
sendResponse(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
sendError(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
// Example static file server
// Initialize the fetch client parent
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
To enable console logging from the iframe to the parent page, the iframe's bootstrap script should override the console methods:
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods:
```javascript
// In the iframe's bootstrap script
class ConsoleInterceptor {
constructor() {
this.originalConsole = {
log: console.log,
warn: console.warn,
error: console.error,
info: console.info,
debug: console.debug
};
this.overrideConsoleMethods();
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
overrideConsoleMethods() {
const methods = ['log', 'warn', 'error', 'info', 'debug'];
init() {
// Store original methods
this.methods.forEach(method => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
}
});
methods.forEach(method => {
console[method] = (...args) => {
// Call original method first
this.originalConsole[method](...args);
// Override console methods
this.methods.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent via JSON-RPC
this.sendConsoleMessage(method, ...args);
};
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map(arg => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
@@ -515,17 +418,26 @@ class ConsoleInterceptor {
return String(arg);
}).join(' ');
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level,
message
}
}, "*");
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Initialize console interception
new ConsoleInterceptor();
```
+17 -17
View File
@@ -54,13 +54,13 @@ blocked.
```
/
├── index.html # Main iframe client page
├── _iframe-client.js # Main coordination script
├── _iframe-client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
├── example-parent.html # Example parent implementation
└── README.md # This file
├── index.html # Main iframe client page
├── _iframe-client/
│ ├── main.js # Main coordination script
│ └── client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
└── README.md # This file
```
## Simplified JSON-RPC Protocol
@@ -150,8 +150,9 @@ Deploy these files to your iframe client subdomain:
```
https://*.example.com/
├── index.html
├── _iframe-client.js
├── _iframe-client.css
├── _iframe-client/
│ ├── main.js
│ └── client.css
└── sw.js
```
@@ -172,8 +173,7 @@ Include the iframe client in your parent page:
</iframe>
```
Implement the JSON-RPC protocol (see `example-parent.html` for a complete
example):
Implement the JSON-RPC protocol:
```javascript
class FetchClientParent {
@@ -284,9 +284,9 @@ function handleRequest(fetchRequest) {
## Testing
1. Open `example-parent.html` in a browser
2. Click "Load Sample Site"
3. The iframe client should load and display the sample app
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
2. Load the iframe client in an iframe pointing to your deployed client domain
3. The iframe client should load and display the served content
4. Test navigation and functionality within the iframe client
## Browser Support
@@ -326,10 +326,10 @@ function handleRequest(fetchRequest) {
To modify the system:
1. **iframe Client:** Edit `index.html`, `_iframe-client.js`,
`_iframe-client.css`, `sw.js`
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
`_iframe-client/client.css`, `sw.js`
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
3. **Testing:** Use `example-parent.html` for testing changes
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
## License
+194 -391
View File
@@ -1,265 +1,8 @@
/**
* iframe Fetch Client Combined Entry Point
* Combines console interception and client initialization
* iframe Fetch Client - Simplified Implementation
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
*/
// Console interception utilities
const CONSOLE_METHODS = ['log', 'warn', 'error', 'info', 'debug'];
// Store original console methods
function storeOriginalConsole() {
const original = {};
CONSOLE_METHODS.forEach(method => {
if (typeof console[method] === 'function') {
original[method] = console[method];
}
});
return original;
}
// Override console methods with custom handler
function overrideConsoleMethods(originalConsole, messageHandler) {
CONSOLE_METHODS.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
// Call original method first
try {
originalConsole[method](...args);
} catch (e) {
// If original fails, at least send to parent
messageHandler(method, ...args);
return;
}
// Send to parent
messageHandler(method, ...args);
};
}
});
}
// Set up global error handlers
function setupGlobalErrorHandlers(messageHandler) {
// Override window.onerror to catch unhandled errors
const originalOnError = window.onerror;
window.onerror = (message, source, lineno, colno, error) => {
// Call original handler first
if (originalOnError) {
originalOnError(message, source, lineno, colno, error);
}
// Send to parent
messageHandler('error', `Uncaught Error: ${message}`, {
source,
lineno,
colno,
error: error ? error.message : 'No error object',
stack: error ? error.stack : 'No stack trace'
});
return false; // Don't prevent default
};
// Override window.onunhandledrejection for Promise rejections
const originalOnUnhandledRejection = window.onunhandledrejection;
window.onunhandledrejection = (event) => {
// Call original handler first
if (originalOnUnhandledRejection) {
originalOnUnhandledRejection(event);
}
// Send to parent
messageHandler('error', 'Unhandled Promise Rejection', {
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
});
event.preventDefault(); // Prevent default console warning
};
}
// Early Console Interception - runs immediately
class EarlyConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.earlyErrors = [];
this.consoleMethods = CONSOLE_METHODS;
this.init();
}
init() {
this.storeOriginalConsole();
this.overrideConsoleMethods();
this.setupGlobalErrorHandlers();
this.exposeToWindow();
}
storeOriginalConsole() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
}
});
}
overrideConsoleMethods() {
this.consoleMethods.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
this.handleConsoleCall(method, args);
};
}
});
}
handleConsoleCall(method, args) {
// Try to call the original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Original method failed, continue
}
// Store error for later processing
if (method === 'error' || method === 'exception') {
this.earlyErrors.push({
level: method,
message: this.serializeArgs(args)
});
}
}
serializeArgs(args) {
return args.map(arg => {
if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
}
setupGlobalErrorHandlers() {
// Handle window errors
window.addEventListener('error', (event) => {
this.earlyErrors.push({
level: 'error',
message: `Global Error: ${event.message} (${event.filename}:${event.lineno}:${event.colno})`
});
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
this.earlyErrors.push({
level: 'error',
message: `Unhandled Promise Rejection: ${event.reason}`
});
});
}
exposeToWindow() {
// Store early errors for the main script to process
window._earlyConsoleErrors = this.earlyErrors;
// Store original console reference for the main script
window._originalConsole = this.originalConsole;
}
}
// Console Interceptor - handles ongoing console interception
class ConsoleInterceptor {
constructor() {
// Use the original console stored by the early interceptor
this.originalConsole = window._originalConsole || console;
overrideConsoleMethods(this.originalConsole, this.sendConsoleMessage.bind(this));
setupGlobalErrorHandlers(this.sendConsoleMessage.bind(this));
this.overrideWindowError();
}
overrideWindowError() {
// Also try to catch errors that might occur during early execution
setTimeout(() => {
// Capture any errors that might have occurred before we were ready
this.sendConsoleMessage('info', 'Console interceptor initialized at:', Date.now());
}, 0);
}
sendConsoleMessage(level, ...args) {
try {
const message = args.map(arg => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
if (typeof arg === 'function') {
return arg.toString();
}
return String(arg);
}).join(' ');
// Try to send to parent, but don't fail if parent isn't ready
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level,
message
}
}, "*");
} catch (postMessageError) {
// Parent might not be ready yet, try again later
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `[DELAYED] ${message}`
}
}, "*");
} catch {
// Give up - parent isn't available
}
}, 100);
}
} catch (error) {
// If serialization fails, at least try to send a simple message
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Console interceptor error: ${error.message}`
}
}, "*");
} catch {
// If even this fails, we can't do anything
}
}
}
}
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
@@ -272,19 +15,17 @@ class JSONRPCClient {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
// Check if this is a response to our own request or a ServiceWorker request
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayJSONRPCToServiceWorker(message);
// Response for ServiceWorker - relay it
this.relayToServiceWorker(message);
}
}
});
}
relayJSONRPCToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
relayToServiceWorker(response) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
@@ -296,7 +37,6 @@ class JSONRPCClient {
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
@@ -304,7 +44,6 @@ class JSONRPCClient {
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
@@ -330,71 +69,133 @@ class JSONRPCClient {
}
}
// Console Interceptor - forwards console messages to parent
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
init() {
// Store original methods
this.methods.forEach(method => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
}
});
// Override console methods
this.methods.forEach(method => {
if (typeof console[method] === 'function') {
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map(arg => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.swReady = false;
this.consoleInterceptor = new ConsoleInterceptor();
// Process any early errors captured by inline script
this.processEarlyErrors();
this.init();
}
processEarlyErrors() {
// Check for early errors captured before main script loaded
if (window._earlyConsoleErrors && Array.isArray(window._earlyConsoleErrors)) {
window._earlyConsoleErrors.forEach(error => {
console.log(`[EARLY ${error.level.toUpperCase()}] ${error.message}`);
});
// Clear the early errors
window._earlyConsoleErrors = [];
}
}
async init() {
try {
await this.registerServiceWorker();
this.setupServiceWorkerCommunication();
await this.waitForServiceWorker();
await this.fetchSiteIndex();
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
this.showError("Failed to initialize fetch client", error);
}
}
async registerServiceWorker() {
async setupServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if SW is already registered
const existingRegistration = await navigator.serviceWorker
.getRegistration();
if (existingRegistration) {
// Check if already registered
const existing = await navigator.serviceWorker.getRegistration();
if (existing) {
console.log("ServiceWorker already registered");
this.swReady = true;
this.setupServiceWorkerCommunication();
return;
}
try {
const registration = await navigator.serviceWorker.register("/sw.js", {
scope: "/",
});
// Register new ServiceWorker
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
console.log("ServiceWorker registered:", registration);
console.log("ServiceWorker registered:", registration);
await navigator.serviceWorker.ready;
this.setupServiceWorkerCommunication();
this.blockFutureRegistrations();
}
// Wait for SW to be ready
await navigator.serviceWorker.ready;
this.swReady = true;
// Block future registrations to prevent site from registering its own SW
this.blockFutureRegistrations();
} catch (error) {
throw new Error(`ServiceWorker registration failed: ${error.message}`);
}
setupServiceWorkerCommunication() {
// Relay JSON-RPC requests from ServiceWorker to parent
navigator.serviceWorker.addEventListener("message", (event) => {
const { data } = event;
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
window.parent.postMessage(data, "*");
}
});
}
blockFutureRegistrations() {
@@ -411,71 +212,35 @@ class FetchClient {
};
}
setupServiceWorkerCommunication() {
// Listen for JSON-RPC requests from ServiceWorker and relay them to parent
navigator.serviceWorker.addEventListener("message", async (event) => {
const { data } = event;
async loadSiteIndex() {
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
// Check if this is a JSON-RPC request from ServiceWorker
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
this.relayJSONRPCToParent(data);
}
});
}
const response = await this.rpcClient.fetch(serializedRequest);
relayJSONRPCToParent(request) {
// Forward the JSON-RPC request directly to parent
window.parent.postMessage(request, "*");
}
async waitForServiceWorker() {
const timeout = 10000; // 10 seconds
const start = Date.now();
while (!this.swReady) {
if (Date.now() - start > timeout) {
throw new Error("Timeout waiting for ServiceWorker readiness");
}
await new Promise((resolve) => setTimeout(resolve, 100));
if (response.status !== 200) {
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
}
console.log("ServiceWorker is ready");
}
async fetchSiteIndex() {
try {
// Request site index from parent via JSON-RPC fetch
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response.status !== 200) {
throw new Error(`Failed to fetch site index: ${response.status} ${response.statusText}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Replace current document with the site index content
this.replaceDocument(text);
} catch (error) {
this.showError("Failed to load site index", error);
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
// Extract scripts for re-execution
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
@@ -484,14 +249,14 @@ class FetchClient {
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.parentNode.removeChild(script);
script.remove();
});
// Replace the entire document
// Replace document content
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts (this is necessary to execute them)
// Re-add scripts to execute them
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
@@ -508,38 +273,76 @@ class FetchClient {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Initialize early console interception immediately
new EarlyConsoleInterceptor();
// Global error handlers
function setupGlobalErrorHandlers() {
window.addEventListener('error', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Uncaught Error: ${event.message}`,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: "Unhandled Promise Rejection",
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
}
// Initialize
setupGlobalErrorHandlers();
// Initialize when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {