import test from "node:test"; import assert from "node:assert/strict"; import * as fs from "node:fs"; import * as path from "node:path"; import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import { createRequire } from "node:module"; const require = createRequire(import.meta.url); const projectRoot = path.resolve(import.meta.dirname, ".."); const unluaTypesPath = path.join(projectRoot, "types", "unlua.d.ts"); const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8"); const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); const { UnLuaDiagnosticCode } = require(pluginPath); /** * 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。 */ function transpileWithUnLua(files) { const virtualFiles = { "unlua.d.ts": unluaTypesContent, ...files, }; return tstl.transpileVirtualProject(virtualFiles, { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler, lib: ["lib.esnext.d.ts"], strict: true, skipLibCheck: true, experimentalDecorators: true, rootDir: ".", luaTarget: tstl.LuaTarget.Lua54, luaLibImport: tstl.LuaLibImportKind.RequireMinimal, noImplicitSelf: false, noHeader: true, luaPlugins: [{ name: pluginPath }], }); } function getUnLuaErrors(result) { return result.diagnostics.filter((d) => d.source === "ts2lua-unlua"); } function getLuaCode(result, luaPath) { const normalized = luaPath.replace(/\\/g, "/"); const found = result.transpiledFiles.find((f) => { const out = (f.outPath || "").replace(/\\/g, "/"); return out === normalized || out.endsWith("/" + normalized); }); assert.ok(found, `Expected emitted file '${luaPath}', got: ${result.transpiledFiles.map((f) => f.outPath).join(", ")}`); return found.lua; } // ============================================================ // 1. 正常转译(Positive Cases) // ============================================================ test("@unlua class extending UE native class compiles to UnLua.Class() + self.Overridden + return ClassName", () => { const result = transpileWithUnLua({ "Game/MyActor.ts": ` @unlua export default class MyActor extends UE.AActor { private hp!: number; static readonly MAX_HP = 100; ReceiveBeginPlay(): void { super.ReceiveBeginPlay(); this.hp = MyActor.MAX_HP; } static Helper(a: number, b = 10): number { return a + b; } } `, }); assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); const lua = getLuaCode(result, "Game/MyActor.lua"); assert.match(lua, /local MyActor = UnLua\.Class\(\)/); assert.match(lua, /function MyActor\.ReceiveBeginPlay\(self\)/); assert.match(lua, /self\.Overridden\.ReceiveBeginPlay\(self\)/); assert.match(lua, /MyActor\.MAX_HP = 100/); assert.match(lua, /function MyActor\.Helper\(a, b\)/); assert.match(lua, /if b == nil then/); assert.match(lua, /return MyActor\s*$/); assert.doesNotMatch(lua, /____exports/); assert.doesNotMatch(lua, /__TS__Class/); assert.doesNotMatch(lua, /__TS__Decorate/); }); test("@unlua subclass extending another @unlua TS class compiles to UnLua.Class('Game.BaseActor') + BaseActor.Method(self)", () => { const result = transpileWithUnLua({ "Game/BaseActor.ts": ` @unlua export default class BaseActor extends UE.AActor { ReceiveBeginPlay(): void { super.ReceiveBeginPlay(); } DoWork(val: number): void { this.ReceiveTick(val); } } `, "Game/SubActor.ts": ` import BaseActor from "./BaseActor"; @unlua export default class SubActor extends BaseActor { ReceiveBeginPlay(): void { super.ReceiveBeginPlay(); super.DoWork(42); } } `, }); assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); const lua = getLuaCode(result, "Game/SubActor.lua"); assert.match(lua, /local BaseActor = require\("Game\.BaseActor"\)/); assert.doesNotMatch(lua, /\.default\b/); assert.match(lua, /local SubActor = UnLua\.Class\("Game\.BaseActor"\)/); assert.match(lua, /BaseActor\.ReceiveBeginPlay\(self\)/); assert.match(lua, /BaseActor\.DoWork\(self, 42\)/); assert.match(lua, /return SubActor\s*$/); }); test("@unlua supports explicit base module path and standalone blueprint classes without extends", () => { const result = transpileWithUnLua({ "UI/WBP_Main.ts": ` export interface MainUIData { title: string; } @unlua("UI.WBP_Base") export default class WBP_Main { Construct(): void { const data: MainUIData = { title: "hello" }; void data; } } `, }); assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); const lua = getLuaCode(result, "UI/WBP_Main.lua"); assert.match(lua, /local WBP_Main = UnLua\.Class\("UI\.WBP_Base"\)/); assert.match(lua, /return WBP_Main\s*$/); }); test("const enum, pure TS class, Delegate member method binding, and @unlua-allow-try are allowed", () => { const result = transpileWithUnLua({ "Logic/State.ts": ` const enum EState { Idle = 0, Run = 1, } export class PureCounter { private count = 0; constructor(initial: number) { this.count = initial; } Inc(): number { this.count += EState.Run; return this.count; } SafeCall(): boolean { /** @unlua-allow-try */ try { return this.count > 0; } catch { return false; } } } `, "UI/ButtonWidget.ts": ` @unlua export default class ButtonWidget extends UE.UUserWidget { OnClicked!: UE.FMulticastScriptDelegate<() => void>; Construct(): void { this.OnClicked.Add(this, this.HandleClick); } Destruct(): void { this.OnClicked.Remove(this, this.HandleClick); } HandleClick(): void { if (this.IsA(UE.UUserWidget.StaticClass())) { return; } } } `, }); assert.equal(getUnLuaErrors(result).length, 0, JSON.stringify(getUnLuaErrors(result), null, 2)); }); // ============================================================ // 2. 禁用语言特性拦截(Negative Cases: 90001 - 90016) // ============================================================ test("forbids get/set accessors in classes and object literals", () => { const result = transpileWithUnLua({ "bad.ts": ` class Foo { private _x = 0; get x(): number { return this._x; } set x(v: number) { this._x = v; } } export const o = { get a() { return 1; }, }; export { Foo }; `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAccessor)); assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenAccessor).length >= 3); }); test("forbids async/await and Promise", () => { const result = transpileWithUnLua({ "bad.ts": ` export async function fetchSomething(): Promise { const p = new Promise((resolve) => resolve(1)); const v = await p; const v2 = await Promise.resolve(2); return v + v2; } `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenAsyncAwait)); assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenPromise)); }); test("forbids try/catch/finally and throw without @unlua-allow-try", () => { const result = transpileWithUnLua({ "bad.ts": ` export function risky(flag: boolean): void { try { if (flag) { throw "boom"; } } catch (e) { void e; } } `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.filter((c) => c === UnLuaDiagnosticCode.ForbiddenTryCatchThrow).length >= 2); }); test("forbids non-whitelisted runtime decorators", () => { const result = transpileWithUnLua({ "bad.ts": ` function myDec(target: any) { return target; } @myDec export class Foo {} `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.ForbiddenDecorator)); }); test("forbids RegExp, Map, Set, Proxy, Symbol, Object.defineProperty, Reflect, generator, for..in, runtime enum, eval, arguments", () => { const result = transpileWithUnLua({ "bad.ts": ` export enum EBadEnum { A = 0, B = 1 } export function* gen() { yield 1; } export function badBuiltins(obj: Record) { const r1 = /abc/; const r2 = new RegExp("abc"); const m = new Map(); const s = new Set(); const p = new Proxy(obj, {}); const sym = Symbol("x"); Object.defineProperty(obj, "k", { value: 1 }); Reflect.get(obj, "k"); eval("1 + 1"); for (const k in obj) { void k; } const a = arguments; return [r1, r2, m, s, p, sym, a]; } `, }); const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRuntimeEnum)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenGenerator)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenRegExp)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenBuiltinType)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenForIn)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDynamicEvalOrWith)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenArguments)); }); test("forbids delete on array/UObject, instanceof UObject, and spreading UObject", () => { const result = transpileWithUnLua({ "bad.ts": ` export function check(arr: number[], actor: UE.AActor): boolean { delete arr[0]; delete (actor as any).SomeProp; const copy = { ...actor }; void copy; return actor instanceof UE.AActor; } `, }); const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenDeleteOnArrayOrUObject)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenInstanceOfUObject)); assert.ok(codes.has(UnLuaDiagnosticCode.ForbiddenUObjectSpread)); }); // ============================================================ // 3. @unlua 绑定类专项拦截(Negative Cases: 90101 - 90110) // ============================================================ test("forbids missing @unlua decorator on class extending UE.UObject (fail-safe)", () => { const result = transpileWithUnLua({ "Game/ForgotDecorator.ts": ` export default class ForgotDecorator extends UE.AActor { ReceiveBeginPlay(): void {} } `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.MissingUnLuaDecorator)); }); test("forbids constructor, field initializer, arrow method, and non-default export in @unlua class", () => { const result = transpileWithUnLua({ "Game/BadActor.ts": ` export const EXTRA = 1; @unlua export class BadActor extends UE.AActor { private hp = 100; OnClick = () => {}; constructor() { super(); } } `, }); const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassMustBeDefaultExport)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaFileExtraRuntimeExport)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenConstructor)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaClassForbiddenPropertyInitializer)); }); test("forbids 'new MyUnLuaActor()' instantiation", () => { const result = transpileWithUnLua({ "Game/MyActor.ts": ` @unlua export default class MyActor extends UE.AActor {} `, "Game/Spawner.ts": ` import MyActor from "./MyActor"; export function spawnBad() { return new MyActor(); } `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaClassForbiddenNew)); }); test("forbids inline arrow/function expression in UE Delegate Add/Bind", () => { const result = transpileWithUnLua({ "UI/BadWidget.ts": ` @unlua export default class BadWidget extends UE.UUserWidget { OnClicked!: UE.FMulticastScriptDelegate<() => void>; Construct(): void { this.OnClicked.Add(this, () => { this.Destruct(); }); } } `, }); const codes = getUnLuaErrors(result).map((d) => d.code); assert.ok(codes.includes(UnLuaDiagnosticCode.UnLuaDelegateForbiddenInlineFunction)); }); test("forbids multiple @unlua classes in one file, invalid @unlua args, and direct super property read", () => { const result = transpileWithUnLua({ "Game/Multi.ts": ` @unlua(123 as any) export default class ActorA extends UE.AActor { ReceiveBeginPlay(): void { const x = super.GetName; void x; } } @unlua class ActorB extends UE.AActor {} void ActorB; `, }); const codes = new Set(getUnLuaErrors(result).map((d) => d.code)); assert.ok(codes.has(UnLuaDiagnosticCode.InvalidUnLuaDecoratorArgs)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaMultipleClassesInFile)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage)); }); // ============================================================ // 4. 端到端示例工程编译验证 // ============================================================ test("examples/tsconfig.json transpiles cleanly with zero diagnostics", () => { const exampleConfigPath = path.join(projectRoot, "examples", "tsconfig.json"); const result = tstl.transpileProject(exampleConfigPath); const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); assert.equal(errors.length, 0, errors.map((e) => ts.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n")); });