예제 #1
0
        public void Can_Create_Engine()
        {
            var compiler = new TypeScriptWriter();
            var engine   = compiler.GetEngine();

            Assert.NotNull(engine);
        }
예제 #2
0
        public void Instanciates()
        {
            var writer = new TypeScriptWriter("./", "graph");

            Assert.NotNull(writer);
            Assert.NotNull(writer.PathSegmenter);
            Assert.Throws <ArgumentNullException>(() => new TypeScriptWriter(null, "graph"));
            Assert.Throws <ArgumentNullException>(() => new TypeScriptWriter("./", null));
        }
예제 #3
0
        private static void CreateTypeScriptServices(ApplicationPartManager applicationPartManager)
        {
            ControllerFeature feature = new ControllerFeature();

            applicationPartManager.PopulateFeature(feature);
            var controllerTypes = feature.Controllers.Select(c => c.AsType());
            var converter       = new Converter();
            var assembly        = converter.ReadControllers(controllerTypes);
            var typeScript      = new TypeScriptWriter();

            typeScript.WriteAssembly(assembly);
            typeScript.WriteToFiles("src/services");
        }
예제 #4
0
        public void Can_Get_Exception_Result()
        {
            var compiler = new TypeScriptWriter();
            var engine   = compiler.GetEngine();

            var test = @"functio greeter(person: stringz) {
                                        return ""Hello, "" +=-+ person;
                                    
                                    var user = ""Jane User"";
                                    document.body.innerHTML = greeter(user);";


            Assert.Throws <TypeScriptCompilationException>(() => compiler.CompileTypeScript(engine, test));
        }
예제 #5
0
        private void WriteRequestTypesAndHelpers(TypeScriptWriter writer)
        {
            writer.WriteInterface("GetRequest", new TypeReference("TResponse"))
            .Configure(i =>
            {
                i.AddProperty("url", new TypeReference("string"));
                i.AddProperty("method", new TypeReference("'GET'"));
            });
            writer.WriteInterface("DeleteRequest", new TypeReference("TResponse"))
            .Configure(i =>
            {
                i.AddProperty("url", new TypeReference("string"));
                i.AddProperty("method", new TypeReference("'DELETE'"));
            });

            writer.WriteInterface("PostRequest", new TypeReference("TRequest"), new TypeReference("TResponse"))
            .Configure(i =>
            {
                i.AddProperty("data", new TypeReference("TRequest"));
                i.AddProperty("url", new TypeReference("string"));
                i.AddProperty("method", new TypeReference("'POST'"));
            });
            writer.WriteInterface("PutRequest", new TypeReference("TRequest"), new TypeReference("TResponse"))
            .Configure(i =>
            {
                i.AddProperty("data", new TypeReference("TRequest"));
                i.AddProperty("url", new TypeReference("string"));
                i.AddProperty("method", new TypeReference("'PUT'"));
            });
            writer.WriteFunction("toQuery")
            .WithReturnType(new TypeReference("string"))
            .WithParams(p => p.Param("o", new TypeReference("{[key: string]: any}")))
            .Static()
            .WithBody(w =>
            {
                w.WriteLine("const q = Object.keys(o)");
                w.Indent();
                w.WriteLine(".map(k => ({k, v: o[k]}))");
                w.WriteLine(".filter(x => x.v !== undefined && x.v !== null)");
                w.WriteLine(".map(x => Array.isArray(x.v)");
                w.Indent();
                w.WriteLine("? x.v.map(v => `${encodeURIComponent(x.k)}=${encodeURIComponent(v)}`).join('&')");
                w.WriteLine(": `${encodeURIComponent(x.k)}=${encodeURIComponent(x.v)}`)");
                w.Deindent();
                w.WriteLine(".join('&');");
                w.Deindent();
                w.WriteLine("return q ? `?${q}` : '';");
            });
        }
예제 #6
0
        private static void CreateTypeScriptServices(ApplicationPartManager applicationPartManager)
        {
            ControllerFeature feature = new ControllerFeature();

            applicationPartManager.PopulateFeature(feature);
            var controllerTypes = feature.Controllers.Select(c => c.AsType());
            var converter       = new Converter();
            var assembly        = converter.ReadControllers(controllerTypes);
            var typeScript      = new TypeScriptWriter(options: TypeScriptOptions.ParametersInObject);

            // Call WriteAssembly twice; once for KO mappings, once for TS
            typeScript.WriteAssembly(assembly, false);
            typeScript.WriteAssembly(assembly, true);
            typeScript.WriteToFiles("src/services");
        }
