public void GlobalizationTypesCreatedWhenNotUsed()
        {
            var ts = TypeScript.Definitions();

            ts.WithConvertor <System.Globalization.CultureInfo>(type => { return("string"); }).For <TestClass>().WithConvertor <System.Globalization.CultureInfo>(type => { return("string"); });
            var result = ts.Generate(TsGeneratorOutput.Properties);
        }
        public static string GetTypeLitePocos(this IEnumerable <Type> types, TsGeneratorOutput output, bool useNamespace = true, bool isExported = true)
        {
            var replacements = new List <string>();
            var def          = TypeScript.Definitions();

            foreach (var type in types)
            {
                def.For(type);
                var r = type.DeclaringType?.FullName;
                if (r != null && string.IsNullOrEmpty(type.Namespace))
                {
                    replacements.Add(r);
                }
            }
            var script = def.Generate(output);

            if (isExported)
            {
                script = script.Replace("interface ", "export interface ");
            }
            if (useNamespace)
            {
                script = script.Replace("declare module ", "namespace ");
            }
            return(script);
        }
        public void SelfReferencingEnumerableInheritorGenerateAnyArray()
        {
            var ts = TypeScript.Definitions();

            ts
            .WithMemberTypeFormatter((tsProperty, memberTypeName) => {
                // The following is a workaround proof-of-concept for the JSON.NET JObject class (among others).
                // Without this, it would be similar to a List<JToken> (in the way that they both
                // implement IEnumerable<JToken>) and emit type "any[]" instead of the desired type "any".
                // Example: tsProperty.PropertyType.Type.FullName == "Newtonsoft.Json.Linq.JObject"
                if (tsProperty.PropertyType.Type.Name == "SelfReferencingEnumerableInheritor")
                {
                    // No "[]" emitted.
                    return(memberTypeName);
                }
                return(ts.ScriptGenerator.DefaultMemberTypeFormatter(tsProperty, memberTypeName));
            })
            .For <SelfReferencingEnumerableInheritorWrapper>();
            string output = ts
                            .Generate(TsGeneratorOutput.Properties);

            Assert.Contains("MyInheritorProperty: any;", output);
            Assert.Contains("MyArrayProperty: any[];", output);
            Assert.Contains("MyListProperty: any[];", output);
        }
        public void SelfReferencingEnumerableGenerateAny()
        {
            string output = TypeScript.Definitions()
                            .For <SelfReferencingEnumerableWrapper>()
                            .Generate(TsGeneratorOutput.Properties);

            Assert.Contains("MyProperty: any;", output);
        }
        public void WhenToModuleTheEnum()
        {
            var ts = TypeScript.Definitions()
                     .For <MyTestEnum>().ToModule("Foo")
                     .For <MyClass>()
                     .Generate();

            Assert.Contains("MyTest: Foo.MyTestEnum;", ts);
        }
예제 #6
0
        public void WhenModuleContainsStandAloneEnumWithToModule_EnumIsGeneratedInTheSpecifiedModule()
        {
            var ts = TypeScript.Definitions()
                     .For <MyTestEnum>().ToModule("Foo")
                     .Generate();

            Console.WriteLine(ts);
            Assert.Contains("namespace Foo", ts);
            Assert.Contains("enum MyTestEnum", ts);
        }
예제 #7
0
        public void GenericClassWithTypeparam()
        {
            // Exception raised documenting generic class with typeparam.
            var ts = TypeScript.Definitions().WithJSDoc()
                     .For <UserPreference>();
            string result;

            Assert.DoesNotThrow(() => result = ts.Generate(TsGeneratorOutput.Properties));
            Debug.Write(ts);
        }
예제 #8
0
        static void Main(string[] args)
        {
            Assembly dto = typeof(FirewallCtlUI.DTO.Settings).Assembly;
            var      x   = TypeScript.Definitions();

            foreach (Type type in dto.GetTypes())
            {
                x.For(type);
            }
            File.WriteAllText(args[0], x.Generate());
        }
