Compare commits
91 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b96473836d | |||
| 54d0fb75ea | |||
| 15774a1c02 | |||
| e3682fd06f | |||
| 33f5ad68bf | |||
| 5bf036bb81 | |||
| 5383af4cc5 | |||
| 47f7cb2bf1 | |||
| 603650fbf4 | |||
| 5d20f5bfeb | |||
| af38de9fd1 | |||
| 18252e24b8 | |||
| 1ce2c10107 | |||
| 48caa23997 | |||
| ea141d9f17 | |||
| 769740a46d | |||
| b472b9eec9 | |||
| 0d5940433d | |||
| e5fd454bb3 | |||
| 03d7bca9a5 | |||
| 2abad3b537 | |||
| fc5cea43ac | |||
| c2ab9674a0 | |||
| 72cd0747a4 | |||
| 3d4c7929c3 | |||
| 8dce016552 | |||
| 64879cfcdd | |||
| 6853ec5388 | |||
| 796ad7bb51 | |||
| 20b34918d3 | |||
| 04e5512777 | |||
| 0510cd8d9c | |||
| 7a237431e0 | |||
| 6ed3772ff5 | |||
| a86ead93e4 | |||
| b0ce384b8d | |||
| b56566f40e | |||
| 6782d0ea23 | |||
| e6092dda6f | |||
| 5f13698129 | |||
| 29ba9a358e | |||
| 3ab56e6cfa | |||
| 56c4faa8ee | |||
| d23c808376 | |||
| 41930b858e | |||
| 9dccf5318e | |||
| f216381619 | |||
| d454d3fa4b | |||
| a5ee45aa4e | |||
| d333f783fe | |||
| faab318127 | |||
| a4296a4bdd | |||
| 7eee89ded3 | |||
| f9bc2d917c | |||
| b96cd4b7c2 | |||
| f185d21f55 | |||
| a61b0cce81 | |||
| 2a75a2d2c8 | |||
| 512f669f57 | |||
| 21dbbb4c3c | |||
| 55d0c99e2b | |||
| 3907a8bf74 | |||
| 46dfa2cffb | |||
| 97e2b26900 | |||
| 39e33f7a5b | |||
| 040f646480 | |||
| 8b007c637d | |||
| f0a62c6306 | |||
| 30edfee00e | |||
| c2da8e184e | |||
| a19319d815 | |||
| d07ea186fa | |||
| 80caec373a | |||
| 3caefd6716 | |||
| 4d0dd2d721 | |||
| 2befaaef9d | |||
| 20b0bf4dd7 | |||
| b4fd8d9b8b | |||
| fe85fa2a62 | |||
| b14a533b17 | |||
| 42969b2218 | |||
| c4ee75a1af | |||
| 6f2137cbb0 | |||
| 70a2246e8b | |||
| b7e3dac661 | |||
| 2e4a1996c8 | |||
| fe4e952853 | |||
| 18654b6806 | |||
| ee7d00c0b1 | |||
| 9cd1a94369 | |||
| 470e85c0ff |
@@ -23,3 +23,6 @@
|
||||
*.meta text
|
||||
*.anim text
|
||||
*.controller text
|
||||
|
||||
# Rust ts-rs 生成的共享契约:保留在仓库中供 TS 消费,但不作为手写源文件统计。
|
||||
packages/shared/src/contracts/generated/** linguist-generated=true
|
||||
|
||||
@@ -221,8 +221,7 @@ jobs:
|
||||
- name: Run AI game creator shell agent-run smoke
|
||||
run: npm run check:native-shells:agc-rust-smoke
|
||||
|
||||
# AGC 壳依赖的共享 / 平台 crate 测试用的是 server-rs workspace 与两个无锁独立 crate
|
||||
# 的 manifest,属另一套依赖图,因此单独一个 job 预热、单独跑。
|
||||
# AGC 壳依赖的共享 / 平台和编辑器插件 crate 各自预热独立 manifest,再运行对应测试。
|
||||
ai-game-creator-shell-rust-crates:
|
||||
name: AI game creator shell Rust crates
|
||||
runs-on: genarrative-ci
|
||||
@@ -263,13 +262,15 @@ jobs:
|
||||
# `cargo test --manifest-path` 单独跑这两个 crate。不在这里预热的话,这两条测试
|
||||
# 会在测试阶段自己 `Updating crates.io index`,crates.io 一抖动整条 job 就红
|
||||
# (见 #327 / PR #316 run 1950)。
|
||||
# 两个 crate 都没有提交 Cargo.lock,所以这里只能做不带锁标志的 fetch:
|
||||
# Cocos 插件也使用独立且未提交的锁文件,一并预热。
|
||||
# 这些 crate 都没有提交 Cargo.lock,所以这里只能做不带锁标志的 fetch:
|
||||
# 加锁标志会因为缺少锁文件直接失败。生成的 Cargo.lock 落在两个 crate 目录内,
|
||||
# 已被各自的 .gitignore 忽略,只留在容器里;随后的测试阶段因此能用锁定版本
|
||||
# 解析,不再触碰 registry index。
|
||||
for manifest_path in \
|
||||
server-rs/crates/agent-runtime-core/Cargo.toml \
|
||||
server-rs/crates/agent-runtime-orchestration/Cargo.toml; do
|
||||
server-rs/crates/agent-runtime-orchestration/Cargo.toml \
|
||||
plugins/agc-cocos-editor/native/cocos-editor-bridge/Cargo.toml; do
|
||||
for attempt in $(seq 1 5); do
|
||||
if cargo fetch \
|
||||
--target x86_64-unknown-linux-gnu \
|
||||
@@ -284,6 +285,40 @@ jobs:
|
||||
done
|
||||
done
|
||||
|
||||
- name: Prepare Unity plugin Rust dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for attempt in $(seq 1 5); do
|
||||
if cargo fetch --locked \
|
||||
--target x86_64-unknown-linux-gnu \
|
||||
--manifest-path plugins/agc-unity-editor/native/unity-editor-bridge/Cargo.toml; then
|
||||
break
|
||||
fi
|
||||
if [[ "${attempt}" -eq 5 ]]; then
|
||||
echo 'Unity plugin Cargo dependency fetch failed after 5 attempts.' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep $((attempt * 2))
|
||||
done
|
||||
|
||||
- name: Prepare Godot plugin Rust dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for attempt in $(seq 1 5); do
|
||||
if cargo fetch --locked \
|
||||
--target x86_64-unknown-linux-gnu \
|
||||
--manifest-path plugins/agc-godot-editor/native/godot-editor-bridge/Cargo.toml; then
|
||||
break
|
||||
fi
|
||||
if [[ "${attempt}" -eq 5 ]]; then
|
||||
echo 'Godot plugin Cargo dependency fetch failed after 5 attempts.' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep $((attempt * 2))
|
||||
done
|
||||
|
||||
- name: Run AI game creator shell shared crate gates
|
||||
run: npm run check:native-shells:agc-rust-crates
|
||||
|
||||
|
||||
+4
-2
@@ -47,9 +47,11 @@ temp*build*/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/codex-package.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/manifest.json
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/NOTICE.md
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-arm64/
|
||||
/apps/ai-game-creator-shell/src-tauri/resources/codex/mac-native/darwin-x64/
|
||||
/plugins/agc-cocos-editor/native/payload/
|
||||
/plugins/agc-unity-editor/dotnet/**/bin/
|
||||
/plugins/agc-unity-editor/dotnet/**/obj/
|
||||
/plugins/agc-unity-editor/dotnet/publish/
|
||||
/plugins/agc-unity-editor/dotnet/native-build/
|
||||
/apps/ai-game-creator-shell/logs/
|
||||
/apps/ai-game-creator-shell/.llm-drafts/
|
||||
/apps/ai-game-creator-shell/game-creator.config.local.json
|
||||
|
||||
+10
-1
@@ -1,5 +1,14 @@
|
||||
{
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"trailingComma": "all"
|
||||
"trailingComma": "all",
|
||||
"overrides": [
|
||||
{
|
||||
"files": "packages/shared/src/contracts/generated/**/*.ts",
|
||||
"options": {
|
||||
"printWidth": 1000,
|
||||
"singleQuote": false
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ import type {
|
||||
AdminLoginResponse,
|
||||
AdminMeResponse,
|
||||
AdminOverviewResponse,
|
||||
AdminProjectSnapshotListQuery,
|
||||
AdminProjectSnapshotListResponse,
|
||||
AdminRechargeOrderListQuery,
|
||||
AdminRechargeOrderListResponse,
|
||||
AdminRechargeRefundActionResponse,
|
||||
@@ -198,6 +200,92 @@ export function listAdminAccounts(token: string) {
|
||||
return request<AdminAccountListResponse>('/admin/api/accounts', { token });
|
||||
}
|
||||
|
||||
export function listAdminProjectSnapshots(
|
||||
token: string,
|
||||
query: AdminProjectSnapshotListQuery = {},
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.cursor) params.set('cursor', query.cursor);
|
||||
params.set('limit', String(query.limit ?? 20));
|
||||
return request<AdminProjectSnapshotListResponse>(
|
||||
`/admin/api/project-snapshots?${params.toString()}`,
|
||||
{ token, signal },
|
||||
);
|
||||
}
|
||||
|
||||
export async function downloadAdminProjectSnapshot(
|
||||
token: string,
|
||||
userId: string,
|
||||
projectId: string,
|
||||
signal?: AbortSignal,
|
||||
) {
|
||||
const path = `/admin/api/project-snapshots/${encodeURIComponent(userId)}/${encodeURIComponent(projectId)}/download`;
|
||||
const response = await fetch(buildRequestUrl(path), {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token.trim()}`,
|
||||
Accept: 'application/zip',
|
||||
[API_RESPONSE_ENVELOPE_HEADER]: 'v1',
|
||||
},
|
||||
signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const responseText = await response.text();
|
||||
throw buildAdminApiError(
|
||||
response,
|
||||
parseJsonResponse(responseText),
|
||||
responseText,
|
||||
);
|
||||
}
|
||||
const contentType = response.headers
|
||||
.get('content-type')
|
||||
?.split(';')[0]
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
if (contentType !== 'application/zip') {
|
||||
await response.body?.cancel();
|
||||
throw new AdminApiError({
|
||||
message: '下载失败:服务端未返回 ZIP 工程文件',
|
||||
status: response.status,
|
||||
code: 'INVALID_PROJECT_ARCHIVE_RESPONSE',
|
||||
});
|
||||
}
|
||||
return {
|
||||
blob: await response.blob(),
|
||||
filename: projectArchiveFilename(
|
||||
response.headers.get('content-disposition'),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function projectArchiveFilename(contentDisposition: string | null): string {
|
||||
const extended = contentDisposition?.match(
|
||||
/(?:^|;)\s*filename\*=UTF-8'[^']*'([^;]+)/i,
|
||||
);
|
||||
const ordinary = contentDisposition?.match(
|
||||
/(?:^|;)\s*filename=(?:"((?:[^"\\]|\\.)*)"|([^;]+))/i,
|
||||
);
|
||||
let filename =
|
||||
ordinary?.[1]?.replace(/\\(.)/g, '$1') ?? ordinary?.[2]?.trim() ?? '';
|
||||
if (extended?.[1]) {
|
||||
try {
|
||||
filename = decodeURIComponent(extended[1].trim());
|
||||
} catch {
|
||||
// 非法扩展编码继续使用普通文件名。
|
||||
}
|
||||
}
|
||||
const safeName = Array.from(filename, (character) => {
|
||||
const code = character.charCodeAt(0);
|
||||
return code < 32 || code === 127 ? '_' : character;
|
||||
})
|
||||
.join('')
|
||||
.replace(/[<>:"/\\|?*]/g, '_')
|
||||
.trim()
|
||||
.replace(/[. ]+$/, '');
|
||||
if (!safeName || safeName.length > 240) return 'project.zip';
|
||||
return /\.zip$/i.test(safeName) ? safeName : `${safeName}.zip`;
|
||||
}
|
||||
|
||||
export function createAdminAccount(
|
||||
token: string,
|
||||
payload: AdminCreateAccountRequest,
|
||||
|
||||
@@ -96,6 +96,27 @@ export interface AdminMeResponse {
|
||||
admin: AdminSessionPayload;
|
||||
}
|
||||
|
||||
export interface AdminProjectSnapshotEntry {
|
||||
userId: string;
|
||||
projectId: string;
|
||||
projectName: string | null;
|
||||
syncRevision: number;
|
||||
syncedAtMs: number;
|
||||
fileCount: number;
|
||||
totalBytes: number;
|
||||
status: 'ready' | 'partial' | 'unverified';
|
||||
}
|
||||
|
||||
export interface AdminProjectSnapshotListQuery {
|
||||
cursor?: string | null;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface AdminProjectSnapshotListResponse {
|
||||
items: AdminProjectSnapshotEntry[];
|
||||
nextCursor: string | null;
|
||||
}
|
||||
|
||||
export interface AdminErrorReportEntry {
|
||||
batchId: string;
|
||||
eventCount: number;
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
downloadAdminProjectSnapshot,
|
||||
listAdminProjectSnapshots,
|
||||
} from './adminApiClient';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test('项目列表携带分页与后台授权,解析标准响应', async () => {
|
||||
const payload = { items: [], nextCursor: 'next' };
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(JSON.stringify({ ok: true, data: payload })),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const controller = new AbortController();
|
||||
expect(
|
||||
await listAdminProjectSnapshots(
|
||||
'admin-token',
|
||||
{ cursor: 'user/a+项目', limit: 20 },
|
||||
controller.signal,
|
||||
),
|
||||
).toEqual(payload);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/admin/api/project-snapshots?cursor=user%2Fa%2B%E9%A1%B9%E7%9B%AE&limit=20',
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Authorization: 'Bearer admin-token' }),
|
||||
signal: controller.signal,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('ZIP 下载以授权请求读取并优先保留中文附件名', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response('PK\u0003\u0004', {
|
||||
headers: {
|
||||
'content-type': 'application/zip',
|
||||
'content-disposition':
|
||||
"attachment; filename=project.zip; filename*=UTF-8''%E4%B8%89%E6%B6%88-r2.zip",
|
||||
},
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const controller = new AbortController();
|
||||
const archive = await downloadAdminProjectSnapshot(
|
||||
'admin-token',
|
||||
'user/a',
|
||||
'project/b',
|
||||
controller.signal,
|
||||
);
|
||||
expect(archive.filename).toBe('三消-r2.zip');
|
||||
expect(archive.blob.type).toBe('application/zip');
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/admin/api/project-snapshots/user%2Fa/project%2Fb/download',
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
Authorization: 'Bearer admin-token',
|
||||
Accept: 'application/zip',
|
||||
}),
|
||||
signal: controller.signal,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['attachment; filename="工程.zip"; filename*=UTF-8\'\'%broken', '工程.zip'],
|
||||
['attachment; filename="../secret.zip"', '.._secret.zip'],
|
||||
["attachment; filename*=UTF-8''unsafe%00%1F%7F.zip", 'unsafe___.zip'],
|
||||
[null, 'project.zip'],
|
||||
])('ZIP 附件名兼容安全回退 %s', async (header, expected) => {
|
||||
const headers: Record<string, string> = { 'content-type': 'application/zip' };
|
||||
// Response 的 Headers 只接受 Latin-1;真实 UTF-8 文件名使用 filename*。
|
||||
if (header)
|
||||
headers['content-disposition'] = header.replace('工程', 'project');
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response('PK', { headers })),
|
||||
);
|
||||
expect(
|
||||
(await downloadAdminProjectSnapshot('token', 'user', 'project')).filename,
|
||||
).toBe(expected.replace('工程', 'project'));
|
||||
});
|
||||
|
||||
test.each([401, 403, 409, 500])(
|
||||
'下载 HTTP %s 保留后台错误,不返回 ZIP',
|
||||
async (status) => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
ok: false,
|
||||
error: { code: 'SNAPSHOT_FAILURE', message: '工程尚未同步完成' },
|
||||
}),
|
||||
{
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
downloadAdminProjectSnapshot('token', 'user', 'project'),
|
||||
).rejects.toMatchObject({
|
||||
status,
|
||||
code: 'SNAPSHOT_FAILURE',
|
||||
message: '工程尚未同步完成',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('200 JSON 或 HTML 不能被保存为成功 ZIP', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(
|
||||
new Response('{"ok":false}', {
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
downloadAdminProjectSnapshot('token', 'user', 'project'),
|
||||
).rejects.toMatchObject({ code: 'INVALID_PROJECT_ARCHIVE_RESPONSE' });
|
||||
});
|
||||
@@ -31,6 +31,7 @@ import { AdminInviteCodePage } from '../pages/AdminInviteCodePage';
|
||||
import { AdminLoginPage } from '../pages/AdminLoginPage';
|
||||
import { AdminOverviewPage } from '../pages/AdminOverviewPage';
|
||||
import { AdminProfileWalletConfigPage } from '../pages/AdminProfileWalletConfigPage';
|
||||
import { AdminProjectSnapshotsPage } from '../pages/AdminProjectSnapshotsPage';
|
||||
import { AdminRechargeOrderPage } from '../pages/AdminRechargeOrderPage';
|
||||
import { AdminRechargeProductPage } from '../pages/AdminRechargeProductPage';
|
||||
import { AdminRedeemCodePage } from '../pages/AdminRedeemCodePage';
|
||||
@@ -308,6 +309,12 @@ export function AdminApp() {
|
||||
{activeRouteId === 'accounts' ? (
|
||||
<AdminAccountsPage token={token} onUnauthorized={handleUnauthorized} />
|
||||
) : null}
|
||||
{activeRouteId === 'project-snapshots' ? (
|
||||
<AdminProjectSnapshotsPage
|
||||
token={token}
|
||||
onUnauthorized={handleUnauthorized}
|
||||
/>
|
||||
) : null}
|
||||
</AdminShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Bug,
|
||||
Coins,
|
||||
Database,
|
||||
FolderArchive,
|
||||
GitBranch,
|
||||
Images,
|
||||
LayoutDashboard,
|
||||
@@ -49,6 +50,7 @@ const routeIcons = {
|
||||
'editor-generation-pricing': Coins,
|
||||
'editor-showcase': Star,
|
||||
'editor-assets': Images,
|
||||
'project-snapshots': FolderArchive,
|
||||
accounts: Users,
|
||||
'agc-models': ListChecks,
|
||||
} satisfies Record<AdminRouteId, typeof LayoutDashboard>;
|
||||
|
||||
@@ -122,3 +122,28 @@ test('零权限 member 不回落到 Dashboard', () => {
|
||||
expect(routes).toEqual([]);
|
||||
expect(resolveAccessibleAdminRoute('#dashboard', routes)).toBeNull();
|
||||
});
|
||||
|
||||
test('项目工程入口对 owner 与已授权 member 开放且可分配权限', () => {
|
||||
const route = {
|
||||
id: 'project-snapshots',
|
||||
label: '项目工程',
|
||||
hash: '#project-snapshots',
|
||||
};
|
||||
expect(adminRoutes.filter((item) => !item.ownerOnly)).toContainEqual(route);
|
||||
expect(resolveAdminRoute('#project-snapshots')).toBe('project-snapshots');
|
||||
expect(
|
||||
getAccessibleAdminRoutes({ accountRole: 'owner', tabPermissions: [] }),
|
||||
).toContainEqual(route);
|
||||
expect(
|
||||
getAccessibleAdminRoutes({
|
||||
accountRole: 'member',
|
||||
tabPermissions: ['project-snapshots'],
|
||||
}),
|
||||
).toEqual([route]);
|
||||
expect(
|
||||
getAccessibleAdminRoutes({
|
||||
accountRole: 'member',
|
||||
tabPermissions: ['tracking'],
|
||||
}),
|
||||
).not.toContainEqual(route);
|
||||
});
|
||||
|
||||
@@ -16,6 +16,7 @@ export type AdminRouteId =
|
||||
| 'editor-generation-pricing'
|
||||
| 'editor-showcase'
|
||||
| 'editor-assets'
|
||||
| 'project-snapshots'
|
||||
| 'agc-models'
|
||||
| 'accounts';
|
||||
|
||||
@@ -54,6 +55,7 @@ export const adminRoutes: AdminRouteDefinition[] = [
|
||||
{ id: 'agc-models', label: 'AGC 模型', hash: '#agc-models', ownerOnly: true },
|
||||
{ id: 'editor-showcase', label: '精选审核', hash: '#editor-showcase' },
|
||||
{ id: 'editor-assets', label: '素材查询', hash: '#editor-assets' },
|
||||
{ id: 'project-snapshots', label: '项目工程', hash: '#project-snapshots' },
|
||||
{ id: 'accounts', label: '账号管理', hash: '#accounts', ownerOnly: true },
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
// @vitest-environment jsdom
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
AdminApiError,
|
||||
downloadAdminProjectSnapshot,
|
||||
listAdminProjectSnapshots,
|
||||
} from '../api/adminApiClient';
|
||||
import type { AdminProjectSnapshotEntry } from '../api/adminApiTypes';
|
||||
import { AdminProjectSnapshotsPage } from './AdminProjectSnapshotsPage';
|
||||
|
||||
vi.mock('../api/adminApiClient', async () => ({
|
||||
...(await vi.importActual<typeof import('../api/adminApiClient')>(
|
||||
'../api/adminApiClient',
|
||||
)),
|
||||
downloadAdminProjectSnapshot: vi.fn(),
|
||||
listAdminProjectSnapshots: vi.fn(),
|
||||
}));
|
||||
|
||||
const entry: AdminProjectSnapshotEntry = {
|
||||
userId: 'user-1',
|
||||
projectId: 'project-1',
|
||||
projectName: '三消工程',
|
||||
syncRevision: 3,
|
||||
syncedAtMs: 1_700_000_000_000,
|
||||
fileCount: 12,
|
||||
totalBytes: 2048,
|
||||
status: 'ready',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(listAdminProjectSnapshots)
|
||||
.mockReset()
|
||||
.mockResolvedValue({ items: [entry], nextCursor: null });
|
||||
vi.mocked(downloadAdminProjectSnapshot).mockReset();
|
||||
});
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('按项目展示完整性并限制未完成工程下载', async () => {
|
||||
vi.mocked(listAdminProjectSnapshots).mockResolvedValue({
|
||||
items: [
|
||||
entry,
|
||||
{
|
||||
...entry,
|
||||
projectId: 'partial-project',
|
||||
projectName: '未完成工程',
|
||||
status: 'partial',
|
||||
},
|
||||
{
|
||||
...entry,
|
||||
projectId: 'legacy-project',
|
||||
projectName: null,
|
||||
status: 'unverified',
|
||||
},
|
||||
],
|
||||
nextCursor: null,
|
||||
});
|
||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const completeRow = (await screen.findByText('三消工程')).closest('tr')!;
|
||||
expect(within(completeRow).getByText('2 KiB')).toBeTruthy();
|
||||
expect(
|
||||
within(completeRow)
|
||||
.getByRole('button', { name: '下载完整工程' })
|
||||
.hasAttribute('disabled'),
|
||||
).toBe(false);
|
||||
expect(
|
||||
screen.getByRole('button', { name: '同步未完成' }).hasAttribute('disabled'),
|
||||
).toBe(true);
|
||||
expect(screen.getByText('完整性未知')).toBeTruthy();
|
||||
expect(
|
||||
screen
|
||||
.getByRole('button', { name: '下载已存文件' })
|
||||
.hasAttribute('disabled'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('加载更多合并项目,刷新失败保留列表和错误,重试从首页开始', async () => {
|
||||
vi.mocked(listAdminProjectSnapshots)
|
||||
.mockResolvedValueOnce({ items: [entry], nextCursor: 'page-2' })
|
||||
.mockResolvedValueOnce({
|
||||
items: [{ ...entry, projectId: 'project-2', projectName: '第二工程' }],
|
||||
nextCursor: null,
|
||||
})
|
||||
.mockRejectedValueOnce(new Error('远端清单读取失败'))
|
||||
.mockResolvedValueOnce({ items: [], nextCursor: null });
|
||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
||||
fireEvent.click(await screen.findByRole('button', { name: '加载更多' }));
|
||||
await screen.findByText('第二工程');
|
||||
expect(listAdminProjectSnapshots).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'token',
|
||||
{ cursor: 'page-2', limit: 20 },
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
expect(screen.getByText('三消工程')).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
||||
await screen.findByRole('alert');
|
||||
expect(screen.getByText('第二工程')).toBeTruthy();
|
||||
expect(screen.queryByText('暂无已上传项目')).toBeNull();
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
||||
await screen.findByText('暂无已上传项目');
|
||||
expect(listAdminProjectSnapshots).toHaveBeenLastCalledWith(
|
||||
'token',
|
||||
{ cursor: null, limit: 20 },
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
});
|
||||
|
||||
test('下载使用返回的中文文件名,随后释放对象 URL', async () => {
|
||||
const createObjectURL = vi.fn(() => 'blob:archive');
|
||||
const revokeObjectURL = vi.fn();
|
||||
vi.stubGlobal(
|
||||
'URL',
|
||||
class extends URL {
|
||||
static createObjectURL = createObjectURL;
|
||||
static revokeObjectURL = revokeObjectURL;
|
||||
},
|
||||
);
|
||||
let savedFilename = '';
|
||||
let savedHref = '';
|
||||
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
|
||||
this: HTMLAnchorElement,
|
||||
) {
|
||||
savedFilename = this.download;
|
||||
savedHref = this.href;
|
||||
});
|
||||
const blob = new Blob(['PK'], { type: 'application/zip' });
|
||||
vi.mocked(downloadAdminProjectSnapshot).mockResolvedValue({
|
||||
blob,
|
||||
filename: '三消工程-r3.zip',
|
||||
});
|
||||
render(<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />);
|
||||
const button = await screen.findByRole('button', { name: '下载完整工程' });
|
||||
vi.useFakeTimers();
|
||||
await act(async () => {
|
||||
fireEvent.click(button);
|
||||
});
|
||||
expect(savedFilename).toBe('三消工程-r3.zip');
|
||||
expect(savedHref).toBe('blob:archive');
|
||||
expect(createObjectURL).toHaveBeenCalledWith(blob);
|
||||
expect(downloadAdminProjectSnapshot).toHaveBeenCalledWith(
|
||||
'token',
|
||||
'user-1',
|
||||
'project-1',
|
||||
expect.any(AbortSignal),
|
||||
);
|
||||
act(() => vi.advanceTimersByTime(1000));
|
||||
expect(revokeObjectURL).toHaveBeenCalledWith('blob:archive');
|
||||
});
|
||||
|
||||
test('取消下载中止请求且不显示错误,卸载中止列表请求', async () => {
|
||||
vi.mocked(downloadAdminProjectSnapshot).mockImplementation(
|
||||
(_token, _user, _project, signal) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
signal?.addEventListener('abort', () =>
|
||||
reject(new DOMException('Aborted', 'AbortError')),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const view = render(
|
||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
||||
fireEvent.click(await screen.findByRole('button', { name: '取消下载' }));
|
||||
expect(
|
||||
vi.mocked(downloadAdminProjectSnapshot).mock.calls[0]?.[3]?.aborted,
|
||||
).toBe(true);
|
||||
await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
|
||||
vi.mocked(listAdminProjectSnapshots).mockReturnValue(new Promise(() => {}));
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
||||
const signal = vi.mocked(listAdminProjectSnapshots).mock.calls.at(-1)?.[2];
|
||||
view.unmount();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
test('下载登录失效走现有会话处理,403 错误保留页面', async () => {
|
||||
const onUnauthorized = vi.fn();
|
||||
vi.mocked(downloadAdminProjectSnapshot)
|
||||
.mockRejectedValueOnce(
|
||||
new AdminApiError({ status: 403, message: '无项目工程权限' }),
|
||||
)
|
||||
.mockRejectedValueOnce(
|
||||
new AdminApiError({ status: 401, message: '已过期' }),
|
||||
);
|
||||
render(
|
||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={onUnauthorized} />,
|
||||
);
|
||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
||||
expect(await screen.findByText('无项目工程权限')).toBeTruthy();
|
||||
expect(onUnauthorized).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('button', { name: '下载完整工程' }));
|
||||
await waitFor(() =>
|
||||
expect(onUnauthorized).toHaveBeenCalledWith('登录状态已失效'),
|
||||
);
|
||||
});
|
||||
|
||||
test('首次列表失败显示错误而非空项目,401 失效回到会话处理', async () => {
|
||||
const onUnauthorized = vi.fn();
|
||||
vi.mocked(listAdminProjectSnapshots)
|
||||
.mockRejectedValueOnce(new Error('清单存储不可用'))
|
||||
.mockRejectedValueOnce(
|
||||
new AdminApiError({ status: 401, message: '已过期' }),
|
||||
);
|
||||
render(
|
||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={onUnauthorized} />,
|
||||
);
|
||||
await screen.findByText('清单存储不可用');
|
||||
expect(screen.queryByText('暂无已上传项目')).toBeNull();
|
||||
fireEvent.click(screen.getByRole('button', { name: '刷新' }));
|
||||
await waitFor(() =>
|
||||
expect(onUnauthorized).toHaveBeenCalledWith('登录状态已失效'),
|
||||
);
|
||||
});
|
||||
|
||||
test('更换登录令牌丢弃旧列表和晚返回请求', async () => {
|
||||
let finishOldRequest!: (value: {
|
||||
items: AdminProjectSnapshotEntry[];
|
||||
nextCursor: null;
|
||||
}) => void;
|
||||
vi.mocked(listAdminProjectSnapshots)
|
||||
.mockReturnValueOnce(
|
||||
new Promise((resolve) => {
|
||||
finishOldRequest = resolve;
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce({
|
||||
items: [{ ...entry, projectName: '新账号工程' }],
|
||||
nextCursor: null,
|
||||
});
|
||||
const onUnauthorized = vi.fn();
|
||||
const view = render(
|
||||
<AdminProjectSnapshotsPage
|
||||
token="old-token"
|
||||
onUnauthorized={onUnauthorized}
|
||||
/>,
|
||||
);
|
||||
const oldSignal = vi.mocked(listAdminProjectSnapshots).mock.calls[0]?.[2];
|
||||
view.rerender(
|
||||
<AdminProjectSnapshotsPage
|
||||
token="new-token"
|
||||
onUnauthorized={onUnauthorized}
|
||||
/>,
|
||||
);
|
||||
await screen.findByText('新账号工程');
|
||||
expect(oldSignal?.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
finishOldRequest({ items: [entry], nextCursor: null });
|
||||
});
|
||||
expect(screen.queryByText('三消工程')).toBeNull();
|
||||
expect(screen.getByText('新账号工程')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('卸载后完成的下载不会创建浏览器文件', async () => {
|
||||
let finishDownload!: (value: { blob: Blob; filename: string }) => void;
|
||||
vi.mocked(downloadAdminProjectSnapshot).mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finishDownload = resolve;
|
||||
}),
|
||||
);
|
||||
const click = vi
|
||||
.spyOn(HTMLAnchorElement.prototype, 'click')
|
||||
.mockImplementation(() => {});
|
||||
const view = render(
|
||||
<AdminProjectSnapshotsPage token="token" onUnauthorized={vi.fn()} />,
|
||||
);
|
||||
fireEvent.click(await screen.findByRole('button', { name: '下载完整工程' }));
|
||||
const signal = vi.mocked(downloadAdminProjectSnapshot).mock.calls[0]?.[3];
|
||||
view.unmount();
|
||||
expect(signal?.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
finishDownload({ blob: new Blob(['PK']), filename: 'old.zip' });
|
||||
});
|
||||
expect(click).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import { Download, RefreshCcw, X } from 'lucide-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
import {
|
||||
downloadAdminProjectSnapshot,
|
||||
listAdminProjectSnapshots,
|
||||
} from '../api/adminApiClient';
|
||||
import type { AdminProjectSnapshotEntry } from '../api/adminApiTypes';
|
||||
import { handlePageError } from './pageUtils';
|
||||
|
||||
interface AdminProjectSnapshotsPageProps {
|
||||
token: string;
|
||||
onUnauthorized: (message?: string) => void;
|
||||
}
|
||||
|
||||
const snapshotStatuses = {
|
||||
ready: {
|
||||
label: '已同步',
|
||||
className: 'admin-status-ok',
|
||||
action: '下载完整工程',
|
||||
},
|
||||
partial: {
|
||||
label: '同步未完成',
|
||||
className: 'admin-status-pending',
|
||||
action: '同步未完成',
|
||||
},
|
||||
unverified: {
|
||||
label: '完整性未知',
|
||||
className: 'admin-status-pending',
|
||||
action: '下载已存文件',
|
||||
},
|
||||
};
|
||||
|
||||
export function AdminProjectSnapshotsPage({
|
||||
token,
|
||||
onUnauthorized,
|
||||
}: AdminProjectSnapshotsPageProps) {
|
||||
const [items, setItems] = useState<AdminProjectSnapshotEntry[]>([]);
|
||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [hasLoaded, setHasLoaded] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState('');
|
||||
const [downloadingKey, setDownloadingKey] = useState<string | null>(null);
|
||||
const listController = useRef<AbortController | null>(null);
|
||||
const downloadController = useRef<AbortController | null>(null);
|
||||
|
||||
const loadPage = useCallback(
|
||||
async (cursor: string | null = null) => {
|
||||
listController.current?.abort();
|
||||
const controller = new AbortController();
|
||||
listController.current = controller;
|
||||
setIsLoading(true);
|
||||
setErrorMessage('');
|
||||
try {
|
||||
const response = await listAdminProjectSnapshots(
|
||||
token,
|
||||
{ cursor, limit: 20 },
|
||||
controller.signal,
|
||||
);
|
||||
if (controller.signal.aborted) return;
|
||||
setItems((current) => {
|
||||
if (!cursor) return response.items;
|
||||
const entries = new Map(
|
||||
current.map((entry) => [snapshotKey(entry), entry]),
|
||||
);
|
||||
response.items.forEach((entry) =>
|
||||
entries.set(snapshotKey(entry), entry),
|
||||
);
|
||||
return [...entries.values()];
|
||||
});
|
||||
setNextCursor(response.nextCursor);
|
||||
setHasLoaded(true);
|
||||
} catch (error: unknown) {
|
||||
if (!controller.signal.aborted)
|
||||
handlePageError(error, onUnauthorized, setErrorMessage);
|
||||
} finally {
|
||||
if (listController.current === controller) {
|
||||
listController.current = null;
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[token, onUnauthorized],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setItems([]);
|
||||
setNextCursor(null);
|
||||
setHasLoaded(false);
|
||||
setDownloadingKey(null);
|
||||
void loadPage();
|
||||
return () => {
|
||||
listController.current?.abort();
|
||||
listController.current = null;
|
||||
downloadController.current?.abort();
|
||||
downloadController.current = null;
|
||||
};
|
||||
}, [loadPage]);
|
||||
|
||||
async function downloadProject(entry: AdminProjectSnapshotEntry) {
|
||||
if (downloadController.current || entry.status === 'partial') return;
|
||||
const controller = new AbortController();
|
||||
downloadController.current = controller;
|
||||
setDownloadingKey(snapshotKey(entry));
|
||||
setErrorMessage('');
|
||||
try {
|
||||
const archive = await downloadAdminProjectSnapshot(
|
||||
token,
|
||||
entry.userId,
|
||||
entry.projectId,
|
||||
controller.signal,
|
||||
);
|
||||
if (controller.signal.aborted) return;
|
||||
const objectUrl = URL.createObjectURL(archive.blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = archive.filename;
|
||||
document.body.append(link);
|
||||
try {
|
||||
link.click();
|
||||
} finally {
|
||||
link.remove();
|
||||
// 给浏览器时间接管下载,随后释放临时 URL。
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (!controller.signal.aborted)
|
||||
handlePageError(error, onUnauthorized, setErrorMessage);
|
||||
} finally {
|
||||
if (downloadController.current === controller) {
|
||||
downloadController.current = null;
|
||||
setDownloadingKey(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function cancelDownload() {
|
||||
downloadController.current?.abort();
|
||||
downloadController.current = null;
|
||||
setDownloadingKey(null);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="admin-page admin-page-wide">
|
||||
<div className="admin-page-heading">
|
||||
<h2>项目工程</h2>
|
||||
<button
|
||||
className="admin-secondary-button"
|
||||
disabled={isLoading}
|
||||
type="button"
|
||||
onClick={() => void loadPage()}
|
||||
>
|
||||
<RefreshCcw size={17} aria-hidden="true" />
|
||||
<span>{isLoading ? '加载中' : '刷新'}</span>
|
||||
</button>
|
||||
</div>
|
||||
{errorMessage ? (
|
||||
<div className="admin-alert" role="alert">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
<section
|
||||
className="admin-panel admin-stack"
|
||||
aria-label="项目工程列表"
|
||||
aria-busy={isLoading}
|
||||
>
|
||||
<div className="admin-table-wrap">
|
||||
<table className="admin-table admin-project-snapshot-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>项目</th>
|
||||
<th>用户 ID</th>
|
||||
<th>同步时间</th>
|
||||
<th>文件数</th>
|
||||
<th>体积</th>
|
||||
<th>完整性</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{items.map((entry) => {
|
||||
const status = snapshotStatuses[entry.status];
|
||||
const isDownloading = downloadingKey === snapshotKey(entry);
|
||||
return (
|
||||
<tr key={snapshotKey(entry)}>
|
||||
<td data-label="项目">
|
||||
<strong>{entry.projectName || entry.projectId}</strong>
|
||||
<small>{entry.projectId}</small>
|
||||
</td>
|
||||
<td data-label="用户 ID">{entry.userId}</td>
|
||||
<td data-label="同步时间">
|
||||
<span>
|
||||
{new Date(entry.syncedAtMs).toLocaleString('zh-CN', {
|
||||
hour12: false,
|
||||
})}
|
||||
<small>版本 {entry.syncRevision}</small>
|
||||
</span>
|
||||
</td>
|
||||
<td data-label="文件数">
|
||||
{entry.fileCount.toLocaleString('zh-CN')}
|
||||
</td>
|
||||
<td data-label="体积">{formatBytes(entry.totalBytes)}</td>
|
||||
<td data-label="完整性">
|
||||
<span className={`admin-status ${status.className}`}>
|
||||
{status.label}
|
||||
</span>
|
||||
</td>
|
||||
<td data-label="操作">
|
||||
{isDownloading ? (
|
||||
<button
|
||||
className="admin-secondary-button"
|
||||
type="button"
|
||||
onClick={cancelDownload}
|
||||
>
|
||||
<X size={16} aria-hidden="true" />
|
||||
<span>取消下载</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="admin-secondary-button"
|
||||
disabled={
|
||||
entry.status === 'partial' ||
|
||||
downloadingKey !== null
|
||||
}
|
||||
type="button"
|
||||
onClick={() => void downloadProject(entry)}
|
||||
>
|
||||
<Download size={16} aria-hidden="true" />
|
||||
<span>{status.action}</span>
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{hasLoaded && items.length === 0 && !errorMessage ? (
|
||||
<p className="admin-muted-text">暂无已上传项目</p>
|
||||
) : null}
|
||||
{nextCursor ? (
|
||||
<div className="admin-action-row">
|
||||
<button
|
||||
className="admin-secondary-button"
|
||||
disabled={isLoading}
|
||||
type="button"
|
||||
onClick={() => void loadPage(nextCursor)}
|
||||
>
|
||||
{isLoading ? '加载中' : '加载更多'}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function snapshotKey(entry: AdminProjectSnapshotEntry) {
|
||||
return `${entry.userId}/${entry.projectId}`;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number) {
|
||||
const units = ['B', 'KiB', 'MiB', 'GiB'];
|
||||
const unit = Math.min(
|
||||
Math.floor(Math.log2(Math.max(1, bytes)) / 10),
|
||||
units.length - 1,
|
||||
);
|
||||
return `${(bytes / 1024 ** unit).toLocaleString('zh-CN', { maximumFractionDigits: 1 })} ${units[unit]}`;
|
||||
}
|
||||
@@ -1452,6 +1452,112 @@ button:disabled {
|
||||
min-width: 1180px;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table {
|
||||
min-width: 0;
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th,
|
||||
.admin-project-snapshot-table td {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:first-child {
|
||||
width: 20%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:nth-child(2) {
|
||||
width: 14%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:nth-child(3) {
|
||||
width: 18%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:nth-child(4) {
|
||||
width: 7%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:nth-child(5) {
|
||||
width: 9%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:nth-child(6) {
|
||||
width: 12%;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table th:last-child {
|
||||
width: 20%;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.admin-project-snapshot-table,
|
||||
.admin-project-snapshot-table tbody {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table thead {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table tr {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 10px 16px;
|
||||
border-bottom: 1px solid #eaded2;
|
||||
padding: 18px 0;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table tr:first-child {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table tr:last-child {
|
||||
border-bottom: 0;
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td::before {
|
||||
flex-shrink: 0;
|
||||
color: #8f7868;
|
||||
font-size: 12px;
|
||||
content: attr(data-label);
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td:first-child,
|
||||
.admin-project-snapshot-table td:nth-child(2),
|
||||
.admin-project-snapshot-table td:nth-child(3),
|
||||
.admin-project-snapshot-table td:nth-child(6),
|
||||
.admin-project-snapshot-table td:last-child {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td:first-child {
|
||||
display: block;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td:first-child::before,
|
||||
.admin-project-snapshot-table td:last-child::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.admin-project-snapshot-table td:last-child button {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.admin-recharge-table {
|
||||
min-width: 1080px;
|
||||
table-layout: fixed;
|
||||
|
||||
@@ -676,11 +676,11 @@ async function runSelfTest() {
|
||||
designFoundationAssetCall?.arguments?.input?.outputPath ===
|
||||
'assets/ui-prototype.png' &&
|
||||
designFoundationAssetCall.arguments.input.aspectRatio === '16:9' &&
|
||||
designFoundationAssetCall.arguments.input.assetKind === 'ui-prototype' &&
|
||||
designFoundationAssetCall.arguments.input.assetKind === 'ui-design' &&
|
||||
artAssetPlanAssetCall?.arguments?.input?.outputPath ===
|
||||
'assets/art-spritesheet.png' &&
|
||||
artAssetPlanAssetCall.arguments.input.aspectRatio === '1:1' &&
|
||||
artAssetPlanAssetCall.arguments.input.assetKind === 'art-spritesheet',
|
||||
artAssetPlanAssetCall.arguments.input.assetKind === 'icon-spritesheet',
|
||||
'self-test-visual-assets-invalid',
|
||||
);
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ const requiredFormalArtifactSpecs = [
|
||||
{ path: 'game/balance.json', kind: 'json' },
|
||||
{ path: 'assets/manifest.art.json', kind: 'json' },
|
||||
{ path: 'assets/manifest.audio.json', kind: 'json' },
|
||||
{ path: 'game/index.html', kind: 'game-entry' },
|
||||
{ path: 'game/index.html', kind: 'file' },
|
||||
{ path: 'exports/README.md', kind: 'file' },
|
||||
];
|
||||
const editorImageArtifactSpecs = [
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { resolveReleaseContext, runTauriBuild } from './build-release.mjs';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
assert.equal(process.platform, 'darwin', '只能在 macOS Agent 执行');
|
||||
assert.equal(
|
||||
process.env.JENKINS_URL?.length > 0,
|
||||
true,
|
||||
'此入口仅用于 Jenkins 独立工作区',
|
||||
);
|
||||
assert.equal(
|
||||
fs.realpathSync(process.env.WORKSPACE || '.'),
|
||||
fs.realpathSync(repoRoot),
|
||||
'必须在 Jenkins workspace 根目录执行',
|
||||
);
|
||||
const space = fs.statfsSync(repoRoot);
|
||||
assert.ok(
|
||||
space.bavail * space.bsize >= 8 * 1024 ** 3,
|
||||
'构建前至少需要 8 GiB 可用空间;禁止自动清理开发缓存',
|
||||
);
|
||||
|
||||
// 本入口永不发布,不使用 Agent 用户可能持有的发布或 Apple 认证环境。
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (/^(TAURI_SIGNING_|APPLE_|AGC_OSS_)/u.test(key)) delete process.env[key];
|
||||
}
|
||||
process.env.RUSTC_WRAPPER = '';
|
||||
process.env.CARGO_TARGET_DIR = path.join(appRoot, 'src-tauri/target');
|
||||
const context = resolveReleaseContext(['--target=universal-apple-darwin']);
|
||||
const args = [
|
||||
'--target=universal-apple-darwin',
|
||||
'--bundles',
|
||||
'app',
|
||||
'--ci',
|
||||
'--no-sign',
|
||||
'--config',
|
||||
'{"bundle":{"createUpdaterArtifacts":false}}',
|
||||
];
|
||||
const command = (binary, argv, options = {}) =>
|
||||
execFileSync(binary, argv, { cwd: repoRoot, stdio: 'inherit', ...options });
|
||||
runTauriBuild(args, context);
|
||||
const app = path.join(context.bundleRoot, 'macos/陶泥儿.app');
|
||||
for (const architecture of ['arm64', 'x86_64']) {
|
||||
command(process.execPath, [
|
||||
path.join(appRoot, 'scripts/check-macos-bundle.mjs'),
|
||||
app,
|
||||
architecture,
|
||||
'--universal',
|
||||
]);
|
||||
}
|
||||
const version = JSON.parse(
|
||||
fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
|
||||
).version;
|
||||
assert.match(version, /^\d+\.\d+\.\d+$/u);
|
||||
const artifacts = path.join(repoRoot, 'artifacts');
|
||||
// 只清理本 Job 的归档输出,不能把上次 DMG 当成本次成功产物。
|
||||
fs.rmSync(artifacts, { recursive: true, force: true });
|
||||
fs.mkdirSync(artifacts, { recursive: true });
|
||||
const dmg = path.join(artifacts, `陶泥儿_${version}_universal.dmg`);
|
||||
const stage = fs.mkdtempSync(path.join(os.tmpdir(), 'agc-ci-dmg-'));
|
||||
try {
|
||||
command('ditto', [app, path.join(stage, '陶泥儿.app')]);
|
||||
fs.symlinkSync('/Applications', path.join(stage, 'Applications'));
|
||||
command('hdiutil', [
|
||||
'create',
|
||||
'-volname',
|
||||
'陶泥儿',
|
||||
'-srcfolder',
|
||||
stage,
|
||||
'-format',
|
||||
'UDZO',
|
||||
dmg,
|
||||
]);
|
||||
command('hdiutil', ['verify', dmg]);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
const hash = createHash('sha256');
|
||||
for await (const chunk of fs.createReadStream(dmg)) hash.update(chunk);
|
||||
fs.writeFileSync(
|
||||
`${dmg}.sha256`,
|
||||
`${hash.digest('hex')} ${path.basename(dmg)}\n`,
|
||||
);
|
||||
const commit = execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
}).trim();
|
||||
fs.writeFileSync(
|
||||
path.join(artifacts, 'build-manifest.json'),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
version,
|
||||
commit,
|
||||
target: context.target,
|
||||
channel: context.channel,
|
||||
signed: false,
|
||||
notarized: false,
|
||||
uploaded: false,
|
||||
smoke: ['arm64', 'x86_64'],
|
||||
intelSmoke: process.arch === 'arm64' ? 'Rosetta' : 'native',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
console.log('[macOS CI] universal 包与校验文件已生成;未发布、未签名或公证');
|
||||
@@ -42,12 +42,16 @@ function explicitBuildTarget(args) {
|
||||
}
|
||||
|
||||
function validateReleaseTarget(target) {
|
||||
if (target === 'universal-apple-darwin') {
|
||||
throw new Error(
|
||||
'内置 Codex 资源仅支持 macOS 单架构构建,请使用 aarch64-apple-darwin 或 x86_64-apple-darwin',
|
||||
);
|
||||
}
|
||||
if (
|
||||
![
|
||||
'x86_64-pc-windows-msvc',
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
'universal-apple-darwin',
|
||||
].includes(target)
|
||||
) {
|
||||
throw new Error(`不支持的发布目标:${target}`);
|
||||
@@ -101,6 +105,8 @@ export const agcReleasePathPatterns = [
|
||||
'packages/',
|
||||
'server-rs/crates/',
|
||||
'plugins/agc-cocos-editor/',
|
||||
'plugins/agc-unity-editor/',
|
||||
'plugins/agc-godot-editor/',
|
||||
'apps/desktop-shell/src-tauri/icons/',
|
||||
'package.json',
|
||||
'package-lock.json',
|
||||
@@ -193,12 +199,10 @@ export function updateManifestUrl(channel = resolveReleaseChannel()) {
|
||||
}
|
||||
|
||||
/**
|
||||
* universal 主程序与双目录原生资源共用一个更新包;单架构只登记实际目标。
|
||||
* 单架构产物只登记实际目标,不能把同一原生资源映射为另一架构。
|
||||
*/
|
||||
export function resolveManifestPlatformKeys(target = defaultTarget()) {
|
||||
validateReleaseTarget(target);
|
||||
if (target === 'universal-apple-darwin')
|
||||
return ['darwin-aarch64', 'darwin-x86_64'];
|
||||
if (target === 'aarch64-apple-darwin') return ['darwin-aarch64'];
|
||||
if (target === 'x86_64-apple-darwin') return ['darwin-x86_64'];
|
||||
if (target.includes('windows')) {
|
||||
@@ -498,6 +502,41 @@ export function selectReleaseArtifact(files, target = defaultTarget()) {
|
||||
);
|
||||
}
|
||||
|
||||
export function selectFirstInstallArtifact(
|
||||
files,
|
||||
{ target, version, artifact },
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
let selected;
|
||||
if (target.includes('windows')) {
|
||||
selected = artifact;
|
||||
if (!selected?.endsWith('.exe')) {
|
||||
throw new Error('Windows 首装包必须复用本次 NSIS .exe 更新包');
|
||||
}
|
||||
} else {
|
||||
// Tauri DMG 文件名使用 aarch64 / x64,而 updater 的 Intel 平台键是 x86_64。
|
||||
const architecture = target.startsWith('aarch64') ? 'aarch64' : 'x64';
|
||||
const suffix = `_${version}_${architecture}.dmg`;
|
||||
const candidates = files.filter((file) =>
|
||||
path.basename(file).endsWith(suffix),
|
||||
);
|
||||
if (candidates.length !== 1) {
|
||||
throw new Error(
|
||||
`首装 DMG 必须唯一匹配本次版本 ${version} 和架构 ${architecture},找到 ${candidates.length} 个`,
|
||||
);
|
||||
}
|
||||
selected = candidates[0];
|
||||
}
|
||||
if (
|
||||
!fs.existsSync(selected) ||
|
||||
!fs.statSync(selected).isFile() ||
|
||||
fs.statSync(selected).size === 0
|
||||
) {
|
||||
throw new Error(`首装包不存在或为空:${selected}`);
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
function readUpdaterSignature(artifactPath) {
|
||||
const signaturePath = `${artifactPath}.sig`;
|
||||
if (!fs.existsSync(signaturePath)) {
|
||||
@@ -518,23 +557,32 @@ export function createUpdateManifest(
|
||||
publishedAt = new Date().toISOString(),
|
||||
notes = readReleaseNotes(),
|
||||
commit = readHeadCommit(),
|
||||
downloadArtifact,
|
||||
} = {},
|
||||
) {
|
||||
validateReleaseTarget(target);
|
||||
resolveReleaseChannel({ AGC_UPDATE_CHANNEL: channel }, target);
|
||||
const signature = readUpdaterSignature(artifactPath);
|
||||
const version = readPackageJson().version;
|
||||
const firstInstallArtifact = selectFirstInstallArtifact(
|
||||
downloadArtifact ? [downloadArtifact] : [],
|
||||
{ target, version, artifact: artifactPath },
|
||||
);
|
||||
const fileName = path.basename(artifactPath);
|
||||
const url = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(fileName)}`;
|
||||
const downloadUrl = `${ossBaseUrl()}/${channel}/${encodeURIComponent(version)}/${encodeURIComponent(path.basename(firstInstallArtifact))}`;
|
||||
const platforms = {};
|
||||
const downloads = {};
|
||||
for (const key of resolveManifestPlatformKeys(target)) {
|
||||
platforms[key] = { signature, url };
|
||||
downloads[key] = { url: downloadUrl };
|
||||
}
|
||||
return {
|
||||
version,
|
||||
...(notes ? { notes } : {}),
|
||||
pub_date: publishedAt,
|
||||
platforms,
|
||||
downloads,
|
||||
// 非标准字段:更新插件会忽略,发布脚本用它定位下一次自动更新摘要的起点。
|
||||
...(commit ? { commit } : {}),
|
||||
};
|
||||
@@ -673,10 +721,16 @@ export async function generateUpdateManifest(
|
||||
context = resolveReleaseContext(),
|
||||
) {
|
||||
const { channel, target, bundleRoot } = context;
|
||||
const artifact = selectReleaseArtifact(listFiles(bundleRoot), target);
|
||||
const files = listFiles(bundleRoot);
|
||||
const artifact = selectReleaseArtifact(files, target);
|
||||
if (!artifact) {
|
||||
throw new Error(`未找到可发布的 AGC 安装包:${bundleRoot}`);
|
||||
}
|
||||
const downloadArtifact = selectFirstInstallArtifact(files, {
|
||||
target,
|
||||
version: readPackageJson().version,
|
||||
artifact,
|
||||
});
|
||||
const manualNotes = readReleaseNotes();
|
||||
const previousCommit = await resolvePreviousReleaseCommit(channel);
|
||||
const commits = collectReleaseCommits(previousCommit);
|
||||
@@ -690,7 +744,12 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 未生成自动更新摘要(上一发布 commit=${previousCommit ?? '未知'},客户端相关提交=${commits ? commits.length : '不可判定'},最近提交=${recentCommits ? recentCommits.length : '不可判定'})`,
|
||||
);
|
||||
}
|
||||
const manifest = createUpdateManifest(artifact, { channel, target, notes });
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
channel,
|
||||
target,
|
||||
notes,
|
||||
downloadArtifact,
|
||||
});
|
||||
const manifestPath = path.join(bundleRoot, 'latest.json');
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
const notesPath = path.join(bundleRoot, 'release-notes.txt');
|
||||
@@ -715,6 +774,7 @@ export async function generateUpdateManifest(
|
||||
`[ai-game-creator-shell] 渠道 ${channel}:已生成 ${manifestPath}`,
|
||||
);
|
||||
console.log(`[ai-game-creator-shell] 安装包:${artifact}`);
|
||||
console.log(`[ai-game-creator-shell] 首装包:${downloadArtifact}`);
|
||||
console.log(
|
||||
manualNotes
|
||||
? '[ai-game-creator-shell] 更新摘要:使用 AGC_UPDATE_RELEASE_NOTES 手动文案'
|
||||
@@ -731,6 +791,7 @@ export async function generateUpdateManifest(
|
||||
return {
|
||||
channel,
|
||||
artifact,
|
||||
downloadArtifact,
|
||||
manifest,
|
||||
manifestPath,
|
||||
notes,
|
||||
|
||||
@@ -32,19 +32,31 @@ import {
|
||||
resolveReleaseContext,
|
||||
resolveRemoteHighWaterVersion,
|
||||
runTauriBuild,
|
||||
selectFirstInstallArtifact,
|
||||
selectReleaseArtifact,
|
||||
updateManifestUrl,
|
||||
} from './build-release.mjs';
|
||||
|
||||
const windowsTarget = 'x86_64-pc-windows-msvc';
|
||||
const universalTarget = 'universal-apple-darwin';
|
||||
const packageVersion = JSON.parse(
|
||||
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
|
||||
).version;
|
||||
|
||||
test('native sidecar builds accept universal and each macOS architecture', () => {
|
||||
for (const target of [
|
||||
universalTarget,
|
||||
'aarch64-apple-darwin',
|
||||
'x86_64-apple-darwin',
|
||||
]) {
|
||||
function createDmgFixture(root, target, version = packageVersion) {
|
||||
const architecture = target.startsWith('aarch64') ? 'aarch64' : 'x64';
|
||||
const dmg = path.join(root, `陶泥儿_${version}_${architecture}.dmg`);
|
||||
writeFileSync(dmg, 'first installation disk image');
|
||||
return dmg;
|
||||
}
|
||||
|
||||
test('native sidecar builds reject universal targets and accept each macOS architecture', () => {
|
||||
assert.throws(() => buildTauriBuildArguments([], universalTarget), /单架构/);
|
||||
assert.throws(
|
||||
() => buildTauriBuildArguments(['--target=universal-apple-darwin']),
|
||||
/单架构/,
|
||||
);
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
assert.deepEqual(buildTauriBuildArguments([], target), [
|
||||
'build',
|
||||
'--target',
|
||||
@@ -151,11 +163,8 @@ test('channel manifest URL and build-time endpoint follow the channel', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('macOS manifests advertise exactly the architectures actually built', () => {
|
||||
assert.deepEqual(resolveManifestPlatformKeys(universalTarget), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
test('macOS manifests only advertise the architecture actually built', () => {
|
||||
assert.throws(() => resolveManifestPlatformKeys(universalTarget), /单架构/);
|
||||
assert.deepEqual(resolveManifestPlatformKeys('aarch64-apple-darwin'), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -199,6 +208,7 @@ test('release context resolves explicit targets before environment/default and f
|
||||
['--target='],
|
||||
['--target', '--no-bundle'],
|
||||
['--target', windowsTarget, '--target=aarch64-apple-darwin'],
|
||||
['--target', universalTarget],
|
||||
['--target', 'unknown'],
|
||||
])
|
||||
assert.throws(() => resolveReleaseContext(args, {}));
|
||||
@@ -255,7 +265,13 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
),
|
||||
artifact,
|
||||
);
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
const manifest = createUpdateManifest(artifact, {
|
||||
...context,
|
||||
downloadArtifact: createDmgFixture(
|
||||
path.dirname(artifact),
|
||||
context.target,
|
||||
),
|
||||
});
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
]);
|
||||
@@ -273,29 +289,118 @@ test('explicit macOS target drives version lookup, Tauri endpoint, artifact and
|
||||
assert.ok(seenContexts.every((context) => context === seenContexts[0]));
|
||||
});
|
||||
|
||||
test('real manifest writer uses the resolved bundle root and does not emit Windows artifacts', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
for (const target of ['aarch64-apple-darwin', 'x86_64-apple-darwin']) {
|
||||
test(`real manifest writer publishes the ${target} updater and first installer separately`, async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-mac-manifest-'));
|
||||
try {
|
||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||
writeFileSync(artifact, 'mac package');
|
||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||
const downloadArtifact = createDmgFixture(root, target);
|
||||
const context = {
|
||||
...resolveReleaseContext([`--target=${target}`], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
() => generateUpdateManifest(context),
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
assert.equal(result.downloadArtifact, downloadArtifact);
|
||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
const key = target.startsWith('aarch64')
|
||||
? 'darwin-aarch64'
|
||||
: 'darwin-x86_64';
|
||||
assert.deepEqual(Object.keys(result.manifest.platforms), [key]);
|
||||
assert.deepEqual(Object.keys(result.manifest.downloads), [key]);
|
||||
assert.match(
|
||||
result.manifest.platforms[key].url,
|
||||
/\/dev-mac\/.*\.app\.tar\.gz$/,
|
||||
);
|
||||
assert.equal(
|
||||
decodeURIComponent(
|
||||
new URL(result.manifest.downloads[key].url).pathname,
|
||||
),
|
||||
`/agc/dev-mac/${packageVersion}/${path.basename(downloadArtifact)}`,
|
||||
);
|
||||
assert.deepEqual(
|
||||
JSON.parse(readFileSync(result.manifestPath, 'utf8')),
|
||||
result.manifest,
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('DMG selection ignores other versions and architectures but rejects missing, empty and ambiguous current packages', () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-dmg-selection-'));
|
||||
try {
|
||||
const target = 'aarch64-apple-darwin';
|
||||
const options = {
|
||||
target,
|
||||
version: '2.3.4',
|
||||
artifact: path.join(root, '陶泥儿.app.tar.gz'),
|
||||
};
|
||||
const oldVersion = createDmgFixture(root, target, '2.3.3');
|
||||
const wrongArchitecture = createDmgFixture(
|
||||
root,
|
||||
'x86_64-apple-darwin',
|
||||
'2.3.4',
|
||||
);
|
||||
assert.throws(() => selectFirstInstallArtifact([], options), /找到 0 个/u);
|
||||
assert.throws(
|
||||
() =>
|
||||
selectFirstInstallArtifact([oldVersion, wrongArchitecture], options),
|
||||
/找到 0 个/u,
|
||||
);
|
||||
const current = createDmgFixture(root, target, '2.3.4');
|
||||
assert.equal(
|
||||
selectFirstInstallArtifact(
|
||||
[oldVersion, wrongArchitecture, current],
|
||||
options,
|
||||
),
|
||||
current,
|
||||
);
|
||||
writeFileSync(current, '');
|
||||
assert.throws(
|
||||
() => selectFirstInstallArtifact([current], options),
|
||||
/不存在或为空/u,
|
||||
);
|
||||
writeFileSync(current, 'valid dmg');
|
||||
const second = path.join(root, '另一包_2.3.4_aarch64.dmg');
|
||||
writeFileSync(second, 'ambiguous dmg');
|
||||
assert.throws(
|
||||
() => selectFirstInstallArtifact([current, second], options),
|
||||
/找到 2 个/u,
|
||||
);
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('manifest writer refuses to create latest when the current Mac DMG is missing', async () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'agc-missing-dmg-'));
|
||||
try {
|
||||
const artifact = path.join(root, '陶泥儿.app.tar.gz');
|
||||
writeFileSync(artifact, 'mac package');
|
||||
writeFileSync(`${artifact}.sig`, 'mac signature');
|
||||
writeFileSync(path.join(root, 'windows.exe'), 'wrong platform');
|
||||
writeFileSync(artifact, 'updater archive');
|
||||
writeFileSync(`${artifact}.sig`, 'signature');
|
||||
const context = {
|
||||
...resolveReleaseContext(['--target=x86_64-apple-darwin'], {}),
|
||||
...resolveReleaseContext(['--target=aarch64-apple-darwin'], {}),
|
||||
bundleRoot: root,
|
||||
};
|
||||
const result = await withStubbedFetch(
|
||||
(url) => {
|
||||
assert.match(url, /\/dev-mac\/latest\.json$/);
|
||||
return jsonResponse({}, 404);
|
||||
},
|
||||
await assert.rejects(
|
||||
() => generateUpdateManifest(context),
|
||||
/首装 DMG 必须唯一匹配/u,
|
||||
);
|
||||
assert.equal(result.artifact, artifact);
|
||||
assert.equal(result.manifestPath, path.join(root, 'latest.json'));
|
||||
assert.equal(result.legacyManifestPath, null);
|
||||
assert.deepEqual(Object.keys(result.manifest.platforms), ['darwin-x86_64']);
|
||||
assert.match(result.manifest.platforms['darwin-x86_64'].url, /\/dev-mac\//);
|
||||
assert.throws(() => readFileSync(path.join(root, 'latest.json')), {
|
||||
code: 'ENOENT',
|
||||
});
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
@@ -315,8 +420,8 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
},
|
||||
};
|
||||
await assert.rejects(
|
||||
() => buildRelease(['--target', 'unknown'], sideEffects),
|
||||
/不支持的发布目标/,
|
||||
() => buildRelease(['--target', universalTarget], sideEffects),
|
||||
/单架构/,
|
||||
);
|
||||
await withEnv({ AGC_UPDATE_CHANNEL: 'dev-win' }, () =>
|
||||
assert.rejects(
|
||||
@@ -327,26 +432,6 @@ test('invalid target or mismatched channel fails before any release side effect'
|
||||
assert.equal(touched, false);
|
||||
});
|
||||
|
||||
test('universal uses the Mac channel and the same signed artifact for both architectures', () => {
|
||||
const context = resolveReleaseContext(['--target', universalTarget], {
|
||||
AGC_BUILD_TARGET: windowsTarget,
|
||||
});
|
||||
assert.equal(context.channel, 'dev-mac');
|
||||
assert.ok(context.bundleRoot.includes(universalTarget));
|
||||
withSignedArtifact('陶泥儿.app.tar.gz', (artifact) => {
|
||||
const manifest = createUpdateManifest(artifact, context);
|
||||
assert.deepEqual(Object.keys(manifest.platforms), [
|
||||
'darwin-aarch64',
|
||||
'darwin-x86_64',
|
||||
]);
|
||||
assert.deepEqual(
|
||||
manifest.platforms['darwin-aarch64'],
|
||||
manifest.platforms['darwin-x86_64'],
|
||||
);
|
||||
assert.match(manifest.platforms['darwin-aarch64'].url, /\/dev-mac\//);
|
||||
});
|
||||
});
|
||||
|
||||
test('Windows remains the default and explicit Windows overrides macOS environment', () => {
|
||||
const files = ['/tmp/mac.app.tar.gz', '/tmp/windows.exe', '/tmp/mac.dmg'];
|
||||
for (const context of [
|
||||
@@ -365,7 +450,11 @@ test('Windows remains the default and explicit Windows overrides macOS environme
|
||||
context,
|
||||
{
|
||||
spawn: (_binary, command) => {
|
||||
assert.ok(command.includes('--features=cocos-editor-execute'));
|
||||
assert.ok(
|
||||
command.includes(
|
||||
'--features=cocos-editor-execute,unity-editor-execute,godot-editor-execute',
|
||||
),
|
||||
);
|
||||
assert.ok(command.includes('user-config.json'));
|
||||
const configIndex = command.lastIndexOf('--config');
|
||||
const config = JSON.parse(
|
||||
@@ -410,6 +499,9 @@ test('channel manifest carries version, platform keys and signature', () => {
|
||||
assert.equal(manifest.notes, '修复与改进');
|
||||
assert.equal(manifest.pub_date, '2026-09-17T00:00:00.000Z');
|
||||
assert.deepEqual(Object.keys(manifest.platforms), ['windows-x86_64']);
|
||||
assert.deepEqual(manifest.downloads, {
|
||||
'windows-x86_64': { url: manifest.platforms['windows-x86_64'].url },
|
||||
});
|
||||
assert.equal(
|
||||
manifest.platforms['windows-x86_64'].signature,
|
||||
'signature-content',
|
||||
@@ -590,18 +682,18 @@ test('recent commit fallback marks that entries may repeat the previous release'
|
||||
}
|
||||
});
|
||||
|
||||
test('release upload forces overwrite for artifact, signature and channel pointers', () => {
|
||||
test('release entry forwards the built artifacts and dry-run mode to the uploader', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.equal(
|
||||
(source.match(/runOssutil\(\[\s*'cp',\s*'--force'/gu) ?? []).length,
|
||||
4,
|
||||
assert.match(
|
||||
source,
|
||||
/const release = await buildRelease\(process\.argv\.slice\(2\)\)/u,
|
||||
);
|
||||
assert.match(source, /agc\/\$\{channel\}\/latest\.json/u);
|
||||
assert.match(source, /agc\/latest\.json/u);
|
||||
assert.match(source, /await buildRelease\(process\.argv\.slice\(2\)\)/u);
|
||||
assert.match(source, /uploadReleaseArtifacts\(release, \{/u);
|
||||
assert.match(source, /const dryRun = readReleaseDryRun\(\);/u);
|
||||
assert.ok(source.includes('\n dryRun,\n'));
|
||||
});
|
||||
|
||||
test('release notes list client commits with short sha and bound their size', () => {
|
||||
|
||||
@@ -19,6 +19,6 @@ export function withDefaultCargoFeatures(argv, features) {
|
||||
|
||||
export function defaultEditorFeatures(target) {
|
||||
return target === 'win32' || target.includes('windows')
|
||||
? ['cocos-editor-execute']
|
||||
? ['cocos-editor-execute', 'unity-editor-execute', 'godot-editor-execute']
|
||||
: [];
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ test('Windows release includes the same editor feature as development', () => {
|
||||
buildTauriBuildArguments([], 'x86_64-pc-windows-msvc', 'win32'),
|
||||
[
|
||||
'build',
|
||||
'--features=cocos-editor-execute',
|
||||
'--features=cocos-editor-execute,unity-editor-execute,godot-editor-execute',
|
||||
'--target',
|
||||
'x86_64-pc-windows-msvc',
|
||||
],
|
||||
|
||||
@@ -127,8 +127,7 @@ const allowedUncalledTauriCommands = [
|
||||
'open_game_creator_launcher_window',
|
||||
'open_game_creator_workspace_window',
|
||||
'read_direct_project_conversation',
|
||||
// 项目定时快照上传只在 Rust 侧触发(周期定时器 / 工作区窗口关闭)与排障调用;
|
||||
// 按产品口径不做客户端可见界面,因此同 `open_game_creator_*_window` 一样按 native-only 登记。
|
||||
// 前端登记工程生命周期,上传由 Rust 调度;以下两个命令仅供本机排障。
|
||||
'read_local_project_snapshot_state',
|
||||
'sync_local_project_snapshot',
|
||||
'reset_design_agent_session',
|
||||
@@ -143,7 +142,6 @@ const allowedUncalledTauriCommands = [
|
||||
'reload_agc_plugin',
|
||||
'call_agc_plugin',
|
||||
'read_agc_plugin_panel',
|
||||
'set_agc_plugin_project_path',
|
||||
'set_agc_plugin_enabled',
|
||||
];
|
||||
const sourceExtensions = new Set([
|
||||
@@ -1367,20 +1365,18 @@ if (windowsTauriConfig.bundle?.useLocalToolsDir !== true) {
|
||||
assert.deepEqual(
|
||||
macosTauriConfig.bundle?.resources,
|
||||
Object.fromEntries([
|
||||
...['darwin-arm64', 'darwin-x64'].flatMap((arch) =>
|
||||
[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${arch}/${file}`,
|
||||
`coding-agent/mac-native/${arch}/${file}`,
|
||||
]),
|
||||
),
|
||||
...[
|
||||
'bin/codex',
|
||||
'bin/codex-code-mode-host',
|
||||
'codex-path/rg',
|
||||
'codex-resources/zsh/bin/zsh',
|
||||
'codex-package.json',
|
||||
'NOTICE.md',
|
||||
'manifest.json',
|
||||
].map((file) => [
|
||||
`resources/codex/mac-native/${file}`,
|
||||
`coding-agent/mac-native/${file}`,
|
||||
]),
|
||||
['resources/plugins', 'plugins'],
|
||||
]),
|
||||
'macOS must bundle the complete native Codex layout and plugin workspace',
|
||||
|
||||
@@ -8,13 +8,6 @@ import path from 'node:path';
|
||||
// 只操作临时复制品;不启动 GUI、不读取开发机凭据、不访问 Provider。
|
||||
assert.equal(process.platform, 'darwin', '此验证必须在 macOS 执行');
|
||||
const source = path.resolve(process.argv[2] || '');
|
||||
const architecture =
|
||||
process.argv[3] || (process.arch === 'arm64' ? 'arm64' : 'x86_64');
|
||||
assert.ok(
|
||||
['arm64', 'x86_64'].includes(architecture),
|
||||
'架构只接受 arm64 / x86_64',
|
||||
);
|
||||
const requireUniversal = process.argv.includes('--universal');
|
||||
assert.ok(
|
||||
source.endsWith('.app') && fs.statSync(source).isDirectory(),
|
||||
'请传入 .app 绝对路径',
|
||||
@@ -38,19 +31,13 @@ const env = {
|
||||
};
|
||||
|
||||
function run(command, args) {
|
||||
// 只强制被测应用切片;本机 Xcode 检查工具可能仅提供宿主架构。
|
||||
const useSlice = command.startsWith(`${app}${path.sep}`);
|
||||
const result = spawnSync(
|
||||
useSlice ? '/usr/bin/arch' : command,
|
||||
useSlice ? [`-${architecture}`, command, ...args] : args,
|
||||
{
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 120_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
},
|
||||
);
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
maxBuffer: 1024 * 1024,
|
||||
});
|
||||
assert.ifError(result.error);
|
||||
return result;
|
||||
}
|
||||
@@ -73,7 +60,7 @@ async function handshake(executable) {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error('app-server 初始化超时')),
|
||||
120_000,
|
||||
15_000,
|
||||
);
|
||||
const finish = (error) => {
|
||||
clearTimeout(timer);
|
||||
@@ -142,39 +129,20 @@ async function handshake(executable) {
|
||||
try {
|
||||
fs.cpSync(source, app, { recursive: true });
|
||||
const resources = path.join(app, 'Contents/Resources');
|
||||
const platform = architecture === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native', platform);
|
||||
const bundle = path.join(resources, 'coding-agent/mac-native');
|
||||
const executable = path.join(bundle, 'bin/codex');
|
||||
const main = path.join(
|
||||
app,
|
||||
'Contents/MacOS/genarrative-ai-game-creator-shell',
|
||||
);
|
||||
const mainArchitectures = run('/usr/bin/lipo', ['-archs', main]);
|
||||
assert.equal(mainArchitectures.status, 0);
|
||||
assert.ok(mainArchitectures.stdout.split(/\s+/).includes(architecture));
|
||||
if (requireUniversal) {
|
||||
assert.deepEqual(mainArchitectures.stdout.trim().split(/\s+/).sort(), [
|
||||
'arm64',
|
||||
'x86_64',
|
||||
]);
|
||||
for (const platform of ['darwin-arm64', 'darwin-x64']) {
|
||||
assert.ok(
|
||||
fs.existsSync(
|
||||
path.join(
|
||||
resources,
|
||||
'coding-agent/mac-native',
|
||||
platform,
|
||||
'manifest.json',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(bundle, 'manifest.json'), 'utf8'),
|
||||
);
|
||||
assert.equal(manifest.schemaVersion, 'genarrative-codex-sidecar.v2');
|
||||
assert.equal(manifest.platform, platform);
|
||||
assert.equal(
|
||||
manifest.platform,
|
||||
process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64',
|
||||
);
|
||||
assert.equal(manifest.version, 'codex-cli 0.147.0');
|
||||
const components = [
|
||||
'bin/codex',
|
||||
@@ -191,7 +159,11 @@ try {
|
||||
fs.accessSync(file, fs.constants.X_OK);
|
||||
const arch = run('/usr/bin/lipo', ['-archs', file]);
|
||||
assert.equal(arch.status, 0, component);
|
||||
assert.equal(arch.stdout.trim(), architecture, component);
|
||||
assert.equal(
|
||||
arch.stdout.trim(),
|
||||
process.arch === 'arm64' ? 'arm64' : 'x86_64',
|
||||
component,
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.ok(fs.existsSync(path.join(bundle, 'NOTICE.md')));
|
||||
@@ -240,7 +212,7 @@ try {
|
||||
assert.notEqual(broken.status, 0);
|
||||
assert.match(`${broken.stdout}\n${broken.stderr}`, /Codex CLI 未安装/);
|
||||
console.log(
|
||||
`PASS (${architecture}): 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝`,
|
||||
'PASS: 隔离安装包资源、架构、摘要、权限、正式 Codex 查找、app-server 握手及缺组件拒绝',
|
||||
);
|
||||
console.log(
|
||||
'未验证:GUI、真实登录/Provider 对话、Cocos macOS 原生桥接;插件 Node 仍为外部前提',
|
||||
|
||||
@@ -290,7 +290,7 @@ function deterministicArtManifest(
|
||||
{
|
||||
id: 'garden-guardians-spritesheet',
|
||||
path: 'assets/art-spritesheet.png',
|
||||
kind: 'art-spritesheet',
|
||||
kind: 'icon-spritesheet',
|
||||
usage: ['defenders', 'enemies', 'battlefield-ui'],
|
||||
source: 'canvas',
|
||||
status: 'ready',
|
||||
@@ -710,7 +710,7 @@ function canvasAssetCall(agentId) {
|
||||
outputPath: 'assets/ui-prototype.png',
|
||||
aspectRatio: '16:9',
|
||||
imageSize: '2K',
|
||||
assetKind: 'ui-prototype',
|
||||
assetKind: 'ui-design',
|
||||
assetLabel: '游戏横屏界面原型图',
|
||||
replaceExisting: false,
|
||||
});
|
||||
@@ -721,7 +721,7 @@ function canvasAssetCall(agentId) {
|
||||
outputPath: 'assets/art-spritesheet.png',
|
||||
aspectRatio: '1:1',
|
||||
imageSize: '1K',
|
||||
assetKind: 'art-spritesheet',
|
||||
assetKind: 'icon-spritesheet',
|
||||
assetLabel: '游戏首版核心美术素材',
|
||||
replaceExisting: false,
|
||||
sliceMode: 'connected-components',
|
||||
@@ -830,12 +830,12 @@ function missingGeneratedVisualAssetObservation(context, agentId) {
|
||||
},
|
||||
'design-foundation': {
|
||||
path: 'assets/ui-prototype.png',
|
||||
kind: 'ui-prototype',
|
||||
kind: 'ui-design',
|
||||
summary: '策划界面原型图尚未按正式视觉流程生成并登记,不能完成任务',
|
||||
},
|
||||
'art-asset-plan': {
|
||||
path: 'assets/art-spritesheet.png',
|
||||
kind: 'art-spritesheet',
|
||||
kind: 'icon-spritesheet',
|
||||
summary: '首版美术素材图尚未按正式视觉流程生成并登记,不能完成任务',
|
||||
},
|
||||
}[agentId];
|
||||
@@ -2667,7 +2667,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
asset: {
|
||||
assetId: `asset-${sliceImageId}`,
|
||||
assetObjectId: sliceAssetObjectId,
|
||||
assetKind: 'art-spritesheet-slice',
|
||||
assetKind: 'icon',
|
||||
projectId,
|
||||
taskId,
|
||||
},
|
||||
@@ -2707,7 +2707,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
spritesheetAsset: {
|
||||
assetId: `asset-${imageId}`,
|
||||
assetObjectId,
|
||||
assetKind: 'art-spritesheet',
|
||||
assetKind: 'icon-spritesheet',
|
||||
projectId,
|
||||
taskId,
|
||||
},
|
||||
@@ -2749,7 +2749,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
const assetObjectId = `asset-object-${imageId}`;
|
||||
const resourceId = `resource-${imageId}`;
|
||||
const assetKind =
|
||||
typeof body?.assetKind === 'string' ? body.assetKind : 'game-art';
|
||||
typeof body?.assetKind === 'string' ? body.assetKind : 'image';
|
||||
images.set(imageId, {
|
||||
...image,
|
||||
objectKey,
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
const platforms = {
|
||||
arm64: 'aarch64-apple-darwin',
|
||||
x64: 'x86_64-apple-darwin',
|
||||
};
|
||||
|
||||
export function lockedMacPackage(lock, arch, version) {
|
||||
assert.ok(Object.hasOwn(platforms, arch), '未知 macOS 架构');
|
||||
const alias = `@openai/codex-darwin-${arch}`;
|
||||
const entry = lock.packages?.[`node_modules/${alias}`];
|
||||
assert.equal(
|
||||
entry?.version,
|
||||
`${version}-darwin-${arch}`,
|
||||
'原生依赖必须与应用锁定版本一致',
|
||||
);
|
||||
assert.deepEqual(entry.os, ['darwin']);
|
||||
assert.deepEqual(entry.cpu, [arch]);
|
||||
const url = new URL(entry.resolved);
|
||||
assert.equal(url.protocol, 'https:');
|
||||
assert.equal(
|
||||
url.hostname,
|
||||
'registry.npmjs.org',
|
||||
'只下载锁定的官方 npm 原生包',
|
||||
);
|
||||
assert.equal(url.username + url.password + url.search + url.hash, '');
|
||||
assert.match(entry.integrity, /^sha512-[A-Za-z0-9+/]+={0,2}$/);
|
||||
return { alias, target: platforms[arch], ...entry };
|
||||
}
|
||||
|
||||
export function verifyPackageIntegrity(bytes, expected) {
|
||||
const actual = `sha512-${createHash('sha512').update(bytes).digest('base64')}`;
|
||||
assert.equal(actual, expected, 'Codex 下载包 lockfile integrity 不匹配');
|
||||
}
|
||||
|
||||
export function validateArchiveListing(listing) {
|
||||
const files = listing.trim().split(/\r?\n/u);
|
||||
assert.ok(files.length > 0);
|
||||
for (const file of files) {
|
||||
assert.ok(file.startsWith('package/'), '原生包必须只有 package 根目录');
|
||||
assert.ok(
|
||||
!file.split('/').includes('..') && !file.includes('\\'),
|
||||
'压缩包路径不安全',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareMacosCodex() {
|
||||
assert.equal(process.platform, 'darwin', '该入口仅用于 macOS 构建机');
|
||||
const lock = JSON.parse(
|
||||
fs.readFileSync(path.join(repoRoot, 'package-lock.json'), 'utf8'),
|
||||
);
|
||||
const app = JSON.parse(
|
||||
fs.readFileSync(path.join(appRoot, 'package.json'), 'utf8'),
|
||||
);
|
||||
const version = app.devDependencies['@openai/codex'];
|
||||
assert.match(version, /^\d+\.\d+\.\d+$/u, 'Codex 必须锁定精确版本');
|
||||
const cache = path.join(appRoot, 'src-tauri/target/.macos-native-cache');
|
||||
fs.mkdirSync(cache, { recursive: true });
|
||||
for (const arch of Object.keys(platforms)) {
|
||||
const entry = lockedMacPackage(lock, arch, version);
|
||||
const archive = path.join(cache, `codex-${entry.version}.tgz`);
|
||||
if (!fs.existsSync(archive)) {
|
||||
const response = await fetch(entry.resolved, {
|
||||
signal: AbortSignal.timeout(300_000),
|
||||
});
|
||||
assert.ok(response.ok, `原生包下载失败 HTTP ${response.status}`);
|
||||
const bytes = Buffer.from(await response.arrayBuffer());
|
||||
verifyPackageIntegrity(bytes, entry.integrity);
|
||||
const partial = `${archive}.${process.pid}.tmp`;
|
||||
fs.writeFileSync(partial, bytes);
|
||||
fs.renameSync(partial, archive);
|
||||
}
|
||||
verifyPackageIntegrity(fs.readFileSync(archive), entry.integrity);
|
||||
validateArchiveListing(
|
||||
execFileSync('tar', ['-tzf', archive], { encoding: 'utf8' }),
|
||||
);
|
||||
// 拒绝链接、设备及其它特殊条目,不能让 tar 在包目录之外写入。
|
||||
const entries = execFileSync('tar', ['-tvzf', archive], {
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.ok(
|
||||
entries
|
||||
.trim()
|
||||
.split(/\r?\n/u)
|
||||
.every((line) => /^[-d]/u.test(line)),
|
||||
'原生包禁止链接或特殊文件',
|
||||
);
|
||||
const parent = path.join(repoRoot, 'node_modules/@openai');
|
||||
fs.mkdirSync(parent, { recursive: true });
|
||||
const stage = fs.mkdtempSync(path.join(parent, '.mac-native-'));
|
||||
try {
|
||||
execFileSync(
|
||||
'tar',
|
||||
['-xzf', archive, '-C', stage, '--strip-components=1'],
|
||||
{ stdio: 'pipe' },
|
||||
);
|
||||
const metadata = JSON.parse(
|
||||
fs.readFileSync(
|
||||
path.join(stage, 'vendor', entry.target, 'codex-package.json'),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
assert.equal(metadata.version, version);
|
||||
assert.equal(metadata.target, entry.target);
|
||||
assert.equal(metadata.entrypoint, 'bin/codex');
|
||||
const destination = path.join(repoRoot, 'node_modules', entry.alias);
|
||||
assert.ok(
|
||||
!fs.existsSync(destination) ||
|
||||
!fs.lstatSync(destination).isSymbolicLink(),
|
||||
'拒绝覆盖链接依赖',
|
||||
);
|
||||
fs.rmSync(destination, { recursive: true, force: true });
|
||||
fs.renameSync(stage, destination);
|
||||
} finally {
|
||||
fs.rmSync(stage, { recursive: true, force: true });
|
||||
}
|
||||
console.log(`[macOS Codex] ${entry.version}: lockfile integrity 已验证`);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
await prepareMacosCodex();
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user