@kevlns/u-cli-mod 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +30 -0
  2. package/README.md +152 -0
  3. package/dist/authenticode.d.ts +13 -0
  4. package/dist/authenticode.js +72 -0
  5. package/dist/cli.d.ts +4 -0
  6. package/dist/cli.js +142 -0
  7. package/dist/commands/cacheClean.d.ts +7 -0
  8. package/dist/commands/cacheClean.js +13 -0
  9. package/dist/commands/cliInstall.d.ts +14 -0
  10. package/dist/commands/cliInstall.js +20 -0
  11. package/dist/commands/doctor.d.ts +22 -0
  12. package/dist/commands/doctor.js +41 -0
  13. package/dist/commands/exec.d.ts +14 -0
  14. package/dist/commands/exec.js +48 -0
  15. package/dist/commands/pipelineInstall.d.ts +17 -0
  16. package/dist/commands/pipelineInstall.js +19 -0
  17. package/dist/commands/routesCmd.d.ts +11 -0
  18. package/dist/commands/routesCmd.js +17 -0
  19. package/dist/commands/setup.d.ts +10 -0
  20. package/dist/commands/setup.js +21 -0
  21. package/dist/config.d.ts +12 -0
  22. package/dist/config.js +42 -0
  23. package/dist/download.d.ts +26 -0
  24. package/dist/download.js +110 -0
  25. package/dist/ensure.d.ts +25 -0
  26. package/dist/ensure.js +102 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.js +8 -0
  29. package/dist/index.d.ts +12 -0
  30. package/dist/index.js +10 -0
  31. package/dist/installer.d.ts +24 -0
  32. package/dist/installer.js +141 -0
  33. package/dist/integrity.d.ts +36 -0
  34. package/dist/integrity.js +84 -0
  35. package/dist/paths.d.ts +7 -0
  36. package/dist/paths.js +21 -0
  37. package/dist/pipeline.d.ts +19 -0
  38. package/dist/pipeline.js +139 -0
  39. package/dist/projectVersion.d.ts +16 -0
  40. package/dist/projectVersion.js +44 -0
  41. package/dist/routes.d.ts +40 -0
  42. package/dist/routes.js +81 -0
  43. package/dist/transform.d.ts +17 -0
  44. package/dist/transform.js +178 -0
  45. package/dist/unityGuard.d.ts +23 -0
  46. package/dist/unityGuard.js +55 -0
  47. package/package.json +66 -0
  48. package/routes/2022.3.62f3c1.json +28 -0
  49. package/routes/expected-tree/2022.3.62f3c1.json +391 -0
  50. package/templates/2022.3.62f3c1/dll-importer-body.txt +31 -0
  51. package/templates/2022.3.62f3c1/mono-importer-body.txt +9 -0
