From ba251d57eb592564e6d4988873a6c63bba6ca541 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Tue, 16 Sep 2025 05:30:26 +0000 Subject: [PATCH] baseline --- iframe-fetch-client/MESSAGING_PROTOCOL.md | 244 +++++++++++++++++++++ iframe-fetch-client/_iframe-client.js | 62 ++++++ iframe-fetch-client/test-console.html | 34 +++ src/components/Shakespeare/PreviewPane.tsx | 145 +++++++++++- 4 files changed, 474 insertions(+), 11 deletions(-) create mode 100644 iframe-fetch-client/test-console.html diff --git a/iframe-fetch-client/MESSAGING_PROTOCOL.md b/iframe-fetch-client/MESSAGING_PROTOCOL.md index a1e4845d..8857a5ee 100644 --- a/iframe-fetch-client/MESSAGING_PROTOCOL.md +++ b/iframe-fetch-client/MESSAGING_PROTOCOL.md @@ -126,6 +126,71 @@ full request body support - `-32002`: Request processing error - `-32003`: Invalid URL +### `console.log` + +**Purpose:** Forward console log messages from iframe to parent for display + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `message` (string): The log message +- `timestamp` (number): Unix timestamp when the log was created +- `args` (array): Additional arguments passed to the console method (optional) + +**Result:** None (notification only, no response expected) + +### `console.warn` + +**Purpose:** Forward console warn messages from iframe to parent for display + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `message` (string): The log message +- `timestamp` (number): Unix timestamp when the log was created +- `args` (array): Additional arguments passed to the console method (optional) + +**Result:** None (notification only, no response expected) + +### `console.error` + +**Purpose:** Forward console error messages from iframe to parent for display + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `timestamp` (number): Unix timestamp when the log was created +- `message` (string): The log message +- `args` (array): Additional arguments passed to the console method (optional) + +**Result:** None (notification only, no response expected) + +### `console.info` + +**Purpose:** Forward console info messages from iframe to parent for display + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `message` (string): The log message +- `timestamp` (number): Unix timestamp when the log was created +- `args` (array): Additional arguments passed to the console method (optional) + +**Result:** None (notification only, no response expected) + +### `console.debug` + +**Purpose:** Forward console debug messages from iframe to parent for display + +**Parameters:** + +- `level` (string): Log level - "log", "warn", "error", "info", "debug" +- `message` (string): The log message +- `timestamp` (number): Unix timestamp when the log was created +- `args` (array): Additional arguments passed to the console method (optional) + +**Result:** None (notification only, no response expected) + **Request Body Support:** The system fully supports request bodies, enabling: - POST/PUT requests with JSON data @@ -326,7 +391,186 @@ const decodedBody = atob(encodedBody); }], ]); + // 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 && message.method.startsWith("console.")) { + this.handleConsoleMessage(message); + } + }); + } + + handleConsoleMessage(message) { + const { method, params } = message; + const { level, message: logMessage, timestamp, args = [] } = params; + + // Store the log message + this.consoleLogs.push({ + level, + message: logMessage, + timestamp, + args, + 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}`, ...args); + } + + 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 new FetchClientParent(files); ``` + +## Console Logging Implementation + +To enable console logging from the iframe to the parent page, the iframe's bootstrap script should override the 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(); + } + + overrideConsoleMethods() { + const methods = ['log', 'warn', 'error', 'info', 'debug']; + + methods.forEach(method => { + console[method] = (...args) => { + // Call original method first + this.originalConsole[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); + } + } + 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; + }) + } + }, "*"); + } +} + +// Initialize console interception +new ConsoleInterceptor(); +``` diff --git a/iframe-fetch-client/_iframe-client.js b/iframe-fetch-client/_iframe-client.js index e7281caa..7252fa41 100644 --- a/iframe-fetch-client/_iframe-client.js +++ b/iframe-fetch-client/_iframe-client.js @@ -3,6 +3,67 @@ * JSON-RPC based communication with parent page */ +class ConsoleInterceptor { + constructor() { + this.originalConsole = { + log: console.log, + warn: console.warn, + error: console.error, + info: console.info, + debug: console.debug + }; + + this.overrideConsoleMethods(); + } + + overrideConsoleMethods() { + const methods = ['log', 'warn', 'error', 'info', 'debug']; + + methods.forEach(method => { + console[method] = (...args) => { + // Call original method first (for local debugging) + this.originalConsole[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); + } + } + 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; + }) + } + }, "*"); + } +} + class JSONRPCClient { constructor() { this.requestId = 0; @@ -76,6 +137,7 @@ class FetchClient { constructor() { this.rpcClient = new JSONRPCClient(); this.swReady = false; + this.consoleInterceptor = new ConsoleInterceptor(); this.init(); } diff --git a/iframe-fetch-client/test-console.html b/iframe-fetch-client/test-console.html new file mode 100644 index 00000000..7beb15a0 --- /dev/null +++ b/iframe-fetch-client/test-console.html @@ -0,0 +1,34 @@ + + + + + + Console Test + + +