예제 #9
0
        public void WhenTypeFormaterIsUsed_ItIsntAppliedToOpenGenericsParameters()
        {
            var ts = TypeScript.Definitions()
                     .For <UserPreference>()
                     .WithTypeFormatter(((type, F) => "I" + ((TypeLitePlus.TsModels.TsClass)type).Name))
                     .Generate();

            Debug.Write(ts);

            Assert.Contains("Key: TKey", ts);
            Assert.Contains("Value: TValue", ts);
        }
예제 #10
0
        public void WhenScriptGeneratorGenerateIsCalledModuleNameFormatterIsUsed()
        {
            var ts = TypeScript.Definitions();

            ts.WithModuleNameFormatter(m => "XXX");
            ts.ModelBuilder.Add <Product>();

            var model  = ts.ModelBuilder.Build();
            var myType = model.Classes.First();
            var name   = ts.ScriptGenerator.GetFullyQualifiedTypeName(myType);

            Assert.Equal("XXX.Product", name);
        }
예제 #11
0
        public ClientTypesExporter(CsharpTypeInfoProvider typeInfoProvider, ClientTypescriptGenerator scriptGenerator)
        {
            _scriptGenerator = scriptGenerator;
            var d = TypeScript.Definitions(scriptGenerator)
                    .WithTypeFormatter(FormatType)
                    .WithMemberFormatter(FormatMember)
                    .WithMemberTypeFormatter(FormatMemberType)
                    .WithVisibility((@class, name) => false)
                    .AsConstEnums(false)
                    .For <DateInterval>()
                    .For <AnalyzerBase>()
                    .WithModuleNameFormatter(module => string.Empty);

            _definitions = typeInfoProvider.ExposedTypes.Aggregate(d, (def, t) => def.For(t));
        }
예제 #12
0
        public static string GetTypeLitePoco(this Type type, bool useNamespace = true, bool isExported = true)
        {
            var name = type.DeclaringType?.FullName;
            var poco = TypeScript.Definitions().For(type).Generate();

            if (isExported)
            {
                poco = poco.Replace("interface ", " export interface ");
            }
            if (useNamespace)
            {
                poco = poco.Replace("declare module ", "namespace ");
            }
            return(poco);
        }
예제 #13
0
        public static void Main()
        {
            var ts = TypeScript.Definitions();

            ts.WithMemberFormatter((identifier) => char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1));
            ts.For <CreatureViewModel>()
            .For <Api.ApiModels.AuthToken>()
            .For <Api.ApiModels.CreateResult>()
            .For <Api.ApiModels.CreatureEditInput>()
            .For <Api.ApiModels.EquipmentSearchInput>()
            .For <Api.ApiModels.EquipmentSearchMode>()
            .For <Api.ApiModels.SearchInput>()
            .For <Api.ApiModels.SearchMode>();

            File.WriteAllText("ViewModelDefinitions.d.ts", ts.Generate());
        }