예제 #7
0
        public void Can_Get_Successfull_Result()
        {
            var compiler = new TypeScriptWriter();
            var engine   = compiler.GetEngine();

            var test = @"function greeter(person: string) {
                            return ""Hello, "" + person;
                        }
                        var user = ""Jane User"";
                        document.body.innerHTML = greeter(user);";

            var result = compiler.CompileTypeScript(engine, test);

            Assert.IsFalse(TypeScriptCompilationErrorParser.HasErrors(result));
        }
예제 #8
0
        public void WriteImports(TypeScriptWriter writer)
        {
            foreach (var importGroup in Types.ImportedLiterals.GroupBy(t => t.ImportFrom))
            {
                writer.WriteLine(
                    $"import {{ {(string.Join(", ", importGroup.Select(g => BuildImport(g.TypeName, g.ImportAs))))} }} from '{importGroup.Key}';");
            }

            foreach (var importGroup in Types.UsedImportedTypes.GroupBy(t => t.ImportFrom))
            {
                writer.WriteLine(
                    $"import {{ {(string.Join(", ", importGroup.Select(g => BuildImport(g.Type))))} }} from '{importGroup.Key}';");
            }

            _importsWritten = true;
        }
        private static void CreateTypeScriptServices(ApplicationPartManager applicationPartManager, bool useKnockout, string outputDir)
        {
            ControllerFeature feature = new ControllerFeature();

            applicationPartManager.PopulateFeature(feature);
            var controllerTypes = feature.Controllers.Select(c => c.AsType());
            var converter       = new Converter();
            var assembly        = converter.ReadControllers(controllerTypes);
            var typeScript      = new TypeScriptWriter();

            // Call WriteAssembly twice ; once for TypeScript objects and once for Knockout mappings
            if (useKnockout)
            {
                typeScript.WriteAssembly(assembly, true);
            }
            typeScript.WriteAssembly(assembly, false);
            typeScript.WriteToFiles(outputDir);
        }
예제 #10
0
        public void WriteToStream(Stream stream)
        {
            var tsWriter = new TypeScriptWriter(stream, _options);

            var webApiWriter = new RouteReflector(_options);

            foreach (var additionalTypes in _types)
            {
                webApiWriter.AddAdditionalTypes(additionalTypes);
            }

            foreach (var assembly in _assemblies ?? Array.Empty <Assembly>())
            {
                webApiWriter.AddAssembly(assembly, _controllerFilter);
            }
            foreach (var controller in _controllers?.Where(_controllerFilter) ?? Array.Empty <Type>())
            {
                webApiWriter.AddController(controller);
            }

            webApiWriter.WriteTo(tsWriter);
        }
예제 #11
0
        public void WriteTo(TypeScriptWriter writer, bool includeHeader = true)
        {
            if (includeHeader)
            {
                _options.WriteHeader(writer);
            }

            if (!_importsWritten)
            {
                WriteImports(writer);
            }

            foreach (var type in Types.LocalTypes.OrderBy(t => t.Name))
            {
                var typeRef = TypeConverter.Convert(type);

                if (typeRef.ExistingType)
                {
                    continue;
                }

                if (typeRef.Enum)
                {
                    var enumValueType = _options.EnumValueTypeStrategy(type);
                    writer.WriteEnum(typeRef.TypeName, enumValueType)
                    .Configure(e =>
                    {
                        foreach (var field in Enum.GetNames(type).Zip(Enum.GetValues(type)
                                                                      .Cast <object>()
                                                                      .Select(x => Convert.ChangeType(x, Enum.GetUnderlyingType(type))),
                                                                      (name, value) => new { name, value }))
                        {
                            var description = type.GetMember(field.name)
                                              .SelectMany(m => m.GetCustomAttributes <DescriptionAttribute>())
                                              .Select(a => a.Description)
                                              .FirstOrDefault();
                            if (enumValueType == EnumValueType.Number)
                            {
                                e.AddValue(TypeConverter.EnumName(field.name), field.value, description);
                            }
                            else
                            {
                                e.AddValue(TypeConverter.EnumName(field.name), field.name, description);
                            }
                        }
                    });
                    continue;
                }

                _options.ComplexTypeStrategy(writer, new ComplexTypeInfo(typeRef.TypeName, typeRef.GenericTypeParams)
                                             .Configure(i =>
                {
                    foreach (var pi in type.GetProperties(_options.PropertyFlags))
                    {
                        i.AddProperty(TypeConverter.PropertyName(pi),
                                      TypeConverter.Convert(pi.PropertyType, type, pi));
                    }

                    foreach (var fi in type.GetFields(_options.FieldFlags))
                    {
                        i.AddProperty(TypeConverter.FieldName(fi),
                                      TypeConverter.Convert(fi.FieldType, type, fi));
                    }

                    if (_options.ReflectMethods(type))
                    {
                        foreach (var mi in type.GetMethods(_options.MethodFlags)
                                 .Where(m => !m.IsSpecialName)
                                 .Where(m => _options.ReflectMethod(type, m)))
                        {
                            i.AddMethod(mi.Name)
                            .WithReturnType(TypeConverter.Convert(mi.ReturnType, type, mi))
                            .WithParams(p =>
                            {
                                foreach (var pi in mi.GetParameters())
                                {
                                    p.Param(pi.Name ?? string.Empty, TypeConverter.Convert(pi.ParameterType, type, mi));
                                }
                            });
                        }
                    }
                })
                                             .Done(), type);
            }

            writer.Flush();
        }
