private void InnerTranslate(IAsset asset, TypeScriptCompiler typeScriptCompiler)
        {
            string         newContent;
            string         assetUrl = asset.Url;
            IList <string> dependencies;

            try
            {
                CompilationResult result = typeScriptCompiler.Compile(assetUrl);
                newContent   = result.CompiledContent;
                dependencies = result.IncludedFilePaths;
            }
            catch (TypeScriptCompilationException e)
            {
                throw new AssetTranslationException(
                          string.Format(CoreStrings.Translators_TranslationSyntaxError,
                                        INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message));
            }
            catch (Exception e)
            {
                throw new AssetTranslationException(
                          string.Format(CoreStrings.Translators_TranslationFailed,
                                        INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message));
            }

            asset.Content = newContent;
            asset.VirtualPathDependencies = dependencies;
        }
        public void CoffeeScriptFailTest()
        {
            var input = "test.invlid.stuff/^/g!%%";

            using (var fixture = new TypeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(
                                                            () => new IEJavaScriptRuntime()))) {
                bool shouldDie = false;

                try {
                    var result = fixture.Compile(input);
                    if (result.StartsWith("ENGINE FAULT"))
                    {
                        shouldDie = true;
                    }
                    else
                    {
                        Console.WriteLine(result);
                    }
                } catch (Exception ex) {
                    Console.WriteLine("Ex: " + ex.Message);
                    shouldDie = true;
                }

                Assert.True(shouldDie);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            try
            {
                IVsHierarchy hierarchy = null;
                uint         itemid    = VSConstants.VSITEMID_NIL;

                if (!TsWspHelpers.IsSingleProjectItemSelection(out hierarchy, out itemid))
                {
                    return;
                }

                var vsProject = (IVsProject)hierarchy;

                // get the name of the item
                string itemFullPath = null;
                if (ErrorHandler.Failed(vsProject.GetMkDocument(itemid, out itemFullPath)))
                {
                    return;
                }

                TypeScriptCompiler.Compile(itemFullPath);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        public void CanCompileMultipleTypeScript()
        {
            var filePath1 = PathHelper.GetScript("A.ts");
            var filePath2 = PathHelper.GetScript("Q.ts");

            var options = new TypeScriptV1CompilerOptions()
            {
                Target = TypeScriptCompilerTarget.ES5
            };

            var compiler = new TypeScriptCompiler();
            var result   = compiler.Compile(new[] { filePath1, filePath2 }, options);

            Assert.IsTrue(result.IsSuccess);

            var outFile1      = PathHelper.GetScript("A.js");
            var outFile2      = PathHelper.GetScript("Q.js");
            var resultSource1 = File.ReadAllText(outFile1);
            var resultSource2 = File.ReadAllText(outFile2);

            var expectedResult1 = "var A;\r\n(function (A) {\r\n    var Foo = (function () {\r\n        function Foo() {\r\n        }\r\n        Foo.prototype.bar = function () {\r\n            alert(\"Foo\");\r\n        };\r\n        return Foo;\r\n    })();\r\n    A.Foo = Foo;\r\n})(A || (A = {}));\r\n";
            var expectedResult2 = "var Q;\r\n(function (Q) {\r\n    var Bar = (function () {\r\n        function Bar() {\r\n        }\r\n        Bar.prototype.bar = function () {\r\n            alert(\"bar\");\r\n        };\r\n\r\n        Object.defineProperty(Bar.prototype, \"getter\", {\r\n            get: function () {\r\n                return \"123\";\r\n            },\r\n            enumerable: true,\r\n            configurable: true\r\n        });\r\n        return Bar;\r\n    })();\r\n    Q.Bar = Bar;\r\n})(Q || (Q = {}));\r\n";

            Assert.AreEqual(expectedResult1, resultSource1);
            Assert.AreEqual(expectedResult2, resultSource2);

            // Clean up
            File.Delete(outFile1);
            File.Delete(outFile2);
        }
        public void CanCompileTypeScriptWithSourceMap()
        {
            var filePath = PathHelper.GetScript("simple.ts");

            var options = new TypeScriptV1CompilerOptions()
            {
                SourceMap = true
            };

            var compiler = new TypeScriptCompiler();
            var result   = compiler.Compile(new[] { filePath }, options);

            Assert.IsTrue(result.IsSuccess);

            var outFile = PathHelper.GetScript("simple.js");
            var outMap  = PathHelper.GetScript("simple.js.map");

            var resultSource = File.ReadAllText(outFile);
            var resultMap    = File.ReadAllText(outMap);

            var expectedResult = "\r\n// Module\r\nvar Shapes;\r\n(function (Shapes) {\r\n    // Class\r\n    var Point = (function () {\r\n        // Constructor\r\n        function Point(x, y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n        // Instance member\r\n        Point.prototype.getDist = function () {\r\n            return Math.sqrt(this.x * this.x + this.y * this.y);\r\n        };\r\n\r\n        Point.origin = new Point(0, 0);\r\n        return Point;\r\n    })();\r\n    Shapes.Point = Point;\r\n})(Shapes || (Shapes = {}));\r\n\r\n// Local variables\r\nvar p = new Shapes.Point(3, 4);\r\nvar dist = p.getDist();\r\n//# sourceMappingURL=simple.js.map\r\n";
            var expectedMap    = "{\"version\":3,\"file\":\"simple.js\",\"sourceRoot\":\"\",\"sources\":[\"simple.ts\"],\"names\":[\"Shapes\",\"Shapes.Point\",\"Shapes.Point.constructor\",\"Shapes.Point.getDist\"],\"mappings\":\";AAKA,SAAS;AACT,IAAO,MAAM;AAaZ,CAbD,UAAO,MAAM;IAETA,QAAQA;IACRA;QAEIC,cADcA;QACdA,eAAaA,CAAgBA,EAAEA,CAAgBA;YAAlCC,MAAQA,GAADA,CAACA;AAAQA,YAAEA,MAAQA,GAADA,CAACA;AAAQA,QAAIA,CAACA;QAGpDD,kBADYA;kCACZA;YAAYE,OAAOA,IAAIA,CAACA,IAAIA,CAACA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,GAAGA,IAAIA,CAACA,CAACA,CAACA;QAAEA,CAACA;;QAGlEF,eAAgBA,IAAIA,KAAKA,CAACA,CAACA,EAAEA,CAACA,CAACA;QACnCA,aAACA;IAADA,CAACA,IAAAD;IATDA,qBASCA;AACLA,CAACA,2BAAA;;AAED,kBAAkB;AAClB,IAAI,CAAC,GAAW,IAAI,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AACtC,IAAI,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC\"}";

            Assert.AreEqual(expectedResult, resultSource);
            Assert.AreEqual(expectedMap, resultMap);

            // Clean up
            File.Delete(outFile);
            File.Delete(outMap);
        }
Exemplo n.º 6
0
        private void DocumentSaved(object sender, TextDocumentFileActionEventArgs e)
        {
            if (e.FileActionType == FileActionTypes.ContentSavedToDisk)
            {
                string sourceFile = e.FilePath;

                TypeScriptCompiler.Compile(sourceFile);
            }
        }
        public void CoffeeScriptSmokeTest()
        {
            var input = @"var foo:number = 5;";

            using (var fixture = new TypeScriptCompiler(new InstanceProvider <IJavaScriptRuntime>(
                                                            () => new IEJavaScriptRuntime()))) {
                var result = fixture.Compile(input);
                Assert.False(String.IsNullOrWhiteSpace(result));
            }
        }
Exemplo n.º 8
0
        public void TypeScriptSmokeTest()
        {
            var code  = @"var foo:number = 5;";
            var input = @"{""someFile.ts"":""" + code + @"""}";

            using (var fixture = new TypeScriptCompiler(new Lazy <IJavaScriptRuntime>(() => new IEJavaScriptRuntime())))
            {
                var result = fixture.Compile(input);
                Assert.False(String.IsNullOrWhiteSpace(result));
            }
        }
        public void CompilerResultContainsError()
        {
            var filePath = PathHelper.GetScript("error.ts");

            var options = new TypeScriptV1CompilerOptions()
            {
            };

            var compiler = new TypeScriptCompiler();
            var result   = compiler.Compile(new[] { filePath }, options);

            Assert.IsFalse(result.IsSuccess);
            Assert.IsFalse(String.IsNullOrEmpty(result.Error));
        }
Exemplo n.º 10
0
        public string Compile(string file)
        {
            if (Accept(file))
            {
                if (!File.Exists(file))
                {
                    throw new Exception("attempt to compile a nonexistent file.");
                }

                using (var reader = new StreamReader(file))
                {
                    return(TypeScriptCompiler.Compile(reader.ReadToEnd()));
                }
            }
            throw new Exception("attempt to compile an invalid file.");
        }
        /// <summary>
        /// Processes a single item.
        /// </summary>
        /// <param name="input">The input to process.</param>
        /// <returns>The output of the process.</returns>
        public override IAssetFile Process(IAssetFile input)
        {
            try
            {
                // !!!!!!!!
                // NOT USED
                // !!!!!!!!

                // Only processes .ts files
                if (input.Extension != ".ts")
                {
                    return(input);
                }

                // Measure
                var watch = new Stopwatch();
                watch.Start();

                // compiles a TS file
                var output = TypeScriptCompiler.Compile(input.Content.AsString());

                // We've compiled
                watch.Stop();

                // Compiled successfully
                Tracing.Info("TypeScript", "Compiled " + input.RelativeName + ", " + watch.ElapsedMilliseconds + " ms.");

                // Return processed output
                return(AssetOutputFile.Create(
                           from: input,
                           content: output,
                           extension: "js"
                           ));
            }
            catch (Exception ex)
            {
                // We didn't manage to create anything
                Tracing.Error("TypeScript", ex);
                return(null);
            }
        }
        public void CanCompileTypeScript()
        {
            var filePath = PathHelper.GetScript("simple.ts");

            var options = new TypeScriptV1CompilerOptions()
            {
            };

            var compiler = new TypeScriptCompiler();
            var result   = compiler.Compile(new[] { filePath }, options);

            Assert.IsTrue(result.IsSuccess);

            var outFile      = PathHelper.GetScript("simple.js");
            var resultSource = File.ReadAllText(PathHelper.GetScript(outFile));

            var expectedResult = "\r\n// Module\r\nvar Shapes;\r\n(function (Shapes) {\r\n    // Class\r\n    var Point = (function () {\r\n        // Constructor\r\n        function Point(x, y) {\r\n            this.x = x;\r\n            this.y = y;\r\n        }\r\n        // Instance member\r\n        Point.prototype.getDist = function () {\r\n            return Math.sqrt(this.x * this.x + this.y * this.y);\r\n        };\r\n\r\n        Point.origin = new Point(0, 0);\r\n        return Point;\r\n    })();\r\n    Shapes.Point = Point;\r\n})(Shapes || (Shapes = {}));\r\n\r\n// Local variables\r\nvar p = new Shapes.Point(3, 4);\r\nvar dist = p.getDist();\r\n";

            Assert.AreEqual(expectedResult, resultSource);

            // Clean up
            File.Delete(outFile);
        }
Exemplo n.º 13
0
        public void RunTests(IEnumerable <Microsoft.VisualStudio.TestPlatform.ObjectModel.TestCase> tests, IRunContext runContext, IFrameworkHandle frameworkHandle)
        {
            var olock = new Object();
            var cache = new Dictionary <string, string>();

            Parallel.ForEach(tests, test =>
            {
                var result = new TestResult(test);

                // full path to temporary file
                string filePath = Path.ChangeExtension(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + DateTime.Now.ToString("HH-mm-ss-fff")), ".js");

                try
                {
                    lock (olock)
                    {
                        if (!cache.ContainsKey(test.CodeFilePath))
                        {
                            TypeScriptCompiler.Compile(test.CodeFilePath, new TypeScriptCompiler.Options(outPath: filePath));
                            cache.Add(test.CodeFilePath, filePath);
                        }
                        else
                        {
                            filePath = cache[test.CodeFilePath];
                        }
                    }

                    var testResult = new JSRunner.TestResult();

                    var scriptFilePath = filePath + Guid.NewGuid().ToString("N") + "exec.js";

                    using (var fs = new FileStream(scriptFilePath, FileMode.Create))
                    {
                        using (var sw = new StreamWriter(fs))
                        {
                            sw.WriteLine("try{");
                            sw.Write(File.ReadAllText(filePath));

                            var className  = test.FullyQualifiedName.Substring(0, test.FullyQualifiedName.LastIndexOf("."));
                            var methodName = test.FullyQualifiedName.Substring(test.FullyQualifiedName.LastIndexOf(".") + 1);

                            sw.WriteLine("var ____TSTestExecutor____ = new " + className + "();____TSTestExecutor____." + methodName + "();");

                            sw.WriteLine("phantom.exit(0)}catch(ex){console.log(ex);phantom.exit(-1)}");
                            sw.Flush();
                        }
                    }
                    testResult = JSRunner.Run(scriptFilePath);

                    result.Outcome = testResult.Outcome;
                    if (result.Outcome != TestOutcome.Passed)
                    {
                        result.ErrorMessage = testResult.Output;
                    }

                    try
                    {
                        File.Delete(scriptFilePath);
                    }
                    catch { }
                }
                catch (InvalidTypeScriptFileException ex)
                {
                    result.Outcome      = TestOutcome.Failed;
                    result.ErrorMessage = ex.Message;
                }
                catch (Exception ex)
                {
                    result.Outcome      = TestOutcome.Failed;
                    result.ErrorMessage = ex.Message + ex.StackTrace;
                }

                frameworkHandle.RecordResult(result);
            });

            foreach (KeyValuePair <string, string> item in cache)
            {
                try
                {
                    File.Delete(item.Value);
                }
                catch { }
            }
        }
        private void InnerTranslate(IAsset asset, TypeScriptCompiler typeScriptCompiler)
        {
            string newContent;
            string assetUrl = asset.Url;
            var dependencies = new DependencyCollection();

            try
            {
                TsScript script = GetTsScript(asset);
                FillDependencies(assetUrl, script, dependencies);

                newContent = typeScriptCompiler.Compile(script.Content, script.Url, dependencies);
                newContent = RemoveReferenceComments(newContent);
            }
            catch (TypeScriptCompilingException e)
            {
                throw new AssetTranslationException(
                    string.Format(CoreStrings.Translators_TranslationSyntaxError,
                        INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message));
            }
            catch (Exception e)
            {
                throw new AssetTranslationException(
                    string.Format(CoreStrings.Translators_TranslationFailed,
                        INPUT_CODE_TYPE, OUTPUT_CODE_TYPE, assetUrl, e.Message));
            }

            asset.Content = newContent;
            asset.VirtualPathDependencies = dependencies
                .Where(d => d.IsObservable)
                .Select(d => d.Url)
                .Distinct()
                .ToList()
                ;
        }