@@ -0,0 +1,17 @@
1
+ import { loadRoute, listEditorVersions } from '../routes.js';
2
+ export function runRoutes(editorVersion) {
3
+ const versions = editorVersion ? [editorVersion] : listEditorVersions();
4
+ const routes = versions.map((v) => {
5
+ const route = loadRoute(v);
6
+ return {
7
+ editorVersion: route.editorVersion,
8
+ editorRevision: route.editorRevision,
9
+ cliVersion: route.cli.version,
10
+ cliSha256: route.cli.sha256,
11
+ pipelineVersion: route.pipeline.version,
12
+ pipelineSha256: route.pipeline.sha256,
13
+ status: route.status ?? 'unknown',
14
+ };
15
+ });
16
+ return { routes };
17
+ }
@@ -0,0 +1,10 @@
1
+ export interface SetupOptions {
2
+ force?: boolean;
3
+ allowRunningEditor?: boolean;
4
+ dryRun?: boolean;
5
+ skipCli?: boolean;
6
+ }
7
+ export declare function runSetup(projectPath: string, options?: SetupOptions): Promise<{
8
+ cli: import("../ensure.js").EnsureCliResult | null;
9
+ install: import("../installer.js").InstallResult;
10
+ }>;
@@ -0,0 +1,21 @@
1
+ import { readProjectInfo } from '../projectVersion.js';
2
+ import { resolveRouteForProject, loadExpectedTree } from '../routes.js';
3
+ import { ensureCliBinary, ensurePipelineSource } from '../ensure.js';
4
+ import { installPipeline } from '../installer.js';
5
+ export async function runSetup(projectPath, options = {}) {
6
+ const project = readProjectInfo(projectPath);
7
+ const route = resolveRouteForProject(project);
8
+ const cli = options.skipCli ?? false
9
+ ? null
10
+ : await ensureCliBinary(route.cli, { force: options.force });
11
+ const expectedTree = loadExpectedTree(project.editorVersion);
12
+ const { sourceDir } = await ensurePipelineSource(project.editorVersion, route, {
13
+ force: options.force,
14
+ });
15
+ const result = await installPipeline(project, route, sourceDir, expectedTree.files, {
16
+ force: options.force,
17
+ allowRunningEditor: options.allowRunningEditor,
18
+ dryRun: options.dryRun,
19
+ });
20
+ return { cli, install: result };
21
+ }
@@ -0,0 +1,12 @@
1
+ /** Package root: dist/<...>/config.ts -> dist -> root. Works from tsc output and vitest (src). */
2
+ export declare function packageRoot(): string;
3
+ export declare function routesDir(): string;
4
+ export declare function templatesDir(): string;
5
+ export declare function expectedTreePath(editorVersion: string): string;
6
+ /** User-scoped cache; never inside node_modules/package dir. */
7
+ export declare function cacheRoot(): string;
8
+ export declare function cliCacheDir(): string;
9
+ export declare function pipelineCacheDir(): string;
10
+ export declare function generatedDir(): string;
11
+ export declare function logsDir(): string;
12
+ export declare function ensureCacheLayout(): void;
package/dist/config.js ADDED
@@ -0,0 +1,42 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { mkdirSync } from 'node:fs';
5
+ function distDir() {
6
+ return dirname(fileURLToPath(import.meta.url));
7
+ }
8
+ /** Package root: dist/<...>/config.ts -> dist -> root. Works from tsc output and vitest (src). */
9
+ export function packageRoot() {
10
+ return resolve(distDir(), '..');
11
+ }
12
+ export function routesDir() {
13
+ return join(packageRoot(), 'routes');
14
+ }
15
+ export function templatesDir() {
16
+ return join(packageRoot(), 'templates');
17
+ }
18
+ export function expectedTreePath(editorVersion) {
19
+ return join(routesDir(), 'expected-tree', `${editorVersion}.json`);
20
+ }
21
+ /** User-scoped cache; never inside node_modules/package dir. */
22
+ export function cacheRoot() {
23
+ const base = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local');
24
+ return join(base, 'editor-pipeline-cli');
25
+ }
26
+ export function cliCacheDir() {
27
+ return join(cacheRoot(), 'cache', 'cli');
28
+ }
29
+ export function pipelineCacheDir() {
30
+ return join(cacheRoot(), 'cache', 'pipeline');
31
+ }
32
+ export function generatedDir() {
33
+ return join(cacheRoot(), 'generated');
34
+ }
35
+ export function logsDir() {
36
+ return join(cacheRoot(), 'logs');
37
+ }
38
+ export function ensureCacheLayout() {
39
+ for (const dir of [cacheRoot(), cliCacheDir(), pipelineCacheDir(), generatedDir(), logsDir()]) {
40
+ mkdirSync(dir, { recursive: true });
41
+ }
42
+ }
@@ -0,0 +1,26 @@
1
+ import { fileSize } from './integrity.js';
2
+ /** Trusted download endpoints: Unity's public CDN and its China redirect target. */
3
+ export declare const DEFAULT_HOST_ALLOWLIST: Set<string>;
4
+ export declare const MAX_REDIRECTS = 5;
5
+ export declare const MAX_DOWNLOAD_BYTES: number;
6
+ export interface DownloadOptions {
7
+ expectedSha256?: string;
8
+ expectedSize?: number;
9
+ hostAllowlist?: Set<string>;
10
+ maxRedirects?: number;
11
+ timeoutMs?: number;
12
+ /** Defaults to HTTPS-only. Tests may allow http on loopback with an explicit allowlist. */
13
+ allowedProtocols?: ReadonlySet<string>;
14
+ }
15
+ export interface DownloadResult {
16
+ file: string;
17
+ size: number;
18
+ sha256: string;
19
+ finalUrl: string;
20
+ }
21
+ /**
22
+ * Download to a temporary file, verify size + sha256, then atomically rename.
23
+ * Any failure removes the temp file; an existing destination is never touched.
24
+ */
25
+ export declare function downloadToFile(url: string, destination: string, options?: DownloadOptions): Promise<DownloadResult>;
26
+ export { fileSize };
@@ -0,0 +1,110 @@
1
+ import { createWriteStream, renameSync, rmSync } from 'node:fs';
2
+ import { basename, join, dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { mkdirSync } from 'node:fs';
5
+ import { CliError } from './errors.js';
6
+ import { sha256File, fileSize } from './integrity.js';
7
+ /** Trusted download endpoints: Unity's public CDN and its China redirect target. */
8
+ export const DEFAULT_HOST_ALLOWLIST = new Set([
9
+ 'public-cdn.cloud.unity3d.com',
10
+ 'download.packages.unity.com',
11
+ 'public-cdn.cloud.unitychina.cn',
12
+ // Real redirect target observed for com.unity.pipeline tarballs.
13
+ 'cdn.packages.unity.com',
14
+ ]);
15
+ export const MAX_REDIRECTS = 5;
16
+ export const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
17
+ function assertHostAllowed(url, allowlist, allowedProtocols) {
18
+ if (!allowedProtocols.has(url.protocol)) {
19
+ throw new CliError(`拒绝非 HTTPS 下载源:${url.protocol}//${url.host}`);
20
+ }
21
+ if (!allowlist.has(url.hostname.toLowerCase())) {
22
+ throw new CliError(`下载主机不在白名单内:${url.hostname}`);
23
+ }
24
+ }
25
+ /**
26
+ * Download to a temporary file, verify size + sha256, then atomically rename.
27
+ * Any failure removes the temp file; an existing destination is never touched.
28
+ */
29
+ export async function downloadToFile(url, destination, options = {}) {
30
+ const allowlist = options.hostAllowlist ?? DEFAULT_HOST_ALLOWLIST;
31
+ const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
32
+ const timeoutMs = options.timeoutMs ?? 600_000;
33
+ const allowedProtocols = options.allowedProtocols ?? new Set(['https:']);
34
+ const destDir = dirname(destination);
35
+ mkdirSync(destDir, { recursive: true });
36
+ const tempFile = join(destDir, `${basename(destination)}.download-${randomUUID()}.part`);
37
+ try {
38
+ let current = new URL(url);
39
+ let finalUrl = current.toString();
40
+ let size = 0;
41
+ let hash = null;
42
+ for (let hop = 0;; hop++) {
43
+ assertHostAllowed(current, allowlist, allowedProtocols);
44
+ // The abort timer stays armed through the whole hop, including the body
45
+ // stream, so a stalled/slow body cannot hang the download forever.
46
+ const controller = new AbortController();
47
+ const timer = setTimeout(() => controller.abort(new Error('下载超时')), timeoutMs);
48
+ try {
49
+ const response = await fetch(current, {
50
+ redirect: 'manual',
51
+ signal: controller.signal,
52
+ headers: { 'user-agent': 'u-cli-mod/0.1' },
53
+ });
54
+ if (response.status >= 300 && response.status < 400) {
55
+ const location = response.headers.get('location');
56
+ if (!location) {
57
+ throw new CliError(`重定向缺少 Location:${current}`);
58
+ }
59
+ if (hop >= maxRedirects) {
60
+ throw new CliError(`重定向次数超过上限(${maxRedirects})`);
61
+ }
62
+ current = new URL(location, current);
63
+ finalUrl = current.toString();
64
+ continue;
65
+ }
66
+ if (!response.ok || !response.body) {
67
+ throw new CliError(`下载失败 HTTP ${response.status}:${current}`);
68
+ }
69
+ const out = createWriteStream(tempFile, { flags: 'w' });
70
+ try {
71
+ for await (const chunk of response.body) {
72
+ size += chunk.length;
73
+ if (size > (options.expectedSize ?? MAX_DOWNLOAD_BYTES) * 2) {
74
+ throw new CliError(`下载内容超过预期大小:${size} bytes`);
75
+ }
76
+ if (!out.write(chunk)) {
77
+ await new Promise((resolve) => out.once('drain', () => resolve()));
78
+ }
79
+ }
80
+ }
81
+ finally {
82
+ out.end();
83
+ await new Promise((resolve) => out.once('close', () => resolve()));
84
+ }
85
+ if (options.expectedSize !== undefined && size !== options.expectedSize) {
86
+ throw new CliError(`文件大小不匹配:期望 ${options.expectedSize},实际 ${size}`);
87
+ }
88
+ if (options.expectedSha256) {
89
+ hash = await sha256File(tempFile);
90
+ if (hash !== options.expectedSha256.toLowerCase()) {
91
+ throw new CliError(`SHA-256 校验失败。期望 ${options.expectedSha256},实际 ${hash}`);
92
+ }
93
+ }
94
+ break;
95
+ }
96
+ finally {
97
+ clearTimeout(timer);
98
+ }
99
+ }
100
+ renameSync(tempFile, destination);
101
+ return { file: destination, size, sha256: hash ?? (await sha256File(destination)), finalUrl };
102
+ }
103
+ catch (err) {
104
+ rmSync(tempFile, { force: true });
105
+ if (err instanceof CliError)
106
+ throw err;
107
+ throw new CliError(`下载失败:${err instanceof Error ? err.message : String(err)}`);
108
+ }
109
+ }
110
+ export { fileSize };
@@ -0,0 +1,25 @@
1
+ import type { CliRoute, VersionRoute } from './routes.js';
2
+ export interface EnsureCliResult {
3
+ path: string;
4
+ state: 'valid' | 'downloaded';
5
+ sha256: string;
6
+ }
7
+ /**
8
+ * Download (or reuse) the pinned CLI binary. Every re-entry path — fresh
9
+ * download AND cache reuse — requires full SHA-256 + Authenticode verification
10
+ * before the binary is placed at (or reported valid from) its final location.
11
+ */
12
+ export declare function ensureCliBinary(route: CliRoute, { force }?: {
13
+ force?: boolean;
14
+ }): Promise<EnsureCliResult>;
15
+ export interface EnsurePipelineResult {
16
+ sourceDir: string;
17
+ fileCount: number;
18
+ state: 'valid' | 'transformed';
19
+ }
20
+ /** Download + extract + deterministically transform the pinned pipeline package. */
21
+ export declare function ensurePipelineSource(editorVersion: string, route: VersionRoute, { force }?: {
22
+ force?: boolean;
23
+ }): Promise<EnsurePipelineResult>;
24
+ /** Re-verify an existing CLI binary hash without downloading. Throws on mismatch. */
25
+ export declare function verifyCliBinary(route: CliRoute): Promise<string>;
package/dist/ensure.js ADDED
@@ -0,0 +1,102 @@
1
+ import { existsSync, rmSync, renameSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { CliError } from './errors.js';
5
+ import { sha256File } from './integrity.js';
6
+ import { downloadToFile } from './download.js';
7
+ import { verifyAuthenticode } from './authenticode.js';
8
+ import { ensurePipelineTgz, extractTgz, resolveExtractedPackageDir } from './pipeline.js';
9
+ import { transformPackage, readTemplateFile } from './transform.js';
10
+ import { verifyPackageRoot } from './installer.js';
11
+ import { loadExpectedTree } from './routes.js';
12
+ import { templatesDir } from './config.js';
13
+ import { cliBinaryPath, pipelineTgzPath, pipelineExtractDir, generatedPackageDir } from './paths.js';
14
+ async function verifyCliFull(route, path) {
15
+ const hash = await sha256File(path);
16
+ if (hash !== route.sha256.toLowerCase()) {
17
+ throw new CliError(`CLI SHA-256 不匹配。期望 ${route.sha256},实际 ${hash}。请运行 "u-cli-mod cli install --force" 修复。`);
18
+ }
19
+ await verifyAuthenticode(path, route.signerSubjectContains, route.signerThumbprint);
20
+ return hash;
21
+ }
22
+ /**
23
+ * Download (or reuse) the pinned CLI binary. Every re-entry path — fresh
24
+ * download AND cache reuse — requires full SHA-256 + Authenticode verification
25
+ * before the binary is placed at (or reported valid from) its final location.
26
+ */
27
+ export async function ensureCliBinary(route, { force = false } = {}) {
28
+ const path = cliBinaryPath(route);
29
+ if (!force && existsSync(path)) {
30
+ try {
31
+ const hash = await verifyCliFull(route, path);
32
+ return { path, state: 'valid', sha256: hash };
33
+ }
34
+ catch {
35
+ // Cached binary failed hash or Authenticode: discard and redownload.
36
+ rmSync(path, { force: true });
37
+ }
38
+ }
39
+ // Verify on a temporary sibling first; only a fully verified binary is
40
+ // renamed into the reusable cache slot.
41
+ const tempPath = `${path}.verify-${randomUUID()}`;
42
+ try {
43
+ await downloadToFile(route.url, tempPath, {
44
+ expectedSha256: route.sha256,
45
+ expectedSize: route.expectedSize,
46
+ });
47
+ const hash = await verifyCliFull(route, tempPath);
48
+ renameSync(tempPath, path);
49
+ return { path, state: 'downloaded', sha256: hash };
50
+ }
51
+ catch (err) {
52
+ rmSync(tempPath, { force: true });
53
+ if (err instanceof CliError)
54
+ throw err;
55
+ throw new CliError(`CLI 下载/校验失败:${err instanceof Error ? err.message : String(err)}`);
56
+ }
57
+ }
58
+ /** Download + extract + deterministically transform the pinned pipeline package. */
59
+ export async function ensurePipelineSource(editorVersion, route, { force = false } = {}) {
60
+ const pipeline = route.pipeline;
61
+ const tgzPath = pipelineTgzPath(pipeline);
62
+ const extractRoot = pipelineExtractDir(pipeline);
63
+ const generated = generatedPackageDir(editorVersion);
64
+ const expectedTree = loadExpectedTree(editorVersion);
65
+ // Already-generated and verified? Reuse.
66
+ if (!force && existsSync(generated)) {
67
+ try {
68
+ const fileCount = await verifyPackageRoot(generated, expectedTree.files);
69
+ return { sourceDir: generated, fileCount, state: 'valid' };
70
+ }
71
+ catch {
72
+ // fall through and regenerate
73
+ }
74
+ }
75
+ await ensurePipelineTgz(tgzPath, pipeline, { force });
76
+ await extractTgz(tgzPath, extractRoot);
77
+ const sourceRoot = resolveExtractedPackageDir(extractRoot);
78
+ const monoImporterBody = readTemplateFile(join(templatesDir(), pipeline.templates, 'mono-importer-body.txt'));
79
+ const dllImporterBody = readTemplateFile(join(templatesDir(), pipeline.templates, 'dll-importer-body.txt'));
80
+ await transformPackage({
81
+ sourceRoot,
82
+ targetRoot: generated,
83
+ route: pipeline,
84
+ expectedTree: expectedTree.files,
85
+ monoImporterBody,
86
+ dllImporterBody,
87
+ });
88
+ const fileCount = Object.keys(expectedTree.files).length;
89
+ return { sourceDir: generated, fileCount, state: 'transformed' };
90
+ }
91
+ /** Re-verify an existing CLI binary hash without downloading. Throws on mismatch. */
92
+ export async function verifyCliBinary(route) {
93
+ const path = cliBinaryPath(route);
94
+ if (!existsSync(path)) {
95
+ throw new CliError(`CLI 未下载:${path}。请先运行 "u-cli-mod cli install"。`);
96
+ }
97
+ const hash = await sha256File(path);
98
+ if (hash !== route.sha256.toLowerCase()) {
99
+ throw new CliError(`CLI SHA-256 不匹配,拒绝执行:${path}。请运行 "u-cli-mod cli install --force" 修复。`);
100
+ }
101
+ return hash;
102
+ }
@@ -0,0 +1,4 @@
1
+ export declare class CliError extends Error {
2
+ readonly exitCode: number;
3
+ constructor(message: string, exitCode?: number);
4
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,8 @@
1
+ export class CliError extends Error {
2
+ exitCode;
3
+ constructor(message, exitCode = 1) {
4
+ super(message);
5
+ this.name = 'CliError';
6
+ this.exitCode = exitCode;
7
+ }
8
+ }
@@ -0,0 +1,12 @@
1
+ export { buildProgram, main } from './cli.js';
2
+ export { CliError } from './errors.js';
3
+ export { parseProjectVersion, readProjectInfo } from './projectVersion.js';
4
+ export type { ProjectInfo } from './projectVersion.js';
5
+ export { loadRoute, listEditorVersions, resolveRouteForProject, loadExpectedTree } from './routes.js';
6
+ export type { VersionRoute, CliRoute, PipelineRoute, ExpectedTree } from './routes.js';
7
+ export { compareTree, assertTreeMatches, sha256File, sha256Buffer } from './integrity.js';
8
+ export { downloadToFile } from './download.js';
9
+ export { verifyAuthenticode } from './authenticode.js';
10
+ export { ensureCliBinary, ensurePipelineSource, verifyCliBinary } from './ensure.js';
11
+ export { installPipeline } from './installer.js';
12
+ export { queryUnityProcesses, guardNoRunningEditor } from './unityGuard.js';
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export { buildProgram, main } from './cli.js';
2
+ export { CliError } from './errors.js';
3
+ export { parseProjectVersion, readProjectInfo } from './projectVersion.js';
4
+ export { loadRoute, listEditorVersions, resolveRouteForProject, loadExpectedTree } from './routes.js';
5
+ export { compareTree, assertTreeMatches, sha256File, sha256Buffer } from './integrity.js';
6
+ export { downloadToFile } from './download.js';
7
+ export { verifyAuthenticode } from './authenticode.js';
8
+ export { ensureCliBinary, ensurePipelineSource, verifyCliBinary } from './ensure.js';
9
+ export { installPipeline } from './installer.js';
10
+ export { queryUnityProcesses, guardNoRunningEditor } from './unityGuard.js';
@@ -0,0 +1,24 @@
1
+ import type { ProjectInfo } from './projectVersion.js';
2
+ import type { VersionRoute } from './routes.js';
3
+ import type { EditorGuardResult } from './unityGuard.js';
4
+ export interface InstallOptions {
5
+ force?: boolean;
6
+ allowRunningEditor?: boolean;
7
+ dryRun?: boolean;
8
+ /** injectable for tests */
9
+ guard?: (projectPath: string) => Promise<EditorGuardResult>;
10
+ /** injectable for tests: file-tree copy (e.g. simulate partial copy failure). */
11
+ copy?: (src: string, dest: string) => Promise<void>;
12
+ }
13
+ export interface InstallResult {
14
+ status: 'Installed' | 'AlreadyInstalled' | 'DryRun';
15
+ projectPath: string;
16
+ editorVersion: string;
17
+ editorRevision: string;
18
+ pipelineVersion: string;
19
+ packagePath: string;
20
+ fileCount: number;
21
+ backupPath?: string;
22
+ }
23
+ export declare function verifyPackageRoot(root: string, expected: Record<string, string>): Promise<number>;
24
+ export declare function installPipeline(project: ProjectInfo, route: VersionRoute, sourceDir: string, expectedTree: Record<string, string>, options?: InstallOptions): Promise<InstallResult>;
@@ -0,0 +1,141 @@
1
+ import { cp, mkdir, rm } from 'node:fs/promises';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { CliError } from './errors.js';
6
+ import { compareTree } from './integrity.js';
7
+ import { guardNoRunningEditor } from './unityGuard.js';
8
+ export async function verifyPackageRoot(root, expected) {
9
+ const { ok, mismatches, fileCount } = await compareTree(root, expected);
10
+ if (!ok) {
11
+ const sample = mismatches
12
+ .slice(0, 10)
13
+ .map((m) => `[${m.kind}] ${m.path}`)
14
+ .join('\n');
15
+ throw new CliError(`com.unity.pipeline 完整性校验失败(${mismatches.length} 项):\n${sample}`);
16
+ }
17
+ return fileCount;
18
+ }
19
+ export async function installPipeline(project, route, sourceDir, expectedTree, options = {}) {
20
+ const destination = join(project.projectPath, 'Packages', 'com.unity.pipeline');
21
+ const guard = options.guard ?? ((path) => guardNoRunningEditor(path));
22
+ const copy = options.copy ??
23
+ ((src, dest) => cp(src, dest, { recursive: true }));
24
+ // 1. Source must already be verified by the caller; double-check once more.
25
+ const sourceFileCount = await verifyPackageRoot(sourceDir, expectedTree);
26
+ // 2. Fail-closed running-editor guard.
27
+ if (!options.allowRunningEditor) {
28
+ const result = await guard(project.projectPath);
29
+ if (!result.ok) {
30
+ const who = result.blockedBy.join(', ');
31
+ throw new CliError(`目标工程正在被 Unity Editor 使用(${who})。请先关闭 Editor;明确继续时使用 --allow-running-editor。${result.reason ?? ''}`);
32
+ }
33
+ }
34
+ // 3. Dry-run takes priority: it only inspects, so it returns before any
35
+ // idempotence/conflict decision that could report a different status.
36
+ if (options.dryRun) {
37
+ return {
38
+ status: 'DryRun',
39
+ projectPath: project.projectPath,
40
+ editorVersion: project.editorVersion,
41
+ editorRevision: project.revision ?? '',
42
+ pipelineVersion: route.pipeline.version,
43
+ packagePath: destination,
44
+ fileCount: sourceFileCount,
45
+ };
46
+ }
47
+ // 4. Idempotence / conflict check.
48
+ let existingIsValid = false;
49
+ if (existsSync(destination)) {
50
+ try {
51
+ await verifyPackageRoot(destination, expectedTree);
52
+ existingIsValid = true;
53
+ }
54
+ catch {
55
+ existingIsValid = false;
56
+ }
57
+ if (existingIsValid && !options.force) {
58
+ return {
59
+ status: 'AlreadyInstalled',
60
+ projectPath: project.projectPath,
61
+ editorVersion: project.editorVersion,
62
+ editorRevision: project.revision ?? '',
63
+ pipelineVersion: route.pipeline.version,
64
+ packagePath: destination,
65
+ fileCount: sourceFileCount,
66
+ };
67
+ }
68
+ if (!options.force) {
69
+ throw new CliError('工程中的 com.unity.pipeline 与当前路由不一致或已损坏。确认备份并覆盖时使用 --force。');
70
+ }
71
+ }
72
+ // 5. Transaction: stage -> backup -> move -> verify -> receipt; rollback on any failure.
73
+ const libRoot = join(project.projectPath, 'Library', 'editor-pipeline-cli');
74
+ const stagingRoot = join(libRoot, `staging-${randomUUID()}`);
75
+ const stagedPackage = join(stagingRoot, 'com.unity.pipeline');
76
+ let backupPath;
77
+ let destMoved = false;
78
+ let destTouched = false;
79
+ try {
80
+ await mkdir(stagingRoot, { recursive: true });
81
+ await copy(sourceDir, stagedPackage);
82
+ await verifyPackageRoot(stagedPackage, expectedTree);
83
+ await mkdir(join(project.projectPath, 'Packages'), { recursive: true });
84
+ if (existsSync(destination)) {
85
+ const backups = join(libRoot, 'backups');
86
+ await mkdir(backups, { recursive: true });
87
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
88
+ backupPath = join(backups, `com.unity.pipeline-${timestamp}-${randomUUID()}`);
89
+ await cp(destination, backupPath, { recursive: true });
90
+ await rm(destination, { recursive: true, force: true });
91
+ destMoved = true;
92
+ }
93
+ destTouched = true;
94
+ await copy(stagedPackage, destination);
95
+ await verifyPackageRoot(destination, expectedTree);
96
+ const receipt = {
97
+ installedAt: new Date().toISOString(),
98
+ projectPath: project.projectPath,
99
+ editorVersion: project.editorVersion,
100
+ editorRevision: project.revision,
101
+ pipelineVersion: route.pipeline.version,
102
+ packagePath: destination,
103
+ backupPath: backupPath ?? null,
104
+ source: `${route.pipeline.packageName}@${route.pipeline.version} (patched ${route.pipeline.patchVersion})`,
105
+ };
106
+ await mkdir(libRoot, { recursive: true });
107
+ const { writeFile } = await import('node:fs/promises');
108
+ await writeFile(join(libRoot, 'receipt.json'), JSON.stringify(receipt, null, 2), 'utf8');
109
+ return {
110
+ status: 'Installed',
111
+ projectPath: project.projectPath,
112
+ editorVersion: project.editorVersion,
113
+ editorRevision: project.revision ?? '',
114
+ pipelineVersion: route.pipeline.version,
115
+ packagePath: destination,
116
+ fileCount: sourceFileCount,
117
+ backupPath,
118
+ };
119
+ }
120
+ catch (err) {
121
+ // If the old package was moved out, unconditionally remove any partial/new
122
+ // destination and restore the backup (partial copy failure included).
123
+ if (destMoved) {
124
+ await rm(destination, { recursive: true, force: true });
125
+ if (backupPath && existsSync(backupPath)) {
126
+ await copy(backupPath, destination);
127
+ }
128
+ }
129
+ else if (destTouched) {
130
+ // Fresh install (no old package): the placement copy started, so any
131
+ // partial tree at the destination must be removed.
132
+ await rm(destination, { recursive: true, force: true });
133
+ }
134
+ throw err instanceof CliError
135
+ ? err
136
+ : new CliError(`安装失败(已回滚):${err instanceof Error ? err.message : String(err)}`);
137
+ }
138
+ finally {
139
+ await rm(stagingRoot, { recursive: true, force: true });
140
+ }
141
+ }
@@ -0,0 +1,36 @@
1
+ import { readdirSync } from 'node:fs';
2
+ export declare function sha256Buffer(data: Buffer): string;
3
+ export declare function sha1Buffer(data: Buffer): string;
4
+ export declare function sha256File(file: string): Promise<string>;
5
+ export interface TreeEntry {
6
+ path: string;
7
+ size: number;
8
+ sha256: string;
9
+ }
10
+ export type TreeEntryKind = 'dir' | 'file' | 'other';
11
+ /** Classify a dirent; any non-regular/non-directory kind is 'other' (fail-closed). */
12
+ export declare function entryKind(entry: {
13
+ isDirectory(): boolean;
14
+ isFile(): boolean;
15
+ isSymbolicLink(): boolean;
16
+ isFIFO(): boolean;
17
+ isSocket(): boolean;
18
+ isBlockDevice(): boolean;
19
+ isCharacterDevice(): boolean;
20
+ }): TreeEntryKind;
21
+ /** Walk a directory and compute {relPath(forward-slash): sha256} for every file. */
22
+ export declare function sha256Tree(root: string, readdirImpl?: typeof readdirSync): Promise<Map<string, string>>;
23
+ export interface TreeMismatch {
24
+ kind: 'missing' | 'extra' | 'hash';
25
+ path: string;
26
+ expected?: string;
27
+ actual?: string;
28
+ }
29
+ /** Two-way comparison: expected entries must exist with exact bytes; extra files are rejected. */
30
+ export declare function compareTree(root: string, expected: Record<string, string>): Promise<{
31
+ ok: boolean;
32
+ mismatches: TreeMismatch[];
33
+ fileCount: number;
34
+ }>;
35
+ export declare function assertTreeMatches(root: string, expected: Record<string, string>, what: string): Promise<number>;
36
+ export declare function fileSize(file: string): number;