예제 #14
0
        public static void Main(string[] args)
        {
            // var json = Mongo.GroupTimers("02_cube_123d", "1_15786_el", "flow_fv.yaml");
            // var bson = json.AsBsonArray();
            // System.Environment.Exit(0);

            if (args.Length > 0 && args[0] == "--generate")
            {
                Directory.CreateDirectory("_client/src/models/");
                var model = TypeScript.Definitions()
                            .For <ColScheduler>()
                            .For <ColTimers>()
                            .For <SimpleTimer>()
                            .For <SimpleTimers>()
                            .For <SimpleTimersEx>()
                            .For <CommitRun>()

                            .For <SchedulerFilter>()
                            .For <TimersFilter>()
                            .For <CompareCommitFilter>()
                            .For <CompareCommitDto>()
                            .For <DurInfoWrapper>()
                            .For <CommitBaseline>()
                            .For <ConfigurationDto>()
                            .For <CompareCommitFlatDto>()

                            .WithVisibility((a, b) => true)
                            .WithMemberTypeFormatter(MemberTypeFormatter)
                            .WithModuleNameFormatter((moduleName) => "")
                            .WithMemberFormatter((identifier) =>
                                                 char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)
                                                 )
                            .WithTypeFormatter((type, f) => "I" + ((TsClass)type).Name)
                            .Generate();

                var fullPath = Path.Combine(Directory.GetCurrentDirectory(), "_client", "src", "models", "DataModel.d.ts");
                File.WriteAllText(fullPath, model);
                Environment.Exit(0);
            }

            CreateWebHostBuilder(args)
            .Build()
            .Run();
        }
        public void Main(string[] args)
        {
            var path = string.Empty;

            if (args.Length == 1)
            {
                path = args[0];
            }

            var fluent = TypeScript.Definitions();

            fluent.ScriptGenerator.IndentationString = "    ";

            fluent.WithMemberTypeFormatter(TsFluentFormatters.FormatPropertyType);
            fluent.WithMemberFormatter(TsFluentFormatters.FormatPropertyName);

            foreach (var model in GetApplicableTypes())
            {
                fluent.For(model);
            }

            var tsModel = fluent.ModelBuilder.Build();

            foreach (var @class in tsModel.Classes.Where(z => z.Module.Name.StartsWith("System", StringComparison.Ordinal)))
            {
                @class.IsIgnored = true;
            }

            var result = fluent.Generate();

            result = string.Join("\n", result, OmnisharpControllerExtractor.GetInterface());
            if (!string.IsNullOrWhiteSpace(path))
            {
                File.WriteAllText(Path.Combine(path, "omnisharp-server.d.ts"), result);
            }
            else
            {
                Console.Write(result);
                Console.ReadLine();
            }
        }
예제 #16
0
        static void Main(string[] args)
        {
            var output = TypeScript.Definitions(new TMogTsGenerator())
                         .For <Item>()
                         .For <Slot>()
                         .For <Source>()
                         .For <TMogSet>()
                         .For <Zone>()

                         .WithModuleNameFormatter(module => "")
                         .WithVisibility((tsClass, type) => true)
                         .WithMemberFormatter(identifier => {
                identifier.IsOptional = true;
                return(char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1));
            })
                         .WithIndentation("  ")
                         .Generate(TsGeneratorOutput.Enums | TsGeneratorOutput.Fields | TsGeneratorOutput.Properties);

            Console.WriteLine(output);
            WriteOutput(output);
        }
예제 #17
0
        public static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine($"Usage: {ProjectName}.CodeGen.exe <pathToAssembly> <outputPath>");
                return(1);
            }

            var dllPath = args[0];

            if (!File.Exists(dllPath))
            {
                Console.WriteLine($"Assembly not found: {dllPath}");
                return(1);
            }

            var outputPaths = args.Reverse().Take(args.Length - 1);

            foreach (var outputPath in outputPaths)
            {
                if (!Directory.Exists(outputPath))
                {
                    Console.WriteLine($"Output path does not exist, creating {outputPath}");
                    Directory.CreateDirectory(outputPath);
                }
            }

            var apiAssembly = Assembly.LoadFrom(dllPath);

            var apiTypes = Types(apiAssembly)
                           .Where(t => t.IsSubclassOf(typeof(Controller)))
                           .SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod))
                           .SelectMany(ParameterAndReturnTypes)
                           .SelectMany(Unwrap)
                           .Where(IsFromCorrectAssembly)
                           .Distinct()
                           .OrderBy(t => t.FullName)
                           .ToList();

            var typeScriptFluent = TypeScript.Definitions()
                                   .WithIndentation("  ")
                                   .WithModuleNameFormatter(tsModule => "Api")
                                   .WithConvertor <DateTimeOffset>(obj => "string")
                                   .WithConvertor <Guid>(obj => "string")
                                   .WithMemberFormatter(mf =>
            {
                if ((mf.MemberInfo as PropertyInfo)?.GetGetMethod().IsStatic ?? false)
                {
                    return($"// Ignore static: {mf.Name}");
                }

                var suffix = ((mf.MemberInfo as PropertyInfo)?.PropertyType.IsNullable() ?? false) ? "?" : "";
                return($"{char.ToLower(mf.Name[0])}{mf.Name.Substring(1)}{suffix}");
            })
                                   .AsConstEnums(false);

            foreach (var type in apiTypes)
            {
                typeScriptFluent = typeScriptFluent.For(type);
            }

            var tsModel = typeScriptFluent.ModelBuilder.Build();

            foreach (var outputPath in outputPaths)
            {
                var typesPath = Path.Combine(outputPath, "api.d.ts");
                Console.WriteLine($"Writing types to {typesPath}");
                File.WriteAllText(typesPath, typeScriptFluent.Generate());

                var enumsPath = Path.Combine(outputPath, "enums.ts");
                Console.WriteLine($"Writing enums to {enumsPath}");
                new EnumGenie.EnumGenie()
                .SourceFrom.List(tsModel.Enums.Select(e => e.Type).Distinct())
                .WriteTo.File(enumsPath, cfg => cfg.TypeScript())
                .Write();
            }

            Console.WriteLine($"Finished generating TypeScript contracts");
            return(0);
        }
