mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 08:23:34 +00:00
Serve raw file paths from sw.js
This commit is contained in:
3 files changed
+189
-35
No files matched your search
+129
@@ -0,0 +1,129 @@
|
||||
// Service Worker for serving files from LightningFS filesystem
|
||||
const CACHE_NAME = 'shakespeare-fs-v1';
|
||||
|
||||
console.log("HELLO?!?!? " + new Date().getMinutes());
|
||||
|
||||
// Handle file requests from the virtual filesystem
|
||||
async function handleFileRequest(url) {
|
||||
const urlObj = new URL(url);
|
||||
const pathMatch = urlObj.pathname.match(/^\/project\/([^\/]+)\/files\/(.+)$/);
|
||||
|
||||
if (!pathMatch) {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
|
||||
console.log(`Handling file request for ${url}`);
|
||||
|
||||
const [, projectId, filePath] = pathMatch;
|
||||
|
||||
try {
|
||||
// Request file content from main thread via message
|
||||
const fileContent = await requestFileFromMainThread(projectId, filePath);
|
||||
|
||||
if (fileContent === null) {
|
||||
return new Response('File Not Found', { status: 404 });
|
||||
}
|
||||
|
||||
// Determine content type based on file extension
|
||||
const contentType = getContentType(filePath);
|
||||
|
||||
console.log(`Serving file ${filePath} from project ${projectId}`);
|
||||
|
||||
return new Response(fileContent, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Cache-Control': 'no-cache', // Don't cache for development
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to read file from main thread:', error);
|
||||
return new Response('File Not Found', { status: 404 });
|
||||
}
|
||||
}
|
||||
|
||||
// Request file content from main thread
|
||||
async function requestFileFromMainThread(projectId, filePath) {
|
||||
return new Promise((resolve) => {
|
||||
const messageId = Math.random().toString(36).substr(2, 9);
|
||||
|
||||
// Set up message listener for response
|
||||
const messageHandler = (event) => {
|
||||
if (event.data.type === 'FILE_RESPONSE' && event.data.messageId === messageId) {
|
||||
self.removeEventListener('message', messageHandler);
|
||||
resolve(event.data.content);
|
||||
}
|
||||
};
|
||||
|
||||
self.addEventListener('message', messageHandler);
|
||||
|
||||
console.log(`Requesting file ${filePath} from project ${projectId}`);
|
||||
|
||||
// Send request to all clients
|
||||
self.clients.matchAll().then(clients => {
|
||||
clients.forEach(client => {
|
||||
client.postMessage({
|
||||
type: 'FILE_REQUEST',
|
||||
messageId,
|
||||
projectId,
|
||||
filePath
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Timeout after 5 seconds
|
||||
setTimeout(() => {
|
||||
self.removeEventListener('message', messageHandler);
|
||||
resolve(null);
|
||||
}, 5000);
|
||||
});
|
||||
}
|
||||
|
||||
// Get content type based on file extension
|
||||
function getContentType(filePath) {
|
||||
const ext = filePath.split('.').pop()?.toLowerCase();
|
||||
|
||||
const mimeTypes = {
|
||||
'html': 'text/html',
|
||||
'css': 'text/css',
|
||||
'js': 'application/javascript',
|
||||
'jsx': 'application/javascript',
|
||||
'ts': 'application/javascript',
|
||||
'tsx': 'application/javascript',
|
||||
'json': 'application/json',
|
||||
'png': 'image/png',
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'gif': 'image/gif',
|
||||
'svg': 'image/svg+xml',
|
||||
'ico': 'image/x-icon',
|
||||
'woff': 'font/woff',
|
||||
'woff2': 'font/woff2',
|
||||
'ttf': 'font/ttf',
|
||||
'eot': 'application/vnd.ms-fontobject',
|
||||
};
|
||||
|
||||
return mimeTypes[ext] || 'text/plain';
|
||||
}
|
||||
|
||||
// Service Worker event listeners
|
||||
self.addEventListener('install', (event) => {
|
||||
console.log('Service Worker installing...');
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
console.log('Service Worker activating...');
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
console.log(`Service Worker fetching: ${event.request.url}`);
|
||||
const url = event.request.url;
|
||||
|
||||
// Only handle requests for project files
|
||||
if (url.includes('/project/') && url.includes('/files/')) {
|
||||
console.log(`Handling fetch request for ${url}`);
|
||||
event.respondWith(handleFileRequest(url));
|
||||
}
|
||||
});
|
||||
@@ -42,8 +42,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
// Load the built HTML content
|
||||
const htmlContent = await fsManager.readFile(projectId, 'dist/index.html');
|
||||
|
||||
// Process the HTML to handle relative asset paths
|
||||
const processedHtml = await processHtmlForPreview(htmlContent, projectId);
|
||||
// Process the HTML to add base tag for asset resolution
|
||||
const processedHtml = processHtmlForPreview(htmlContent, projectId);
|
||||
setPreviewHtml(processedHtml);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -52,48 +52,29 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const processHtmlForPreview = async (html: string, projectId: string): Promise<string> => {
|
||||
const processHtmlForPreview = (html: string, projectId: string): string => {
|
||||
try {
|
||||
// Create a temporary DOM to process the HTML
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
|
||||
// Process script tags with relative paths
|
||||
const scripts = doc.querySelectorAll('script[src]');
|
||||
for (const script of scripts) {
|
||||
const src = script.getAttribute('src');
|
||||
if (src && !src.startsWith('http') && !src.startsWith('//')) {
|
||||
try {
|
||||
const assetPath = src.startsWith('/') ? `dist${src}` : `dist/${src}`;
|
||||
const assetContent = await fsManager.readFile(projectId, assetPath);
|
||||
// Add base tag to resolve relative paths through service worker
|
||||
const baseUrl = `/project/${projectId}/files/dist/`;
|
||||
|
||||
// Replace the script tag with inline script
|
||||
const inlineScript = doc.createElement('script');
|
||||
inlineScript.textContent = assetContent;
|
||||
script.parentNode?.replaceChild(inlineScript, script);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to load script asset: ${src}`, error);
|
||||
}
|
||||
}
|
||||
// Remove existing base tag if present
|
||||
const existingBase = doc.querySelector('base');
|
||||
if (existingBase) {
|
||||
existingBase.remove();
|
||||
}
|
||||
|
||||
// Process CSS link tags
|
||||
const links = doc.querySelectorAll('link[rel="stylesheet"]');
|
||||
for (const link of links) {
|
||||
const href = link.getAttribute('href');
|
||||
if (href && !href.startsWith('http') && !href.startsWith('//')) {
|
||||
try {
|
||||
const assetPath = href.startsWith('/') ? `dist${href}` : `dist/${href}`;
|
||||
const cssContent = await fsManager.readFile(projectId, assetPath);
|
||||
// Add new base tag
|
||||
const baseTag = doc.createElement('base');
|
||||
baseTag.href = baseUrl;
|
||||
|
||||
// Replace the link tag with inline style
|
||||
const style = doc.createElement('style');
|
||||
style.textContent = cssContent;
|
||||
link.parentNode?.replaceChild(style, link);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to load CSS asset: ${href}`, error);
|
||||
}
|
||||
}
|
||||
// Insert base tag as first child of head
|
||||
const head = doc.querySelector('head');
|
||||
if (head) {
|
||||
head.insertBefore(baseTag, head.firstChild);
|
||||
}
|
||||
|
||||
return doc.documentElement.outerHTML;
|
||||
|
||||
@@ -9,4 +9,48 @@ import './index.css';
|
||||
// Using Inter Variable font for modern, clean typography
|
||||
import '@fontsource-variable/inter';
|
||||
|
||||
// Register service worker for file serving
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', async () => {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register('/sw.js');
|
||||
console.log('SW registered: ', registration);
|
||||
|
||||
// Set up message handler for file requests from service worker
|
||||
navigator.serviceWorker.addEventListener('message', async (event) => {
|
||||
if (event.data.type === 'FILE_REQUEST') {
|
||||
const { messageId, projectId, filePath } = event.data;
|
||||
|
||||
try {
|
||||
// Dynamically import fsManager to avoid circular dependencies
|
||||
const { fsManager } = await import('./lib/fs');
|
||||
const content = await fsManager.readFile(projectId, filePath);
|
||||
|
||||
// Send response back to service worker
|
||||
if (navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage({
|
||||
type: 'FILE_RESPONSE',
|
||||
messageId,
|
||||
content
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to read file for service worker:', error);
|
||||
// Send null response to indicate file not found
|
||||
if (navigator.serviceWorker.controller) {
|
||||
navigator.serviceWorker.controller.postMessage({
|
||||
type: 'FILE_RESPONSE',
|
||||
messageId,
|
||||
content: null
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (registrationError) {
|
||||
console.log('SW registration failed: ', registrationError);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
Reference in new issue
Block a user