refactor: reformat code for improved readability and consistent style

This commit is contained in:
2026-10-31 01:24:34 +01:00
parent 53945a56df
commit 51251e444a
+240 -39
View File
@@ -18,7 +18,9 @@ const sensitivePattern = /(^|[\\/])(?:\.git|\.env(?:\.|$)|node_modules[\\/]\.bin
export interface DevServer { export interface DevServer {
listen(): Promise<void>; listen(): Promise<void>;
close(): Promise<void>; close(): Promise<void>;
readonly url: string | undefined; readonly url: string | undefined;
readonly port: number | undefined; readonly port: number | undefined;
readonly config: ResolvedIcebergConfig; readonly config: ResolvedIcebergConfig;
@@ -34,30 +36,59 @@ class IcebergDevServer implements DevServer {
private watcher?: FSWatcher; private watcher?: FSWatcher;
private ws?: WebSocketServer; private ws?: WebSocketServer;
private boundPort?: number; private boundPort?: number;
constructor(public readonly config: ResolvedIcebergConfig) {}
get url() { return this.boundPort === undefined ? undefined : `http://${displayHost(this.config.server.host)}:${this.boundPort}${this.config.base}`; } constructor(public readonly config: ResolvedIcebergConfig) {
get port() { return this.boundPort; } }
get url() {
return this.boundPort === undefined ? undefined : `http://${displayHost(this.config.server.host)}:${this.boundPort}${this.config.base}`;
}
get port() {
return this.boundPort;
}
async listen() { async listen() {
if (this.server) return; if (this.server) return;
this.server = http.createServer((request, response) => void this.handle(request, response)); this.server = http.createServer((request, response) => void this.handle(request, response));
this.ws = new WebSocketServer({noServer: true}); this.ws = new WebSocketServer({noServer: true});
this.ws.on('connection', socket => { this.sockets.add(socket); socket.send(JSON.stringify({ type: 'connected' })); socket.on('close', () => this.sockets.delete(socket)); }); this.ws.on('connection', socket => {
this.server.on('upgrade', (request, socket, head) => { const pathname = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`).pathname; if (pathname !== `${this.config.base}__iceberg_ws` && pathname !== '/__iceberg_ws') { socket.destroy(); return; } this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request)); }); this.sockets.add(socket);
socket.send(JSON.stringify({type: 'connected'}));
socket.on('close', () => this.sockets.delete(socket));
});
this.server.on('upgrade', (request, socket, head) => {
const pathname = new URL(request.url ?? '/', `http://${request.headers.host ?? 'localhost'}`).pathname;
if (pathname !== `${this.config.base}__iceberg_ws` && pathname !== '/__iceberg_ws') {
socket.destroy();
return;
}
this.ws!.handleUpgrade(request, socket, head, client => this.ws!.emit('connection', client, request));
});
this.boundPort = await listenOnAvailablePort(this.server, this.config.server.host, this.config.server.port, this.config.server.strictPort); this.boundPort = await listenOnAvailablePort(this.server, this.config.server.host, this.config.server.port, this.config.server.strictPort);
this.watcher = chokidar.watch(this.config.root, { ignored: file => /[\\/]node_modules[\\/]|[\\/]\.git[\\/]|[\\/]dist[\\/]|[\\/]build[\\/]/.test(file), ignoreInitial: true }); this.watcher = chokidar.watch(this.config.root, {
ignored: file => /[\\/]node_modules[\\/]|[\\/]\.git[\\/]|[\\/]dist[\\/]|[\\/]build[\\/]/.test(file),
ignoreInitial: true
});
this.watcher.on('all', (event, file) => this.onFileChange(event, path.resolve(file))); this.watcher.on('all', (event, file) => this.onFileChange(event, path.resolve(file)));
await new Promise<void>((resolve, reject) => { this.watcher!.once('ready', () => resolve()); this.watcher!.once('error', reject); }); await new Promise<void>((resolve, reject) => {
this.watcher!.once('ready', () => resolve());
this.watcher!.once('error', reject);
});
logger.info(`ICEBERG v0.2.0\n\n Local: ${this.url}\n Network: use --host to expose\n\n Ready`); logger.info(`ICEBERG v0.2.0\n\n Local: ${this.url}\n Network: use --host to expose\n\n Ready`);
if (this.config.server.open && this.url) openBrowser(this.url); if (this.config.server.open && this.url) openBrowser(this.url);
} }
async close() { async close() {
await this.watcher?.close(); this.watcher = undefined; await this.watcher?.close();
for (const socket of this.sockets) socket.close(); this.sockets.clear(); this.watcher = undefined;
this.ws?.close(); this.ws = undefined; for (const socket of this.sockets) socket.close();
this.sockets.clear();
this.ws?.close();
this.ws = undefined;
if (this.server) await new Promise<void>(resolve => this.server!.close(() => resolve())); if (this.server) await new Promise<void>(resolve => this.server!.close(() => resolve()));
this.server = undefined; this.boundPort = undefined; this.server = undefined;
this.boundPort = undefined;
} }
private async handle(request: http.IncomingMessage, response: http.ServerResponse) { private async handle(request: http.IncomingMessage, response: http.ServerResponse) {
@@ -83,35 +114,205 @@ class IcebergDevServer implements DevServer {
} }
if (!path.extname(relative)) return this.serveHtml(path.join(this.config.root, 'index.html'), response); if (!path.extname(relative)) return this.serveHtml(path.join(this.config.root, 'index.html'), response);
return send(response, 404, 'Not Found', 'text/plain'); return send(response, 404, 'Not Found', 'text/plain');
} catch (error) { const message = error instanceof Error ? error.message : String(error); logger.error(message); return send(response, 500, message, 'text/plain'); } } catch (error) {
const message = error instanceof Error ? error.message : String(error);
logger.error(message);
return send(response, 500, message, 'text/plain');
}
} }
private async serveHtml(file: string, response: http.ServerResponse) { const html = await readFile(file, 'utf8'); const client = `${this.config.base}@iceberg/client.js`; const injected = html.includes('</body>') ? html.replace(/<\/body>/i, `<script type="module" src="${client}"></script></body>`) : `${html}\n<script type="module" src="${client}"></script>`; send(response, 200, injected, 'text/html'); } private async serveHtml(file: string, response: http.ServerResponse) {
private async serveModuleFile(file: string, response: http.ServerResponse) { const source = await readFile(file, 'utf8'); const result = await transform(file, source, { lang: languageFor(file), sourceType: 'module', sourcemap: true }); if (result.errors.length) throw new Error(result.errors.map(error => error.message).join('\n')); let code = rewriteImports(String(result.code), file, this.config); if (result.map) code += `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(result.map)).toString('base64')}`; send(response, 200, code, 'application/javascript'); } const html = await readFile(file, 'utf8');
private async serveModule(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing module file', 'text/plain'); return this.serveModuleFile(file, response); } const client = `${this.config.base}@iceberg/client.js`;
private async serveCss(file: string, response: http.ServerResponse) { const result = await bundleAsync({ filename: file, minify: false, sourceMap: true }); const sourceMap = result.map ? `\n/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.map).toString('base64')} */` : ''; send(response, 200, Buffer.concat([result.code, Buffer.from(sourceMap)]), 'text/css'); } const injected = html.includes('</body>') ? html.replace(/<\/body>/i, `<script type="module" src="${client}"></script></body>`) : `${html}\n<script type="module" src="${client}"></script>`;
private async serveCssProxy(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing CSS file', 'text/plain'); const cssUrl = this.browserUrl(file); const code = `const href = ${JSON.stringify(cssUrl)}; let link = document.querySelector('link[data-iceberg-css="' + href + '"]'); if (!link) { link = document.createElement('link'); link.rel = 'stylesheet'; link.dataset.icebergCss = href; link.href = href; document.head.append(link); } export default link;`; send(response, 200, code, 'application/javascript'); } send(response, 200, injected, 'text/html');
private async serveAssetModule(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); send(response, 200, `export default ${JSON.stringify(this.browserUrl(file))};`, 'application/javascript'); }
private async serveAsset(url: URL, response: http.ServerResponse) { const file = this.requestedFile(url); if (!file) return send(response, 400, 'Missing asset file', 'text/plain'); return this.serveFile(file, response); }
private async serveFile(file: string, response: http.ServerResponse) { const content = await readFile(file); send(response, 200, content, contentType(file)); }
private requestedFile(url: URL) { const raw = url.searchParams.get('file'); if (!raw) return undefined; const file = path.resolve(raw); return this.isAllowed(file) ? file : undefined; }
private async safeFile(file: string) { const resolved = path.resolve(file); return this.isAllowed(resolved) ? resolved : undefined; }
private isAllowed(file: string) { const root = path.resolve(this.config.root); return isWithin(root, file) && !sensitivePattern.test(path.relative(root, file)); }
private browserUrl(file: string) { const relative = `/${path.relative(this.config.root, file).replace(/\\/g, '/')}`; return `${this.config.base === '/' ? '' : this.config.base.slice(0, -1)}${relative}`; }
private onFileChange(event: string, file: string) { if (event === 'unlink') { this.broadcast({ type: 'reload' }); return; } if (file.endsWith('.css')) this.broadcast({ type: 'css-update', path: this.browserUrl(file) }); else this.broadcast({ type: 'reload' }); }
private broadcast(message: object) { const data = JSON.stringify(message); for (const socket of this.sockets) if (socket.readyState === 1) socket.send(data); }
} }
function rewriteImports(code: string, importer: string, config: ResolvedIcebergConfig) { return code.replace(/(\b(?:import|export)\s*(?:[^'"`]*?\sfrom\s*)?|\bimport\s*\()(["'`])([^"'`]+)\2/g, (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${browserImport(specifier, importer, config)}${quote}`); } private async serveModuleFile(file: string, response: http.ServerResponse) {
function browserImport(specifier: string, importer: string, config: ResolvedIcebergConfig) { if (/^(node:|https?:|data:|\/\/)/.test(specifier)) return specifier; const file = resolveImport(specifier, importer, config.root); if (file.endsWith('.css')) return internalUrl('css-proxy', file, config); if (assetPattern.test(file)) return internalUrl('asset-module', file, config); return internalUrl('module', file, config); } const source = await readFile(file, 'utf8');
function resolveImport(specifier: string, importer: string, root: string) { const require = createRequire(pathToFileURL(importer)); try { const resolved = require.resolve(specifier); if (!isWithin(path.resolve(root), path.resolve(resolved))) throw new Error(`Dependency is outside the project root: ${specifier}`); return resolved; } catch (error) { throw new Error(`Could not resolve '${specifier}' from ${importer}: ${error instanceof Error ? error.message : String(error)}`); } } const result = await transform(file, source, {lang: languageFor(file), sourceType: 'module', sourcemap: true});
function internalUrl(kind: string, file: string, config: ResolvedIcebergConfig) { return `${config.base}@iceberg/${kind}?file=${encodeURIComponent(file)}`; } if (result.errors.length) throw new Error(result.errors.map(error => error.message).join('\n'));
function languageFor(file: string): 'js' | 'jsx' | 'ts' | 'tsx' { if (file.endsWith('.tsx')) return 'tsx'; if (file.endsWith('.jsx')) return 'jsx'; if (file.endsWith('.ts')) return 'ts'; return 'js'; } let code = rewriteImports(String(result.code), file, this.config);
function contentType(file: string) { if (file.endsWith('.css')) return 'text/css'; if (file.endsWith('.html')) return 'text/html'; if (file.endsWith('.js') || file.endsWith('.ts')) return 'application/javascript'; if (file.endsWith('.json')) return 'application/json'; if (file.endsWith('.svg')) return 'image/svg+xml'; if (file.endsWith('.png')) return 'image/png'; if (file.endsWith('.jpg') || file.endsWith('.jpeg')) return 'image/jpeg'; if (file.endsWith('.woff2')) return 'font/woff2'; return 'application/octet-stream'; } if (result.map) code += `\n//# sourceMappingURL=data:application/json;base64,${Buffer.from(JSON.stringify(result.map)).toString('base64')}`;
function send(response: http.ServerResponse, status: number, body: string | Uint8Array, type: string) { response.statusCode = status; response.setHeader('content-type', `${type}; charset=utf-8`); response.end(body); } send(response, 200, code, 'application/javascript');
function isWithin(root: string, file: string) { const relative = path.relative(root, file); return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)); } }
async function isFile(file: string) { try { return (await stat(file)).isFile(); } catch { return false; } }
function escapeRegExp(value: string) { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } private async serveModule(url: URL, response: http.ServerResponse) {
function displayHost(host: string) { return host === '0.0.0.0' ? 'localhost' : host; } const file = this.requestedFile(url);
function openBrowser(url: string) { const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open'; const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]; spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref(); } if (!file) return send(response, 400, 'Missing module file', 'text/plain');
async function listenOnAvailablePort(server: http.Server, host: string, start: number, strict: boolean) { let port = start; while (true) { try { await new Promise<void>((resolve, reject) => { const onError = (error: NodeJS.ErrnoException) => { server.off('listening', onListen); reject(error); }; const onListen = () => { server.off('error', onError); resolve(); }; server.once('error', onError); server.once('listening', onListen); server.listen(port, host); }); return (server.address() as { port: number }).port; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE' || strict) throw new Error(`Could not start server on ${host}:${port}. ${(error as Error).message}`); port++; } } } return this.serveModuleFile(file, response);
}
private async serveCss(file: string, response: http.ServerResponse) {
const result = await bundleAsync({filename: file, minify: false, sourceMap: true});
const sourceMap = result.map ? `\n/*# sourceMappingURL=data:application/json;base64,${Buffer.from(result.map).toString('base64')} */` : '';
send(response, 200, Buffer.concat([result.code, Buffer.from(sourceMap)]), 'text/css');
}
private async serveCssProxy(url: URL, response: http.ServerResponse) {
const file = this.requestedFile(url);
if (!file) return send(response, 400, 'Missing CSS file', 'text/plain');
const cssUrl = this.browserUrl(file);
const code = `const href = ${JSON.stringify(cssUrl)}; let link = document.querySelector('link[data-iceberg-css="' + href + '"]'); if (!link) { link = document.createElement('link'); link.rel = 'stylesheet'; link.dataset.icebergCss = href; link.href = href; document.head.append(link); } export default link;`;
send(response, 200, code, 'application/javascript');
}
private async serveAssetModule(url: URL, response: http.ServerResponse) {
const file = this.requestedFile(url);
if (!file) return send(response, 400, 'Missing asset file', 'text/plain');
send(response, 200, `export default ${JSON.stringify(this.browserUrl(file))};`, 'application/javascript');
}
private async serveAsset(url: URL, response: http.ServerResponse) {
const file = this.requestedFile(url);
if (!file) return send(response, 400, 'Missing asset file', 'text/plain');
return this.serveFile(file, response);
}
private async serveFile(file: string, response: http.ServerResponse) {
const content = await readFile(file);
send(response, 200, content, contentType(file));
}
private requestedFile(url: URL) {
const raw = url.searchParams.get('file');
if (!raw) return undefined;
const file = path.resolve(raw);
return this.isAllowed(file) ? file : undefined;
}
private async safeFile(file: string) {
const resolved = path.resolve(file);
return this.isAllowed(resolved) ? resolved : undefined;
}
private isAllowed(file: string) {
const root = path.resolve(this.config.root);
return isWithin(root, file) && !sensitivePattern.test(path.relative(root, file));
}
private browserUrl(file: string) {
const relative = `/${path.relative(this.config.root, file).replace(/\\/g, '/')}`;
return `${this.config.base === '/' ? '' : this.config.base.slice(0, -1)}${relative}`;
}
private onFileChange(event: string, file: string) {
if (event === 'unlink') {
this.broadcast({type: 'reload'});
return;
}
if (file.endsWith('.css')) this.broadcast({
type: 'css-update',
path: this.browserUrl(file)
}); else this.broadcast({type: 'reload'});
}
private broadcast(message: object) {
const data = JSON.stringify(message);
for (const socket of this.sockets) if (socket.readyState === 1) socket.send(data);
}
}
function rewriteImports(code: string, importer: string, config: ResolvedIcebergConfig) {
return code.replace(/(\b(?:import|export)\s*(?:[^'"`]*?\sfrom\s*)?|\bimport\s*\()(["'`])([^"'`]+)\2/g, (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${browserImport(specifier, importer, config)}${quote}`);
}
function browserImport(specifier: string, importer: string, config: ResolvedIcebergConfig) {
if (/^(node:|https?:|data:|\/\/)/.test(specifier)) return specifier;
const file = resolveImport(specifier, importer, config.root);
if (file.endsWith('.css')) return internalUrl('css-proxy', file, config);
if (assetPattern.test(file)) return internalUrl('asset-module', file, config);
return internalUrl('module', file, config);
}
function resolveImport(specifier: string, importer: string, root: string) {
const require = createRequire(pathToFileURL(importer));
try {
const resolved = require.resolve(specifier);
if (!isWithin(path.resolve(root), path.resolve(resolved))) throw new Error(`Dependency is outside the project root: ${specifier}`);
return resolved;
} catch (error) {
throw new Error(`Could not resolve '${specifier}' from ${importer}: ${error instanceof Error ? error.message : String(error)}`);
}
}
function internalUrl(kind: string, file: string, config: ResolvedIcebergConfig) {
return `${config.base}@iceberg/${kind}?file=${encodeURIComponent(file)}`;
}
function languageFor(file: string): 'js' | 'jsx' | 'ts' | 'tsx' {
if (file.endsWith('.tsx')) return 'tsx';
if (file.endsWith('.jsx')) return 'jsx';
if (file.endsWith('.ts')) return 'ts';
return 'js';
}
function contentType(file: string) {
if (file.endsWith('.css')) return 'text/css';
if (file.endsWith('.html')) return 'text/html';
if (file.endsWith('.js') || file.endsWith('.ts')) return 'application/javascript';
if (file.endsWith('.json')) return 'application/json';
if (file.endsWith('.svg')) return 'image/svg+xml';
if (file.endsWith('.png')) return 'image/png';
if (file.endsWith('.jpg') || file.endsWith('.jpeg')) return 'image/jpeg';
if (file.endsWith('.woff2')) return 'font/woff2';
return 'application/octet-stream';
}
function send(response: http.ServerResponse, status: number, body: string | Uint8Array, type: string) {
response.statusCode = status;
response.setHeader('content-type', `${type}; charset=utf-8`);
response.end(body);
}
function isWithin(root: string, file: string) {
const relative = path.relative(root, file);
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
}
async function isFile(file: string) {
try {
return (await stat(file)).isFile();
} catch {
return false;
}
}
function escapeRegExp(value: string) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function displayHost(host: string) {
return host === '0.0.0.0' ? 'localhost' : host;
}
function openBrowser(url: string) {
const command = process.platform === 'win32' ? 'cmd' : process.platform === 'darwin' ? 'open' : 'xdg-open';
const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
spawn(command, args, {detached: true, stdio: 'ignore', windowsHide: true}).unref();
}
async function listenOnAvailablePort(server: http.Server, host: string, start: number, strict: boolean) {
let port = start;
while (true) {
try {
await new Promise<void>((resolve, reject) => {
const onError = (error: NodeJS.ErrnoException) => {
server.off('listening', onListen);
reject(error);
};
const onListen = () => {
server.off('error', onError);
resolve();
};
server.once('error', onError);
server.once('listening', onListen);
server.listen(port, host);
});
return (server.address() as { port: number }).port;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE' || strict) throw new Error(`Could not start server on ${host}:${port}. ${(error as Error).message}`);
port++;
}
}
}