예제 #18
0
        public static void Main(string[] args)
        {
            if (args.Length > 1 && args[0] == "--prod")
            {
                Console.WriteLine($"Assembly      = {Directory.GetParent(typeof(Program).Assembly.Location).FullName}");
                Console.WriteLine($"BaseDirectory = {AppDomain.CurrentDomain.BaseDirectory}");
                Console.WriteLine($"GetCurrentDir = {Directory.GetCurrentDirectory()}");
                Directory.SetCurrentDirectory(Directory.GetParent(typeof(Program).Assembly.Location).FullName);
                Console.WriteLine($"GetCurrentDir = {Directory.GetCurrentDirectory()}");
            }

            if (args.Length > 0 && args[0] == "--docs" || true.Equals(false))
            {
                var docs = "../docs/";
                Directory.CreateDirectory(docs);
                var sections = new List <string>
                {
                    DocGeneration.For <CourseProblem>(),
                    DocGeneration.For <CourseProblemCollaborationConfig>(),
                    DocGeneration.For <CourseProblemCase>(),
                    DocGeneration.For <CourseReference>(),
                };
                File.WriteAllText($"{docs}/README.md", sections.AsString("\n\n\n"));
                return;
            }

            if (args.Length > 0 && args[0] == "--generate")
            {
                var enumImports = new List <Type> {
                    typeof(ProcessStatus),
                    typeof(SubmissionStatus),
                    typeof(ProblemType),
                    typeof(ProblemStatus),
                    typeof(CcEventType),
                    typeof(CcUserGroupStatus),
                    typeof(DiffResultLineType),
                    typeof(ProcessStatusCodes),
                    typeof(ChangeType),
                };

                Directory.CreateDirectory("_client/src/models/");
                var destModelPath    = "_client/src/models/DataModel.d.ts";
                var modelDefinitions = TypeScript.Definitions();

                enumImports.ForEach(T =>
                {
                    modelDefinitions = modelDefinitions.RegisterTypeConvertor(T, i => T.Name);
                });

                modelDefinitions = modelDefinitions
                                   .For <User>()
                                   .For <Language>()
                                   .For <Course>()
                                   .For <CcData>()
                                   .For <CcEvent>()
                                   .For <CcDataAgg>()
                                   .For <MarkSolutionItem>()
                                   .For <TableRequest>()
                                   .For <TableResponse>()
                                   .For <SingleCourse>()
                                   .For <ProcessStatus>()
                                   .For <CommentServiceItem>()
                                   .For <GradeDto>()
                                   .For <StudentScoreboardCourse>()
                                   .For <CcGroup>()
                                   .For <UnauthorizedObjectIface>()
                                   .For <SimpleFileDto>()

                                   .For <ApiError>()
                                   .For <CcDataDto>()
                                   .For <CcDataLight>()

                                   .For <DiffResult>()
                                   .For <AppUser>()
                                   .For <DiffResultComposite>();

                var destModel = modelDefinitions
                                .WithModuleNameFormatter((moduleName) => "")
                                .WithMemberFormatter((identifier) =>
                                                     char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)
                                                     )
                                .WithTypeFormatter((type, f) => "I" + ((TsClass)type).Name)
                                .Generate();

                var importLine = $"import {{ {enumImports.Select(i => i.Name).AsString(", ")} }} from  './Enums'";
                var dateLine   = $"// generated at {DateTime.Now.ToUniversalTime()} (UTC)";
                var guidLine   = $"export const __uuid = '{Guid.NewGuid()}'";
                File.WriteAllText(destModelPath, $"{importLine}\n{destModel}\n\n{dateLine}\n{guidLine}");

                var enumDefinition = TypeScript.Definitions();
                enumImports.ForEach(T =>
                {
                    enumDefinition = enumDefinition.For(T);
                });

                var enumBase = enumDefinition
                               .WithModuleNameFormatter((moduleName) => "")
                               .WithMemberFormatter((identifier) =>
                                                    char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)
                                                    )
                               .WithTypeFormatter((type, f) => "I" + ((TsClass)type).Name)
                               .Generate();

                enumBase += AddEnumLike <ProcessStatus>();

                File.WriteAllText(
                    "_client/src/models/Enums.ts",
                    enumBase.Replace("export const enum", "export enum")
                    );
                Environment.Exit(0);
            }

            CreateWebHostBuilder(args)
            .Build()
            .Run();
        }
