@@ -318,6 +345,26 @@ function SourceSettingsCard({
) : null}
+ {pendingArchive ? (
+
-
-
- {showLegacySources
- ? '这些来源已在两处保留:本列表可改刷新周期与启停,「来源与目录」里照旧浏览它们的内容。'
- : `AList 来源已由钉盘文件替代,钉钉知识库来源改为按当前账号发现;这 ${legacyConnections.length} 个已接入来源未删除,数据不变。`}
-
+
+
+
+
PP 导入
+
+ 公开只读的 PP 资料下载中心。这里的「去掉来源」是归档下架:从列表、来源与目录、计划刷新里摘掉,
+ 但目录快照与发布记录不删,随时可恢复。
+
+
- ) : null}
- {visibleConnections.length ? (
-
- {visibleConnections.map((connection) => (
-
- ))}
- {sources.length ? null : (
- 尚无快照数据;快照将在来源首次刷新完成后出现。
- )}
-
- ) : legacyConnections.length ? (
-
- 本页只列 PP 资料;AList/钉钉知识库来源已收在上方开关里(共 {legacyConnections.length}{' '}
- 个,未删除)。
-
- ) : (
-
尚无可显示的来源连接。
- )}
+ {ppConnections.length ? (
+
+ {ppConnections.map((connection) => (
+
+ ))}
+ {sources.length ? null : (
+ 尚无快照数据;快照将在来源首次刷新完成后出现。
+ )}
+
+ ) : (
+
本页只列 PP 来源;现在还没有已接入的 PP 来源。
+ )}
+
) : null}
{section === 'services' ? (
diff --git a/web/src/sourceConnections.test.ts b/web/src/sourceConnections.test.ts
index c169a34..8926aa4 100644
--- a/web/src/sourceConnections.test.ts
+++ b/web/src/sourceConnections.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
activateSourceSettingsRevision,
+ archiveSourceConnection,
createSourceSettingsRevision,
fetchSourceConnectionList,
fetchSourceConnections,
@@ -11,6 +12,7 @@ import {
parseSourceConnectionsResponse,
parseSourceScanDetailResponse,
parseSourceScansResponse,
+ restoreSourceConnection,
triggerSourceScan,
} from './sourceConnections'
@@ -19,31 +21,65 @@ afterEach(() => vi.unstubAllGlobals())
describe('parseSourceConnectionsResponse', () => {
it('normalizes only the safe source connection projection', () => {
const result = parseSourceConnectionsResponse({
- data: [{
- id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
- schedule_configured: true, health_status: 'healthy', item_count: 42,
- updated_at: '2026-09-06T01:00:00Z', base_url: 'https://secret-origin.example', secret_ref: 'secret-name',
- last_scan: {
- id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
- added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
- planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
- completed_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip', previous_revision: 'must-strip',
+ data: [
+ {
+ id: 'conn-safe',
+ source_type: 'alist',
+ name: 'AList只读源',
+ enabled: true,
+ schedule_configured: true,
+ health_status: 'healthy',
+ item_count: 42,
+ updated_at: '2026-09-06T01:00:00Z',
+ base_url: 'https://secret-origin.example',
+ secret_ref: 'secret-name',
+ last_scan: {
+ id: 'scan-1',
+ state: 'completed',
+ observed_items: 42,
+ unchanged_items: 40,
+ added_items: 1,
+ updated_items: 1,
+ over_limit_items: 0,
+ missing_items: 0,
+ planned_uploads: 1,
+ error_code: '',
+ created_at: '2026-09-06T00:59:00Z',
+ completed_at: '2026-09-06T01:00:00Z',
+ snapshot_sha256: 'must-strip',
+ previous_revision: 'must-strip',
+ },
},
- }],
+ ],
summary: { total: 1, enabled: 1, disabled: 0, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
})
- expect(result.items).toEqual([{
- id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
- schedule_configured: true, health_status: 'healthy', item_count: 42,
- updated_at: '2026-09-06T01:00:00Z',
- last_scan: {
- id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
- added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
- planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
- completed_at: '2026-09-06T01:00:00Z',
+ expect(result.items).toEqual([
+ {
+ id: 'conn-safe',
+ source_type: 'alist',
+ name: 'AList只读源',
+ enabled: true,
+ schedule_configured: true,
+ health_status: 'healthy',
+ item_count: 42,
+ updated_at: '2026-09-06T01:00:00Z',
+ last_scan: {
+ id: 'scan-1',
+ state: 'completed',
+ observed_items: 42,
+ unchanged_items: 40,
+ added_items: 1,
+ updated_items: 1,
+ over_limit_items: 0,
+ missing_items: 0,
+ planned_uploads: 1,
+ error_code: '',
+ created_at: '2026-09-06T00:59:00Z',
+ completed_at: '2026-09-06T01:00:00Z',
+ },
},
- }])
+ ])
expect(result.summary.total).toBe(1)
expect(result.items[0]).not.toHaveProperty('base_url')
expect(result.items[0]).not.toHaveProperty('secret_ref')
@@ -66,7 +102,7 @@ describe('fetchSourceConnections', () => {
expect(fetchMock).toHaveBeenCalledWith(
'/api/v1/source-connections',
- expect.objectContaining({ headers: { Accept: 'application/json' } }),
+ expect.objectContaining({ headers: { Accept: 'application/json' } })
)
})
})
@@ -76,54 +112,120 @@ describe('triggerSourceScan', () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
- id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending',
- created_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip',
+ id: 'scan-safe',
+ source_connection_id: 'conn/a',
+ source_type: 'pp',
+ state: 'pending',
+ created_at: '2026-09-06T01:00:00Z',
+ snapshot_sha256: 'must-strip',
}),
})
vi.stubGlobal('fetch', fetchMock)
const scan = await triggerSourceScan('conn/a')
- expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-connections/conn%2Fa/scan', expect.objectContaining({ method: 'POST' }))
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/v1/source-connections/conn%2Fa/scan',
+ expect.objectContaining({ method: 'POST' })
+ )
expect(scan).toEqual({
- id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending', created_at: '2026-09-06T01:00:00Z',
+ id: 'scan-safe',
+ source_connection_id: 'conn/a',
+ source_type: 'pp',
+ state: 'pending',
+ created_at: '2026-09-06T01:00:00Z',
})
})
})
describe('source scan history and details', () => {
const scan = {
- id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
- added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
- planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
- snapshot_sha256: 'must-be-dropped', stable_external_id: 'must-be-dropped',
+ id: 'scan-safe',
+ state: 'completed',
+ observed_items: 2,
+ unchanged_items: 0,
+ added_items: 1,
+ updated_items: 0,
+ over_limit_items: 0,
+ missing_items: 1,
+ planned_uploads: 1,
+ error_code: '',
+ created_at: '2026-09-06T06:00:00Z',
+ completed_at: '2026-09-06T06:01:00Z',
+ snapshot_sha256: 'must-be-dropped',
+ stable_external_id: 'must-be-dropped',
}
it('strictly parses safe history and detail projections', () => {
expect(parseSourceScansResponse({ data: [scan], total: 1, limit: 20, offset: 0 })).toEqual({
- items: [{
- id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
- added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
- planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
- }], total: 1, limit: 20, offset: 0,
+ items: [
+ {
+ id: 'scan-safe',
+ state: 'completed',
+ observed_items: 2,
+ unchanged_items: 0,
+ added_items: 1,
+ updated_items: 0,
+ over_limit_items: 0,
+ missing_items: 1,
+ planned_uploads: 1,
+ error_code: '',
+ created_at: '2026-09-06T06:00:00Z',
+ completed_at: '2026-09-06T06:01:00Z',
+ },
+ ],
+ total: 1,
+ limit: 20,
+ offset: 0,
})
- expect(parseSourceScanDetailResponse({ data: {
- ...scan,
- changes: [{
- id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42,
- created_at: '2026-09-06T06:01:00Z', previous_revision: 'must-be-dropped', observed_revision: 'must-be-dropped',
- }],
- }})).toEqual({
- id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
- added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
- planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
- changes: [{ id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42, created_at: '2026-09-06T06:01:00Z' }],
+ expect(
+ parseSourceScanDetailResponse({
+ data: {
+ ...scan,
+ changes: [
+ {
+ id: 'chg-safe',
+ source_item_id: 'si-safe',
+ change_type: 'updated',
+ observed_size_bytes: 42,
+ created_at: '2026-09-06T06:01:00Z',
+ previous_revision: 'must-be-dropped',
+ observed_revision: 'must-be-dropped',
+ },
+ ],
+ },
+ })
+ ).toEqual({
+ id: 'scan-safe',
+ state: 'completed',
+ observed_items: 2,
+ unchanged_items: 0,
+ added_items: 1,
+ updated_items: 0,
+ over_limit_items: 0,
+ missing_items: 1,
+ planned_uploads: 1,
+ error_code: '',
+ created_at: '2026-09-06T06:00:00Z',
+ completed_at: '2026-09-06T06:01:00Z',
+ changes: [
+ {
+ id: 'chg-safe',
+ source_item_id: 'si-safe',
+ change_type: 'updated',
+ observed_size_bytes: 42,
+ created_at: '2026-09-06T06:01:00Z',
+ },
+ ],
})
})
it('requests connection-scoped history and details', async () => {
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 }))
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 })
+ )
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...scan, changes: [] } }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
await fetchSourceScans('conn / pp')
@@ -135,47 +237,165 @@ describe('source scan history and details', () => {
describe('V1 source settings client', () => {
it('projects the connection list without sensitive fields', async () => {
- const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
- data: [{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
- health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z',
- base_url: 'https://strip.me', secret_ref: 'strip-too' }],
- }), { status: 200 }))
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: [
+ {
+ id: 'conn-1',
+ source_type: 'alist',
+ name: 'A',
+ enabled: true,
+ schedule_configured: true,
+ health_status: 'healthy',
+ item_count: 3,
+ updated_at: '2026-09-12T01:00:00Z',
+ next_refresh_at: '2026-09-12T09:00:00Z',
+ base_url: 'https://strip.me',
+ secret_ref: 'strip-too',
+ },
+ ],
+ }),
+ { status: 200 }
+ )
+ )
vi.stubGlobal('fetch', fetchMock)
const items = await fetchSourceConnectionList()
- expect(items).toEqual([{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
- health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z' }])
+ expect(items).toEqual([
+ {
+ id: 'conn-1',
+ source_type: 'alist',
+ name: 'A',
+ enabled: true,
+ schedule_configured: true,
+ health_status: 'healthy',
+ item_count: 3,
+ updated_at: '2026-09-12T01:00:00Z',
+ next_refresh_at: '2026-09-12T09:00:00Z',
+ },
+ ])
expect(JSON.stringify(items)).not.toContain('strip')
})
it('rejects malformed connection items', async () => {
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
- data: [{ id: 'x' }],
- }), { status: 200 })))
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: [{ id: 'x' }],
+ }),
+ { status: 200 }
+ )
+ )
+ )
await expect(fetchSourceConnectionList()).rejects.toThrow('invalid source connection item')
})
it('creates and activates revisions with intent + idempotency headers and surfaces operation', async () => {
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 }))
- .mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 }))
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 })
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), {
+ status: 200,
+ })
+ )
vi.stubGlobal('fetch', fetchMock)
- expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).toEqual({ operation: 'created', id: 'scr-2' })
+ expect(
+ await createSourceSettingsRevision('conn/1', {
+ source_type: 'alist',
+ name: 'A',
+ endpoint: '',
+ credential_ref: '',
+ enabled: true,
+ schedule: { refresh_interval_seconds: 3600 },
+ })
+ ).toEqual({ operation: 'created', id: 'scr-2' })
expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null })
const [createCall, activateCall] = fetchMock.mock.calls
expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions')
expect((createCall[1] as RequestInit).headers).toMatchObject({ 'X-Governance-Action': 'source-settings' })
- expect(((createCall[1] as RequestInit).headers as Record
)['Idempotency-Key']).toMatch(/[0-9a-f-]{36}/)
+ expect(((createCall[1] as RequestInit).headers as Record)['Idempotency-Key']).toMatch(
+ /[0-9a-f-]{36}/
+ )
expect(activateCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions/scr%2F2/activate')
expect(createCall[1]).not.toBe(activateCall[1])
})
it('surfaces server error details on failure', async () => {
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })))
- await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })
+ )
+ )
+ await expect(
+ createSourceSettingsRevision('c', {
+ source_type: 'manual',
+ name: 'A',
+ endpoint: '',
+ credential_ref: '',
+ enabled: true,
+ schedule: { refresh_interval_seconds: 3600 },
+ })
+ ).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
})
it('parses revision history strictly', async () => {
- const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null }
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 })))
+ const revision = {
+ id: 'scr-1',
+ revision_number: 1,
+ state: 'active',
+ name: 'A',
+ endpoint: 'http://x',
+ credential_ref: 'ref',
+ enabled: true,
+ refresh_interval_seconds: '3600',
+ created_by: 'z',
+ created_at: '2026-09-12T01:00:00Z',
+ validated_at: null,
+ activated_at: '2026-09-12T01:00:00Z',
+ retired_at: null,
+ }
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 }))
+ )
const history = await fetchSourceSettingsRevisions('c')
expect(history[0].state).toBe('active')
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 })))
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 }))
+ )
await expect(fetchSourceSettingsRevisions('c')).rejects.toThrow('invalid source settings revision')
})
})
+
+describe('去掉来源(归档)客户端', () => {
+ it('归档/恢复都带写意图头与幂等键,并正确编码来源 ID', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }))
+ vi.stubGlobal('fetch', fetchMock)
+ await archiveSourceConnection('conn/1')
+ const [archiveURL, archiveInit] = fetchMock.mock.calls[0]
+ expect(archiveURL).toBe('/api/v1/source-connections/conn%2F1/archive')
+ expect(archiveInit.method).toBe('POST')
+ expect(archiveInit.headers['X-Governance-Action']).toBe('source-archive')
+ expect(typeof archiveInit.headers['Idempotency-Key']).toBe('string')
+ expect(archiveInit.headers['Idempotency-Key'].length).toBeGreaterThan(0)
+
+ await restoreSourceConnection('conn/1')
+ const [restoreURL, restoreInit] = fetchMock.mock.calls[1]
+ expect(restoreURL).toBe('/api/v1/source-connections/conn%2F1/restore')
+ expect(restoreInit.headers['X-Governance-Action']).toBe('source-restore')
+ })
+ it('后端拒绝时把原因带出来(不吞错误)', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'source connection not found' }), { status: 404 }))
+ )
+ await expect(archiveSourceConnection('conn-x')).rejects.toThrow('去掉来源失败:source connection not found')
+ })
+})
diff --git a/web/src/sourceConnections.ts b/web/src/sourceConnections.ts
index 298cd7d..3924ed8 100644
--- a/web/src/sourceConnections.ts
+++ b/web/src/sourceConnections.ts
@@ -79,7 +79,13 @@ const healthStatuses = new Set(['unknown', 'healthy', 'degra
const scanStates = new Set(['pending', 'running', 'completed', 'failed'])
const scanChangeTypes = new Set(['added', 'updated', 'unavailable'])
const summaryKeys: ReadonlyArray = [
- 'total', 'enabled', 'disabled', 'healthy', 'degraded', 'unhealthy', 'unknown',
+ 'total',
+ 'enabled',
+ 'disabled',
+ 'healthy',
+ 'degraded',
+ 'unhealthy',
+ 'unknown',
]
export function parseSourceConnectionsResponse(value: unknown): SourceConnectionPage {
@@ -87,11 +93,19 @@ export function parseSourceConnectionsResponse(value: unknown): SourceConnection
throw new Error('invalid source connections response')
}
const items = value.data.map((raw): SourceConnectionView => {
- if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_type !== 'string' ||
- !sourceTypes.has(raw.source_type as SourceConnectionType) || typeof raw.name !== 'string' ||
- typeof raw.enabled !== 'boolean' || typeof raw.schedule_configured !== 'boolean' ||
- typeof raw.health_status !== 'string' || !healthStatuses.has(raw.health_status as SourceHealthStatus) ||
- !isCount(raw.item_count) || typeof raw.updated_at !== 'string') {
+ if (
+ !isRecord(raw) ||
+ typeof raw.id !== 'string' ||
+ typeof raw.source_type !== 'string' ||
+ !sourceTypes.has(raw.source_type as SourceConnectionType) ||
+ typeof raw.name !== 'string' ||
+ typeof raw.enabled !== 'boolean' ||
+ typeof raw.schedule_configured !== 'boolean' ||
+ typeof raw.health_status !== 'string' ||
+ !healthStatuses.has(raw.health_status as SourceHealthStatus) ||
+ !isCount(raw.item_count) ||
+ typeof raw.updated_at !== 'string'
+ ) {
throw new Error('invalid source connection item')
}
const lastScan = parseSourceScanSummary(raw.last_scan)
@@ -131,18 +145,28 @@ export interface SourceConnectionListItem {
function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
if (!Array.isArray(raw)) throw new Error('invalid source connections list')
return raw.map((item): SourceConnectionListItem => {
- if (!isRecord(item) || typeof item.id !== 'string' || typeof item.source_type !== 'string' ||
- typeof item.name !== 'string' || typeof item.enabled !== 'boolean' ||
- typeof item.schedule_configured !== 'boolean' || typeof item.item_count !== 'number' ||
- typeof item.updated_at !== 'string' ||
- (item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')) {
+ if (
+ !isRecord(item) ||
+ typeof item.id !== 'string' ||
+ typeof item.source_type !== 'string' ||
+ typeof item.name !== 'string' ||
+ typeof item.enabled !== 'boolean' ||
+ typeof item.schedule_configured !== 'boolean' ||
+ typeof item.item_count !== 'number' ||
+ typeof item.updated_at !== 'string' ||
+ (item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')
+ ) {
throw new Error('invalid source connection item')
}
return {
- id: item.id, source_type: item.source_type as SourceConnectionType, name: item.name,
- enabled: item.enabled, schedule_configured: item.schedule_configured,
+ id: item.id,
+ source_type: item.source_type as SourceConnectionType,
+ name: item.name,
+ enabled: item.enabled,
+ schedule_configured: item.schedule_configured,
health_status: typeof item.health_status === 'string' ? item.health_status : '',
- item_count: item.item_count, updated_at: item.updated_at,
+ item_count: item.item_count,
+ updated_at: item.updated_at,
next_refresh_at: (item.next_refresh_at as string | null) ?? null,
}
})
@@ -151,7 +175,7 @@ function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
export async function fetchSourceConnectionList(signal?: AbortSignal): Promise {
const response = await fetch('/api/v1/source-connections', { headers: { Accept: 'application/json' }, signal })
if (!response.ok) throw new Error(`加载来源连接失败(HTTP ${response.status})`)
- const value = await response.json() as unknown
+ const value = (await response.json()) as unknown
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source connections response')
return parseConnectionList(value.data)
}
@@ -175,10 +199,17 @@ export async function triggerSourceScan(connectionID: string): Promise {
- if (!isRecord(raw) || typeof raw.id !== 'string' ||
- (raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
- typeof raw.change_type !== 'string' || !scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
- (raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) || typeof raw.created_at !== 'string') {
+ if (
+ !isRecord(raw) ||
+ typeof raw.id !== 'string' ||
+ (raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
+ typeof raw.change_type !== 'string' ||
+ !scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
+ (raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) ||
+ typeof raw.created_at !== 'string'
+ ) {
throw new Error('invalid source scan change')
}
return {
@@ -231,31 +273,59 @@ export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail
return { ...summary, changes }
}
-export async function fetchSourceScans(connectionID: string, limit = 20, offset = 0, signal?: AbortSignal): Promise {
+export async function fetchSourceScans(
+ connectionID: string,
+ limit = 20,
+ offset = 0,
+ signal?: AbortSignal
+): Promise {
const params = new URLSearchParams({ limit: String(limit), offset: String(offset) })
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans?${params}`, {
- headers: { Accept: 'application/json' }, signal,
+ headers: { Accept: 'application/json' },
+ signal,
})
if (!response.ok) throw new Error(`加载扫描历史失败(HTTP ${response.status})`)
return parseSourceScansResponse(await response.json())
}
-export async function fetchSourceScanDetail(connectionID: string, scanID: string, signal?: AbortSignal): Promise {
- const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`, {
- headers: { Accept: 'application/json' }, signal,
- })
+export async function fetchSourceScanDetail(
+ connectionID: string,
+ scanID: string,
+ signal?: AbortSignal
+): Promise {
+ const response = await fetch(
+ `/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`,
+ {
+ headers: { Accept: 'application/json' },
+ signal,
+ }
+ )
if (!response.ok) throw new Error(`加载扫描详情失败(HTTP ${response.status})`)
return parseSourceScanDetailResponse(await response.json())
}
function parseSourceScanSummary(raw: unknown): SourceScanSummary | null {
if (raw === null || raw === undefined) return null
- if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.state !== 'string' ||
- !scanStates.has(raw.state as SourceScanState) || typeof raw.error_code !== 'string' ||
- typeof raw.created_at !== 'string' || (raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
+ if (
+ !isRecord(raw) ||
+ typeof raw.id !== 'string' ||
+ typeof raw.state !== 'string' ||
+ !scanStates.has(raw.state as SourceScanState) ||
+ typeof raw.error_code !== 'string' ||
+ typeof raw.created_at !== 'string' ||
+ (raw.completed_at !== null && typeof raw.completed_at !== 'string')
+ ) {
throw new Error('invalid source scan summary')
}
- const countKeys = ['observed_items', 'unchanged_items', 'added_items', 'updated_items', 'over_limit_items', 'missing_items', 'planned_uploads'] as const
+ const countKeys = [
+ 'observed_items',
+ 'unchanged_items',
+ 'added_items',
+ 'updated_items',
+ 'over_limit_items',
+ 'missing_items',
+ 'planned_uploads',
+ ] as const
for (const key of countKeys) {
if (!isCount(raw[key])) throw new Error('invalid source scan summary')
}
@@ -315,63 +385,153 @@ export interface SourceSettingsDraftRequest {
const revisionStates = new Set(['validated', 'active', 'retired', 'failed'])
function parseSettingsRevision(raw: unknown): SourceSettingsRevision {
- if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.revision_number !== 'number' ||
- typeof raw.state !== 'string' || !revisionStates.has(raw.state as SourceSettingsRevisionState) ||
- typeof raw.name !== 'string' || typeof raw.endpoint !== 'string' || typeof raw.credential_ref !== 'string' ||
- typeof raw.enabled !== 'boolean' || typeof raw.refresh_interval_seconds !== 'string' ||
- typeof raw.created_by !== 'string' || typeof raw.created_at !== 'string' ||
- (raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
- (raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
- (raw.retired_at !== null && typeof raw.retired_at !== 'string')) {
+ if (
+ !isRecord(raw) ||
+ typeof raw.id !== 'string' ||
+ typeof raw.revision_number !== 'number' ||
+ typeof raw.state !== 'string' ||
+ !revisionStates.has(raw.state as SourceSettingsRevisionState) ||
+ typeof raw.name !== 'string' ||
+ typeof raw.endpoint !== 'string' ||
+ typeof raw.credential_ref !== 'string' ||
+ typeof raw.enabled !== 'boolean' ||
+ typeof raw.refresh_interval_seconds !== 'string' ||
+ typeof raw.created_by !== 'string' ||
+ typeof raw.created_at !== 'string' ||
+ (raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
+ (raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
+ (raw.retired_at !== null && typeof raw.retired_at !== 'string')
+ ) {
throw new Error('invalid source settings revision')
}
return {
- id: raw.id, revision_number: raw.revision_number, state: raw.state as SourceSettingsRevisionState,
- name: raw.name, endpoint: raw.endpoint, credential_ref: raw.credential_ref, enabled: raw.enabled,
- refresh_interval_seconds: raw.refresh_interval_seconds, created_by: raw.created_by, created_at: raw.created_at,
+ id: raw.id,
+ revision_number: raw.revision_number,
+ state: raw.state as SourceSettingsRevisionState,
+ name: raw.name,
+ endpoint: raw.endpoint,
+ credential_ref: raw.credential_ref,
+ enabled: raw.enabled,
+ refresh_interval_seconds: raw.refresh_interval_seconds,
+ created_by: raw.created_by,
+ created_at: raw.created_at,
validated_at: (raw.validated_at as string | null) ?? null,
activated_at: (raw.activated_at as string | null) ?? null,
retired_at: (raw.retired_at as string | null) ?? null,
}
}
-export async function fetchSourceSettingsRevisions(connectionID: string, signal?: AbortSignal): Promise {
+export async function fetchSourceSettingsRevisions(
+ connectionID: string,
+ signal?: AbortSignal
+): Promise {
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, {
headers: { Accept: 'application/json' },
signal,
})
if (!response.ok) throw new Error(`加载来源设置历史失败(HTTP ${response.status})`)
- const value = await response.json() as unknown
+ const value = (await response.json()) as unknown
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source settings revisions response')
return value.data.map(parseSettingsRevision)
}
-async function postSourceSettings(path: string, body: string, errorMessage: string): Promise<{ operation: string; id: string | null }> {
+async function postSourceSettings(
+ path: string,
+ body: string,
+ errorMessage: string
+): Promise<{ operation: string; id: string | null }> {
const response = await fetch(path, {
method: 'POST',
- headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'source-settings', 'Idempotency-Key': newOperationID() },
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'X-Governance-Action': 'source-settings',
+ 'Idempotency-Key': newOperationID(),
+ },
body,
})
if (!response.ok) {
let detail = ''
try {
- const parsed = await response.json() as unknown
+ const parsed = (await response.json()) as unknown
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
- } catch { /* keep status-only message */ }
+ } catch {
+ /* keep status-only message */
+ }
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
}
- const value = await response.json() as unknown
- if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data)) throw new Error('invalid source settings response')
+ const value = (await response.json()) as unknown
+ if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data))
+ throw new Error('invalid source settings response')
const id = typeof value.data.id === 'string' ? value.data.id : null
return { operation: value.operation, id }
}
-export async function createSourceSettingsRevision(connectionID: string, draft: SourceSettingsDraftRequest): Promise<{ operation: string; id: string }> {
- const result = await postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, JSON.stringify(draft), '保存来源设置草稿失败')
+export async function createSourceSettingsRevision(
+ connectionID: string,
+ draft: SourceSettingsDraftRequest
+): Promise<{ operation: string; id: string }> {
+ const result = await postSourceSettings(
+ `/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`,
+ JSON.stringify(draft),
+ '保存来源设置草稿失败'
+ )
if (!result.id) throw new Error('创建来源设置草稿未返回修订号')
return result as { operation: string; id: string }
}
-export async function activateSourceSettingsRevision(connectionID: string, revisionID: string): Promise<{ operation: string }> {
- return postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`, '{}', '启用来源设置修订失败')
+export async function activateSourceSettingsRevision(
+ connectionID: string,
+ revisionID: string
+): Promise<{ operation: string }> {
+ return postSourceSettings(
+ `/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`,
+ '{}',
+ '启用来源设置修订失败'
+ )
+}
+
+/**
+ * 「去掉来源」:归档下架(**不是物理删除**)。
+ * 来源会从数据源配置、来源与目录、计划刷新与手动扫描里消失;目录快照、发布记录与
+ * 审计数据原样保留 —— 再用 dws 重新登记同一个来源就会原地复活。幂等,仅管理员可用。
+ */
+export async function archiveSourceConnection(connectionID: string): Promise {
+ await postSourceArchive(
+ `/api/v1/source-connections/${encodeURIComponent(connectionID)}/archive`,
+ 'source-archive',
+ '去掉来源失败'
+ )
+}
+
+/** 撤销归档:来源重新出现,但保持停用(调度不会自动恢复)。 */
+export async function restoreSourceConnection(connectionID: string): Promise {
+ await postSourceArchive(
+ `/api/v1/source-connections/${encodeURIComponent(connectionID)}/restore`,
+ 'source-restore',
+ '恢复来源失败'
+ )
+}
+
+async function postSourceArchive(path: string, intent: string, errorMessage: string): Promise {
+ const response = await fetch(path, {
+ method: 'POST',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'X-Governance-Action': intent,
+ 'Idempotency-Key': newOperationID(),
+ },
+ body: '{}',
+ })
+ if (!response.ok) {
+ let detail = ''
+ try {
+ const parsed = (await response.json()) as unknown
+ if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
+ } catch {
+ /* keep status-only message */
+ }
+ throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
+ }
}