Files
vibemake/js/cad/api.js
T
2026-11-05 17:50:35 +08:00

306 lines
13 KiB
JavaScript

import { auth, API_BASE, ApiError } from '../api.js';
import { locale } from './i18n.js';
import { cadAgentRateLimiter } from './agent-rate-limit.js';
export { auth, ApiError };
const id = encodeURIComponent;
const PROJECTS = '/cad/workspace/projects';
const AI = '/cad/ai';
export const MAX_COVER_BYTES = 5 * 1024 * 1024;
export const userId = () => auth.user?.userCode ?? null;
export function projectCoverUrl(value) {
if (typeof value !== 'string' || !value || value.length > 2048) return null;
try {
const url = new URL(value);
return url.protocol === 'https:' && !url.username && !url.password ? url.href : null;
} catch { return null; }
}
export function cadError(code, message = code) {
const error = new Error(message);
error.code = code;
return error;
}
function shanghaiTime(value) {
if (typeof value !== 'string' || !value) return value ?? null;
const zoned = /(?:Z|[+-]\d{2}:\d{2})$/i.test(value)
? value
: (value.includes('T') ? value : value.replace(' ', 'T')) + '+08:00';
const date = new Date(zoned);
return Number.isNaN(date.valueOf()) ? value : date.toISOString();
}
function projectRecord(value) {
const record = value?.project ?? value;
if (!record || typeof record.cadProjectCode !== 'string' || !record.cadProjectCode) throw cadError('BAD_RESPONSE');
return {
...record,
coverUrl: projectCoverUrl(record.coverUrl),
id: record.cadProjectCode,
cadProjectCode: record.cadProjectCode,
headVersion: record.version,
savedAt: shanghaiTime(record.savedAt),
lastSavedAt: shanghaiTime(record.savedAt),
createdAt: shanghaiTime(record.createdAt),
updatedAt: shanghaiTime(record.updatedAt),
};
}
function signatureRecord(value) {
const record = value?.upload ?? value;
if (!record || typeof record.uploadCode !== 'string' || !record.uploadCode
|| typeof record.uploadUrl !== 'string' || !record.formFields || typeof record.formFields !== 'object'
|| Array.isArray(record.formFields)) throw cadError('BAD_RESPONSE');
for (const item of Object.values(record.formFields)) if (typeof item !== 'string') throw cadError('BAD_RESPONSE');
return record;
}
function aiCapabilities(value) {
const limits = value?.limits ?? {};
const tools = value?.tools;
const limitNames = [
'requestBytes', 'imageBytes', 'imageMaxEdge', 'imagesPerRequest', 'textBytes',
'toolResultTextBytes', 'historyItems',
'requestTimeoutSeconds', 'requestsPerMinute',
];
if (!value || typeof value.enabled !== 'boolean' || value.protocolVersion !== 'cad-agent-v1'
|| typeof value.model !== 'string' || !Array.isArray(tools) || tools.length > 64
|| !limits || typeof limits !== 'object' || Array.isArray(limits)
|| limitNames.some((name) => limits[name] != null && (!Number.isSafeInteger(limits[name]) || limits[name] < 0))) throw cadError('BAD_RESPONSE');
if (value.enabled && (!value.model.trim() || !tools.length)) throw cadError('BAD_RESPONSE');
for (const tool of tools) {
if (!tool || typeof tool.name !== 'string' || !/^[a-z][a-z0-9_]{0,63}$/.test(tool.name)
|| typeof tool.description !== 'string' || !tool.parameters || typeof tool.parameters !== 'object'
|| Array.isArray(tool.parameters)) throw cadError('BAD_RESPONSE');
}
return { ...value, limits };
}
export class CadApi {
constructor({ token = auth.token, user = userId(), fetcher = globalThis.fetch.bind(globalThis), agentRateLimiter = cadAgentRateLimiter } = {}) {
this.token = token;
this.user = user;
this.fetcher = fetcher;
this.agentRateLimiter = agentRateLimiter;
this.agentRequestsPerMinute = 0;
}
assertIdentity() {
if (!this.token || auth.token !== this.token || userId() !== this.user) throw cadError('STALE_IDENTITY');
}
async call(path, { method = 'GET', body, query, signal } = {}) {
this.assertIdentity();
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query || {})) {
if (value !== undefined && value !== '') params.set(key, String(value));
}
const headers = {
Accept: 'application/json',
Authorization: 'Bearer ' + this.token,
'Accept-Language': locale() === 'zh' ? 'zh-CN' : 'en',
};
if (body !== undefined) headers['Content-Type'] = 'application/json';
const response = await this.fetcher(API_BASE + path + (params.size ? '?' + params : ''), {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
cache: 'no-store',
credentials: 'omit',
signal,
});
this.assertIdentity();
const result = await response.json().catch(() => null);
this.assertIdentity();
if (response.ok && result && Object.hasOwn(result, 'data') && (!result.code || result.code === 'OK')) return result.data;
if (response.status === 401 && auth.token === this.token) auth.clear();
const error = new ApiError(response.status, result?.code || 'BAD_RESPONSE', result?.message || 'Invalid API response',
result?.requestId || response.headers.get('X-Request-Id'), result?.data);
error.retryAfter = response.headers.get('Retry-After');
throw error;
}
async aiCapabilities(signal) {
const capabilities = aiCapabilities(await this.call(AI + '/capabilities', { signal }));
this.agentRequestsPerMinute = capabilities.limits.requestsPerMinute || 0;
return capabilities;
}
async aiChat(body, signal, onStart) {
this.assertIdentity();
if (!body || typeof body !== 'object' || Array.isArray(body)) throw cadError('BAD_REQUEST');
const key = 'vm.cad.ai-rate:' + API_BASE + ':' + this.user;
const response = await this.agentRateLimiter.run(key, this.agentRequestsPerMinute, () => {
onStart?.();
return this.fetcher(API_BASE + AI + '/chat', {
method: 'POST',
headers: {
Accept: 'text/event-stream',
Authorization: 'Bearer ' + this.token,
'Content-Type': 'application/json',
'Accept-Language': locale() === 'zh' ? 'zh-CN' : 'en',
},
body: JSON.stringify(body),
cache: 'no-store',
credentials: 'omit',
redirect: 'error',
signal,
});
}, signal, () => this.assertIdentity());
this.assertIdentity();
if (response.status === 401 && auth.token === this.token) auth.clear();
if (response.status === 429) {
await this.agentRateLimiter.defer(key, response.headers.get('Retry-After'));
this.assertIdentity();
}
return response;
}
async list({ page = 1, pageSize = 20, keyword = '' } = {}, signal) {
const result = await this.call(PROJECTS, { query: { page, size: pageSize, keyword }, signal });
if (!result || !Array.isArray(result.items) || !Number.isSafeInteger(result.total)) throw cadError('BAD_RESPONSE');
return { ...result, items: result.items.map(projectRecord), page: result.page, size: result.size };
}
async create(name, description = '', coverUrl) {
if (coverUrl != null && coverUrl !== '' && !projectCoverUrl(coverUrl)) throw cadError('BAD_COVER');
return projectRecord(await this.call(PROJECTS, { method: 'POST', body: { name, description, ...(coverUrl === undefined ? {} : { coverUrl }) } }));
}
async get(project) {
return projectRecord(await this.call(PROJECTS + '/' + id(project)));
}
async rename(project, name) {
return projectRecord(await this.call(PROJECTS + '/' + id(project), { method: 'PATCH', body: { name } }));
}
async setCover(project, coverUrl) {
if (coverUrl !== '' && !projectCoverUrl(coverUrl)) throw cadError('BAD_COVER');
return projectRecord(await this.call(PROJECTS + '/' + id(project), { method: 'PATCH', body: { coverUrl } }));
}
async uploadCover(cover, signal) {
if (!(cover?.bytes instanceof Uint8Array) || cover.bytes.byteLength <= 0
|| cover.bytes.byteLength > MAX_COVER_BYTES || !['image/png', 'image/jpeg', 'image/webp'].includes(cover.mimeType)) throw cadError('BAD_COVER');
const signature = await this.call('/uploads/project-covers/signature', {
method: 'POST', body: { contentType: cover.mimeType, fileSize: cover.bytes.byteLength }, signal,
});
if (!signature || !projectCoverUrl(signature.coverUrl) || typeof signature.uploadUrl !== 'string'
|| !signature.formFields || typeof signature.formFields !== 'object' || Array.isArray(signature.formFields)
|| Object.values(signature.formFields).some((value) => typeof value !== 'string')) throw cadError('BAD_RESPONSE');
this.assertIdentity();
const body = new FormData();
for (const [key, value] of Object.entries(signature.formFields)) body.append(key, value);
const extension = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }[cover.mimeType];
body.append('file', new Blob([cover.bytes], { type: cover.mimeType }), 'cover.' + extension);
const response = await this.fetcher(storageUrl(signature.uploadUrl), {
method: 'POST', body, credentials: 'omit', cache: 'no-store', signal, referrerPolicy: 'no-referrer',
});
this.assertIdentity();
if (response.status !== 200) throw cadError('COVER_UPLOAD_FAILED');
return signature.coverUrl;
}
delete(project) {
return this.call(PROJECTS + '/' + id(project), { method: 'DELETE' });
}
async document(project) {
const value = await this.call(PROJECTS + '/' + id(project) + '/document');
if (!value || !Number.isSafeInteger(value.version) || !Number.isSafeInteger(value.sizeBytes)
|| typeof value.downloadUrl !== 'string' || typeof value.fileName !== 'string') throw cadError('BAD_RESPONSE');
return { ...value, savedAt: shanghaiTime(value.savedAt) };
}
async signUpload(project, request) {
return signatureRecord(await this.call(PROJECTS + '/' + id(project) + '/uploads/signature', {
method: 'POST',
body: request,
}));
}
async commit(project, uploadCode) {
const result = await this.call(PROJECTS + '/' + id(project) + '/document', {
method: 'PUT',
body: { uploadCode },
});
if (!result || typeof result.cadProjectCode !== 'string' || !Number.isSafeInteger(result.version)
|| typeof result.savedAt !== 'string') throw cadError('BAD_RESPONSE');
return { ...result, savedAt: shanghaiTime(result.savedAt) };
}
}
export function storageUrl(value) {
const url = new URL(value, location.href);
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.origin === location.origin)) throw cadError('BAD_RESPONSE');
if (url.username || url.password) throw cadError('BAD_RESPONSE');
return url.href;
}
export async function sha256(bytes) {
return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))]
.map((byte) => byte.toString(16).padStart(2, '0')).join('');
}
export async function downloadSource(file, maxBytes, progress = () => {}, signal) {
const size = file?.sizeBytes;
if (!Number.isSafeInteger(size) || size <= 0 || size > maxBytes) throw cadError('SOURCE_TOO_LARGE');
const response = await fetch(storageUrl(file.downloadUrl), {
credentials: 'omit',
cache: 'no-store',
signal,
referrerPolicy: 'no-referrer',
});
if (!response.ok) throw cadError(response.status === 403 ? 'DOWNLOAD_FORBIDDEN' : 'DOWNLOAD_FAILED');
if (!response.body) {
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.byteLength !== size || bytes.byteLength > maxBytes) throw cadError('BAD_DESIGN');
progress(bytes.byteLength, size);
return bytes;
}
const reader = response.body.getReader();
const chunks = [];
let total = 0;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > size || total > maxBytes) throw cadError('SOURCE_TOO_LARGE');
chunks.push(value);
progress(total, size);
}
} catch (error) {
await reader.cancel().catch(() => {});
throw error;
}
if (total !== size) throw cadError('BAD_DESIGN');
const bytes = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
return bytes;
}
export async function uploadSource(signature, bytes, fileName, signal) {
const authorization = signatureRecord(signature);
if (typeof fileName !== 'string' || !/^[^\\/:\u0000-\u001f\u007f]+\.sc$/i.test(fileName)) throw cadError('BAD_FILE_NAME');
const body = new FormData();
for (const [key, value] of Object.entries(authorization.formFields)) body.append(key, value);
body.append('file', new Blob([bytes], { type: 'application/octet-stream' }), fileName);
const response = await fetch(storageUrl(authorization.uploadUrl), {
method: 'POST',
body,
credentials: 'omit',
cache: 'no-store',
signal,
referrerPolicy: 'no-referrer',
});
if (!response.ok) throw cadError('UPLOAD_FAILED');
}