예제 #19
0
        static int Main(string[] args)
        {
            var executingAssembly = Assembly.GetExecutingAssembly();
            var version           = executingAssembly.GetName().Version;
            var executableName    = executingAssembly.GetName().Name;


            Console.WriteLine("TypeScript definition file generator.");
            Console.WriteLine($"Version { version }, runtime version { executingAssembly.ImageRuntimeVersion}");
            if (args.Length != 2)
            {
                Console.WriteLine();
                Console.WriteLine("This utility extract the models from assemblies marked with attribute [TsClass]");
                Console.WriteLine("and converts them to TypeScript definition format.");
                Console.WriteLine();
                Console.WriteLine($"Usage: {executableName} [inputfile] [outputfile]");
                Console.WriteLine();
                Console.WriteLine($"Example: {executableName} MyFile.exe MyFile.ts.d");
                return(-1);
            }
            else
            {
                try
                {
                    if (!File.Exists(args[0]))
                    {
                        throw new FileNotFoundException($"File {args[0]} not found.");
                    }

                    // We want to load the provided assembly and also the referenced once from the same folder.
                    // So a little hook will do the trick.
                    applicationDirectory = Path.GetDirectoryName(args[0]);
                    AppDomain currentDomain = AppDomain.CurrentDomain;
                    currentDomain.AssemblyResolve += currentDomain_AssemblyResolve;

                    Console.WriteLine($"Loading assembly {args[0]}");
                    Assembly.LoadFile(args[0]);

                    var ts = TypeScript.Definitions()
                             .ForLoadedAssemblies()
                             .WithIndentation("    ")
                             .WithVisibility(VisibilityFormatter)                                                                  // All interfaces should be exported
                             .WithMemberFormatter((identifier) => Char.ToLower(identifier.Name[0]) + identifier.Name.Substring(1)) // Convert to camelCase
                             .WithTypeFormatter(TypeFormatter)                                                                     //Prefix classname with I and convert GUID to string
                             .AsConstEnums(false)
                             .WithConvertor <Guid>(c => "string")
                             .WithModuleNameFormatter(module => module.Name = module.Name.Replace(".", "_")); // Convert Guids to string

                    Console.WriteLine("Generate typescript.");
                    var generatedTypeScript = ts.Generate();

                    // According to ES6 we need to export the module, its not a nice way but TypeLite is not able to change this behaviour (line 246 in TsGenerator.cs)
                    generatedTypeScript = generatedTypeScript.Replace("declare namespace ", "export module ");

                    Console.WriteLine("Writing to file.");
                    using (StreamWriter sw = new StreamWriter(File.Open(args[1], FileMode.Create), Encoding.UTF8))
                    {
                        sw.WriteLine("// Do not modify this file!");
                        sw.Write(generatedTypeScript);
                    }
                    Console.WriteLine("Done.");

                    return(0);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An error occurred : {ex.Message}");
                }
                return(-2);
            }
        }
