Files
openmotion/editor-server.ts
Tom Huang 61ee4787c8 Unify Home navigation, provider settings, and local Agent selection (#393)
* Unify Studio navigation, provider settings, and local Agent workflows

* Serve the public provider notice from the editor file handler

The provider icon set added by this branch publishes
packages/design-system/providers/NOTICE.md through publicDesignFiles, but
serveEditorFile rejected .md because its MIME table only knew application
assets. The distribution regression test requests every public design file
and got 404 for the notice, so the attribution file was unreachable in the
editor package.

Map .md like the existing application server does (text/plain, UTF-8) so
the published notice is served with its bytes intact.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

* Include the provider icon manifest in the bundled adapter fixture

export-adapters.ts and the bundled runtime import
packages/design-system/index.js, which now also imports provider-icons.js to
publish the provider artwork. The adapter fixture copied every runtime file
the export reads except that new module, so the bundled launch failed with
ERR_MODULE_NOT_FOUND for provider-icons.js in the distribution regression
job.

Copy the icon manifest into the fixture alongside index.js, matching the
runtime distribution list that already ships it.

Generated-By: looper 0.16.2 (runner=fixer, agent=pi)

---------

Co-authored-by: pftom <pftom@pftomdeMacBook-Pro.local>
Co-authored-by: 罗高 <luogao@users.noreply.github.com>
2026-11-15 11:56:47 +08:00

70 lines
4.1 KiB
TypeScript

import { renderFilenameStem } from './shared/render-name.ts';
import { request } from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { pluginRoot } from './hyperframes.ts';
import { resolveDesignSystemFile } from './packages/design-system/index.js';
const mime: Record<string, string> = { '.jpg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json', '.map': 'application/json', '.ttf': 'font/ttf', '.woff2': 'font/woff2', '.txt': 'text/plain', '.md': 'text/plain; charset=utf-8' };
/** Only application bundle and design-system files are exposed, never Studio source or project files. */
export async function serveEditorFile(url: URL, res: ServerResponse): Promise<boolean> {
let relative: string;
const designFile = resolveDesignSystemFile(url.pathname);
if (url.pathname === '/') relative = 'studio/build/index.html';
else if (designFile) relative = 'packages/design-system/' + designFile;
else if (url.pathname === '/favicon.svg') relative = 'packages/design-system/brand/favicon.svg';
else if (/^\/editor-assets\/[a-zA-Z0-9_.-]+$/.test(url.pathname)) relative = 'studio/build' + url.pathname;
else if (/^\/web\/catalog\/(?:hyperframes|template-frames|provenance|covers)\.json$/.test(url.pathname) || /^\/web\/catalog\/(?:template-frames|covers)\/[a-f0-9]{24}\.(?:jpg|webp)$/.test(url.pathname)) relative = url.pathname.slice(1);
else return false;
const type = mime[path.extname(relative)];
if (!type) return false;
try {
const data = await readFile(path.join(pluginRoot, relative));
res.writeHead(200, { 'Content-Type': type, 'Content-Length': data.length }); res.end(data);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
res.writeHead(503, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(relative.endsWith('index.html') ? '编辑器尚未构建。请运行 npm run build:studio。' : '编辑器资源不存在,请刷新页面。');
}
return true;
}
/** Suggest a portable name without changing the immutable render's storage path. */
export function renderDownloadDisposition(title: string | undefined, extension: string): string {
const stem = renderFilenameStem(title);
const encoded = encodeURIComponent(stem + extension).replace(/['()*]/g, char =>
'%' + char.charCodeAt(0).toString(16).toUpperCase());
return `attachment; filename="OpenMotion${extension}"; filename*=UTF-8''${encoded}`;
}
/** Preserve native HTTP semantics (SSE, byte ranges, multipart uploads and optimistic file writes). */
export function proxyStudio(req: IncomingMessage, res: ServerResponse, url: URL, studioUrl: string, downloadDisposition?: string): Promise<void> {
const target = new URL(studioUrl);
target.pathname = url.pathname; target.search = url.search; target.hash = '';
const headers = { ...req.headers, host: target.host };
if (headers.origin) headers.origin = target.origin;
if (headers.referer) headers.referer = target.origin + '/';
delete headers.connection;
return new Promise(resolve => {
const upstream = request(target, { method: req.method, headers }, response => {
const outgoing = { ...response.headers };
delete outgoing.connection;
if (downloadDisposition && response.statusCode === 200) outgoing['content-disposition'] = downloadDisposition;
res.writeHead(response.statusCode || 502, outgoing);
response.on('error', () => { res.destroy(); resolve(); });
response.pipe(res);
});
upstream.on('error', () => {
if (!res.headersSent) { res.writeHead(502, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: '原生编辑服务连接中断,请刷新重试' })); }
else res.destroy();
resolve();
});
res.on('close', () => { upstream.destroy(); resolve(); });
res.on('finish', resolve);
req.on('error', () => upstream.destroy());
req.pipe(upstream);
});
}