From 92f3c06f51dc264cc5f64be2f1ab804a6f6d796b Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 18 Sep 2025 06:00:08 +0000 Subject: [PATCH] cleanup --- cloudflare-worker/README.md | 185 ----------------- cloudflare-worker/setup.sh | 137 ------------- cloudflare-worker/test.sh | 138 ------------- cloudflare-worker/worker.js | 117 ----------- cloudflare-worker/wrangler.toml | 16 -- iframe-fetch-client/_iframe-client.js | 222 +++++++++++++++++---- iframe-fetch-client/index.html | 94 +++++++++ src/components/Shakespeare/PreviewPane.tsx | 22 +- 8 files changed, 298 insertions(+), 633 deletions(-) delete mode 100644 cloudflare-worker/README.md delete mode 100755 cloudflare-worker/setup.sh delete mode 100755 cloudflare-worker/test.sh delete mode 100644 cloudflare-worker/worker.js delete mode 100644 cloudflare-worker/wrangler.toml diff --git a/cloudflare-worker/README.md b/cloudflare-worker/README.md deleted file mode 100644 index e87ed233..00000000 --- a/cloudflare-worker/README.md +++ /dev/null @@ -1,185 +0,0 @@ -# Shakespeare Iframe Proxy - Cloudflare Worker Setup - -This Cloudflare Worker acts as a reverse proxy for the Shakespeare iframe-fetch-client, removing restrictive headers and adding CORS support to enable iframe embedding. - -## Quick Setup - -### Step 1: Deploy iframe-fetch-client to Surge - -First, deploy your iframe-fetch-client files to Surge: - -```bash -cd ../iframe-fetch-client -npx -y surge . your-unique-name.surge.sh -``` - -Replace `your-unique-name` with something unique. - -### Step 2: Update Worker Configuration - -Edit `worker.js` and update the `surgeDomain` variable: - -```javascript -// Change this line -const surgeDomain = 'your-unique-name.surge.sh'; // TODO: Update this! -``` - -Use the same Surge domain you deployed to in Step 1. - -### Step 3: Deploy the Cloudflare Worker - -#### Option A: Quick Setup (via Dashboard) - -1. Go to [Cloudflare Dashboard](https://dash.cloudflare.com/) -2. Navigate to Workers & Pages → Create application -3. Select "Create Worker" -4. Copy the contents of `worker.js` into the editor -5. Click "Save and Deploy" -6. Note your worker's URL (e.g., `shakespeare-iframe-proxy.your-account.workers.dev`) - -#### Option B: Using Wrangler CLI - -1. Install Wrangler: - ```bash - npm install -g wrangler - ``` - -2. Login to Cloudflare: - ```bash - wrangler login - ``` - -3. Deploy from this directory: - ```bash - cd cloudflare-worker - wrangler deploy - ``` - -### Step 4: Set Up Custom Domain (Optional but Recommended) - -#### Using Cloudflare Dashboard: - -1. Go to your domain in Cloudflare DNS -2. Create a wildcard CNAME record: - - Type: `CNAME` - - Name: `*` (or a specific subdomain like `iframe`) - - Target: Your worker URL (e.g., `shakespeare-iframe-proxy.your-account.workers.dev`) - - Proxy status: Enabled (orange cloud) - -3. Add a route to your worker: - - In Workers & Pages, select your worker - - Go to Settings → Triggers → Routes - - Add route: `*.your-domain.com/*` - -#### Using Wrangler: - -Update your `wrangler.toml`: - -```toml -[env.production] -vars = { ENVIRONMENT = "production" } - -[[env.production.routes]] -pattern = "*.your-domain.com/*" -zone_name = "your-domain.com" -``` - -Then deploy: -```bash -wrangler deploy --env production -``` - -### Step 5: Update Your Environment - -Update your `.env` file in the main project: - -```bash -# Change from: -VITE_IFRAME_DOMAIN=local-shakespeare.dev - -# To (using your custom domain): -VITE_IFRAME_DOMAIN=your-domain.com - -# Or (using worker subdomain): -VITE_IFRAME_DOMAIN=your-account.workers.dev -``` - -### Step 6: Test the Setup - -1. Rebuild your main project: - ```bash - cd .. - npm run build - # Or start development server - npm run dev - ``` - -2. Open Shakespeare and create/load a project -3. Build the project -4. Switch to preview tab -5. Open browser console to see: - - Successful iframe loading - - Console messages being forwarded - - No CORS or security errors - -## Local Development - -### Test Worker Locally: - -```bash -cd cloudflare-worker -wrangler dev --local-port 8787 -``` - -Test with curl: -```bash -curl http://localhost:8787 -``` - -### Test with Local Shakespeare: - -Update your `.env` temporarily: -```bash -VITE_IFRAME_DOMAIN=localhost:8787 -``` - -## Troubleshooting - -### Common Issues: - -1. **CORS Errors**: Make sure CORS headers are properly set in the worker -2. **X-Frame-Options Blocked**: Ensure these headers are removed in the worker -3. **Mixed Content**: Use HTTPS everywhere -4. **Service Worker Registration**: Check MIME types for `.js` files - -### Debug Headers: - -You can test what headers are being sent/received: - -```bash -curl -I https://project123.your-domain.com/ -``` - -### Check Worker Logs: - -Use Cloudflare Dashboard to view worker logs and debug requests. - -## Architecture - -``` -┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ -│ Shakespeare App │ │ Cloudflare │ │ Surge.sh │ -│ (Parent Window) │ │ Worker Proxy │ │ (File Hosting) │ -│ │ │ │ │ │ -│ - PreviewPane │───▶│ - Remove │───▶│ - iframe- │ -│ - JSON-RPC │ │ X-Frame-Opt │ │ fetch-client │ -│ - Console UI │ │ - Add CORS │ │ - sw.js │ -│ │ │ - Route │ │ - index.html │ -└─────────────────┘ └─────────────────┘ └─────────────────┘ -``` - -The worker enables secure iframe embedding by: -1. Removing headers that prevent iframe embedding -2. Adding appropriate CORS headers for cross-origin communication -3. Providing a stable domain for project subdomains -4. Handling SSL/TLS automatically \ No newline at end of file diff --git a/cloudflare-worker/setup.sh b/cloudflare-worker/setup.sh deleted file mode 100755 index 92ebd30f..00000000 --- a/cloudflare-worker/setup.sh +++ /dev/null @@ -1,137 +0,0 @@ -#!/bin/bash - -# Shakespeare Iframe Proxy Setup Script -# This script helps you set up the Cloudflare Worker for iframe proxying - -set -e - -echo "🚀 Shakespeare Iframe Proxy Setup" -echo "==================================" - -# Check if surge is installed -if ! command -v surge &> /dev/null; then - echo "❌ Surge is not installed. Installing..." - npm install -g surge -fi - -# Check if wrangler is installed -if ! command -v wrangler &> /dev/null; then - echo "❌ Wrangler is not installed. Installing..." - npm install -g wrangler -fi - -# Ask for surge domain -read -p "📦 Enter a unique name for your Surge deployment (e.g., shakespeare-iframe-123): " SURGE_DOMAIN - -# Deploy to surge -echo "📤 Deploying iframe-fetch-client to Surge..." -cd ../iframe-fetch-client -surge . "${SURGE_DOMAIN}.surge.sh" -cd ../cloudflare-worker - -# Update worker configuration -echo "⚙️ Updating worker configuration..." -sed -i "s/your-unique-name.surge.sh/${SURGE_DOMAIN}.surge.sh/g" worker.js - -# Ask for Cloudflare setup -echo "" -echo "🌐 Cloudflare Worker Setup" -echo "------------------------" -echo "Choose your setup method:" -echo "1) Quick setup (via Cloudflare Dashboard - recommended for beginners)" -echo "2) Advanced setup (using Wrangler CLI - recommended for developers)" -read -p "Enter your choice (1 or 2): " SETUP_CHOICE - -if [ "$SETUP_CHOICE" = "1" ]; then - echo "" - echo "📋 Quick Setup Instructions:" - echo "============================" - echo "1. Go to https://dash.cloudflare.com/" - echo "2. Navigate to Workers & Pages → Create application" - echo "3. Select 'Create Worker'" - echo "4. Copy the contents of worker.js into the editor" - echo "5. Click 'Save and Deploy'" - echo "6. Note your worker's URL (e.g., shakespeare-iframe-proxy.your-account.workers.dev)" - echo "" - read -p "🔗 Enter your worker URL (e.g., shakespeare-iframe-proxy.your-account.workers.dev): " WORKER_URL - - # Update environment variable - echo "" - echo "🔧 Updating environment configuration..." - cd .. - - # Extract domain from worker URL - if [[ $WORKER_URL == *workers.dev ]]; then - IFRAME_DOMAIN=$(echo $WORKER_URL | sed 's|https://||' | sed 's|/.*||') - else - echo "❌ Invalid worker URL format. Please enter a valid workers.dev URL." - exit 1 - fi - - sed -i "s/VITE_IFRAME_DOMAIN=.*/VITE_IFRAME_DOMAIN=${IFRAME_DOMAIN}/" .env - - echo "✅ Setup complete!" - echo "" - echo "Next steps:" - echo "1. Run: npm run dev (or npm run build)" - echo "2. Open Shakespeare and test the preview" - echo "3. Check browser console for any errors" - -else - echo "" - echo "🔧 Advanced Setup with Wrangler" - echo "================================" - - # Check if logged in - if ! wrangler whoami &> /dev/null; then - echo "🔐 Logging in to Cloudflare..." - wrangler login - fi - - # Deploy worker - echo "📤 Deploying Cloudflare Worker..." - WORKER_URL=$(wrangler deploy --json | jq -r '.workers_dev.url') - - if [ -z "$WORKER_URL" ]; then - echo "❌ Failed to deploy worker. Please check the error messages above." - exit 1 - fi - - echo "✅ Worker deployed to: $WORKER_URL" - - # Update environment variable - echo "" - echo "🔧 Updating environment configuration..." - cd .. - - # Extract domain from worker URL - IFRAME_DOMAIN=$(echo $WORKER_URL | sed 's|https://||' | sed 's|/.*||') - - sed -i "s/VITE_IFRAME_DOMAIN=.*/VITE_IFRAME_DOMAIN=${IFRAME_DOMAIN}/" .env - - echo "✅ Setup complete!" - echo "" - echo "Next steps:" - echo "1. Run: npm run dev (or npm run build)" - echo "2. Open Shakespeare and test the preview" - echo "3. Check browser console for any errors" - echo "" - echo "🎉 For production use, consider setting up a custom domain." - echo " See cloudflare-worker/README.md for instructions." -fi - -echo "" -echo "🧪 Testing Instructions" -echo "======================" -echo "To test your setup:" -echo "1. Start Shakespeare: npm run dev" -echo "2. Create or open a project" -echo "3. Build the project" -echo "4. Switch to preview tab" -echo "5. Open browser console (F12)" -echo "6. Look for successful iframe loading and console messages" -echo "" -echo "If you see any errors, check:" -echo "- Browser console for CORS or security errors" -echo "- Network tab for failed requests" -echo "- Cloudflare Worker logs (in dashboard)" \ No newline at end of file diff --git a/cloudflare-worker/test.sh b/cloudflare-worker/test.sh deleted file mode 100755 index 98238eab..00000000 --- a/cloudflare-worker/test.sh +++ /dev/null @@ -1,138 +0,0 @@ -#!/bin/bash - -# Test script for Shakespeare Iframe Proxy -# This script helps verify that your Cloudflare Worker setup is working - -echo "🧪 Shakespeare Iframe Proxy Test" -echo "================================" - -# Get current IFRAME_DOMAIN from .env -if [ -f "../.env" ]; then - IFRAME_DOMAIN=$(grep VITE_IFRAME_DOMAIN ../.env | cut -d'=' -f2) -else - echo "❌ .env file not found. Please run setup first." - exit 1 -fi - -if [ -z "$IFRAME_DOMAIN" ]; then - echo "❌ VITE_IFRAME_DOMAIN not set in .env file." - exit 1 -fi - -echo "📡 Testing iframe domain: ${IFRAME_DOMAIN}" -echo "" - -# Test 1: Basic connectivity -echo "Test 1: Basic connectivity" -echo "--------------------------" -TEST_URL="https://${IFRAME_DOMAIN}" -echo "🔗 Testing: ${TEST_URL}" - -if command -v curl &> /dev/null; then - HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${TEST_URL}" 2>/dev/null || echo "000") - - if [ "$HTTP_CODE" = "200" ]; then - echo "✅ Successfully connected (HTTP 200)" - elif [ "$HTTP_CODE" = "000" ]; then - echo "❌ Connection failed - check domain and network" - else - echo "⚠️ Connected but got HTTP ${HTTP_CODE}" - fi -else - echo "❌ curl not available. Please install curl to run tests." -fi - -echo "" - -# Test 2: CORS headers -echo "Test 2: CORS Headers" -echo "--------------------" -if command -v curl &> /dev/null; then - CORS_HEADER=$(curl -s -I "${TEST_URL}" 2>/dev/null | grep -i "access-control-allow-origin" || echo "") - - if [ -n "$CORS_HEADER" ]; then - echo "✅ CORS headers present:" - echo " ${CORS_HEADER}" - else - echo "❌ No CORS headers found" - fi -else - echo "❌ curl not available. Skip CORS test." -fi - -echo "" - -# Test 3: X-Frame-Options (should be absent) -echo "Test 3: X-Frame-Options Check" -echo "------------------------------" -if command -v curl &> /dev/null; then - X_FRAME_HEADER=$(curl -s -I "${TEST_URL}" 2>/dev/null | grep -i "x-frame-options" || echo "") - - if [ -z "$X_FRAME_HEADER" ]; then - echo "✅ X-Frame-Options header correctly removed" - else - echo "❌ X-Frame-Options header still present:" - echo " ${X_FRAME_HEADER}" - fi -else - echo "❌ curl not available. Skip X-Frame-Options test." -fi - -echo "" - -# Test 4: Content-Type for JavaScript -echo "Test 4: JavaScript Content-Type" -echo "-------------------------------" -JS_URL="https://${IFRAME_DOMAIN}/_iframe-client.js" - -if command -v curl &> /dev/null; then - CONTENT_TYPE=$(curl -s -I "${JS_URL}" 2>/dev/null | grep -i "content-type" || echo "") - - if [[ $CONTENT_TYPE == *"application/javascript"* ]]; then - echo "✅ JavaScript files have correct Content-Type" - echo " ${CONTENT_TYPE}" - else - echo "❌ JavaScript Content-Type may be incorrect:" - echo " ${CONTENT_TYPE}" - fi -else - echo "❌ curl not available. Skip Content-Type test." -fi - -echo "" - -# Test 5: Service Worker -echo "Test 5: Service Worker Accessibility" -echo "-----------------------------------" -SW_URL="https://${IFRAME_DOMAIN}/sw.js" - -if command -v curl &> /dev/null; then - HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${SW_URL}" 2>/dev/null || echo "000") - - if [ "$HTTP_CODE" = "200" ]; then - echo "✅ Service Worker accessible (HTTP 200)" - else - echo "❌ Service Worker not accessible (HTTP ${HTTP_CODE})" - fi -else - echo "❌ curl not available. Skip Service Worker test." -fi - -echo "" -echo "🎯 Next Steps" -echo "=============" -echo "If all tests pass, your setup should be working!" -echo "" -echo "To test in Shakespeare:" -echo "1. cd .." -echo "2. npm run dev" -echo "3. Open a project in Shakespeare" -echo "4. Build the project" -echo "5. Switch to preview tab" -echo "6. Check browser console for any errors" -echo "" -echo "If you encounter issues:" -echo "- Check browser console for CORS errors" -echo "- Check Network tab for failed requests" -echo "- Verify Cloudflare Worker logs in dashboard" -echo "- Ensure .env has correct IFRAME_DOMAIN" \ No newline at end of file diff --git a/cloudflare-worker/worker.js b/cloudflare-worker/worker.js deleted file mode 100644 index 21f0be19..00000000 --- a/cloudflare-worker/worker.js +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Cloudflare Worker for Shakespeare iframe-fetch-client proxy - * - * This worker acts as a reverse proxy that: - * 1. Removes X-Frame-Options and other headers that prevent iframe embedding - * 2. Adds CORS headers for communication between iframe and parent - * 3. Routes all subdomain requests to the deployed iframe-fetch-client - */ - -export default { - async fetch(request, env, ctx) { - const url = new URL(request.url); - const { pathname, hostname, method } = url; - - // Handle OPTIONS preflight requests for CORS - if (method === 'OPTIONS') { - return new Response(null, { - headers: { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', - 'Access-Control-Allow-Headers': '*', - 'Access-Control-Max-Age': '86400', - } - }); - } - - // Extract project ID from subdomain (e.g., project123.your-domain.com) - const subdomain = hostname.split('.')[0]; - console.log(`[${new Date().toISOString()}] Request for project: ${subdomain}, path: ${pathname}, method: ${method}`); - - // Route to your surge deployment (update this URL to your surge deployment) - const surgeDomain = 'your-unique-name.surge.sh'; // TODO: Update this! - const targetUrl = new URL(pathname, `https://${surgeDomain}`); - - // Copy request headers, excluding problematic ones - const headers = new Headers(); - for (const [key, value] of request.headers.entries()) { - // Skip headers that might cause issues - if (!['host', 'origin', 'referer'].includes(key.toLowerCase())) { - headers.set(key, value); - } - } - - try { - // Forward the request to surge - const response = await fetch(targetUrl, { - method: method, - headers: headers, - body: request.body, - redirect: 'follow', - }); - - // Copy response headers but remove problematic ones - const newHeaders = new Headers(response.headers); - - // Remove headers that prevent iframe embedding - newHeaders.delete('X-Frame-Options'); - newHeaders.delete('Content-Security-Policy'); - newHeaders.delete('X-Content-Type-Options'); - newHeaders.delete('Strict-Transport-Security'); - - // Add CORS headers for communication between iframe and parent - newHeaders.set('Access-Control-Allow-Origin', '*'); - newHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - newHeaders.set('Access-Control-Allow-Headers', '*'); - newHeaders.set('Access-Control-Allow-Credentials', 'false'); - - // Ensure correct content types for specific file extensions - if (pathname.endsWith('.js')) { - newHeaders.set('Content-Type', 'application/javascript; charset=utf-8'); - } else if (pathname.endsWith('.mjs')) { - newHeaders.set('Content-Type', 'application/javascript; charset=utf-8'); - } else if (pathname.endsWith('.css')) { - newHeaders.set('Content-Type', 'text/css; charset=utf-8'); - } else if (pathname.endsWith('.html')) { - newHeaders.set('Content-Type', 'text/html; charset=utf-8'); - } else if (pathname.endsWith('.json')) { - newHeaders.set('Content-Type', 'application/json; charset=utf-8'); - } else if (pathname.endsWith('.svg')) { - newHeaders.set('Content-Type', 'image/svg+xml'); - } else if (pathname.endsWith('.png')) { - newHeaders.set('Content-Type', 'image/png'); - } else if (pathname.endsWith('.jpg') || pathname.endsWith('.jpeg')) { - newHeaders.set('Content-Type', 'image/jpeg'); - } - - // Add security headers that are iframe-friendly - newHeaders.set('X-Content-Type-Options', 'nosniff'); - - // Log successful proxy - console.log(`[${new Date().toISOString()}] Successfully proxied: ${response.status} ${response.statusText}`); - - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers: newHeaders - }); - - } catch (error) { - console.error(`[${new Date().toISOString()}] Proxy error for ${targetUrl}:`, error); - - return new Response(JSON.stringify({ - error: 'Proxy error', - message: error.message, - url: targetUrl.toString(), - timestamp: new Date().toISOString() - }), { - status: 502, - statusText: 'Bad Gateway', - headers: { - 'Content-Type': 'application/json', - 'Access-Control-Allow-Origin': '*', - } - }); - } - }, -}; \ No newline at end of file diff --git a/cloudflare-worker/wrangler.toml b/cloudflare-worker/wrangler.toml deleted file mode 100644 index 0211b72c..00000000 --- a/cloudflare-worker/wrangler.toml +++ /dev/null @@ -1,16 +0,0 @@ -name = "shakespeare-iframe-proxy" -main = "worker.js" -compatibility_date = "2023-10-30" - -# Development environment -[env.development] -vars = { ENVIRONMENT = "development" } - -# Production environment -[env.production] -vars = { ENVIRONMENT = "production" } - -# Optional: Add custom domains for production -# [env.production.routes] -# pattern = "your-domain.com/*" -# zone_name = "your-domain.com" \ No newline at end of file diff --git a/iframe-fetch-client/_iframe-client.js b/iframe-fetch-client/_iframe-client.js index 7252fa41..759d0033 100644 --- a/iframe-fetch-client/_iframe-client.js +++ b/iframe-fetch-client/_iframe-client.js @@ -10,57 +10,193 @@ class ConsoleInterceptor { warn: console.warn, error: console.error, info: console.info, - debug: console.debug + debug: console.debug, + exception: console.exception, + assert: console.assert, + clear: console.clear, + count: console.count, + countReset: console.countReset, + dir: console.dir, + dirxml: console.dirxml, + group: console.group, + groupCollapsed: console.groupCollapsed, + groupEnd: console.groupEnd, + table: console.table, + time: console.time, + timeEnd: console.timeEnd, + timeLog: console.timeLog, + trace: console.trace, }; this.overrideConsoleMethods(); + this.overrideErrorHandlers(); + this.overrideWindowError(); } overrideConsoleMethods() { - const methods = ['log', 'warn', 'error', 'info', 'debug']; + const methods = ['log', 'warn', 'error', 'info', 'debug', 'exception', 'assert', 'clear', 'count', 'countReset', 'dir', 'dirxml', 'group', 'groupCollapsed', 'groupEnd', 'table', 'time', 'timeEnd', 'timeLog', 'trace']; methods.forEach(method => { - console[method] = (...args) => { - // Call original method first (for local debugging) - this.originalConsole[method](...args); + if (typeof console[method] === 'function') { + console[method] = (...args) => { + // Call original method first (for local debugging) + try { + this.originalConsole[method](...args); + } catch (e) { + // If original method fails, at least try to send to parent + this.sendConsoleMessage(method, ...args); + return; + } - // Send to parent via JSON-RPC - this.sendConsoleMessage(method, ...args); - }; + // Send to parent via JSON-RPC + this.sendConsoleMessage(method, ...args); + }; + } }); } - sendConsoleMessage(level, ...args) { - const message = args.map(arg => { - if (typeof arg === 'object') { - try { - return JSON.stringify(arg); - } catch { - return String(arg); - } + overrideErrorHandlers() { + // 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); } - return String(arg); - }).join(' '); - window.parent.postMessage({ - jsonrpc: "2.0", - method: `console.${level}`, - params: { - level, - message, - timestamp: Date.now(), - args: args.map(arg => { - if (typeof arg === 'object') { - try { - return JSON.parse(JSON.stringify(arg)); - } catch { - return String(arg); - } - } - return arg; - }) + // Send to parent + this.sendConsoleMessage('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 + this.sendConsoleMessage('error', 'Unhandled Promise Rejection', { + reason: event.reason, + promise: event.promise ? 'Promise object' : 'No promise object' + }); + + event.preventDefault(); // Prevent default console warning + }; + } + + 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.${level}`, + params: { + level, + message, + timestamp: Date.now(), + args: args.map(arg => { + if (arg === undefined) return undefined; + if (arg === null) return null; + if (typeof arg === 'object') { + try { + return JSON.parse(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 arg; + }) + } + }, "*"); + } catch (postMessageError) { + // Parent might not be ready yet, try again later + setTimeout(() => { + try { + window.parent.postMessage({ + jsonrpc: "2.0", + method: `console.${level}`, + params: { + level, + message: `[DELAYED] ${message}`, + timestamp: Date.now(), + args: [] + } + }, "*"); + } 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.error", + params: { + level: "error", + message: `Console interceptor error: ${error.message}`, + timestamp: Date.now(), + args: [] + } + }, "*"); + } catch { + // If even this fails, we can't do anything + } + } } } @@ -139,9 +275,23 @@ class FetchClient { 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}`, ...error.args); + }); + // Clear the early errors + window._earlyConsoleErrors = []; + } + } + async init() { try { await this.registerServiceWorker(); diff --git a/iframe-fetch-client/index.html b/iframe-fetch-client/index.html index 001b1ea8..7bc770de 100644 --- a/iframe-fetch-client/index.html +++ b/iframe-fetch-client/index.html @@ -5,6 +5,100 @@ Site Preview + +
diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 43f21754..8cbf5dc5 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -208,16 +208,30 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { jsonrpc: '2.0'; method: string; params: { - level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + level: 'log' | 'warn' | 'error' | 'info' | 'debug' | 'exception' | 'assert' | 'clear' | 'count' | 'countReset' | 'dir' | 'dirxml' | 'group' | 'groupCollapsed' | 'groupEnd' | 'table' | 'time' | 'timeEnd' | 'timeLog' | 'trace'; message: string; timestamp: number; args: unknown[]; }; }) => { const { params } = message; + + // Normalize level to ensure it's one of our supported types + let normalizedLevel: ConsoleMessage['level'] = params.level; + if (!['log', 'warn', 'error', 'info', 'debug'].includes(normalizedLevel)) { + // Map other console methods to appropriate levels + if (['exception', 'assert'].includes(normalizedLevel)) { + normalizedLevel = 'error'; + } else if (['clear', 'count', 'countReset', 'dir', 'dirxml', 'group', 'groupCollapsed', 'groupEnd', 'table', 'time', 'timeEnd', 'timeLog', 'trace'].includes(normalizedLevel)) { + normalizedLevel = 'info'; + } else { + normalizedLevel = 'log'; + } + } + const newConsoleMessage: ConsoleMessage = { id: Date.now(), - level: params.level, + level: normalizedLevel, message: params.message, timestamp: params.timestamp, args: params.args, @@ -225,8 +239,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { setConsoleMessages(prev => [...prev, newConsoleMessage]); - // Log to parent console for debugging - console.log(`[IFRAME ${params.level.toUpperCase()}] ${params.message}`, ...params.args); + // Log to parent console for debugging with appropriate level + console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`, ...params.args); }, []); const handleFetch = useCallback(async (request: JSONRPCRequest) => {