예제 #12
0
 public TestConverter()
 {
     converter = new Converter();
     writer    = new TypeScriptWriter();
 }
예제 #13
0
        public void WriteTo(TypeScriptWriter writer)
        {
            _options.WriteHeader(writer);

            var rWriter = new ReflectiveWriter(_options);

            if (!_options.RequestHelperTypeOption.ShouldEmitTypes)
            {
                foreach (var type in _options.RequestHelperTypeOption.Types)
                    _options.Types.AddLiteralImport(_options.RequestHelperTypeOption.ImportFrom, type);
            }

            AddTypeDependencies(rWriter);

            rWriter.WriteImports(writer);


            if (_options.RequestHelperTypeOption.ShouldEmitTypes)
            {
                WriteRequestTypesAndHelpers(writer);
            }

            foreach (var factory in _requests.GroupBy(r => r.FactoryName))
            {
                writer.WriteClass(factory.Key)
                    .Configure(c =>
                    {
                        c.MakeAbstract();


                        foreach (var req in factory)
                        {
                            var methodBuilder = c.AddMethod($"{req.Name}")
                                .Static();

                            if (req.Method.HasRequestBody())
                            {
                                var requestBodyType = req.GetRequestBodyKind() == RequestBodyKind.Json
                                    ? _options.TypeConverter.Convert(req.GetRequestBodyType())
                                    : (req.GetRequestBodyKind() == RequestBodyKind.FormData
                                        ? new TypeReference("FormData")
                                        : _options.EmptyRequestBodyType);
                                if (requestBodyType.Optional)
                                {
                                    requestBodyType = new TypeReference($"{requestBodyType.FullName} | undefined");
                                }

                                methodBuilder
                                    .WithReturnType(new TypeReference($"{req.Method.GetName()}Request",
                                        new[]
                                        {
                                            requestBodyType,
                                            _options.TypeConverter.Convert(req.ResponseType)
                                        }));
                            }
                            else
                            {
                                methodBuilder
                                    .WithReturnType(new TypeReference($"{req.Method.GetName()}Request",
                                        new[]
                                        {
                                            _options.TypeConverter.Convert(req.ResponseType)
                                        }));
                            }

                            methodBuilder.WithParams(p =>
                                {
                                    foreach (var rp in req.RequestParams.Where(x => x.Kind != ParameterKind.Body))

                                    {
                                        p.Param(rp.NameOrDestructureExpression,
                                            _options.TypeConverter.Convert(rp.Type)
                                                .MakeOptional(rp.Kind == ParameterKind.Query && rp.Type.IsNullable()));
                                    }

                                    if (req.Method.HasRequestBody() && req.GetRequestBodyKind() == RequestBodyKind.Json)
                                        p.Param("data", _options.TypeConverter.Convert(req.GetRequestBodyType()));
                                })
                                .WithBody(w =>
                                {
                                    var queryParams = req.RequestParams.Where(x => x.Kind == ParameterKind.Query)
                                        .ToArray();
                                    if (queryParams.Any())
                                    {
                                        w.Write($"const {_options.QueryVariableName} = toQuery({{ ", true);
                                        w.WriteDelimited(queryParams,
                                            (p, wr) => wr.Write(_options.TypeConverter.TreatAsPrimitive(p.Type.UnwrapNullable())
                                                || p.Type.IsCollection() ? p.Name : $"...{p.Name}"),
                                            ", ");
                                        w.WriteLine(" });", false);
                                    }

                                    var formParams = req.RequestParams.Where(x => x.Kind == ParameterKind.Form)
                                        .ToArray();
                                    if ((formParams.Any()))
                                    {
                                        w.WriteLine("const data = new FormData();");
                                        foreach (var formParam in formParams)
                                        {
                                            w.WriteLine($"data.append('{formParam.Name}', {formParam.Name});");
                                        }
                                    }

                                    w.WriteLine("return {");
                                    w.Indent();
                                    w.WriteLine($"method: '{req.Method.GetName().ToUpper()}',");
                                    if (req.Method.HasRequestBody() &&
                                        req.GetRequestBodyKind() != RequestBodyKind.Empty)
                                        w.WriteLine("data,");
                                    else if (req.Method.HasRequestBody())
                                        w.WriteLine("data: undefined,");
                                    w.WriteLine(
                                        $"url: `{req.Path.Replace("{", "${")}{(queryParams.Any() ? $"${{{_options.QueryVariableName}}}" : "")}`");
                                    w.Deindent();
                                    w.WriteLine("};");
                                });
                        }
                    });
            }


            rWriter.WriteTo(writer, false);
        }
예제 #14
0
        public void WriteTo(TypeScriptWriter writer)
        {
            CheckConfigured();
            _options.WriteHeader(writer);

            var rWriter = new ReflectiveWriter(_options);

            if (!_options.RequestHelperTypeOption.ShouldEmitTypes)
            {
                foreach (var type in _options.RequestHelperTypeOption.Types)
                {
                    _options.Types.AddLiteralImport(_options.RequestHelperTypeOption.ImportFrom, type);
                }
            }

            AddTypeDependencies(rWriter);

            rWriter.WriteImports(writer);


            if (_options.RequestHelperTypeOption.ShouldEmitTypes)
            {
                WriteRequestTypesAndHelpers(writer);
            }

            if (_requests.Any())
            {
                writer.WriteClass("RequestFactory")
                .Configure(c =>
                {
                    c.MakeAbstract();


                    foreach (var req in _requests)
                    {
                        var methodBuilder = c.AddMethod($"{req.Name}")
                                            .Static();

                        if (req.Method.HasRequestBody())
                        {
                            var requestBodyType = _options.TypeConverter.Convert(req.GetRequestBodyType(), null);
                            if (requestBodyType.Optional)
                            {
                                requestBodyType = new TypeReference($"{requestBodyType.FullName} | undefined");
                            }

                            methodBuilder
                            .WithReturnType(new TypeReference($"{req.Method.GetName()}Request",
                                                              new[]
                            {
                                requestBodyType,
                                _options.TypeConverter.Convert(req.ResponseType, null)
                            }));
                        }
                        else
                        {
                            methodBuilder
                            .WithReturnType(new TypeReference($"{req.Method.GetName()}Request",
                                                              new[]
                            {
                                _options.TypeConverter.Convert(req.ResponseType, null)
                            }));
                        }

                        methodBuilder.WithParams(p =>
                        {
                            foreach (var rp in req.RequestParams.Where(x => x.Kind != ParameterKind.Body))

                            {
                                p.Param(rp.Name,
                                        _options.TypeConverter.Convert(rp.Type)
                                        .MakeOptional(rp.Kind == ParameterKind.Query));
                            }

                            if (req.Method.HasRequestBody())
                            {
                                p.Param("data", _options.TypeConverter.Convert(req.GetRequestBodyType(), null));
                            }
                        })
                        .WithBody(w =>
                        {
                            var queryParams = req.RequestParams.Where(x => x.Kind == ParameterKind.Query)
                                              .ToArray();
                            if (queryParams.Any())
                            {
                                w.Write("const query = toQuery({", true);
                                w.WriteDelimited(queryParams,
                                                 (p, wr) => wr.Write(p.Name), ", ");
                                w.WriteLine("});", false);
                            }

                            w.WriteLine("return {");
                            w.Indent();
                            w.WriteLine($"method: '{req.Method.GetName().ToUpper()}',");
                            if (req.Method.HasRequestBody())
                            {
                                w.WriteLine("data,");
                            }
                            w.WriteLine(
                                $"url: `{req.Path.Replace("{", "${")}{(queryParams.Any() ? "${query}" : "")}`");
                            w.Deindent();
                            w.WriteLine("};");
                        });
                    }
                });
            }


            rWriter.WriteTo(writer, false);
        }
예제 #15
0
 public TypeScriptEnumBlock(TypeScriptWriter writer, string name)
     : base(writer, prefix: $"enum {name}")
 {
 }