Console Test Page

+

This page tests console logging functionality.

+ + + + \ No newline at end of file diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index c795e9d8..cca41f01 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -6,10 +6,15 @@ import { useFS } from '@/hooks/useFS'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; -import { FolderOpen, ArrowLeft } from 'lucide-react'; +import { FolderOpen, ArrowLeft, Terminal, X } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; @@ -49,6 +54,14 @@ interface JSONRPCResponse { id: number; } +interface ConsoleMessage { + id: number; + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; + timestamp: number; + args: unknown[]; +} + export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const { t } = useTranslation(); const [selectedFile, setSelectedFile] = useState(null); @@ -60,6 +73,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); + const [consoleMessages, setConsoleMessages] = useState([]); const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); @@ -187,6 +201,31 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { } }, [projectId]); + const handleConsoleMessage = useCallback((message: { + jsonrpc: '2.0'; + method: string; + params: { + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; + timestamp: number; + args: unknown[]; + }; + }) => { + const { params } = message; + const newConsoleMessage: ConsoleMessage = { + id: Date.now(), + level: params.level, + message: params.message, + timestamp: params.timestamp, + args: params.args, + }; + + setConsoleMessages(prev => [...prev, newConsoleMessage]); + + // Log to parent console for debugging + console.log(`[IFRAME ${params.level.toUpperCase()}] ${params.message}`, ...params.args); + }, []); + const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; const { request: fetchRequest } = params; @@ -302,12 +341,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { console.log('Received message from iframe:', message); if (message.jsonrpc === '2.0' && message.method === 'fetch') { handleFetch(message); + } else if (message.jsonrpc === '2.0' && message.method && message.method.startsWith('console.')) { + handleConsoleMessage(message); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); - }, [handleFetch, projectId]); + }, [handleFetch, handleConsoleMessage, projectId]); useEffect(() => { if (selectedFile) { @@ -352,21 +393,103 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { } }; + const ConsoleDropdown = () => { + const getLevelColor = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return 'text-red-500'; + case 'warn': return 'text-yellow-500'; + case 'info': return 'text-blue-500'; + case 'debug': return 'text-gray-500'; + default: return 'text-gray-400'; + } + }; + + const getLevelIcon = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return '!'; + case 'warn': return '⚠'; + case 'info': return 'ℹ'; + case 'debug': return '🔍'; + default: return '•'; + } + }; + + const formatTimestamp = (timestamp: number) => { + return new Date(timestamp).toLocaleTimeString(); + }; + + const clearConsole = () => { + setConsoleMessages([]); + }; + + return ( + + + + + +
+ Console Output + +
+ +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+ {getLevelIcon(msg.level)} + {formatTimestamp(msg.timestamp)} +
+
{msg.message}
+ {msg.args.length > 0 && ( +
+ Args: {JSON.stringify(msg.args)} +
+ )} +
+ )) + )} +
+
+
+
+ ); +}; + return (
{hasBuiltProject ? (
- 0} - canGoForward={historyIndex < navigationHistory.length - 1} - /> +
+ 0} + canGoForward={historyIndex < navigationHistory.length - 1} + /> + +