721 lines
36 KiB
TypeScript
721 lines
36 KiB
TypeScript
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||
import { consumeEventStream, type StreamEvent } from './eventStream';
|
||
import { publicErrorMessage } from './publicDataDisplay';
|
||
import { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
||
import type {
|
||
AuthUser,
|
||
FilterField,
|
||
SourceColumnField,
|
||
Collection,
|
||
FineDefectTopResponse,
|
||
MetricsResponse,
|
||
OptionsResponse,
|
||
QueryParams,
|
||
RecordExportParams,
|
||
RecordsParams,
|
||
RecordsResponse,
|
||
} from './types';
|
||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||
|
||
export class ApiError extends Error {
|
||
status: number;
|
||
details: unknown;
|
||
|
||
constructor(status: number, message: string, details?: unknown) {
|
||
super(publicErrorMessage(message, status));
|
||
this.name = 'ApiError';
|
||
this.status = status;
|
||
this.details = details;
|
||
}
|
||
}
|
||
|
||
let csrfToken: string | undefined;
|
||
|
||
async function fetchApi(path: string, init: RequestInit): Promise<Response> {
|
||
try { return await fetch(path, init); }
|
||
catch (error) {
|
||
if (init.signal?.aborted || (error instanceof DOMException && error.name === 'AbortError')) throw error;
|
||
throw new ApiError(0, '无法连接质量数据服务,请检查网络后重试;当前无法确认数据覆盖。');
|
||
}
|
||
}
|
||
|
||
async function readResponse<T>(response: Response): Promise<T> {
|
||
const raw = await response.text();
|
||
let payload: unknown;
|
||
if (raw) {
|
||
try {
|
||
payload = JSON.parse(raw) as unknown;
|
||
} catch {
|
||
payload = raw;
|
||
}
|
||
}
|
||
if (!response.ok) {
|
||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||
// Spring ProblemDetail uses `detail`; older endpoints may use `message` or `error`.
|
||
const message = typeof body?.detail === 'string'
|
||
? body.detail
|
||
: typeof body?.message === 'string'
|
||
? body.message
|
||
: typeof body?.error === 'string'
|
||
? body.error
|
||
: typeof payload === 'string' && payload.trim()
|
||
? payload
|
||
: `请求失败(${response.status})`;
|
||
throw new ApiError(response.status, message, payload);
|
||
}
|
||
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||
return payload as T;
|
||
}
|
||
|
||
async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||
const headers = new Headers(init.headers);
|
||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||
const send = async (signal = init.signal) => {
|
||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||
return readResponse<T>(response);
|
||
};
|
||
if (!timeoutMs) return send();
|
||
try { return await withRequestDeadline(signal => send(signal), timeoutMs); }
|
||
catch (error) {
|
||
if (error instanceof RequestTimeoutError) throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
|
||
if (!response.ok) {
|
||
const raw = await response.text();
|
||
let payload: unknown = raw;
|
||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||
throw new ApiError(response.status, message, payload);
|
||
}
|
||
const disposition = response.headers.get('Content-Disposition') || '';
|
||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||
let filename = 'source-evidence.xlsx';
|
||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||
return { blob: await response.blob(), filename };
|
||
}
|
||
|
||
export type { StreamEvent } from './eventStream';
|
||
|
||
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
||
const headers = new Headers({ Accept: 'text/event-stream' });
|
||
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||
if (!response.ok) {
|
||
const raw = await response.text();
|
||
let payload: unknown = raw;
|
||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||
}
|
||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||
await consumeEventStream(response.body, options.onEvent);
|
||
}
|
||
|
||
export async function refreshCsrf(): Promise<string> {
|
||
const result = await request<{ token: string }>('/api/auth/csrf', {}, 8000);
|
||
csrfToken = result.token;
|
||
return csrfToken;
|
||
}
|
||
|
||
async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutMs?: number): Promise<T> {
|
||
const token = csrfToken ?? await refreshCsrf();
|
||
const headers = new Headers({ 'X-XSRF-TOKEN': token });
|
||
const result = await request<T>(path, {
|
||
method,
|
||
headers,
|
||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||
}, timeoutMs);
|
||
if (!/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||
return result;
|
||
}
|
||
|
||
async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal): Promise<T> {
|
||
const token = csrfToken ?? await refreshCsrf();
|
||
return request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body: JSON.stringify(body), signal });
|
||
}
|
||
|
||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||
const token = csrfToken ?? await refreshCsrf();
|
||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
||
window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||
return result;
|
||
}
|
||
|
||
export const api = {
|
||
sourceColumnCatalog(releaseId?: string) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`); },
|
||
sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); },
|
||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); },
|
||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
||
filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); },
|
||
saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); },
|
||
refreshCsrf,
|
||
async me(): Promise<AuthUser> {
|
||
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
||
return result.user;
|
||
},
|
||
login(username: string, password: string) {
|
||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||
},
|
||
logout() {
|
||
return mutate<void>('/api/auth/logout');
|
||
},
|
||
changePassword(currentPassword: string, newPassword: string) {
|
||
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
||
},
|
||
options() {
|
||
return request<OptionsResponse>('/api/options');
|
||
},
|
||
referenceNames() {
|
||
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
||
},
|
||
metrics(params: QueryParams, signal?: AbortSignal) {
|
||
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
||
},
|
||
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
||
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
||
},
|
||
records(params: RecordsParams, signal?: AbortSignal) {
|
||
return request<RecordsResponse>(`/api/records?${toQuery(params)}`, { signal });
|
||
},
|
||
exportRecords(params: RecordExportParams, signal?: AbortSignal) {
|
||
return requestBlob(`/api/records/export?${toQuery(params)}`, signal);
|
||
},
|
||
sources() {
|
||
return request<Collection<import('./types').SourceItem>>('/api/sources');
|
||
},
|
||
sourceDeletionPreview(id: string) {
|
||
return request<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/deletion-preview`);
|
||
},
|
||
deletedSources() {
|
||
return request<{ items: SourceDeletionPreview[] }>('/api/sources/deleted');
|
||
},
|
||
deleteSource(id: string, body: { expectedCurrentReleaseId: string | null; expectedDeleteVersion: number; expectedRevisionId?: string; reason: string; idempotencyKey: string }) {
|
||
return mutate<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/delete`, body);
|
||
},
|
||
restoreSource(id: string, body: { expectedCurrentReleaseId: string | null; expectedDeleteVersion: number; reason: string }) {
|
||
return mutate<SourceDeletionPreview>(`/api/sources/${encodeURIComponent(id)}/restore`, body);
|
||
},
|
||
scanSources() {
|
||
return mutate<{ items: import('./types').SourceItem[]; scannedAt: string }>('/api/sources/scan');
|
||
},
|
||
uploadSource(file: File) {
|
||
const body = new FormData();
|
||
body.append('file', file);
|
||
return mutateForm<{ source: import('./types').SourceItem }>('/api/sources/upload', body);
|
||
},
|
||
sourceUploadOptions() {
|
||
return request<SourceUploadOptions>('/api/sources/upload-options');
|
||
},
|
||
previewSourceWorkbook(file: File) {
|
||
const body = new FormData(); body.append('file', file);
|
||
return mutateForm<WorkbookPreview>('/api/sources/workbook-preview', body);
|
||
},
|
||
sourceWorkbookPreview(uploadId: string, params: { sheetName: string; headerRow: number; stage: DataStage }) {
|
||
return request<WorkbookPreview>(`/api/sources/workbook-preview/${encodeURIComponent(uploadId)}?${toQuery(params)}`);
|
||
},
|
||
configureSourceWorkbook(body: ConfigureSourceBody) {
|
||
return mutate<{ source: import('./types').SourceItem; configuration: Record<string, unknown>; currentReleaseId: string | null }>('/api/sources/configure', body);
|
||
},
|
||
previewMasterWorkbook(file: File) {
|
||
const body = new FormData(); body.append('file', file);
|
||
return mutateForm<MasterWorkbookPreview>('/api/master-data/workbooks/preview', body);
|
||
},
|
||
importMasterWorkbook(body: MasterWorkbookImportBody) {
|
||
return mutate<Record<string, unknown>>('/api/master-data/workbooks/import', body);
|
||
},
|
||
prepareMasterWorkbook(body: MasterWorkbookImportBody) {
|
||
return mutate<Record<string, unknown>>('/api/master-data/workbooks/prepare', body);
|
||
},
|
||
startImport(body: { sourceIds: string[]; idempotencyKey: string; expectedCurrentReleaseId: string | null }) {
|
||
return mutate<unknown>('/api/import-runs', body);
|
||
},
|
||
importRun(id: string) {
|
||
return request<{ run: Record<string, unknown> }>(`/api/import-runs/${encodeURIComponent(id)}`);
|
||
},
|
||
importIssues(id: string, page = 1, pageSize = 50) {
|
||
return request<Collection>(`/api/import-runs/${encodeURIComponent(id)}/issues?page=${page}&pageSize=${pageSize}`);
|
||
},
|
||
classificationMetadata() { return request<{ defaultRules: unknown[] }>('/api/governance/mapping-issues/classification-metadata'); },
|
||
previewClassification(body: {stage:string;target:string;conditions:{field:string;operator:string;value:string}[]}) {
|
||
return queryPost<Record<string,unknown>>('/api/governance/mapping-issues/classification-preview',body);
|
||
},
|
||
unclassifiedSources(page = 1, pageSize = 50) {
|
||
return request<Collection>(`/api/governance/mapping-issues/unclassified?${toQuery({ page, pageSize })}`);
|
||
},
|
||
mappingIssues(params: { mappingType?: string; importRunId?: string; status?: string; page?: number; pageSize?: number; customerCode?: string; businessGroup?: string; department?: string } = {}) {
|
||
return request<Collection & { filterOptions?: { customerCodes: string[]; businessGroups: string[]; departments: string[] } }>(`/api/governance/mapping-issues?${toQuery({ page: 1, pageSize: 50, ...params })}`);
|
||
},
|
||
mappingIssue(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}`);
|
||
},
|
||
resolveMappingIssue(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}/resolve`, body);
|
||
},
|
||
revalidateMappingIssue(id: string, body: { decisionId: string; expectedCurrentReleaseId: string | null; idempotencyKey: string }) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}/revalidate`, body);
|
||
},
|
||
taskOverview() {
|
||
return request<Collection>('/api/tasks/overview');
|
||
},
|
||
latestBackup() {
|
||
return request<Record<string, unknown>>('/api/governance/backups/latest');
|
||
},
|
||
tasks() {
|
||
return request<Collection>('/api/tasks');
|
||
},
|
||
retryTask(id: string, body: { idempotencyKey: string; expectedCurrentReleaseId: string | null }) {
|
||
return mutate<unknown>(`/api/tasks/${encodeURIComponent(id)}/retry`, body);
|
||
},
|
||
cancelTask(id: string, body: { expectedStatus: string }) {
|
||
return mutate<unknown>(`/api/tasks/${encodeURIComponent(id)}/cancel`, body);
|
||
},
|
||
releases() {
|
||
return request<Collection>('/api/releases');
|
||
},
|
||
publishRelease(id: string, body: ReleaseActionBody) {
|
||
return mutate<unknown>(`/api/releases/${encodeURIComponent(id)}/publish`, body);
|
||
},
|
||
rules() {
|
||
return request<Collection>('/api/rules');
|
||
},
|
||
ruleSchema() {
|
||
return request<Record<string, unknown>>('/api/rules/schema');
|
||
},
|
||
createRule(body: Record<string, unknown>) {
|
||
return mutate<unknown>('/api/rules', body);
|
||
},
|
||
updateRule(id: string, body: Record<string, unknown>) {
|
||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
validateRule(id: string, body: { expectedRowVersion: number }) {
|
||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}/validate`, body);
|
||
},
|
||
ruleRegressions(id: string) {
|
||
return request<{ items: Record<string, unknown>[] }>(`/api/governance/rules/${encodeURIComponent(id)}/regressions`);
|
||
},
|
||
ruleRegression(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/rule-regressions/${encodeURIComponent(id)}`);
|
||
},
|
||
activateRule(id: string, body: { expectedRowVersion: number; confirmDifferences?: boolean; regressionRunId?: string }) {
|
||
return mutate<unknown>(`/api/rules/${encodeURIComponent(id)}/activate`, body);
|
||
},
|
||
metricDictionary() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/metric-dictionary');
|
||
},
|
||
metricDictionaryMigration() {
|
||
return request<{ items: Record<string, unknown>[]; verification?: Record<string, unknown> }>('/api/metric-dictionary/migration');
|
||
},
|
||
updateMetricDictionary(code: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/metric-dictionary/${encodeURIComponent(code)}`, body, 'PUT');
|
||
},
|
||
mappings() {
|
||
return request<Collection>('/api/mappings');
|
||
},
|
||
createMapping(body: Record<string, unknown>) {
|
||
return mutate<unknown>('/api/mappings', body);
|
||
},
|
||
updateMapping(id: string, body: Record<string, unknown>) {
|
||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
validateMapping(id: string, body: { expectedRowVersion: number }) {
|
||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}/validate`, body);
|
||
},
|
||
activateMapping(id: string, body: { expectedRowVersion: number }) {
|
||
return mutate<unknown>(`/api/mappings/${encodeURIComponent(id)}/activate`, body);
|
||
},
|
||
dataWorkflowStatus() {
|
||
return request<DataWorkflowStatus>('/api/data-workflow/status');
|
||
},
|
||
applyDataWorkflow(body: { kind: 'mapping' | 'rule'; name: string; definition: Record<string, unknown>; description?: string; expectedCurrentReleaseId: string | null }) {
|
||
const matchRules = body.definition.matchRules;
|
||
const definition = Array.isArray(matchRules) ? {
|
||
...body.definition,
|
||
matchRules: matchRules.map(rule => {
|
||
if (!rule || typeof rule !== 'object' || Array.isArray(rule)) return rule;
|
||
const row = rule as Record<string, unknown>;
|
||
if (!Array.isArray(row.conditions)) return row;
|
||
return {
|
||
...row,
|
||
conditions: row.conditions.map(condition => {
|
||
if (!condition || typeof condition !== 'object' || Array.isArray(condition)) return condition;
|
||
const item = condition as Record<string, unknown>;
|
||
return ['IS_BLANK', 'IS_NOT_BLANK'].includes(String(item.operator)) ? { ...item, value: '' } : item;
|
||
}),
|
||
};
|
||
}),
|
||
} : body.definition;
|
||
return mutate<DataWorkflowOperation>('/api/data-workflow/apply', { ...body, definition });
|
||
},
|
||
recalculateDataWorkflow() {
|
||
return mutate<DataWorkflowOperation>('/api/data-workflow/recalculate', {});
|
||
},
|
||
importDataWorkflow(body: { sourceIds: string[] }) {
|
||
return mutate<DataWorkflowOperation>('/api/data-workflow/import', body);
|
||
},
|
||
deleteDataWorkflowSource(id: string) {
|
||
return mutate<DataWorkflowOperation>(`/api/data-workflow/sources/${encodeURIComponent(id)}/delete`, {});
|
||
},
|
||
deleteDataWorkflowSources(body: { sourceIds: string[]; expectedCurrentReleaseId: string | null }) {
|
||
return mutate<DataWorkflowOperation>('/api/data-workflow/sources/delete-batch', body);
|
||
},
|
||
restoreDataWorkflowSource(id: string) {
|
||
return mutate<DataWorkflowOperation>(`/api/data-workflow/sources/${encodeURIComponent(id)}/restore`, {});
|
||
},
|
||
dataWorkflowOperation(id: string) {
|
||
return request<DataWorkflowOperation>(`/api/data-workflow/operations/${encodeURIComponent(id)}`);
|
||
},
|
||
audit(page = 1, pageSize = 50) {
|
||
return request<Collection>(`/api/audit?page=${page}&pageSize=${pageSize}`);
|
||
},
|
||
users() {
|
||
return request<Collection>('/api/users');
|
||
},
|
||
createUser(body: Record<string, unknown>) {
|
||
return mutate<unknown>('/api/users', body);
|
||
},
|
||
updateUser(id: string, body: Record<string, unknown>) {
|
||
return mutate<unknown>(`/api/users/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
analysis(body: { query: string; sessionId?: string; context?: Record<string, unknown> }) {
|
||
return mutate<unknown>('/api/analysis', body);
|
||
},
|
||
analysisStatus() {
|
||
return request<Record<string, unknown>>('/api/analysis/status');
|
||
},
|
||
analysisReports() { return request<{ items: Record<string, unknown>[] }>('/api/analysis/reports'); },
|
||
createAnalysisReport(body: { periodType: string; periodKey: string }) {
|
||
return mutate<{ report: Record<string, unknown>; turn: Record<string, unknown> }>('/api/analysis/reports', body);
|
||
},
|
||
analysisReportPlans() { return request<{ items: Record<string, unknown>[] }>('/api/analysis/report-plans'); },
|
||
createAnalysisReportPlan(body: Record<string, unknown>) {
|
||
return mutate<{ plan: Record<string, unknown> }>('/api/analysis/report-plans', body);
|
||
},
|
||
updateAnalysisReportPlan(id: string, body: Record<string, unknown>) {
|
||
return mutate<{ plan: Record<string, unknown> }>(`/api/analysis/report-plans/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
analysisSessions() {
|
||
return request<Collection<Record<string, unknown>>>('/api/analysis/sessions');
|
||
},
|
||
analysisSession(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analysis/sessions/${encodeURIComponent(id)}`);
|
||
},
|
||
deleteAnalysisSession(id: string) {
|
||
return mutate<{ deleted: boolean; sessionId: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, undefined, 'DELETE');
|
||
},
|
||
renameAnalysisSession(id: string, title: string) {
|
||
return mutate<{ sessionId: string; title: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, { title }, 'PATCH');
|
||
},
|
||
analysisSessionTurns(id: string) {
|
||
return request<{ items: Record<string, unknown>[] }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`);
|
||
},
|
||
createAnalysisSession(body: { title?: string; releaseId?: string; context?: Record<string, unknown> }) {
|
||
return mutate<{ session: Record<string, unknown> }>('/api/analysis/sessions', body);
|
||
},
|
||
startAnalysisTurn(id: string, body: { question: string; context?: Record<string, unknown>; idempotencyKey?: string }) {
|
||
return mutate<{ turn: Record<string, unknown> }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`, body);
|
||
},
|
||
analysisTurn(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}`);
|
||
},
|
||
analysisTurnSnapshot(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/snapshot`, {}, 30000);
|
||
},
|
||
analysisSettings() {
|
||
return request<import('./AnalysisApiSettings').AnalysisModelSettings>('/api/analysis/settings');
|
||
},
|
||
saveAnalysisSettings(body: import('./AnalysisApiSettings').AnalysisModelSettingsInput) {
|
||
return mutate<import('./AnalysisApiSettings').AnalysisModelSettings>('/api/analysis/settings', body, 'PUT');
|
||
},
|
||
testAnalysisSettings(body: import('./AnalysisApiSettings').AnalysisModelSettingsInput) {
|
||
return mutate<{ success: boolean; message: string; elapsedMs?: number }>('/api/analysis/settings/test', body);
|
||
},
|
||
retryAnalysisTurn(id: string) {
|
||
return mutate<{ turn: Record<string, unknown> }>(`/api/analysis/turns/${encodeURIComponent(id)}/retry`);
|
||
},
|
||
recoverAnalysisVisuals(id: string) {
|
||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/visual-recovery`, undefined, 'POST', 60000);
|
||
},
|
||
analysisTurnEvents(id: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }) {
|
||
return readEventStream(`/api/analysis/turns/${encodeURIComponent(id)}/events`, options);
|
||
},
|
||
cancelAnalysisTurn(id: string, reason?: string) {
|
||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/cancel`, reason ? { reason } : {});
|
||
},
|
||
feedbackAnalysisTurn(id: string, body: { rating: string; comment?: string }) {
|
||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/feedback`, body);
|
||
},
|
||
analyticsTop(params: Record<string, unknown>) {
|
||
return request<Record<string, unknown>>(`/api/analytics/top?${toQuery(params)}`);
|
||
},
|
||
checklists() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/checklists');
|
||
},
|
||
createChecklist(body: { title: string }) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/checklists', body);
|
||
},
|
||
checklist(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analytics/checklists/${encodeURIComponent(id)}`);
|
||
},
|
||
addChecklistItem(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/checklists/${encodeURIComponent(id)}/items`, body);
|
||
},
|
||
deleteChecklistItem(id: string, itemId: string) {
|
||
return mutate<void>(`/api/analytics/checklists/${encodeURIComponent(id)}/items/${encodeURIComponent(itemId)}`, undefined, 'DELETE');
|
||
},
|
||
analyticsCompare(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/compare', body);
|
||
},
|
||
analyticsImpact(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/impact', body);
|
||
},
|
||
structureDecomposition(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/structure-decomposition', body);
|
||
},
|
||
comparisonViews() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views');
|
||
},
|
||
sharedComparisonViews() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views/shared');
|
||
},
|
||
comparisonViewShareCandidates() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/comparison-views/share-candidates');
|
||
},
|
||
comparisonViewShares(id: string) {
|
||
return request<{ items: Record<string, unknown>[]; viewRowVersion: number }>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares`);
|
||
},
|
||
shareComparisonView(id: string, body: { recipientUserId: string; expectedRowVersion: number }) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares`, body);
|
||
},
|
||
revokeComparisonViewShare(id: string, recipientUserId: string, expectedRowVersion: number) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/shares/${encodeURIComponent(recipientUserId)}?expectedRowVersion=${expectedRowVersion}`, undefined, 'DELETE');
|
||
},
|
||
createComparisonView(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/comparison-views', body);
|
||
},
|
||
updateComparisonView(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
deleteComparisonView(id: string) {
|
||
return mutate<void>(`/api/analytics/comparison-views/${encodeURIComponent(id)}`, undefined, 'DELETE');
|
||
},
|
||
openComparisonView(id: string) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/comparison-views/${encodeURIComponent(id)}/open`, {});
|
||
},
|
||
analyticsTarget(params: Record<string, unknown>) {
|
||
return request<Record<string, unknown>>(`/api/analytics/targets?${toQuery(params)}`);
|
||
},
|
||
targetVersions() {
|
||
return request<{ items: Record<string, unknown>[]; currentVersionId?: string }>('/api/analytics/targets/versions');
|
||
},
|
||
targetVersion(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}`);
|
||
},
|
||
createTargetVersion(body: { name: string }) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/targets/versions', body);
|
||
},
|
||
updateTargetVersion(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
updateCurrentTargets(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/targets/current', body, 'PUT');
|
||
},
|
||
validateTargetVersion(id: string, body: { expectedRowVersion: number }) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}/validate`, body);
|
||
},
|
||
activateTargetVersion(id: string, body: { expectedRowVersion: number }) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/targets/versions/${encodeURIComponent(id)}/activate`, body);
|
||
},
|
||
governanceProtocols() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/governance/protocols');
|
||
},
|
||
governanceSourceDocuments() {
|
||
return request<{ items: Record<string, unknown>[]; revisions: Record<string, unknown>[] }>('/api/governance/source-documents');
|
||
},
|
||
createGovernanceProtocol(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/protocols', body);
|
||
},
|
||
governanceCoverage(releaseId?: string) {
|
||
const suffix = releaseId ? `?releaseId=${encodeURIComponent(releaseId)}` : '';
|
||
return request<Record<string, unknown>>(`/api/governance/coverage${suffix}`);
|
||
},
|
||
governanceReleaseInspect(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/inspect`);
|
||
},
|
||
governanceReleaseDiff(id: string, againstReleaseId: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/diff?againstReleaseId=${encodeURIComponent(againstReleaseId)}`);
|
||
},
|
||
governanceReleaseReconciliations(id: string) {
|
||
return request<{ items: Record<string, unknown>[]; acceptanceId?: string }>(`/api/governance/releases/${encodeURIComponent(id)}/reconciliations`);
|
||
},
|
||
createGovernanceReconciliation(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/releases/${encodeURIComponent(id)}/reconciliations`, body);
|
||
},
|
||
governanceReconciliation(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/reconciliations/${encodeURIComponent(id)}`);
|
||
},
|
||
confirmGovernanceReconciliation(id: string, body: { expectedRowVersion: number; expectedDifferenceHash: string; expectedTransitionDifferenceHash?: string; reason: string }) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/reconciliations/${encodeURIComponent(id)}/confirm`, body);
|
||
},
|
||
governanceDependencyImpact(kind: 'rule' | 'mapping', id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/dependencies/${kind}/${encodeURIComponent(id)}/impact`);
|
||
},
|
||
governanceBackups() {
|
||
return request<Record<string, unknown>>('/api/governance/backups');
|
||
},
|
||
createBackupJob(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/backups/jobs', body);
|
||
},
|
||
updateBackupPlan(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/backups/plan', body, 'PUT');
|
||
},
|
||
resolveSourceCandidate(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/sources/${encodeURIComponent(id)}/resolve`, body);
|
||
},
|
||
sourceChanges() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/governance/source-changes');
|
||
},
|
||
createSourceChange(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/source-changes', body);
|
||
},
|
||
reviewSourceChange(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/source-changes/${encodeURIComponent(id)}/review`, body);
|
||
},
|
||
buildSourceChange(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/source-changes/${encodeURIComponent(id)}/build`, body);
|
||
},
|
||
governanceMonitor() {
|
||
return request<Record<string, unknown>>('/api/governance/monitor');
|
||
},
|
||
inspectionStrategies() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/analytics/inspection-strategies');
|
||
},
|
||
inspectionStrategy(id: string) {
|
||
return request<Record<string, unknown>>(`/api/analytics/inspection-strategies/${encodeURIComponent(id)}`);
|
||
},
|
||
createInspectionStrategy(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/analytics/inspection-strategies', body);
|
||
},
|
||
updateInspectionStrategy(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/analytics/inspection-strategies/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
inspectionRuns(releaseId?: string) {
|
||
const query = releaseId ? `?releaseId=${encodeURIComponent(releaseId)}` : '';
|
||
return request<{ items: Record<string, unknown>[]; resultAvailable?: boolean }>(`/api/analytics/inspection-runs${query}`);
|
||
},
|
||
runInspection(releaseId: string) {
|
||
return mutate<{ items: Record<string, unknown>[]; resultAvailable?: boolean }>('/api/analytics/inspection-runs/run', { releaseId });
|
||
},
|
||
refreshGovernanceMonitor() {
|
||
return mutate<Record<string, unknown>>('/api/governance/monitor/refresh', {});
|
||
},
|
||
governanceAlertPolicy() {
|
||
return request<Record<string, unknown>>('/api/governance/monitor/alert-policy');
|
||
},
|
||
updateGovernanceAlertPolicy(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/monitor/alert-policy', body, 'PUT');
|
||
},
|
||
serviceIdentities() {
|
||
return request<{ items: Record<string, unknown>[]; allowedActions?: string[]; serviceTypes?: string[] }>('/api/governance/service-identities');
|
||
},
|
||
createServiceIdentity(body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>('/api/governance/service-identities', body);
|
||
},
|
||
updateServiceIdentity(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}`, body, 'PUT');
|
||
},
|
||
rotateServiceIdentity(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}/rotate`, body);
|
||
},
|
||
userAccessPolicy(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/access-policy`);
|
||
},
|
||
updateUserAccessPolicy(id: string, body: Record<string, unknown>) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/access-policy`, body, 'PUT');
|
||
},
|
||
effectiveUserAccess(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/effective-access`);
|
||
},
|
||
userScopePreview(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/users/${encodeURIComponent(id)}/scope-preview`);
|
||
},
|
||
downloadSourceRevision(id: string, signal?: AbortSignal) {
|
||
return requestBlob(`/api/governance/source-revisions/${encodeURIComponent(id)}/download`, signal);
|
||
},
|
||
sourceRevisionEvidence(id: string) {
|
||
return request<Record<string, unknown>>(`/api/governance/source-revisions/${encodeURIComponent(id)}/evidence`);
|
||
},
|
||
serviceRotations(id: string) {
|
||
return request<{ items: Record<string, unknown>[] }>(`/api/governance/service-identities/${encodeURIComponent(id)}/rotations`);
|
||
},
|
||
authorizeServiceAction(id: string, action: string) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/service-identities/${encodeURIComponent(id)}/authorize`, { action });
|
||
},
|
||
serviceBindings() {
|
||
return request<{ items: Record<string, unknown>[] }>('/api/governance/service-bindings');
|
||
},
|
||
updateServiceBinding(type: string, body: { identityId: string; reason: string }) {
|
||
return mutate<Record<string, unknown>>(`/api/governance/service-bindings/${encodeURIComponent(type)}`, body, 'PUT');
|
||
},
|
||
};
|
||
|
||
export interface ReleaseActionBody {
|
||
expectedCurrentReleaseId: string | null;
|
||
idempotencyKey: string;
|
||
reason: string;
|
||
}
|
||
|
||
function toQuery(values: object): string {
|
||
const query = new URLSearchParams();
|
||
for (const [key, value] of Object.entries(values)) {
|
||
if (value === undefined || value === null || value === '') continue;
|
||
if (key === 'columnFilters') query.set(key, JSON.stringify(value));
|
||
else if (Array.isArray(value)) value.forEach(item => {
|
||
if (item !== undefined && item !== null && item !== '') query.append(key, String(item));
|
||
});
|
||
else query.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
|
||
}
|
||
return query.toString();
|
||
}
|
||
|
||
const MULTI_VALUE_MARKER = '~qv1~';
|
||
|
||
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
||
export function encodeQueryValueList(values: string[] | undefined): string | undefined {
|
||
if (!values?.length) return undefined;
|
||
const normalized = [...new Set(values.map(value => value.trim()).filter(Boolean))];
|
||
if (normalized.length === 0) return undefined;
|
||
if (normalized.length === 1) return normalized[0];
|
||
const bytes = new TextEncoder().encode(JSON.stringify(normalized));
|
||
let binary = '';
|
||
bytes.forEach(byte => { binary += String.fromCharCode(byte); });
|
||
return `${MULTI_VALUE_MARKER}${btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '')}`;
|
||
}
|
||
|
||
/** Reads a plain scalar or the versioned multi-value query wire format. */
|
||
export function decodeQueryValueList(value: string | undefined): string[] {
|
||
if (!value) return [];
|
||
if (!value.startsWith(MULTI_VALUE_MARKER)) return [value];
|
||
try {
|
||
const encoded = value.slice(MULTI_VALUE_MARKER.length).replaceAll('-', '+').replaceAll('_', '/');
|
||
const binary = atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, '='));
|
||
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
|
||
const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
||
return Array.isArray(parsed) ? [...new Set(parsed.filter(item => typeof item === 'string').map(item => item.trim()).filter(Boolean))] : [];
|
||
} catch {
|
||
return [];
|
||
}
|
||
}
|
||
|
||
export function collectionItems<T>(value: Collection<T> | T[] | null | undefined): T[] {
|
||
if (Array.isArray(value)) return value;
|
||
if (value && Array.isArray(value.items)) return value.items;
|
||
return [];
|
||
}
|