页面快照支持勾选查询条件、指标卡片、趋势、汇总表、不良构成和细分缺陷图,复制PNG或下载;增加取消、分阶段提示和等待超时恢复。 修复公共Select弹层准备帧被opacity覆盖导致的先闪出再展开,并取消查询字段原生label的重复点击转发。 同步已经验收上线的销售订单类型映射、排除筛选及预聚合,以及其线上权限、删除确认配套源码;保留既有公式编辑和名录编码修改。源码范围按发布清单冻结,不纳入本机数据、凭据及未发布工作。 验证:前后端独立源码构建通过;10项前端检查、4项订单分类单元测试通过;实际系统剪贴板粘贴PNG验证通过;线上配置及筛选结果与发布前一致,后端未重启。
913 lines
47 KiB
TypeScript
913 lines
47 KiB
TypeScript
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||
import { consumeEventStream, type StreamEvent } from './eventStream';
|
||
import { publicErrorMessage } from './publicDataDisplay';
|
||
import type { SalesOrderTypePreview,SalesOrderTypeStatus } from './salesOrderTypes';
|
||
import {
|
||
clearReadCache,
|
||
configureRequestScope,
|
||
coordinateRequest,
|
||
getRequestDiagnostics,
|
||
invalidateReadResources,
|
||
resetRequestScope,
|
||
type CoordinatedResult,
|
||
} from './requestCoordinator';
|
||
import type {
|
||
AuthUser,
|
||
FilterField,
|
||
SourceColumnField,
|
||
Collection,
|
||
FineDefectTopResponse,
|
||
MetricsResponse,
|
||
TrendResponse,
|
||
OptionsResponse,
|
||
QueryParams,
|
||
RecordExportParams,
|
||
RecordsParams,
|
||
RecordsResponse,
|
||
} from './types';
|
||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||
|
||
export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope };
|
||
|
||
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<CoordinatedResult<T>> {
|
||
const raw = await response.text();
|
||
const responseBytes = new TextEncoder().encode(raw).byteLength;
|
||
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})`;
|
||
const error = new ApiError(response.status, message, payload);
|
||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||
throw error;
|
||
}
|
||
if (typeof payload === 'string') {
|
||
const error = new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||
throw error;
|
||
}
|
||
return { data: payload as T, status: response.status, bytes: responseBytes };
|
||
}
|
||
|
||
export 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 method = (init.method ?? 'GET').toUpperCase();
|
||
try {
|
||
return await coordinateRequest({
|
||
url: path,
|
||
method,
|
||
signal: init.signal ?? undefined,
|
||
timeoutMs: timeoutMs ?? requestTimeoutFor(path),
|
||
cache: method === 'GET' && isImmutableRead(path),
|
||
tags: requestResourceTags(path),
|
||
category: requestCategory(path),
|
||
priority: requestPriority(path),
|
||
execute: async signal => {
|
||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||
return readResponse<T>(response);
|
||
},
|
||
});
|
||
}
|
||
catch (error) {
|
||
handleAccessFailure(error);
|
||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||
try {
|
||
return await coordinateRequest({
|
||
url: path,
|
||
method: 'GET',
|
||
signal,
|
||
timeoutMs: 900_000,
|
||
queue: false,
|
||
retry: false,
|
||
tags: requestResourceTags(path),
|
||
category: 'export',
|
||
priority: 'active',
|
||
execute: async requestSignal => {
|
||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal: requestSignal });
|
||
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})`;
|
||
const error = new ApiError(response.status, message, payload);
|
||
Object.defineProperty(error, 'responseBytes', { value: new TextEncoder().encode(raw).byteLength });
|
||
throw error;
|
||
}
|
||
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; }
|
||
const blob = await response.blob();
|
||
return { data: { blob, filename }, status: response.status, bytes: blob.size };
|
||
},
|
||
});
|
||
} catch (error) {
|
||
handleAccessFailure(error);
|
||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '文件导出超时,请稍后重试。');
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
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);
|
||
try {
|
||
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);
|
||
} catch (error) {
|
||
handleAccessFailure(error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
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, silent = false): 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 (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) invalidateAfterMutation(path);
|
||
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 }, 900_000);
|
||
invalidateAfterMutation(path);
|
||
return result;
|
||
}
|
||
|
||
export const api = {
|
||
salesOrderTypeStatus() { return request<SalesOrderTypeStatus>('/api/sales-order-types'); },
|
||
async salesOrderTypePreview(file:File,mode:string) {
|
||
const body=new FormData();body.append('file',file);body.append('mode',mode);
|
||
const token=csrfToken??await refreshCsrf();
|
||
return request<SalesOrderTypePreview>('/api/sales-order-types/preview',{method:'POST',headers:{'X-XSRF-TOKEN':token},body},900_000);
|
||
},
|
||
importSalesOrderTypes(file:File,mode:string,expectedVersion:string,sha256:string) {
|
||
const body=new FormData();body.append('file',file);body.append('mode',mode);body.append('expectedVersion',expectedVersion);body.append('sha256',sha256);
|
||
return mutateForm<{versionId:string}>('/api/sales-order-types/import',body);
|
||
},
|
||
activateSalesOrderTypes(versionId:string,expectedVersion:string) { return mutate<{versionId:string}>('/api/sales-order-types/activate',{versionId,expectedVersion}); },
|
||
sourceColumnCatalog(releaseId?: string, signal?: AbortSignal) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`, { signal }); },
|
||
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; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); },
|
||
filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); },
|
||
filterFieldOptions(key: string, search = '', signal?: AbortSignal,releaseId?:string,stage?:string) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search,releaseId,stage})}`, { signal }); },
|
||
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;
|
||
},
|
||
async login(username: string, password: string) {
|
||
csrfToken = undefined;
|
||
resetRequestScope();
|
||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||
},
|
||
async logout() {
|
||
try { return await mutate<void>('/api/auth/logout'); }
|
||
finally { csrfToken = undefined; resetRequestScope(); }
|
||
},
|
||
changePassword(currentPassword: string, newPassword: string) {
|
||
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
||
},
|
||
options(signal?: AbortSignal) {
|
||
return request<OptionsResponse>('/api/options', { signal });
|
||
},
|
||
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 });
|
||
},
|
||
trend(params: QueryParams, signal?: AbortSignal) {
|
||
return request<TrendResponse>(`/api/metrics/trend?${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'); },
|
||
classificationSources(body: {stage:string;conditions:{field:string;operator:string;value:string}[];page:number;pageSize:number;releaseId?:string}, signal?:AbortSignal) {
|
||
return queryPost<{rows:Record<string,unknown>[];total:number;page:number;pageSize:number;releaseId?:string}>('/api/governance/mapping-issues/classification-sources',body,signal);
|
||
},
|
||
previewClassification(body: {kind?:'group'|'projectGroup';stage:string;target:string;conditions:{field:string;operator:string;value:string}[]}) {
|
||
return queryPost<Record<string,unknown>>('/api/governance/mapping-issues/classification-preview',body);
|
||
},
|
||
unclassifiedProjects(params: {page:number;pageSize:number;customerCode?:string;businessGroup?:string;department?:string}) {
|
||
return request<Collection & { releaseId?:string; filterOptions?: {customerCodes:string[];businessGroups:string[];departments:string[]} }>(`/api/governance/mapping-issues/unclassified-projects?${toQuery(params)}`);
|
||
},
|
||
unclassifiedSources(page = 1, pageSize = 50) {
|
||
return request<Collection & {releaseId?:string}>(`/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 & { releaseId?:string; 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 }, silent = false) {
|
||
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 }, 'POST', undefined, silent);
|
||
},
|
||
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');
|
||
},
|
||
deleteUser(id: string, expectedRowVersion: number) {
|
||
return mutate<{ deleted: boolean; id: string }>(`/api/users/${encodeURIComponent(id)}`, { expectedRowVersion }, 'DELETE');
|
||
},
|
||
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();
|
||
}
|
||
|
||
function requestPath(path: string): string {
|
||
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||
return new URL(path, base).pathname;
|
||
}
|
||
|
||
function requestTimeoutFor(path: string): number | undefined {
|
||
const pathname = requestPath(path);
|
||
return pathname === '/api/workspace/state' || pathname === '/api/auth/me' || pathname === '/api/auth/csrf' ? 8_000 : undefined;
|
||
}
|
||
|
||
function isImmutableRead(path: string): boolean {
|
||
const pathname = requestPath(path);
|
||
if (pathname === '/api/metrics' || pathname === '/api/metrics/trend') return true;
|
||
if (pathname === '/api/options' || pathname === '/api/options/reference-names') return true;
|
||
if (pathname === '/api/analysis/source/catalog' || pathname === '/api/rules/schema') return true;
|
||
if (/^\/api\/governance\/releases\/[^/]+\/(?:inspect|diff)$/.test(pathname)) return true;
|
||
if (pathname === '/api/governance/coverage') {
|
||
const url = new URL(path, typeof location === 'undefined' ? 'http://localhost' : location.origin);
|
||
return Boolean(url.searchParams.get('releaseId'));
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function requestResourceTags(path: string): string[] {
|
||
const pathname = requestPath(path);
|
||
if(pathname.startsWith('/api/sales-order-types'))return ['configuration','metrics','trend','records','options','catalog','query'];
|
||
if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', 'query'];
|
||
if (pathname.startsWith('/api/options')) return ['options', 'query'];
|
||
if (pathname.startsWith('/api/filter-fields') || pathname === '/api/analysis/source/catalog') return ['options', 'catalog', 'configuration'];
|
||
if (pathname.startsWith('/api/records')) return ['records', 'query'];
|
||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'query'];
|
||
if (pathname.startsWith('/api/sources')) return ['sources', 'workflow', 'catalog'];
|
||
if (pathname.startsWith('/api/data-workflow')) return ['workflow', 'sources', 'tasks', 'releases'];
|
||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return ['tasks', 'workflow'];
|
||
if (pathname.startsWith('/api/analysis/')) return ['analysis', 'reports', 'options', 'catalog'];
|
||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues')) return ['configuration', 'metrics', 'trend', 'records', 'options', 'catalog'];
|
||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow'];
|
||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow'];
|
||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||
if (pathname.startsWith('/api/analytics/')) return ['configuration', 'targets'];
|
||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['access', 'users', 'audit', 'policy'];
|
||
return [];
|
||
}
|
||
|
||
function requestCategory(path: string): string {
|
||
const pathname = requestPath(path);
|
||
if (pathname === '/api/workspace/state') return 'workspace';
|
||
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||
if (pathname.includes('/export') || pathname.endsWith('/download')) return 'export';
|
||
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return 'tasks';
|
||
if (pathname.startsWith('/api/sources')) return 'sources';
|
||
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||
return 'other';
|
||
}
|
||
|
||
function requestPriority(path: string): 'active' | 'background' {
|
||
const pathname = requestPath(path);
|
||
return pathname.startsWith('/api/data-workflow/operations/') || pathname.startsWith('/api/import-runs/') || pathname.startsWith('/api/tasks/')
|
||
? 'background'
|
||
: 'active';
|
||
}
|
||
|
||
function mutationResources(path: string): string[] | null {
|
||
const pathname = requestPath(path);
|
||
if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/analysis/')) return [];
|
||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['*'];
|
||
if (pathname.startsWith('/api/sources') || pathname.startsWith('/api/releases') || pathname.startsWith('/api/data-workflow') || pathname.startsWith('/api/import-runs')) {
|
||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'sources', 'workflow', 'tasks', 'releases', 'configuration'];
|
||
}
|
||
if (pathname.startsWith('/api/filter-fields')) return ['options', 'catalog', 'query', 'configuration'];
|
||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues') || pathname.startsWith('/api/metric-dictionary')) {
|
||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'configuration'];
|
||
}
|
||
if (pathname.startsWith('/api/tasks')) return ['tasks', 'workflow'];
|
||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow', 'configuration'];
|
||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow', 'configuration'];
|
||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'configuration'];
|
||
if (pathname.startsWith('/api/analytics/')) return ['configuration'];
|
||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||
if (pathname.startsWith('/api/')) return null;
|
||
return null;
|
||
}
|
||
|
||
function invalidateAfterMutation(path: string): void {
|
||
const resources = mutationResources(path);
|
||
if (resources?.length === 0) return;
|
||
const invalidated = resources ?? ['*'];
|
||
invalidateReadResources(resources?.includes('*') ? undefined : resources ?? undefined);
|
||
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: invalidated } }));
|
||
}
|
||
|
||
function hasStatus(error: unknown, status: number): boolean {
|
||
return !!error && typeof error === 'object' && (error as { status?: unknown }).status === status;
|
||
}
|
||
|
||
function handleAccessFailure(error: unknown): void {
|
||
if (hasStatus(error, 401)) {
|
||
csrfToken = undefined;
|
||
resetRequestScope();
|
||
} else if (hasStatus(error, 403)) {
|
||
clearReadCache();
|
||
window.dispatchEvent(new Event('quality-permission-recheck'));
|
||
}
|
||
}
|
||
|
||
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 [];
|
||
}
|