183 lines
8.7 KiB
JavaScript
183 lines
8.7 KiB
JavaScript
import http from 'node:http';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { assistantModel } from './assistant-model.mjs';
|
|
|
|
const projects = new Map(), uploads = new Map(), objects = new Map();
|
|
const owner = 'cad-browser-test-user', token = 'cad-browser-test-token';
|
|
const json = (res, data, status = 200, code = 'OK') => {
|
|
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
res.end(JSON.stringify({ code, message: code, data, requestId: 'cad-browser-test' }));
|
|
};
|
|
const bodyOf = async (req) => {
|
|
const chunks = [];
|
|
for await (const chunk of req) chunks.push(Buffer.from(chunk));
|
|
return Buffer.concat(chunks);
|
|
};
|
|
const timestamp = () => new Date().toISOString();
|
|
function projectData(project) {
|
|
return {
|
|
cadProjectCode: project.cadProjectCode,
|
|
name: project.name,
|
|
description: project.description,
|
|
coverUrl: project.coverUrl || null,
|
|
hasDocument: !!project.document,
|
|
version: project.version,
|
|
fileName: project.document?.upload.request.fileName || '',
|
|
sizeBytes: project.document?.upload.request.sizeBytes || 0,
|
|
savedAt: project.document?.savedAt || null,
|
|
createdAt: project.createdAt,
|
|
updatedAt: project.updatedAt,
|
|
};
|
|
}
|
|
function createProject(name, description = '', coverUrl = null) {
|
|
const cadProjectCode = 'cad-' + randomUUID();
|
|
const project = { cadProjectCode, name, description, coverUrl, version: 0, document: null, createdAt: timestamp(), updatedAt: timestamp() };
|
|
projects.set(cadProjectCode, project);
|
|
return project;
|
|
}
|
|
|
|
for (const name of ['支架', '底盘', '外壳']) createProject(name);
|
|
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url, 'http://localhost');
|
|
if (url.pathname.startsWith('/api/')) url.pathname = url.pathname.slice('/api'.length);
|
|
const body = await bodyOf(req);
|
|
if (await assistantModel(req, res, url, body)) return;
|
|
|
|
if (url.pathname === '/auth/captcha') return json(res, {
|
|
captchaCode: 'browser-test',
|
|
image: 'data:image/svg+xml;base64,' + Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"><rect width="100" height="40" fill="white"/><text x="15" y="28" font-size="24">1234</text></svg>').toString('base64'),
|
|
});
|
|
if (url.pathname === '/auth/login') return json(res, {
|
|
token,
|
|
user: { userCode: owner, nickname: 'CAD Browser Test', email: 'cad-test@example.test' },
|
|
expiresIn: 86400,
|
|
});
|
|
if (url.pathname === '/auth/logout') return json(res, {});
|
|
if (url.pathname === '/users/me') return req.headers.authorization === 'Bearer ' + token
|
|
? json(res, { userCode: owner, nickname: 'CAD Browser Test', email: 'cad-test@example.test' })
|
|
: json(res, null, 401, 'UNAUTHORIZED');
|
|
|
|
const sourceMatch = url.pathname.match(/^\/cad\/mock-source\/([^/]+)$/);
|
|
if (sourceMatch) {
|
|
const bytes = objects.get(sourceMatch[1]);
|
|
if (!bytes) return json(res, null, 404, 'NOT_FOUND');
|
|
res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Length': bytes.length, 'Cache-Control': 'no-store' });
|
|
return res.end(bytes);
|
|
}
|
|
|
|
const coverMatch = url.pathname.match(/^\/cad\/mock-cover-source\/([^/]+)\.png$/);
|
|
if (coverMatch) {
|
|
const bytes = objects.get(coverMatch[1]);
|
|
if (!bytes) return json(res, null, 404, 'NOT_FOUND');
|
|
res.writeHead(200, { 'Content-Type': 'image/png', 'Content-Length': bytes.length, 'Cache-Control': 'no-store' });
|
|
return res.end(bytes);
|
|
}
|
|
|
|
const ossMatch = url.pathname.match(/^\/cad\/mock-oss\/([^/]+)$/);
|
|
if (ossMatch && req.method === 'POST') {
|
|
const uploadCode = ossMatch[1], contentType = String(req.headers['content-type'] || '');
|
|
const boundary = contentType.split('boundary=')[1];
|
|
const marker = Buffer.from('name=\"file\"');
|
|
const start = body.indexOf(marker);
|
|
const dataStart = body.indexOf(Buffer.from('\r\n\r\n'), start) + 4;
|
|
const end = boundary ? body.indexOf(Buffer.from('\r\n--' + boundary), dataStart) : -1;
|
|
if (!boundary || start < 0 || dataStart < 4 || end < dataStart) return json(res, null, 400, 'INVALID_UPLOAD');
|
|
const existing = objects.get(uploadCode);
|
|
const incoming = body.subarray(dataStart, end);
|
|
if (existing) return json(res, null, 409, 'OBJECT_ALREADY_EXISTS');
|
|
objects.set(uploadCode, Buffer.from(incoming));
|
|
res.writeHead(200).end();
|
|
return;
|
|
}
|
|
|
|
if (req.headers.authorization !== 'Bearer ' + token) return json(res, null, 401, 'UNAUTHORIZED');
|
|
if (url.pathname === '/uploads/project-covers/signature' && req.method === 'POST') {
|
|
const input = JSON.parse(body);
|
|
if (!['image/png', 'image/jpeg', 'image/webp'].includes(input.contentType) || !Number.isSafeInteger(input.fileSize)
|
|
|| input.fileSize <= 0 || input.fileSize > 5 * 1024 * 1024) return json(res, null, 400, 'BAD_REQUEST');
|
|
const code = 'cover-' + randomUUID();
|
|
return json(res, {
|
|
uploadUrl: '/api/cad/mock-oss/' + code,
|
|
formFields: { key: code, policy: 'mock-cover-policy' },
|
|
coverUrl: 'https://cad-covers.example.test/' + code + '.png',
|
|
});
|
|
}
|
|
const root = '/cad/workspace/projects';
|
|
if (url.pathname === root && req.method === 'GET') {
|
|
const page = Number(url.searchParams.get('page') || 1);
|
|
const size = Number(url.searchParams.get('size') || 20);
|
|
const keyword = url.searchParams.get('keyword') || '';
|
|
const matches = [...projects.values()].filter((project) => !project.deleted && project.name.includes(keyword))
|
|
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
return json(res, { items: matches.slice((page - 1) * size, page * size).map(projectData), page, size, total: matches.length });
|
|
}
|
|
if (url.pathname === root && req.method === 'POST') {
|
|
const input = JSON.parse(body);
|
|
return json(res, projectData(createProject(input.name, input.description || '', input.coverUrl || null)));
|
|
}
|
|
|
|
const match = url.pathname.match(/^\/cad\/workspace\/projects\/([^/]+)(?:\/(.*))?$/);
|
|
if (!match) return json(res, null, 404, 'NOT_FOUND');
|
|
const project = projects.get(decodeURIComponent(match[1])), tail = match[2];
|
|
if (!project || project.deleted) return json(res, null, 404, 'NOT_FOUND');
|
|
if (!tail) {
|
|
if (req.method === 'PATCH') {
|
|
const input = JSON.parse(body);
|
|
if (input.name !== undefined && input.name !== null) project.name = input.name;
|
|
if (input.description !== undefined && input.description !== null) project.description = input.description;
|
|
if (input.coverUrl !== undefined && input.coverUrl !== null) project.coverUrl = input.coverUrl || null;
|
|
project.updatedAt = timestamp();
|
|
return json(res, projectData(project));
|
|
}
|
|
if (req.method === 'DELETE') {
|
|
project.deleted = true;
|
|
return json(res, null);
|
|
}
|
|
return json(res, projectData(project));
|
|
}
|
|
if (tail === 'document' && req.method === 'GET') {
|
|
if (!project.document) return json(res, null, 404, 'CAD_DOCUMENT_NOT_FOUND');
|
|
return json(res, {
|
|
downloadUrl: '/api/cad/mock-source/' + project.document.upload.uploadCode,
|
|
expiresAt: null,
|
|
version: project.document.version,
|
|
fileName: project.document.upload.request.fileName,
|
|
sizeBytes: project.document.upload.request.sizeBytes,
|
|
savedAt: project.document.savedAt,
|
|
});
|
|
}
|
|
if (tail === 'uploads/signature' && req.method === 'POST') {
|
|
const request = JSON.parse(body);
|
|
const uploadCode = randomUUID();
|
|
const upload = { uploadCode, cadProjectCode: project.cadProjectCode, request, committed: null };
|
|
uploads.set(uploadCode, upload);
|
|
return json(res, {
|
|
uploadCode,
|
|
uploadUrl: '/api/cad/mock-oss/' + uploadCode,
|
|
formFields: { key: uploadCode, policy: 'mock-policy' },
|
|
expiresAt: timestamp(),
|
|
});
|
|
}
|
|
if (tail === 'document' && req.method === 'PUT') {
|
|
const { uploadCode } = JSON.parse(body);
|
|
const upload = uploads.get(uploadCode);
|
|
if (!upload || upload.cadProjectCode !== project.cadProjectCode) return json(res, null, 404, 'NOT_FOUND');
|
|
if (upload.committed) return json(res, upload.committed);
|
|
if (upload.request.expectedVersion !== project.version) return json(res, null, 409, 'CAD_VERSION_CONFLICT');
|
|
const bytes = objects.get(uploadCode);
|
|
if (!bytes) return json(res, null, 409, 'CAD_FILE_MISSING');
|
|
if (bytes.length !== upload.request.sizeBytes) return json(res, null, 409, 'CAD_FILE_SIZE_MISMATCH');
|
|
project.version++;
|
|
project.updatedAt = timestamp();
|
|
const savedAt = timestamp();
|
|
upload.committed = { cadProjectCode: project.cadProjectCode, version: project.version, savedAt };
|
|
project.document = { upload, version: project.version, savedAt };
|
|
return json(res, upload.committed);
|
|
}
|
|
return json(res, null, 404, 'NOT_FOUND');
|
|
});
|
|
|
|
server.listen(Number(process.env.VM_CAD_MOCK_PORT || 8092), '127.0.0.1', () =>
|
|
console.log('CAD browser mock listening on ' + server.address().port));
|