public string Compile(CompileOptions options = null) { var code = new StringBuilder(); code.AppendLine(Declare.Info); #region Compile Types for (int skipCount = 0; skipCount < TsTypes.Count; skipCount++) { var cache = TsTypes.Values.Skip(skipCount).First(); cache.Value.TsProperties.Update(); } // Struct & Struct? should map to the same type, so 'Distinct' is required. var typeGroups = TsTypes.Values.Select(x => x.Value).Distinct().Where(x => !x.Declare).GroupBy(x => x.Namespace); if (typeGroups.Any()) { code.AppendLine(); } foreach (var typeGroup in typeGroups) { var tsNamespace = typeGroup.Key; code.AppendLine($"declare namespace {tsNamespace} {{"); foreach (var tsType in typeGroup) { switch (tsType.TypeClass) { case TsTypeClass.Interface: code.AppendLine($"{" ".Repeat(4)}interface {tsType.TypeName} {{"); foreach (var tsProperty in tsType.TsProperties.Value) { var typeString = tsProperty.PropertyTypeDefinition ?? tsProperty.PropertyType.ReferenceName; typeString = typeString.RegexReplace(new Regex($@"(?<![\w\d\._]){tsNamespace}\."), ""); code.AppendLine($"{" ".Repeat(8)}{tsProperty.PropertyName}{(tsProperty.Required ? "" : "?")}: {typeString};"); } code.AppendLine($"{" ".Repeat(4)}}}"); if (options?.OutputNames ?? false) { code.AppendLine($"{" ".Repeat(4)}export const enum {tsType.PureName}_names {{"); foreach (var tsProperty in tsType.TsProperties.Value) { code.AppendLine($"{" ".Repeat(8)}{tsProperty.PropertyName} = '{tsProperty.ClrName}',"); } code.AppendLine($"{" ".Repeat(4)}}}"); } break; case TsTypeClass.Enum: code.AppendLine($"{" ".Repeat(4)}export const enum {tsType.TypeName} {{"); foreach (var tsEnumValue in tsType.TsEnumValues) { code.AppendLine($"{" ".Repeat(8)}{tsEnumValue.Name} = {tsEnumValue.Value},"); } code.AppendLine($"{" ".Repeat(4)}}}"); break; } } code.AppendLine($"}}"); } #endregion #region Compile Consts var tsConstOuterGroups = TsConsts.Values.ToArray().GroupBy(x => x.OuterNamespace); if (tsConstOuterGroups.Any()) { code.AppendLine(); } foreach (var tsConstOuterGroup in tsConstOuterGroups) { var tsConstInnerGroups = tsConstOuterGroup.GroupBy(x => x.InnerNamespace); code.AppendLine($"namespace {tsConstOuterGroup.Key} {{"); foreach (var tsConstInnerGroup in tsConstInnerGroups) { code.AppendLine($"{" ".Repeat(4)}export namespace {tsConstInnerGroup.Key} {{"); foreach (var tsConst in tsConstInnerGroup) { code.AppendLine($"{" ".Repeat(8)}export const {tsConst.ConstName}: {tsConst.ConstType.TypeName} = {tsConst.ConstValue};"); } code.AppendLine($"{" ".Repeat(4)}}}"); } code.AppendLine($"}}"); } #endregion return(code.ToString()); }
public void WriteTo(string path, CompileOptions options = null) => File.WriteAllText(path, Compile(options));