예제 #20
0
 public void GenerateTsFiles()
 {
     TypeScript.Definitions().ForLoadedAssemblies();
 }
예제 #21
0
        public static void Main(string[] args)
        {
            var path = string.Empty;

            if (args.Length == 1)
            {
                path = args[0];
            }

            var fluent = TypeScript.Definitions();

            fluent.ScriptGenerator.IndentationString = "    ";

            fluent.WithMemberTypeFormatter(TsFluentFormatters.FormatPropertyType);
            fluent.WithMemberFormatter(TsFluentFormatters.FormatPropertyName);

            foreach (var model in GetApplicableTypes())
            {
                fluent.For(model);
            }

            var tsModel = fluent.ModelBuilder.Build();

            foreach (var @class in tsModel.Classes.Where(z => z.Module.Name.StartsWith("System", StringComparison.Ordinal)))
            {
                @class.IsIgnored = true;
            }

            var result = fluent.Generate();

            var generated         = string.Join("\n", OmnisharpControllerExtractor.GetInterface());
            var projectInterfaces = $@"
declare module {OmnisharpControllerExtractor.InferNamespace(typeof(Request)).TrimEnd('.')} {{
    interface ProjectInformationResponse {{
        MsBuildProject: OmniSharp.Models.MSBuildProject;
        DotNetProject: OmniSharp.Models.DotNetProjectInformation;
    }}

    interface WorkspaceInformationResponse {{
        DotNet: OmniSharp.Models.DotNetWorkspaceInformation;
        MSBuild: OmniSharp.Models.MsBuildWorkspaceInformation;
        ScriptCs: OmniSharp.ScriptCs.ScriptCsContextModel;
    }}
}}
            ";

            result = string.Join("\n", "import {Observable} from \"rxjs\";", result, generated, OmnisharpEventExtractor.GetInterface(), projectInterfaces);
            result = result
                     .Replace("interface", "export interface")
                     .Replace("declare module", "export module")
                     .Replace("export module OmniSharp {", "")
                     .Replace("OmniSharp.", "")
                     .Replace("DotNet.Models", "Models")
            ;

            var lines = result.Split('\n');
            var opens = 0;

            for (var i = 0; i < lines.Length; i++)
            {
                if (lines[i].Contains('{'))
                {
                    opens++;
                }
                if (lines[i].Contains('}'))
                {
                    opens--;
                }
                if (opens < 0 && lines[i].TrimEnd().Length == 1)
                {
                    lines[i] = string.Empty;
                    opens    = 0;
                }
            }

            result = string.Join("\n", lines);

            result = "/* tslint:disable */\n" + result + "\n";

            if (!string.IsNullOrWhiteSpace(path))
            {
                File.WriteAllText(Path.Combine(path, "lib", "omnisharp-server.ts"), result);
                foreach (var item in OmnisharpAugmentationExtractor.GetAugmentationMethods())
                {
                    var p        = Path.Combine(path, "lib", item.Key, item.Value.Item1);
                    var contents = File.ReadAllText(p);
                    contents  = contents.Substring(0, contents.IndexOf("// <#GENERATED />"));
                    contents += "// <#GENERATED />\n" + item.Value.Item2;
                    File.WriteAllText(p, contents);
                }
            }
            else
            {
                Console.Write(result);
                Console.ReadLine();
            }
        }