@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,84 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readdirSync, statSync } from 'node:fs';
4
+ import { join, relative } from 'node:path';
5
+ import { CliError } from './errors.js';
6
+ export function sha256Buffer(data) {
7
+ return createHash('sha256').update(data).digest('hex');
8
+ }
9
+ export function sha1Buffer(data) {
10
+ return createHash('sha1').update(data).digest('hex');
11
+ }
12
+ export async function sha256File(file) {
13
+ const hash = createHash('sha256');
14
+ const stream = createReadStream(file);
15
+ for await (const chunk of stream) {
16
+ hash.update(chunk);
17
+ }
18
+ return hash.digest('hex');
19
+ }
20
+ /** Classify a dirent; any non-regular/non-directory kind is 'other' (fail-closed). */
21
+ export function entryKind(entry) {
22
+ if (entry.isDirectory())
23
+ return 'dir';
24
+ if (entry.isFile())
25
+ return 'file';
26
+ return 'other';
27
+ }
28
+ /** Walk a directory and compute {relPath(forward-slash): sha256} for every file. */
29
+ export async function sha256Tree(root, readdirImpl = readdirSync) {
30
+ const result = new Map();
31
+ const stack = [root];
32
+ while (stack.length > 0) {
33
+ const dir = stack.pop();
34
+ for (const entry of readdirImpl(dir, { withFileTypes: true })) {
35
+ const abs = join(dir, entry.name);
36
+ const rel = relative(root, abs).split('\\').join('/');
37
+ const kind = entryKind(entry);
38
+ if (kind === 'dir') {
39
+ stack.push(abs);
40
+ }
41
+ else if (kind === 'file') {
42
+ result.set(rel, await sha256File(abs));
43
+ }
44
+ else {
45
+ throw new CliError(`完整性校验拒绝非常规条目(可能是符号链接):${rel}`);
46
+ }
47
+ }
48
+ }
49
+ return result;
50
+ }
51
+ /** Two-way comparison: expected entries must exist with exact bytes; extra files are rejected. */
52
+ export async function compareTree(root, expected) {
53
+ const actual = await sha256Tree(root);
54
+ const mismatches = [];
55
+ for (const [path, hash] of Object.entries(expected)) {
56
+ const real = actual.get(path);
57
+ if (real === undefined) {
58
+ mismatches.push({ kind: 'missing', path });
59
+ }
60
+ else if (real !== hash) {
61
+ mismatches.push({ kind: 'hash', path, expected: hash, actual: real });
62
+ }
63
+ }
64
+ for (const path of actual.keys()) {
65
+ if (!(path in expected)) {
66
+ mismatches.push({ kind: 'extra', path });
67
+ }
68
+ }
69
+ return { ok: mismatches.length === 0, mismatches, fileCount: Object.keys(expected).length };
70
+ }
71
+ export async function assertTreeMatches(root, expected, what) {
72
+ const { ok, mismatches, fileCount } = await compareTree(root, expected);
73
+ if (!ok) {
74
+ const sample = mismatches
75
+ .slice(0, 10)
76
+ .map((m) => `[${m.kind}] ${m.path}`)
77
+ .join('\n');
78
+ throw new CliError(`${what} 完整性校验失败(${mismatches.length} 项):\n${sample}`);
79
+ }
80
+ return fileCount;
81
+ }
82
+ export function fileSize(file) {
83
+ return statSync(file).size;
84
+ }
@@ -0,0 +1,7 @@
1
+ import type { CliRoute, PipelineRoute } from './routes.js';
2
+ export declare function cliBinaryPath(route: CliRoute): string;
3
+ export declare function pipelineTgzPath(route: PipelineRoute): string;
4
+ export declare function pipelineSrcDir(route: PipelineRoute): string;
5
+ export declare function pipelineExtractDir(route: PipelineRoute): string;
6
+ export declare function generatedPackageDir(editorVersion: string): string;
7
+ export declare function exists(path: string): boolean;
package/dist/paths.js ADDED
@@ -0,0 +1,21 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { cliCacheDir, pipelineCacheDir, generatedDir } from './config.js';
4
+ export function cliBinaryPath(route) {
5
+ return join(cliCacheDir(), route.version, 'unity.exe');
6
+ }
7
+ export function pipelineTgzPath(route) {
8
+ return join(pipelineCacheDir(), `${route.version}-${route.sha1}.tgz`);
9
+ }
10
+ export function pipelineSrcDir(route) {
11
+ return join(pipelineCacheDir(), `${route.version}-${route.sha1}-src`);
12
+ }
13
+ export function pipelineExtractDir(route) {
14
+ return join(pipelineCacheDir(), `${route.version}-${route.sha1}-extract`);
15
+ }
16
+ export function generatedPackageDir(editorVersion) {
17
+ return join(generatedDir(), editorVersion, 'com.unity.pipeline');
18
+ }
19
+ export function exists(path) {
20
+ return existsSync(path);
21
+ }
@@ -0,0 +1,19 @@
1
+ import type { PipelineRoute } from './routes.js';
2
+ /** Download + verify pinned pipeline tgz (SHA-256 primary, SHA-1 cross-check). */
3
+ export declare function ensurePipelineTgz(tgzPath: string, route: PipelineRoute, { force, hostAllowlist }?: {
4
+ force?: boolean;
5
+ hostAllowlist?: Set<string>;
6
+ }): Promise<{
7
+ file: string;
8
+ state: 'valid' | 'downloaded';
9
+ }>;
10
+ /**
11
+ * Safe extraction via the maintained `tar` package (no system-tar dependency):
12
+ * every entry is validated BEFORE anything is written (listing pass), then the
13
+ * extract pass re-validates each entry with a filter that throws before write.
14
+ */
15
+ export declare function extractTgz(tgz: string, targetRoot: string): Promise<void>;
16
+ /** Locate the package root inside an extraction (top-level `package/` or in-place). */
17
+ export declare function resolveExtractedPackageDir(extractRoot: string): string;
18
+ export declare function writeMarker(file: string, content: string): void;
19
+ export declare function verifyMarker(file: string, expected: string): boolean;
@@ -0,0 +1,139 @@
1
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, existsSync, } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CliError } from './errors.js';
4
+ import { sha1Buffer, sha256Buffer } from './integrity.js';
5
+ import { downloadToFile } from './download.js';
6
+ import { list, extract } from 'tar';
7
+ /** Download + verify pinned pipeline tgz (SHA-256 primary, SHA-1 cross-check). */
8
+ export async function ensurePipelineTgz(tgzPath, route, { force = false, hostAllowlist } = {}) {
9
+ if (!force && existsSync(tgzPath)) {
10
+ const buf = readFileSync(tgzPath);
11
+ const sha1 = sha1Buffer(buf);
12
+ const sha256 = sha256Buffer(buf);
13
+ const want1 = route.sha1.toLowerCase();
14
+ const want256 = route.sha256.toLowerCase();
15
+ if (sha1 === want1 && sha256 === want256) {
16
+ return { file: tgzPath, state: 'valid' };
17
+ }
18
+ // sha1/sha256 mismatch -> treat as corrupt, redownload
19
+ rmSync(tgzPath, { force: true });
20
+ }
21
+ await downloadToFile(route.url, tgzPath, {
22
+ expectedSha256: route.sha256,
23
+ expectedSize: route.expectedSize,
24
+ hostAllowlist,
25
+ });
26
+ const buf = readFileSync(tgzPath);
27
+ const sha1 = sha1Buffer(buf);
28
+ if (sha1 !== route.sha1.toLowerCase()) {
29
+ rmSync(tgzPath, { force: true });
30
+ throw new CliError(`Pipeline tgz SHA-1 交叉校验失败。期望 ${route.sha1},实际 ${sha1}`);
31
+ }
32
+ return { file: tgzPath, state: 'downloaded' };
33
+ }
34
+ function assertSafeEntryPath(entryPath) {
35
+ const normalized = entryPath.replace(/\\/g, '/');
36
+ if (normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized)) {
37
+ throw new CliError(`解包拒绝绝对路径:${entryPath}`);
38
+ }
39
+ if (normalized.split('/').includes('..')) {
40
+ throw new CliError(`解包拒绝路径穿越:${entryPath}`);
41
+ }
42
+ }
43
+ function assertSafeEntryType(type, entryPath) {
44
+ switch (type) {
45
+ case 'File':
46
+ case 'Directory':
47
+ return;
48
+ case 'SymbolicLink':
49
+ case 'Link':
50
+ throw new CliError(`解包拒绝符号链接/硬链接:${entryPath}`);
51
+ default:
52
+ throw new CliError(`解包拒绝非常规条目类型 ${type}:${entryPath}`);
53
+ }
54
+ }
55
+ function validateTarEntry(entryPath, type) {
56
+ assertSafeEntryPath(entryPath);
57
+ assertSafeEntryType(type, entryPath);
58
+ }
59
+ /**
60
+ * Safe extraction via the maintained `tar` package (no system-tar dependency):
61
+ * every entry is validated BEFORE anything is written (listing pass), then the
62
+ * extract pass re-validates each entry with a filter that throws before write.
63
+ */
64
+ export async function extractTgz(tgz, targetRoot) {
65
+ rmSync(targetRoot, { recursive: true, force: true });
66
+ mkdirSync(targetRoot, { recursive: true });
67
+ try {
68
+ // Pass 1: list and collect every entry BEFORE any write; reject unsafe
69
+ // paths/types as a whole once the (pure) listing pass has completed.
70
+ const seen = [];
71
+ await list({
72
+ file: tgz,
73
+ strict: true,
74
+ preservePaths: true,
75
+ onReadEntry: (entry) => {
76
+ seen.push({ path: entry.path, type: entry.type });
77
+ },
78
+ });
79
+ for (const entry of seen) {
80
+ validateTarEntry(entry.path, entry.type);
81
+ }
82
+ // Pass 2: extract; the filter re-validates at parse time and throws before
83
+ // any offending entry is written.
84
+ await extract({
85
+ file: tgz,
86
+ cwd: targetRoot,
87
+ strict: true,
88
+ preservePaths: true,
89
+ filter: (entryPath, entry) => {
90
+ validateTarEntry(entryPath, entry.type);
91
+ return true;
92
+ },
93
+ });
94
+ }
95
+ catch (err) {
96
+ rmSync(targetRoot, { recursive: true, force: true });
97
+ throw new CliError(`tgz 解包失败或包含不安全条目:${err instanceof Error ? err.message : String(err)}`);
98
+ }
99
+ // Defensive post-walk: no symlinks or non-regular files may exist in the tree.
100
+ const stack = [targetRoot];
101
+ while (stack.length > 0) {
102
+ const dir = stack.pop();
103
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
104
+ const abs = join(dir, entry.name);
105
+ if (entry.isDirectory()) {
106
+ stack.push(abs);
107
+ }
108
+ else if (!entry.isFile()) {
109
+ throw new CliError(`解包后存在非普通文件,拒绝:${abs}`);
110
+ }
111
+ }
112
+ }
113
+ }
114
+ /** Locate the package root inside an extraction (top-level `package/` or in-place). */
115
+ export function resolveExtractedPackageDir(extractRoot) {
116
+ const packageSubdir = join(extractRoot, 'package');
117
+ if (existsSync(join(packageSubdir, 'package.json'))) {
118
+ return packageSubdir;
119
+ }
120
+ if (existsSync(join(extractRoot, 'package.json'))) {
121
+ return extractRoot;
122
+ }
123
+ throw new CliError(`tgz 解包内容缺少 package.json:${extractRoot}`);
124
+ }
125
+ export function writeMarker(file, content) {
126
+ const slash = Math.max(file.lastIndexOf('/'), file.lastIndexOf('\\'));
127
+ if (slash > 0) {
128
+ mkdirSync(file.slice(0, slash), { recursive: true });
129
+ }
130
+ writeFileSync(file, content, 'utf8');
131
+ }
132
+ export function verifyMarker(file, expected) {
133
+ try {
134
+ return existsSync(file) && readFileSync(file, 'utf8') === expected;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ }
@@ -0,0 +1,16 @@
1
+ export interface ProjectInfo {
2
+ /** Absolute normalized project path, no trailing slash. */
3
+ projectPath: string;
4
+ /** m_EditorVersion, e.g. 2022.3.62f3c1. */
5
+ editorVersion: string;
6
+ /** m_EditorVersionWithRevision revision, e.g. 1623fc0bbb97; null when the line is missing. */
7
+ revision: string | null;
8
+ versionFile: string;
9
+ }
10
+ /** Strict Unity editor version format: YYYY.MAJOR.MINOR[baf]PATCH[+alnum suffix]. */
11
+ export declare const UNITY_EDITOR_VERSION_RE: RegExp;
12
+ export declare function parseProjectVersion(content: string): {
13
+ version: string;
14
+ revision: string | null;
15
+ };
16
+ export declare function readProjectInfo(projectPath: string): ProjectInfo;
@@ -0,0 +1,44 @@
1
+ import { join, resolve } from 'node:path';
2
+ import { readFileSync, existsSync, realpathSync } from 'node:fs';
3
+ import { CliError } from './errors.js';
4
+ const VERSION_RE = /^m_EditorVersion:\s*(.+?)\s*$/m;
5
+ const REVISION_RE = /^m_EditorVersionWithRevision:\s*\S+\s+\(([^)]+)\)\s*$/m;
6
+ /** Strict Unity editor version format: YYYY.MAJOR.MINOR[baf]PATCH[+alnum suffix]. */
7
+ export const UNITY_EDITOR_VERSION_RE = /^[0-9]{4}\.[0-9]+\.[0-9]+[abf][0-9a-z]*$/i;
8
+ export function parseProjectVersion(content) {
9
+ const versionMatch = VERSION_RE.exec(content);
10
+ if (!versionMatch || !versionMatch[1]) {
11
+ throw new CliError('ProjectVersion.txt 缺少 m_EditorVersion 字段。');
12
+ }
13
+ const version = versionMatch[1].trim();
14
+ if (!UNITY_EDITOR_VERSION_RE.test(version)) {
15
+ throw new CliError(`m_EditorVersion 格式非法(拒绝使用):${version}`);
16
+ }
17
+ const revisionMatch = REVISION_RE.exec(content);
18
+ return {
19
+ version,
20
+ revision: revisionMatch?.[1]?.trim() ?? null,
21
+ };
22
+ }
23
+ export function readProjectInfo(projectPath) {
24
+ // Normalize to an absolute, canonical path so the editor guard and --project-path
25
+ // binding never compare a relative input against absolute process command lines.
26
+ let resolved = resolve(projectPath);
27
+ let real;
28
+ try {
29
+ real = realpathSync(resolved);
30
+ }
31
+ catch {
32
+ // Project dir may not exist yet (dry-run on a fresh path); keep the resolved form.
33
+ }
34
+ if (real)
35
+ resolved = real;
36
+ const full = resolved.replace(/[\\/]+$/, '');
37
+ const versionFile = join(full, 'ProjectSettings', 'ProjectVersion.txt');
38
+ if (!existsSync(versionFile)) {
39
+ throw new CliError(`不是有效的 Unity 工程:缺少 ${versionFile}`);
40
+ }
41
+ const content = readFileSync(versionFile, 'utf8');
42
+ const { version, revision } = parseProjectVersion(content);
43
+ return { projectPath: full, editorVersion: version, revision, versionFile };
44
+ }
@@ -0,0 +1,40 @@
1
+ import type { ProjectInfo } from './projectVersion.js';
2
+ export interface CliRoute {
3
+ version: string;
4
+ url: string;
5
+ sha256: string;
6
+ expectedSize?: number;
7
+ signerSubjectContains: string;
8
+ signerThumbprint: string;
9
+ }
10
+ export interface PipelineRoute {
11
+ packageName: string;
12
+ version: string;
13
+ upstreamRevision: string;
14
+ url: string;
15
+ sha1: string;
16
+ sha256: string;
17
+ expectedSize?: number;
18
+ expectedTree: string;
19
+ templates: string;
20
+ targetUnityVersion: string;
21
+ patchVersion: number;
22
+ }
23
+ export interface VersionRoute {
24
+ schemaVersion: number;
25
+ editorVersion: string;
26
+ editorRevision: string;
27
+ cli: CliRoute;
28
+ pipeline: PipelineRoute;
29
+ status?: string;
30
+ }
31
+ export interface ExpectedTree {
32
+ algorithm: string;
33
+ entries: number;
34
+ files: Record<string, string>;
35
+ }
36
+ export declare function loadRoute(editorVersion: string, dir?: string): VersionRoute;
37
+ export declare function listEditorVersions(dir?: string): string[];
38
+ /** Exact version + revision gate. Fail-closed: no fallback, no wildcard, no nearest-version. */
39
+ export declare function resolveRouteForProject(project: ProjectInfo, dir?: string): VersionRoute;
40
+ export declare function loadExpectedTree(editorVersion: string, treeFile?: string): ExpectedTree;
package/dist/routes.js ADDED
@@ -0,0 +1,81 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CliError } from './errors.js';
4
+ import { routesDir, expectedTreePath } from './config.js';
5
+ import { UNITY_EDITOR_VERSION_RE } from './projectVersion.js';
6
+ export function loadRoute(editorVersion, dir = routesDir()) {
7
+ if (!UNITY_EDITOR_VERSION_RE.test(editorVersion)) {
8
+ throw new CliError(`Unity Editor 版本格式非法,拒绝路由查询:${editorVersion}`);
9
+ }
10
+ const file = join(dir, `${editorVersion}.json`);
11
+ let raw;
12
+ try {
13
+ raw = readFileSync(file, 'utf8');
14
+ }
15
+ catch {
16
+ const supported = listEditorVersions(dir);
17
+ throw new CliError(`不支持 Unity Editor ${editorVersion}。当前精确路由:${supported.join(', ') || '(无)'}`);
18
+ }
19
+ const route = JSON.parse(raw);
20
+ if (route.schemaVersion !== 1) {
21
+ throw new CliError(`路由 ${editorVersion} 的 schemaVersion 不支持:${route.schemaVersion}`);
22
+ }
23
+ if (route.editorVersion !== editorVersion) {
24
+ throw new CliError(`路由文件名与内容不一致:${editorVersion} != ${route.editorVersion}`);
25
+ }
26
+ for (const [field, value] of [
27
+ ['cli.version', route.cli?.version],
28
+ ['cli.url', route.cli?.url],
29
+ ['cli.sha256', route.cli?.sha256],
30
+ ['cli.signerSubjectContains', route.cli?.signerSubjectContains],
31
+ ['cli.signerThumbprint', route.cli?.signerThumbprint],
32
+ ['pipeline.packageName', route.pipeline?.packageName],
33
+ ['pipeline.version', route.pipeline?.version],
34
+ ['pipeline.url', route.pipeline?.url],
35
+ ['pipeline.sha1', route.pipeline?.sha1],
36
+ ['pipeline.sha256', route.pipeline?.sha256],
37
+ ['pipeline.expectedTree', route.pipeline?.expectedTree],
38
+ ['pipeline.templates', route.pipeline?.templates],
39
+ ['pipeline.targetUnityVersion', route.pipeline?.targetUnityVersion],
40
+ ]) {
41
+ if (typeof value !== 'string' || value.length === 0) {
42
+ throw new CliError(`路由 ${editorVersion} 缺少字段 ${field}`);
43
+ }
44
+ }
45
+ return route;
46
+ }
47
+ export function listEditorVersions(dir = routesDir()) {
48
+ const files = readdirSync(dir);
49
+ return files
50
+ .filter((f) => f.endsWith('.json') && UNITY_EDITOR_VERSION_RE.test(f.slice(0, -'.json'.length)))
51
+ .map((f) => f.slice(0, -'.json'.length))
52
+ .sort();
53
+ }
54
+ /** Exact version + revision gate. Fail-closed: no fallback, no wildcard, no nearest-version. */
55
+ export function resolveRouteForProject(project, dir = routesDir()) {
56
+ const route = loadRoute(project.editorVersion, dir);
57
+ if (!route.editorRevision) {
58
+ throw new CliError(`路由缺少 editorRevision 配置,拒绝使用:${route.editorVersion}`);
59
+ }
60
+ if (project.revision === null) {
61
+ throw new CliError('工程缺少 m_EditorVersionWithRevision,无法验证精确 Editor revision。');
62
+ }
63
+ if (route.editorRevision !== project.revision) {
64
+ throw new CliError(`Unity 版本号相同但 revision 不匹配。工程:${project.revision},路由:${route.editorRevision}`);
65
+ }
66
+ return route;
67
+ }
68
+ export function loadExpectedTree(editorVersion, treeFile = expectedTreePath(editorVersion)) {
69
+ if (!UNITY_EDITOR_VERSION_RE.test(editorVersion)) {
70
+ throw new CliError(`Unity Editor 版本格式非法,拒绝 expected-tree 查询:${editorVersion}`);
71
+ }
72
+ const tree = JSON.parse(readFileSync(treeFile, 'utf8'));
73
+ if (tree.algorithm !== 'SHA256') {
74
+ throw new CliError(`expected-tree 算法不支持:${tree.algorithm}`);
75
+ }
76
+ const fileCount = Object.keys(tree.files ?? {}).length;
77
+ if (typeof tree.entries !== 'number' || tree.entries !== fileCount) {
78
+ throw new CliError(`expected-tree entries 与 files 数量不一致:entries=${tree.entries},files=${fileCount}`);
79
+ }
80
+ return tree;
81
+ }
@@ -0,0 +1,17 @@
1
+ import type { PipelineRoute } from './routes.js';
2
+ export interface TransformInput {
3
+ sourceRoot: string;
4
+ targetRoot: string;
5
+ route: PipelineRoute;
6
+ expectedTree: Record<string, string>;
7
+ monoImporterBody: string;
8
+ dllImporterBody: string;
9
+ }
10
+ export declare function shouldRemove(relPath: string): boolean;
11
+ /** JSON rewrite matching the verified reference: compact separators, non-ASCII escaped, key order kept. */
12
+ export declare function rewritePackageJson(bytes: Buffer, targetUnity: string): Buffer;
13
+ /** Deterministic transform: upstream tgz package -> adapted package (byte-exact vs expected tree). */
14
+ export declare function transformPackage(input: TransformInput): Promise<{
15
+ fileCount: number;
16
+ }>;
17
+ export declare function readTemplateFile(path: string): string;
@@ -0,0 +1,178 @@
1
+ import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync, existsSync, } from 'node:fs';
2
+ import { dirname, join, relative, sep } from 'node:path';
3
+ import { CliError } from './errors.js';
4
+ import { sha256Buffer, compareTree } from './integrity.js';
5
+ /** Files/dirs present upstream that must NOT ship in the adapted package. */
6
+ const REMOVE_EXACT = new Set([
7
+ '.attestation.p7m',
8
+ '.signature',
9
+ 'CLAUDE.md',
10
+ 'CLAUDE.md.meta',
11
+ 'CODEOWNERS',
12
+ 'CODEOWNERS.meta',
13
+ '.claude',
14
+ ]);
15
+ const REMOVE_PREFIX = ['.claude/', 'Tests/'];
16
+ // NOTE: upstream `Tests.meta` (the folder meta for the empty Tests/ dir) is
17
+ // intentionally KEPT. Unity 2022.3 recreates an empty Tests/ folder inside
18
+ // embedded packages when Tests.meta is absent, generating a fresh meta with a
19
+ // different GUID that breaks exact-tree verification and idempotence. When the
20
+ // meta is already present, Unity leaves it untouched (observed on the
21
+ // reference project), so shipping it keeps the installed tree byte-stable.
22
+ const DLL_META_NAMES = [
23
+ 'Microsoft.CodeAnalysis.CSharp.dll.meta',
24
+ 'Microsoft.CodeAnalysis.dll.meta',
25
+ 'System.Collections.Immutable.dll.meta',
26
+ 'System.Reflection.Metadata.dll.meta',
27
+ 'System.Runtime.CompilerServices.Unsafe.dll.meta',
28
+ ];
29
+ const ALIAS_EXTRA_LF = '#if !UNITY_6000_0_OR_NEWER\n' +
30
+ 'using PhysicsMaterial = UnityEngine.PhysicMaterial;\n' +
31
+ '#endif\n';
32
+ const HELPER_LF = ' public static class MaterialCommands\n {\n' +
33
+ ' private static int GetRawRenderQueue(Material material)\n' +
34
+ ' {\n' +
35
+ ' var serialized = new SerializedObject(material);\n' +
36
+ ' var property = serialized.FindProperty("m_CustomRenderQueue");\n' +
37
+ ' return property != null ? property.intValue : material.renderQueue;\n' +
38
+ ' }\n' +
39
+ '\n';
40
+ export function shouldRemove(relPath) {
41
+ if (REMOVE_EXACT.has(relPath))
42
+ return true;
43
+ return REMOVE_PREFIX.some((p) => relPath.startsWith(p));
44
+ }
45
+ function normalizeCrlf(buf) {
46
+ return Buffer.from(buf.toString('utf8').replace(/\r?\n/g, '\r\n'), 'utf8');
47
+ }
48
+ /** JSON rewrite matching the verified reference: compact separators, non-ASCII escaped, key order kept. */
49
+ export function rewritePackageJson(bytes, targetUnity) {
50
+ const text = bytes.toString('utf8');
51
+ if (!text.startsWith('{')) {
52
+ throw new CliError('package.json 不是 JSON 对象');
53
+ }
54
+ const obj = JSON.parse(text);
55
+ if (obj.unity !== targetUnity) {
56
+ obj.unity = targetUnity;
57
+ }
58
+ const json = JSON.stringify(obj);
59
+ // Match Python json.dumps(ensure_ascii=True): escape every code unit > 0x7F as
60
+ // \uXXXX, iterating UTF-16 code units so astral (surrogate-pair) characters are
61
+ // emitted as their proper \ud83d\ude00 escapes (not orphaned high surrogates).
62
+ let out = '';
63
+ for (let i = 0; i < json.length; i++) {
64
+ const code = json.charCodeAt(i);
65
+ out += code > 0x7f ? `\\u${code.toString(16).padStart(4, '0')}` : json[i];
66
+ }
67
+ if (out.endsWith('\n'))
68
+ out = out.slice(0, -1);
69
+ return Buffer.from(out, 'utf8');
70
+ }
71
+ function patchAssetCommands(bytes) {
72
+ let s = bytes.toString('utf8');
73
+ const hasAlias = s.includes('using PhysicsMaterial = UnityEngine.PhysicMaterial;');
74
+ if (!hasAlias) {
75
+ const eol = s.includes('\r\n') ? '\r\n' : '\n';
76
+ const marker = `using Object = UnityEngine.Object;${eol}`;
77
+ if (!s.includes(marker)) {
78
+ throw new CliError('AssetCommands.cs 缺少锚点 "using Object = UnityEngine.Object;"');
79
+ }
80
+ const extra = ALIAS_EXTRA_LF.split('\n').join(eol);
81
+ s = s.replace(marker, marker + extra);
82
+ }
83
+ return normalizeCrlf(Buffer.from(s, 'utf8'));
84
+ }
85
+ function patchMaterialCommands(bytes) {
86
+ let s = bytes.toString('utf8');
87
+ if (!s.includes('private static int GetRawRenderQueue(Material material)')) {
88
+ const eol = s.includes('\r\n') ? '\r\n' : '\n';
89
+ const marker = ` public static class MaterialCommands${eol} {${eol}`;
90
+ if (!s.includes(marker)) {
91
+ throw new CliError('MaterialCommands.cs 缺少锚点 "public static class MaterialCommands"');
92
+ }
93
+ const helper = HELPER_LF.split('\n').join(eol);
94
+ s = s.replace(marker, helper);
95
+ }
96
+ if (s.includes('RenderQueue = mat.rawRenderQueue,')) {
97
+ s = s.replace('RenderQueue = mat.rawRenderQueue,', 'RenderQueue = GetRawRenderQueue(mat),');
98
+ }
99
+ return normalizeCrlf(Buffer.from(s, 'utf8'));
100
+ }
101
+ function metaBody(bytes) {
102
+ const text = bytes.toString('utf8');
103
+ const m = /^fileFormatVersion: 2\nguid: ([0-9a-f]{32})\n?(.*)$/s.exec(text);
104
+ if (!m?.[1]) {
105
+ throw new CliError('无法从 .meta 读取 guid(fileFormatVersion: 2 + guid 32hex)');
106
+ }
107
+ return { guid: m[1], rest: m[2] ?? '' };
108
+ }
109
+ /** Deterministic transform: upstream tgz package -> adapted package (byte-exact vs expected tree). */
110
+ export async function transformPackage(input) {
111
+ const { sourceRoot, targetRoot, route, expectedTree, monoImporterBody, dllImporterBody } = input;
112
+ rmSync(targetRoot, { recursive: true, force: true });
113
+ mkdirSync(targetRoot, { recursive: true });
114
+ const stack = [sourceRoot];
115
+ while (stack.length > 0) {
116
+ const dir = stack.pop();
117
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
118
+ const abs = join(dir, entry.name);
119
+ const rel = relative(sourceRoot, abs).split(sep).join('/');
120
+ if (shouldRemove(rel))
121
+ continue;
122
+ const destAbs = join(targetRoot, rel.split('/').join(sep));
123
+ if (entry.isDirectory()) {
124
+ mkdirSync(destAbs, { recursive: true });
125
+ stack.push(abs);
126
+ continue;
127
+ }
128
+ if (!entry.isFile()) {
129
+ throw new CliError(`不支持的条目类型:${rel}`);
130
+ }
131
+ const bytes = readFileSync(abs);
132
+ let out;
133
+ if (rel === 'package.json') {
134
+ out = rewritePackageJson(bytes, route.targetUnityVersion);
135
+ }
136
+ else if (rel === 'Editor/Commands/Assets/AssetCommands.cs') {
137
+ out = patchAssetCommands(bytes);
138
+ }
139
+ else if (rel === 'Editor/Commands/Materials/MaterialCommands.cs') {
140
+ out = patchMaterialCommands(bytes);
141
+ }
142
+ else if (DLL_META_NAMES.includes(rel.split('/').pop())) {
143
+ const { guid } = metaBody(bytes);
144
+ out = Buffer.from(`fileFormatVersion: 2\nguid: ${guid}\n${dllImporterBody}`, 'utf8');
145
+ }
146
+ else if (rel.endsWith('.cs.meta')) {
147
+ const expectedHash = expectedTree[rel];
148
+ if (expectedHash !== undefined && sha256Buffer(bytes) === expectedHash) {
149
+ out = bytes; // Unity kept this meta as-is
150
+ }
151
+ else {
152
+ const { guid } = metaBody(bytes);
153
+ out = Buffer.from(`fileFormatVersion: 2\nguid: ${guid}\n${monoImporterBody}`, 'utf8');
154
+ }
155
+ }
156
+ else {
157
+ out = bytes;
158
+ }
159
+ mkdirSync(dirname(destAbs), { recursive: true });
160
+ writeFileSync(destAbs, out);
161
+ }
162
+ }
163
+ const { ok, mismatches } = await compareTree(targetRoot, expectedTree);
164
+ if (!ok) {
165
+ const sample = mismatches
166
+ .slice(0, 10)
167
+ .map((m) => `[${m.kind}] ${m.path}`)
168
+ .join('\n');
169
+ throw new CliError(`transform 输出与 expected-tree 不一致(${mismatches.length} 项):\n${sample}`);
170
+ }
171
+ return { fileCount: Object.keys(expectedTree).length };
172
+ }
173
+ export function readTemplateFile(path) {
174
+ if (!existsSync(path)) {
175
+ throw new CliError(`缺少模板文件:${path}`);
176
+ }
177
+ return readFileSync(path, 'utf8');
178
+ }