Files
opal-ios-studio/server/static.cjs
T

69 lines
4.2 KiB
JavaScript

const fs = require('node:fs/promises');
const path = require('node:path');
const { createHash } = require('node:crypto');
const { gzipSync } = require('node:zlib');
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff': 'font/woff', '.woff2': 'font/woff2' };
const ROOT_FILES = new Set(['index.html', 'app.js', 'workspace.js', 'style.css', 'sw.js', 'manifest.json', 'favicon.svg']);
function createStaticHandler(publicDirectory, { maxCacheBytes = 16 * 1024 * 1024 } = {}) {
const root = path.resolve(publicDirectory), cache = new Map();
let cachedBytes = 0;
function missing(response, status = 404) {
response.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Content-Type-Options': 'nosniff' });
response.end(status === 404 ? 'Not found' : 'Method not allowed');
}
return async function serve(request, response) {
if (!['GET', 'HEAD'].includes(request.method)) return missing(response, 405);
let pathname;
try { pathname = decodeURIComponent(request.url.split('?')[0]); } catch { return missing(response); }
if (pathname.includes('\\') || pathname.includes('\0') || pathname.split('/').some(p => p.startsWith('.'))) return missing(response);
let relative = pathname === '/' ? 'index.html' : (pathname === '/favicon.ico' ? 'favicon.svg' : pathname.replace(/^\/+/, ''));
const asset = relative.startsWith('assets/') && MIME[path.extname(relative).toLowerCase()];
if (!ROOT_FILES.has(relative) && !asset) {
if (!path.extname(relative) && !/^(?:server|docs|test|data|node_modules)(?:\/|$)/.test(relative) && String(request.headers.accept || '').includes('text/html')) relative = 'index.html';
else return missing(response);
}
try {
const resolved = await fs.realpath(path.join(root, relative));
const actualRoot = await fs.realpath(root);
if (!resolved.startsWith(actualRoot + path.sep)) return missing(response);
const stat = await fs.stat(resolved);
if (!stat.isFile()) return missing(response);
const version = stat.mtimeMs + ':' + stat.size;
let entry = cache.get(relative);
if (!entry || entry.version !== version) {
if (entry) { cachedBytes -= entry.bytes; cache.delete(relative); }
const body = await fs.readFile(resolved);
const compressible = /\.(?:html|js|css|json|svg)$/.test(relative);
const gzip = compressible && body.length > 1024 ? gzipSync(body) : null;
entry = { version, body, gzip, bytes: body.length + (gzip?.length || 0), etag: 'W/"' + createHash('sha256').update(body).digest('hex') + '"' };
if (entry.bytes <= maxCacheBytes) {
while (cache.size && cachedBytes + entry.bytes > maxCacheBytes) {
const key = cache.keys().next().value; cachedBytes -= cache.get(key).bytes; cache.delete(key);
}
cache.set(relative, entry); cachedBytes += entry.bytes;
}
}
const html = relative.endsWith('.html');
const gzip = entry.gzip && /\bgzip\b/.test(request.headers['accept-encoding'] || '');
const body = gzip ? entry.gzip : entry.body;
const headers = {
'Content-Type': MIME[path.extname(relative).toLowerCase()] || 'application/octet-stream',
'Cache-Control': html || relative === 'sw.js' ? 'no-cache, no-store, must-revalidate, max-age=0' : 'no-cache, must-revalidate, max-age=0',
'X-Content-Type-Options': 'nosniff', 'X-Frame-Options': 'SAMEORIGIN',
'Access-Control-Allow-Origin': '*', Vary: 'Accept-Encoding', ETag: entry.etag,
...(gzip ? { 'Content-Encoding': 'gzip' } : {})
};
if (!html && request.headers['if-none-match'] === entry.etag) { response.writeHead(304, headers); return response.end(); }
response.writeHead(200, { ...headers, 'Content-Length': body.length });
response.end(request.method === 'HEAD' ? undefined : body);
} catch (error) {
if (['ENOENT', 'ENOTDIR', 'EACCES'].includes(error.code)) return missing(response);
throw error;
}
};
}
module.exports = { createStaticHandler };