import * as fs from "fs"; import * as path from "path"; import * as ts from "typescript"; import * as tstl from "typescript-to-lua"; import { hasJsDocTag, hasUnLuaDecorator, makeSafeModuleAlias, resolveImportTarget, } from "./type-utils"; export interface ModuleImportRefreshEntry { localVarName: string; moduleAlias: string; propertyKey: string; } export interface ReexportEntry { kind: "named" | "star"; moduleAlias: string; exportName?: string; propertyKey?: string; } export interface ModuleDataEntry { varName: string; isExported: boolean; } export interface FileModuleState { isUnLuaFile: boolean; /** 已导入的模块名 -> 本文件内对应的局部表变量名(如 M__Framework_Log 或 namespace 名) */ importedModules: Map; usedAliases: Set; /** 需插入文件头部的 __MODULE__.Import 与局部解包语句 */ moduleImportStatements: tstl.Statement[]; /** 需在 __module.UpdateImports() 中刷新的局部绑定 */ importRefreshes: ModuleImportRefreshEntry[]; /** 需通过 ____syncReexports() 同步的 `export ... from` 再导出 */ reexports: ReexportEntry[]; /** `import { x } from "./a"; export { x }` 形式的两步再导出 */ localReexportExports: Array<{ exportName: string; localVarName: string }>; /** 通过 `export { x }` 导出的本地非 export 变量(用于 @module_data 恢复后同步) */ localExportAliases: Map; /** 模块顶层 @module_data 变量 */ moduleDataEntries: ModuleDataEntry[]; /** 记录哪些本地变量名来自 __MODULE__.Import 命名/默认解包 */ importedLocalNames: Set; /** 是否替换过顶层类为 __TS__DefineClass */ replacedTopLevelClass: boolean; /** 是否存在未替换的匿名/函数内类仍需 lualib.__TS__Class */ usedRawTstlClass: boolean; } const fileModuleStates = new WeakMap(); let cachedRuntimeModuleLua: string | undefined; let cachedRuntimeClassLua: string | undefined; function getRuntimeFileContent(fileName: "Module.lua" | "Class.lua"): string { if (fileName === "Module.lua" && cachedRuntimeModuleLua !== undefined) { return cachedRuntimeModuleLua; } if (fileName === "Class.lua" && cachedRuntimeClassLua !== undefined) { return cachedRuntimeClassLua; } // dist/plugin/module-transform.js -> ../../runtime/Lib/ const filePath = path.resolve(__dirname, "..", "..", "runtime", "Lib", fileName); const content = fs.readFileSync(filePath, "utf8"); if (fileName === "Module.lua") { cachedRuntimeModuleLua = content; } else { cachedRuntimeClassLua = content; } return content; } export function initFileModuleState(sourceFile: ts.SourceFile, isUnLuaFile: boolean): FileModuleState { const state: FileModuleState = { isUnLuaFile, importedModules: new Map(), usedAliases: new Set(), moduleImportStatements: [], importRefreshes: [], reexports: [], localReexportExports: [], localExportAliases: new Map(), moduleDataEntries: [], importedLocalNames: new Set(), replacedTopLevelClass: false, usedRawTstlClass: false, }; // 预收集模块顶层 @module_data 声明(仅对常规模块启用) if (!isUnLuaFile) { for (const stmt of sourceFile.statements) { if (!ts.isVariableStatement(stmt)) continue; const stmtTagged = hasJsDocTag(stmt, "module_data"); const modifiers = ts.canHaveModifiers(stmt) ? ts.getModifiers(stmt) : undefined; const isExported = modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false; const isDeclare = modifiers?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword) ?? false; if (isDeclare) continue; for (const decl of stmt.declarationList.declarations) { if ((stmtTagged || hasJsDocTag(decl, "module_data")) && ts.isIdentifier(decl.name)) { state.moduleDataEntries.push({ varName: decl.name.text, isExported, }); } } } } fileModuleStates.set(sourceFile, state); return state; } export function getFileModuleState(sourceFile: ts.SourceFile): FileModuleState | undefined { return fileModuleStates.get(sourceFile); } function isExportsIdentifier(expr: tstl.Node | undefined): boolean { return expr !== undefined && tstl.isIdentifier(expr) && expr.text === "____exports"; } function isEmptyExportsDeclaration(stmt: tstl.Statement): boolean { if (!tstl.isVariableDeclarationStatement(stmt)) return false; if (stmt.left.length !== 1 || !isExportsIdentifier(stmt.left[0])) return false; if (!stmt.right || stmt.right.length !== 1) return false; const rhs = stmt.right[0]; return tstl.isTableExpression(rhs) && rhs.fields.length === 0; } function isReturnExportsStatement(stmt: tstl.Statement): boolean { if (!tstl.isReturnStatement(stmt)) return false; return stmt.expressions.length === 1 && isExportsIdentifier(stmt.expressions[0]); } function createModuleImportCall( moduleName: string, includeCallerModule: boolean, originalNode?: ts.Node ): tstl.CallExpression { const args: tstl.Expression[] = [tstl.createStringLiteral(moduleName, originalNode)]; if (includeCallerModule) { args.push(tstl.createIdentifier("__module")); } return tstl.createCallExpression( tstl.createTableIndexExpression( tstl.createIdentifier("__MODULE__"), tstl.createStringLiteral("Import") ), args, originalNode ); } /** * 确保目标模块在当前文件中已通过 `__MODULE__.Import` 引入,返回其局部别名(去重复用)。 */ function ensureModuleImported( state: FileModuleState, moduleName: string, preferredAlias: string | undefined, originalNode: ts.Node ): string { const existing = state.importedModules.get(moduleName); if (existing) { if (preferredAlias && preferredAlias !== existing) { state.moduleImportStatements.push( tstl.createVariableDeclarationStatement( tstl.createIdentifier(preferredAlias, originalNode), tstl.createIdentifier(existing), originalNode ) ); return preferredAlias; } return existing; } let alias: string; if (preferredAlias && !state.usedAliases.has(preferredAlias)) { alias = preferredAlias; state.usedAliases.add(alias); } else { alias = makeSafeModuleAlias(moduleName, state.usedAliases); } state.importedModules.set(moduleName, alias); state.moduleImportStatements.push( tstl.createVariableDeclarationStatement( tstl.createIdentifier(alias, originalNode), createModuleImportCall(moduleName, !state.isUnLuaFile, originalNode), originalNode ) ); return alias; } function shouldImportRuntimeNode( context: tstl.TransformationContext, node: ts.ImportClause | ts.NamespaceImport | ts.ImportSpecifier ): boolean { if (ts.isTypeOnlyImportOrExportDeclaration(node)) { return false; } return context.resolver.isReferencedAliasDeclaration(node); } /** * 将指向项目 TS 模块的 ImportDeclaration 转换为 `__MODULE__.Import("...", __module)`, * 外部 `.d.ts` / `@noResolution` / `@unlua` 目标返回 `undefined` 交给默认逻辑处理。 */ export function tryTransformHotReloadImport( node: ts.ImportDeclaration, context: tstl.TransformationContext ): tstl.Statement[] | undefined { const sf = node.getSourceFile() ?? context.sourceFile; const state = getFileModuleState(sf); if (!state) return undefined; const target = resolveImportTarget(node.moduleSpecifier, context); if (target.kind === "external" || target.isUnLuaTarget) { return undefined; } // 副作用导入:import "./init"; if (!node.importClause) { state.moduleImportStatements.push( tstl.createExpressionStatement( createModuleImportCall(target.moduleName, !state.isUnLuaFile, node), node ) ); return []; } // import type { ... } from "..." if (node.importClause.isTypeOnly) { return []; } const needDefault = node.importClause.name !== undefined && shouldImportRuntimeNode(context, node.importClause); const namedBindings = node.importClause.namedBindings; const needNamespace = namedBindings !== undefined && ts.isNamespaceImport(namedBindings) && shouldImportRuntimeNode(context, namedBindings); const runtimeNamedSpecifiers = namedBindings !== undefined && ts.isNamedImports(namedBindings) ? namedBindings.elements.filter((el) => shouldImportRuntimeNode(context, el)) : []; if (!needDefault && !needNamespace && runtimeNamedSpecifiers.length === 0) { return []; } // 纯命名空间导入:import * as Log from "./Log" -> local Log = __MODULE__.Import("Framework.Log", __module) if (needNamespace && !needDefault && runtimeNamedSpecifiers.length === 0 && ts.isNamespaceImport(namedBindings!)) { ensureModuleImported(state, target.moduleName, namedBindings.name.text, node); return []; } const moduleAlias = ensureModuleImported( state, target.moduleName, needNamespace && ts.isNamespaceImport(namedBindings!) ? namedBindings.name.text : undefined, node ); // 默认导入:import Foo from "./foo" -> local Foo = M__foo.default if (needDefault && node.importClause.name) { const localName = node.importClause.name.text; state.moduleImportStatements.push( tstl.createVariableDeclarationStatement( tstl.createIdentifier(localName, node.importClause.name), tstl.createTableIndexExpression( tstl.createIdentifier(moduleAlias), tstl.createStringLiteral("default", node.importClause.name) ), node.importClause.name ) ); state.importedLocalNames.add(localName); if (!state.isUnLuaFile) { state.importRefreshes.push({ localVarName: localName, moduleAlias, propertyKey: "default", }); } } // 命名导入:import { A, B as C } from "./foo" -> local A = M__foo.A; local C = M__foo.B for (const spec of runtimeNamedSpecifiers) { const localName = spec.name.text; const propName = (spec.propertyName ?? spec.name).text; state.moduleImportStatements.push( tstl.createVariableDeclarationStatement( tstl.createIdentifier(localName, spec.name), tstl.createTableIndexExpression( tstl.createIdentifier(moduleAlias), tstl.createStringLiteral(propName, spec.propertyName ?? spec.name) ), spec ) ); state.importedLocalNames.add(localName); if (!state.isUnLuaFile) { state.importRefreshes.push({ localVarName: localName, moduleAlias, propertyKey: propName, }); } } return []; } /** * 转换 `export { ... } from "./sub"`、`export * from "./sub"`、`export * as NS from "./sub"` * 以及记录本地 `export { A, B as C }`。 */ export function tryTransformHotReloadExportDeclaration( node: ts.ExportDeclaration, context: tstl.TransformationContext ): tstl.Statement[] | undefined { const sf = node.getSourceFile() ?? context.sourceFile; const state = getFileModuleState(sf); if (!state || state.isUnLuaFile) return undefined; if (node.isTypeOnly) { return []; } // 本地 `export { A, B as C }`(无 from) if (!node.moduleSpecifier) { if (node.exportClause && ts.isNamedExports(node.exportClause)) { for (const spec of node.exportClause.elements) { if (spec.isTypeOnly || !context.resolver.isValueAliasDeclaration(spec)) continue; const localName = (spec.propertyName ?? spec.name).text; const exportName = spec.name.text; if (state.importedLocalNames.has(localName)) { state.localReexportExports.push({ exportName, localVarName: localName }); } else { const existing = state.localExportAliases.get(localName) ?? []; existing.push(exportName); state.localExportAliases.set(localName, existing); } } } return undefined; // 让 TSTL 正常生成 `____exports.X = X` } const target = resolveImportTarget(node.moduleSpecifier, context); if (target.kind === "external" || target.isUnLuaTarget) { return undefined; } // `export * from "./sub"` if (!node.exportClause) { const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); state.reexports.push({ kind: "star", moduleAlias, }); return []; } // `export * as Sub from "./sub"` if (ts.isNamespaceExport(node.exportClause)) { const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); return [ tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.createStringLiteral(node.exportClause.name.text, node.exportClause.name) ), tstl.createIdentifier(moduleAlias), node ), ]; } // `export { A, B as C } from "./sub"` const runtimeSpecifiers = node.exportClause.elements.filter( (spec) => !spec.isTypeOnly && context.resolver.isValueAliasDeclaration(spec) ); if (runtimeSpecifiers.length === 0) { return []; } const moduleAlias = ensureModuleImported(state, target.moduleName, undefined, node); for (const spec of runtimeSpecifiers) { const propName = (spec.propertyName ?? spec.name).text; const exportName = spec.name.text; state.reexports.push({ kind: "named", moduleAlias, exportName, propertyKey: propName, }); } return []; } function isRawTstlClassCall(expr: tstl.Expression | undefined): boolean { if (!expr || !tstl.isCallExpression(expr)) return false; return ( tstl.isIdentifier(expr.expression) && expr.expression.text === "__TS__Class" && expr.params.length === 0 ); } function createDefineClassCall(classKeyName: string, originalNode?: ts.Node): tstl.CallExpression { return tstl.createCallExpression( tstl.createIdentifier("__TS__DefineClass"), [tstl.createStringLiteral(classKeyName, originalNode), tstl.createIdentifier("__module")], originalNode ); } function hasDefaultExportModifier(node: ts.ClassDeclaration): boolean { if (!ts.canHaveModifiers(node)) return false; return ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) ?? false; } /** * 将顶层纯 TS `ClassDeclaration` 的 `__TS__Class()` 替换为扁平全局调用 `__TS__DefineClass("Name", __module)`, * 以便运行时单文件热更时复用类与原型表,同时避免额外表查询与 `lualib.__TS__Class` 引入。 */ export function transformPureClassForHotReload( node: ts.ClassDeclaration, context: tstl.TransformationContext ): tstl.Statement[] { const sf = node.getSourceFile() ?? context.sourceFile; const state = getFileModuleState(sf); const statements = context.superTransformStatements(node); if (!state || state.isUnLuaFile || hasUnLuaDecorator(node)) { return statements; } const isTopLevel = ts.isSourceFile(node.parent); const classKeyName = node.name?.text ?? (hasDefaultExportModifier(node) ? "default" : undefined); if (!isTopLevel || !classKeyName || statements.length === 0) { state.usedRawTstlClass = true; return statements; } const first = statements[0]; if ( tstl.isVariableDeclarationStatement(first) && first.right && first.right.length === 1 && isRawTstlClassCall(first.right[0]) ) { statements[0] = tstl.createVariableDeclarationStatement( first.left, [createDefineClassCall(classKeyName, node)], node ); state.replacedTopLevelClass = true; return statements; } if ( tstl.isAssignmentStatement(first) && first.right.length === 1 && isRawTstlClassCall(first.right[0]) ) { statements[0] = tstl.createAssignmentStatement( first.left, [createDefineClassCall(classKeyName, node)], node ); state.replacedTopLevelClass = true; return statements; } state.usedRawTstlClass = true; return statements; } export function markRawTstlClassUsed(sourceFile: ts.SourceFile): void { const state = getFileModuleState(sourceFile); if (state) { state.usedRawTstlClass = true; } } /** * 允许业务 TS 直接书写 `const cjson = require("cjson")`、`require("UnLua.HotReload")` 等外部原生 Lua/C 插件: * 对非项目内相对路径的 `require("...")` 临时添加 `@NoResolution:` 前缀,由 TSTL resolve 阶段自动剥离并原样输出 `require("cjson")`, * 避免触发 TSTL 100000 ("Could not resolve lua source files") 报错,无需在 tsconfig 手工枚举 noResolvePaths。 */ export function tryTransformNativeRequireCall( node: ts.CallExpression, context: tstl.TransformationContext ): tstl.Expression | undefined { if (!ts.isIdentifier(node.expression) || node.expression.text !== "require") { return undefined; } if (node.arguments.length !== 1) { return undefined; } const arg = node.arguments[0]; if (!ts.isStringLiteral(arg)) { return undefined; } const text = arg.text; if (text.startsWith("@NoResolution:") || text.startsWith(".")) { return undefined; } const target = resolveImportTarget(arg, context); if (target.kind === "project") { return undefined; } return tstl.createCallExpression( tstl.createIdentifier("require", node.expression), [tstl.createStringLiteral(`@NoResolution:${text}`, arg)], node ); } function createModuleDataAccessExpr(entry: ModuleDataEntry): tstl.AssignmentLeftHandSideExpression { if (entry.isExported) { return tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.createStringLiteral(entry.varName) ); } return tstl.createIdentifier(entry.varName); } function buildStashAndRestoreStatements(state: FileModuleState): tstl.Statement[] { if (state.moduleDataEntries.length === 0) { return []; } // function __module.StashData(env, to) ... end const stashBody: tstl.Statement[] = [ tstl.createVariableDeclarationStatement( tstl.createIdentifier("____has"), tstl.createTableIndexExpression( tstl.createIdentifier("to"), tstl.createStringLiteral("__has__") ) ), tstl.createIfStatement( tstl.createUnaryExpression( tstl.createIdentifier("____has"), tstl.SyntaxKind.NotOperator ), tstl.createBlock([ tstl.createAssignmentStatement( tstl.createIdentifier("____has"), tstl.createTableExpression([]) ), tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("to"), tstl.createStringLiteral("__has__") ), tstl.createIdentifier("____has") ), ]) ), ]; for (const entry of state.moduleDataEntries) { stashBody.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("to"), tstl.createStringLiteral(entry.varName) ), createModuleDataAccessExpr(entry) ) ); stashBody.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____has"), tstl.createStringLiteral(entry.varName) ), tstl.createBooleanLiteral(true) ) ); } const stashFn = tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("__module"), tstl.createStringLiteral("StashData") ), tstl.createFunctionExpression( tstl.createBlock(stashBody), [tstl.createIdentifier("env"), tstl.createIdentifier("to")], undefined, tstl.NodeFlags.Declaration ) ); // function __module.RestoreData(env, from) ... end const restoreBody: tstl.Statement[] = [ tstl.createVariableDeclarationStatement( tstl.createIdentifier("____has"), tstl.createTableIndexExpression( tstl.createIdentifier("from"), tstl.createStringLiteral("__has__") ) ), tstl.createIfStatement( tstl.createUnaryExpression( tstl.createIdentifier("____has"), tstl.SyntaxKind.NotOperator ), tstl.createBlock([tstl.createReturnStatement([])]) ), ]; for (const entry of state.moduleDataEntries) { const assignBlockStmts: tstl.Statement[] = [ tstl.createAssignmentStatement( createModuleDataAccessExpr(entry), tstl.createTableIndexExpression( tstl.createIdentifier("from"), tstl.createStringLiteral(entry.varName) ) ), ]; // 若该本地变量同时通过 `export { x }` 导出,恢复后同步写回 ____exports if (!entry.isExported) { const aliasExports = state.localExportAliases.get(entry.varName); if (aliasExports) { for (const expName of aliasExports) { assignBlockStmts.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.createStringLiteral(expName) ), tstl.createIdentifier(entry.varName) ) ); } } } restoreBody.push( tstl.createIfStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____has"), tstl.createStringLiteral(entry.varName) ), tstl.createBlock(assignBlockStmts) ) ); } const restoreFn = tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("__module"), tstl.createStringLiteral("RestoreData") ), tstl.createFunctionExpression( tstl.createBlock(restoreBody), [tstl.createIdentifier("env"), tstl.createIdentifier("from")], undefined, tstl.NodeFlags.Declaration ) ); return [stashFn, restoreFn]; } function buildSyncReexportsStatements(state: FileModuleState): tstl.Statement[] { if (state.reexports.length === 0) { return []; } const body: tstl.Statement[] = []; for (const entry of state.reexports) { if (entry.kind === "named" && entry.exportName && entry.propertyKey) { body.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.createStringLiteral(entry.exportName) ), tstl.createTableIndexExpression( tstl.createIdentifier(entry.moduleAlias), tstl.createStringLiteral(entry.propertyKey) ) ) ); } else if (entry.kind === "star") { const kId = tstl.createIdentifier("____exportKey"); const vId = tstl.createIdentifier("____exportValue"); const cond = tstl.createBinaryExpression( tstl.createBinaryExpression( tstl.cloneIdentifier(kId), tstl.createStringLiteral("default"), tstl.SyntaxKind.InequalityOperator ), tstl.createBinaryExpression( tstl.cloneIdentifier(kId), tstl.createStringLiteral("__module"), tstl.SyntaxKind.InequalityOperator ), tstl.SyntaxKind.AndOperator ); const assign = tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.cloneIdentifier(kId) ), tstl.cloneIdentifier(vId) ); body.push( tstl.createForInStatement( tstl.createBlock([tstl.createIfStatement(cond, tstl.createBlock([assign]))]), [kId, vId], [ tstl.createCallExpression(tstl.createIdentifier("pairs"), [ tstl.createIdentifier(entry.moduleAlias), ]), ] ) ); } } const fnDecl = tstl.createVariableDeclarationStatement( tstl.createIdentifier("____syncReexports"), tstl.createFunctionExpression(tstl.createBlock(body), [], undefined, tstl.NodeFlags.Declaration) ); const initialCall = tstl.createExpressionStatement( tstl.createCallExpression(tstl.createIdentifier("____syncReexports"), []) ); return [fnDecl, initialCall]; } function buildUpdateImportsStatement(state: FileModuleState): tstl.Statement { const body: tstl.Statement[] = []; for (const ref of state.importRefreshes) { body.push( tstl.createAssignmentStatement( tstl.createIdentifier(ref.localVarName), tstl.createTableIndexExpression( tstl.createIdentifier(ref.moduleAlias), tstl.createStringLiteral(ref.propertyKey) ) ) ); } if (state.reexports.length > 0) { body.push( tstl.createExpressionStatement( tstl.createCallExpression(tstl.createIdentifier("____syncReexports"), []) ) ); } for (const localReexp of state.localReexportExports) { body.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("____exports"), tstl.createStringLiteral(localReexp.exportName) ), tstl.createIdentifier(localReexp.localVarName) ) ); } return tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("__module"), tstl.createStringLiteral("UpdateImports") ), tstl.createFunctionExpression( tstl.createBlock(body), [], undefined, tstl.NodeFlags.Declaration ) ); } /** * 组装常规 TS 模块的 hot-reload 产物: * - `local ____exports = {}` -> `local ____exports = __module.env` * - 移除尾部 `return ____exports` * - 头部注入 `__MODULE__.Import` 语句(以及 Barrel `__module.hasReexports = true`) * - 尾部注入 `____syncReexports` / `__module.StashData` / `__module.RestoreData` / `__module.UpdateImports` * - 按需剔除已完全替换为 `__TS__DefineClass` 的 `LuaLibFeature.Class` */ export function transformHotReloadSourceFile( node: ts.SourceFile, context: tstl.TransformationContext ): tstl.File { const state = initFileModuleState(node, false); const [luaFile] = context.superTransformNode(node) as [tstl.File]; const bodyStatements: tstl.Statement[] = []; let hadExportsDecl = false; for (let i = 0; i < luaFile.statements.length; i++) { const stmt = luaFile.statements[i]; if (isEmptyExportsDeclaration(stmt)) { hadExportsDecl = true; continue; } if (i === luaFile.statements.length - 1 && isReturnExportsStatement(stmt)) { continue; } bodyStatements.push(stmt); } const hasReexports = state.reexports.length > 0 || state.localReexportExports.length > 0; const finalStatements: tstl.Statement[] = []; if (hadExportsDecl || hasReexports || state.moduleDataEntries.some((d) => d.isExported)) { finalStatements.push( tstl.createVariableDeclarationStatement( tstl.createIdentifier("____exports"), tstl.createTableIndexExpression( tstl.createIdentifier("__module"), tstl.createStringLiteral("env") ) ) ); } if (hasReexports) { finalStatements.push( tstl.createAssignmentStatement( tstl.createTableIndexExpression( tstl.createIdentifier("__module"), tstl.createStringLiteral("hasReexports") ), tstl.createBooleanLiteral(true) ) ); } finalStatements.push(...state.moduleImportStatements); finalStatements.push(...bodyStatements); finalStatements.push(...buildSyncReexportsStatements(state)); finalStatements.push(...buildStashAndRestoreStatements(state)); finalStatements.push(buildUpdateImportsStatement(state)); const luaLibFeatures = new Set(luaFile.luaLibFeatures); if (state.replacedTopLevelClass && !state.usedRawTstlClass) { luaLibFeatures.delete(tstl.LuaLibFeature.Class); } return tstl.createFile(finalStatements, luaLibFeatures, luaFile.trivia, node); } /** * 在 `beforeEmit` 阶段自动向编译产物目录输出 `Lib/Module.lua` 与 `Lib/Class.lua`(不覆盖已有同名产物)。 */ export function emitModuleRuntimeFiles( _program: ts.Program, options: tstl.CompilerOptions, result: tstl.EmitFile[], runtimeDir: string ): void { const outDir = options.outDir ?? options.rootDir ?? "."; const existingPaths = new Set( result.map((f) => path.normalize(f.outputPath).replace(/\\/g, "/")) ); const filesToEmit: Array<"Module.lua" | "Class.lua"> = ["Module.lua", "Class.lua"]; for (const fileName of filesToEmit) { const outputPath = path.join(outDir, runtimeDir, fileName); const normalized = path.normalize(outputPath).replace(/\\/g, "/"); if (existingPaths.has(normalized)) { continue; } result.push({ outputPath, code: getRuntimeFileContent(fileName), }); } }