Skip to content

Commit

Permalink
WIP api bundle
Browse files Browse the repository at this point in the history
  • Loading branch information
wartoshika authored and Oliver Leve committed Sep 16, 2019
1 parent c1af47b commit b8a766e
Show file tree
Hide file tree
Showing 11 changed files with 167 additions and 77 deletions.
7 changes: 5 additions & 2 deletions package.json
Expand Up @@ -5,6 +5,9 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": "dist/bin/qhun-transpiler.js",
"bugs": {
"url": "https://github.com/wartoshika/qhun-transpiler/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/wartoshika/qhun-transpiler"
Expand All @@ -15,9 +18,9 @@
"test-seperate": "./node_modules/.bin/mocha -r ts-node/register \"test/**/*.spec.sep.ts\"",
"test:coverage": "./node_modules/.bin/nyc ./node_modules/.bin/mocha -r ts-node/register \"test/**/*.spec.ts\"",
"coverage:send:coveralls": "nyc report --reporter=text-lcov | coveralls",
"build-ts": "./node_modules/.bin/tsc",
"build-ts": "./node_modules/.bin/webpack --config ./webpack.api.config.js",
"build-declaration": "./node_modules/.bin/tsc -p tsconfig.api.json",
"build-cli": "./node_modules/.bin/webpack --config ./webpack.config.js",
"build-cli": "./node_modules/.bin/webpack --config ./webpack.cli.config.js",
"build": "./node_modules/.bin/npm-run-all build-ts build-cli build-declaration",
"run-ts": "./node_modules/.bin/ts-node src/cli/Cli.ts",
"postversion": "git push --follow-tags"
Expand Down
40 changes: 33 additions & 7 deletions src/api/Api.ts
Expand Up @@ -5,10 +5,15 @@ import { DefaultConfig } from "../config/DefaultConfig";
import { SupportedTargets } from "../target/TargetFactory";
import { TranspilePipeline } from "./TranspilePipeline";
import { CompileResult } from "../compiler/CompileResult";
import { Logger } from "../cli/Logger";
import { ErrorWithNode } from "../error/ErrorWithNode";
import { CommandLineColors } from "../cli/CommandLineColors";
import { CommandLine } from "../cli/CommandLine";

import { Observable, TeardownLogic } from "rxjs";

import * as fs from "fs";
import { Logger } from "../cli/Logger";
import * as ts from "typescript";

export class Api<T extends keyof SupportedTargets> {

Expand All @@ -29,6 +34,9 @@ export class Api<T extends keyof SupportedTargets> {

// save target
this.options.configuration.target = target;

// print cli head
CommandLine.printHead();
}

/**
Expand Down Expand Up @@ -57,7 +65,7 @@ export class Api<T extends keyof SupportedTargets> {
this.compiler = new Compiler(project);

// other work will be done by the internal transpiler
observer.next(new TranspilePipeline(this.internalTranspile(), this.compiler.postProjectTranspile.bind(this.compiler)));
observer.next(new TranspilePipeline(project, this.internalTranspile(), this.compiler.postProjectTranspile.bind(this.compiler)));

// bind watcher if actiavted
if (this.options.watch) {
Expand All @@ -66,19 +74,17 @@ export class Api<T extends keyof SupportedTargets> {
new FileWatcher(project, () => {

try {
observer.next(new TranspilePipeline(this.internalTranspile(), this.compiler.postProjectTranspile.bind(this.compiler)));
observer.next(new TranspilePipeline(project, this.internalTranspile(), this.compiler.postProjectTranspile.bind(this.compiler)));
} catch (e) {
Logger.error("Error in the transpile pipeline: " + e);
observer.error(e);
this.printError(e);
}
});
} else {
observer.complete();
}

} catch (e) {
Logger.error("Error in the transpile pipeline: " + e);
observer.error(e);
this.printError(e);
observer.complete();
}

Expand Down Expand Up @@ -108,4 +114,24 @@ export class Api<T extends keyof SupportedTargets> {

return true;
}

private printError(e: Error): void {

if (e instanceof ErrorWithNode) {

const sourceFile = e.node.getSourceFile();
const position = ts.getLineAndCharacterOfPosition(sourceFile, e.node.pos);

Logger.error();
Logger.error(e.message, "[Error] ", CommandLineColors.RED);
Logger.log(`File: ${sourceFile.fileName}`, " at ");
Logger.log(`Line: ${position.line + 1}, Column: ${position.character}`, " at ");
Logger.error();
} else {

Logger.error(e.message);
}
}


}
2 changes: 1 addition & 1 deletion src/api/FileWatcher.ts
Expand Up @@ -104,7 +104,7 @@ export class FileWatcher {

// print some info
Logger.log(""); // one empty line
Logger.log("Detected file change: " + filename + " > Transpiling started.");
Logger.log("Detected file change: " + filename.replace(this.project.rootDir, "") + " > Transpiling started.");

const result = this.executeOnChange([absolutePath]);
this.changeStack.forEach(callable => callable(result));
Expand Down
27 changes: 19 additions & 8 deletions src/api/TranspilePipeline.ts
@@ -1,13 +1,12 @@
import { CompileResult } from "../compiler/CompileResult";
import { Logger } from "../cli/Logger";
import { CommandLineColors } from "../cli/CommandLineColors";

import * as ts from "typescript";
import * as path from "path";
import { Project } from "../config/Project";

export class TranspilePipeline {

constructor(
private project: Project<any>,
private files: CompileResult[],
private postProjectTranspile: () => boolean
) { }
Expand All @@ -17,24 +16,34 @@ export class TranspilePipeline {
*/
public printResult(): TranspilePipeline {

Logger.log();
Logger.log("Successfully transpiled " + this.files.length + " files", "> ", CommandLineColors.GREEN);
Logger.log();
return this;
}

/**
* prints the transpiling result more prettier :)
*/
public prettyPrintResult(): TranspilePipeline {

Logger.log("Transpiling successfull. Result: " + this.files.length + " files");
Logger.log();
Logger.log(`${this.files.length} file(s) transpiled`, "[Success] ", CommandLineColors.GREEN);

const amountOfTopFiles = 8;
this.files.slice(0, amountOfTopFiles).forEach(file => {
const size = Math.round(file.generatedSourcecode.length / 1024);
Logger.log(path.basename(file.file.fileName) + " [" + size + " KB]", " + ", CommandLineColors.GREEN);
let fileName = file.file.fileName.replace(this.project.rootDir, "");
if (fileName[0] !== "/") {
fileName = "/" + fileName;
}
Logger.log(fileName + " [" + size + " KB]", " + ");
});

const otherFiles = this.files.length - amountOfTopFiles;
if (otherFiles > 0) {
const otherFilesLength = Math.round(this.files.slice(amountOfTopFiles).reduce<number>((a, b) => a + b.generatedSourcecode.length, 0) / 1024);
Logger.log("And " + otherFiles + " other files [" + otherFilesLength + " KB]", " ", CommandLineColors.GREEN);
Logger.log("And " + otherFiles + " other file(s) [" + otherFilesLength + " KB]", " ");
}

return this;
Expand All @@ -47,11 +56,13 @@ export class TranspilePipeline {
*/
public applyPostProjectTranspile(): TranspilePipeline {

Logger.log("Applying postProjectTranspile ...");
Logger.log();
Logger.log("Applying postProjectTranspile ...", "> ");
if (!this.postProjectTranspile()) {
throw new Error("Error in the postProjectTranspile process!");
}
Logger.log("PostProjectTranspile successfull", " + ", CommandLineColors.GREEN);
Logger.log("PostProjectTranspile done", "[Success] ", CommandLineColors.GREEN);
Logger.log();
return this;
}

Expand Down
22 changes: 20 additions & 2 deletions src/cli/CommandLine.ts
Expand Up @@ -52,6 +52,19 @@ export class CommandLine {
}) as ProgramArguments;
}

// tslint:disable-next-line member-ordering
public static printHead(): void {

Logger.log();
Logger.log(`${packageJson.name} (${packageJson.version})${CommandLineColors.RESET} by ${packageJson.author}`, "", CommandLineColors.BRIGHT);
Logger.log("--------------------------------------------------------------------------------------", "");
Logger.log(`Visit ${packageJson.repository.url} for a description and help.`, " - ");
Logger.log(`Please post issues at ${packageJson.bugs.url}`, " - ");
Logger.log("--------------------------------------------------------------------------------------", "");
Logger.log("Thanks for using!", " ");
Logger.log();
}

/**
* prepares the execution of the transpiling process
*/
Expand Down Expand Up @@ -96,11 +109,16 @@ export class CommandLine {
*/
private init(): void {

CommandLine.printHead();

if (!fs.existsSync("./qhun-transpiler.js")) {
fs.writeFileSync("./qhun-transpiler.js", initFile.default);
Logger.log("The file qhun-transpiler.js has been created!", "> ", CommandLineColors.GREEN);
Logger.log("The file qhun-transpiler.js has been created!", "[Success] ", CommandLineColors.GREEN);
} else {
Logger.log("This project allready contains a qhun-transpiler.js file.", "> ", CommandLineColors.RED);
Logger.error("This project allready contains a qhun-transpiler.js file.", "[Error] ");
}

// empty line
Logger.log();
}
}
5 changes: 4 additions & 1 deletion src/cli/CommandLineColors.ts
Expand Up @@ -2,5 +2,8 @@ export enum CommandLineColors {

RESET = "\x1b[0m",
RED = "\x1b[31m",
GREEN = "\x1b[32m"
GREEN = "\x1b[32m",
WHITE = "\x1b[37m",
GREY = "\x1b[2m\x1b[37m",
BRIGHT = "\x1b[1m"
}
96 changes: 42 additions & 54 deletions src/compiler/Compiler.ts
Expand Up @@ -55,9 +55,9 @@ export class Compiler<T extends keyof SupportedTargets> {
/**
* compiles the given files and transpiles them into the target language
* @param files the files to compile and transpile
* @returns the amount of successfully transpiled and written files. false on error
* @returns the amount of successfully transpiled and written files.
*/
public compile(files: string[]): CompileResult[] | false {
public compile(files: string[]): CompileResult[] {

// create a typescript program
const program = ts.createProgram(files, this.project.compilerOptions);
Expand All @@ -70,59 +70,47 @@ export class Compiler<T extends keyof SupportedTargets> {
const transpilerMetadata: QhunTranspilerMetadata = this.getMetadata();
const transpileResult: CompileResult[] = [];

// iterate over every source file
try {

// analyze all source files and detect external modules
this.externalModuleService.analyseSourceFilesAndCastToSourceFile(

// analyse all program sourcefiles
program.getSourceFiles()
// that are not declaration files
.filter(file => !file.isDeclarationFile)
).forEach(sourceFile => {

// create the transpiler
const target = targetFactory.create(this.project.configuration.target,
this.project, typeChecker,
sourceFile, transpilerMetadata,
this.keyValueStorage
);
const extension = target.getFileExtension();
const transpiler = new Transpiler(target);

// declare last instances
lastSourceFile = sourceFile;
this.lastTarget = target;

// transpile this file
let transpiledCode = transpiler.transpile(sourceFile);

// restore replacements
transpiledCode = TranspilerFunctions.restoreReservedChars(transpiledCode);

// save result
transpileResult.push(new CompileResult(
sourceFile,
transpiledCode,
(code: string) => {
this.writeDestinationFile(sourceFile, code, extension);
}
));
});

// cleanup compiler vars and return the amount
this.writtenFileStack = [];
return transpileResult;

} catch (e) {

// handle this error
this.handleCompileError(e, lastSourceFile);
}
// analyze all source files and detect external modules
this.externalModuleService.analyseSourceFilesAndCastToSourceFile(

// analyse all program sourcefiles
program.getSourceFiles()
// that are not declaration files
.filter(file => !file.isDeclarationFile)
).forEach(sourceFile => {

// create the transpiler
const target = targetFactory.create(this.project.configuration.target,
this.project, typeChecker,
sourceFile, transpilerMetadata,
this.keyValueStorage
);
const extension = target.getFileExtension();
const transpiler = new Transpiler(target);

// declare last instances
lastSourceFile = sourceFile;
this.lastTarget = target;

// transpile this file
let transpiledCode = transpiler.transpile(sourceFile);

// restore replacements
transpiledCode = TranspilerFunctions.restoreReservedChars(transpiledCode);

// save result
transpileResult.push(new CompileResult(
sourceFile,
transpiledCode,
(code: string) => {
this.writeDestinationFile(sourceFile, code, extension);
}
));
});

// compiling not successfill
return false;
// cleanup compiler vars and return the amount
this.writtenFileStack = [];
return transpileResult;
}

/**
Expand Down
1 change: 1 addition & 0 deletions tsconfig.api.json
@@ -1,6 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outFile": "dist/index.d.ts",
"declaration": true,
"emitDeclarationOnly": true,
"removeComments": false
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.base.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"module": "commonjs",
"module": "umd",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
Expand Down

0 comments on commit b8a766e

Please sign in to comment.