Fixing to update stuff to the library

This commit is contained in:
Martin Karkowski 2022-01-17 18:53:06 +01:00
parent 585ece2d39
commit fce545d2c4
22 changed files with 1298 additions and 3894 deletions

3
.gitignore vendored
View File

@ -80,7 +80,8 @@ typings/
# Nuxt.js build / generate output
.nuxt
dist
dist-nodejs
dist-browser
temp
# Gatsby files

View File

@ -3,8 +3,21 @@ set DIR=%~dp0
cd "%DIR%"
SETLOCAL
echo Compiling Backend
(npx tsc -p ./tsconfigBackend.json --pretty) && (
echo Done
) || (
echo Done
)
(npm run-script prettier-format) && (
(npm run-script compile-nodejs) && (
echo Done
) || (
(npm run-script compile-browser) && (
echo Done
) || (
(npm run-script build) && (
echo Done
) || (
echo Error
)
)
)
) || (
echo Failed to pettier code
)

View File

@ -1,4 +0,0 @@
set DIR=%~dp0
cd "%DIR%"
call npx webpack -c .\webpack-typescript.config.js

11
10-push-to-npm.bat Normal file
View File

@ -0,0 +1,11 @@
set DIR=%~dp0
cd "%DIR%"
node contribute/toBrowser.js
(npm publish --registry https://npm.zema.de/) && (
node contribute/toNodejs.js
npm publish --registry https://npm.zema.de/
) || (
node contribute/toNodejs.js
npm publish --registry https://npm.zema.de/
)

View File

@ -1,7 +0,0 @@
set DIR=%~dp0
cd "%DIR%"
call npx webpack -c .\webpack-typescript.config.js
cd build
xcopy * ..\..\nope-browser\

View File

@ -1,2 +1,2 @@
#! /usr/bin/env node
require("../dist/cli/nope").main().catch(console.error);
require("../dist-nodejs/cli/nope").main().catch(console.error);

1
contribute/VERSION Normal file
View File

@ -0,0 +1 @@
1.0.7

20
contribute/toBrowser.js Normal file
View File

@ -0,0 +1,20 @@
const { readFileSync, writeFileSync } = require("fs");
const version = readFileSync("./contribute/VERSION", { encoding: "utf-8" });
const package = JSON.parse(readFileSync("./package.json", { encoding: "utf-8" }));
package.description = "NoPE Runtime for the Browser";
delete package.main;
delete package.browser;
delete package.bin;
package.name = "nope-browser"
package.browser = "build/nope.js";
package.main = "build/nope.js";
package.version = version;
package.files = [
"build/**/*"
];
writeFileSync("./package.json", JSON.stringify(package, undefined, 2), { encoding: "utf-8" });

23
contribute/toNodejs.js Normal file
View File

@ -0,0 +1,23 @@
const { readFileSync, writeFileSync } = require("fs");
const version = readFileSync("./contribute/VERSION", { encoding: "utf-8" });
const package = JSON.parse(readFileSync("./package.json", { encoding: "utf-8" }));
package.description = "NoPE Runtime for Nodejs. For Browser-Support please use nope-browser";
delete package.main;
delete package.browser;
package.bin = {
"nope-js": "./bin/nope"
};
package.name = "nope"
package.main = "dist-nodejs/index.nodejs.js";
package.version = version;
package.files = [
"dist-nodejs/**/*",
"lib/**/*",
"bin/*"
];
writeFileSync("./package.json", JSON.stringify(package, undefined, 2), { encoding: "utf-8" });

View File

@ -12,10 +12,7 @@ import { join } from "path";
import { createPath } from "../helpers/fileMethods";
import { getNopeLogger } from "../logger/getLogger";
const FOLDERS_TO_CREATE = [
"config",
"modules"
];
const FOLDERS_TO_CREATE = ["config", "modules"];
const BASE_FOLDER = __dirname;
const FILES_TO_COPY = [
// Config-Files

View File

@ -1,42 +0,0 @@
// server.js
const { createServer } = require('http')
const { parse,format } = require('url')
const next = require('next')
const join = require('path').join
const dev = process.env.NODE_ENV !== 'production'
const app = next({
dev,
useFileSystemPublicRoutes: false,
});
const handle = app.getRequestHandler()
const staticFiles = ['/hello']
app.prepare().then(() => {
const server = require('express')();
server.listen(3000, 'localhost', () => {
server.get('*', (req,res) => {
const { pathname, query } = parse(req.url, true);
if (staticFiles.indexOf(pathname) > -1) {
const path = join(__dirname, "..", pathname);
console.log(path)
// return handle(req,res,path)
// return app.serveStatic(req, res, path);
return res.redirect(
format({
pathname: path,
query,
}),
);
}
return handle(req,res)
})
});
})

View File

@ -1,51 +0,0 @@
import { runMiddleware } from "./runMiddleware";
import { Application } from "express";
import { assignIn } from "lodash";
export interface ICallOptions {
method: "post";
headers?: { "Content-Type": "application/json" };
body: {
[index: string]: any;
};
}
/**
* Function that will generate an async accessor Function.
* @param app the provided Express App.
*/
export function getBackendAccesors(app: Application) {
// Create a Run-Middle-Ware
runMiddleware(app);
// Define a apiCall Function, which could be used to perform internal
// Request on the API.
function apiCall<T>(url: string, options: ICallOptions) {
return new Promise<T>((resolve, reject) => {
// Define the Default Options
const defaults: Partial<ICallOptions> = {
headers: { "Content-Type": "application/json" },
};
// Mix the Options.
const opts: ICallOptions = assignIn(defaults, options);
// Perform the Call
(app as any).runMiddleware(url, opts, (responseCode: number, body: T) => {
// Based on the Response code, decide whether the call was a Fail or not.
if (responseCode === 200) {
// If everything is fine,
// Just return the body.
return resolve(body);
} else {
const error = new Error(
"Call Ended with responseCode = " + responseCode.toString()
);
return reject(error);
}
});
});
}
return apiCall;
}

View File

@ -1,112 +0,0 @@
// Adapted File from 'run-middleware'
import * as _ from "lodash";
export function runMiddleware(app) {
app.use((req, res, next) => {
req.runMiddleware = (path, options, callback) => {
if (_.isFunction(options)) {
callback = options;
options = {};
}
options.original_req = req;
options.original_res = res;
app.runMiddleware(path, options, callback);
};
next();
});
if (app.runMiddleware) return; // Do not able to add us twice
app.runMiddleware = function (path, options, callback) {
if (callback) callback = _.once(callback);
if (typeof options == "function") {
callback = options;
options = null;
}
options = options || {};
options.url = path;
let new_req, new_res;
if (options.original_req) {
new_req = options.original_req;
for (const i in options) {
if (i == "original_req") continue;
new_req[i] = options[i];
}
} else {
new_req = _createReq(path, options);
}
new_res = _createRes(callback);
app(new_req, new_res);
};
/* end - APP.runMiddleware*/
}
function _createReq(path, options) {
if (!options) options = {};
const req = _.extend(
{
method: "GET",
host: "",
cookies: {},
query: {},
url: path,
headers: {},
},
options
);
req.method = req.method.toUpperCase();
// req.connection=_req.connection
return req;
}
function _createRes(callback) {
const res: any = {
_removedHeader: {},
};
// res=_.extend(res,require('express/lib/response'));
const headers = {};
let code = 200;
res.set = res.header = function (x, y) {
if (arguments.length === 2) {
res.setHeader(x, y);
} else {
for (const key in x) {
res.setHeader(key, x[key]);
}
}
return res;
};
res.setHeader = function (x, y) {
headers[x] = y;
headers[x.toLowerCase()] = y;
return res;
};
res.get = function (x) {
return headers[x];
};
res.redirect = function (_code, url) {
if (!_.isNumber(_code)) {
code = 301;
url = _code;
} else {
code = _code;
}
res.setHeader("Location", url);
res.end();
// callback(code,url)
};
res.status = function (number) {
code = number;
return res;
};
res.end =
res.send =
res.write =
function (data) {
if (callback) callback(code, data, headers);
// else if (!options.quiet){
// _res.send(data)
// }
};
return res;
}

View File

@ -1,8 +0,0 @@
import { readInArgs } from "../cli/runNopeBackend";
import { getNopeLogger } from "../logger/getLogger";
import { startOpenApiBackend } from "./startOpenApiBackend";
startOpenApiBackend(readInArgs(), {
port: 3001,
logger: getNopeLogger("open-api-server", "debug"),
});

View File

@ -1,136 +0,0 @@
/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-12 11:21:41
* @modify date 2021-08-04 17:19:12
* @desc [description]
*/
import * as bodyParser from "body-parser";
import * as cors from "cors";
import * as express from "express";
import { initialize } from "express-openapi";
import { readFile } from "fs/promises";
import { ILogger } from "js-logger";
import { assignIn } from "lodash";
import { join } from "path";
import "reflect-metadata";
import { INopeDispatcher } from "../types/nope/nopeDispatcher.interface";
import { getBackendAccesors } from "./getBackendAccessors";
/**
* Function to generate the Base Api Documentation
* @param title The Title of the API
* @param version The Version
* @param basePath A Basepath for the API
*/
function _genApiDoc(
title: string,
version: string,
basePath: string,
definitions: any = {}
) {
// Default API Doc
const apiDoc = {
swagger: "2.0",
basePath: basePath || "/v1",
info: {
title,
version,
},
definitions,
paths: {},
};
return apiDoc;
}
/**
* Function to start a Open-API-Server
* @param _dispatcher The Dispatcher, which should be used.
* @param options Options for the Server
*/
export async function startOpenApiBackend(
_dispatcher: INopeDispatcher,
options: {
port?: number;
backendPort?: number;
basePath?: string;
logger?: ILogger;
} = {}
) {
const app: express.Application = (express as any)();
// Define the Default Options
const defaults = {
port: 3001,
backendPort: 3002,
basePath: "/api",
};
// Mix the Options.
const opts = assignIn(defaults, options);
app.use(bodyParser.json());
app.use(cors());
let _definition = {};
try {
// Extract the Elements provided in the API-Document.
_definition = JSON.parse(
await readFile(join(__dirname, "apidoc.json"), {
encoding: "utf8",
})
).definitions;
} catch (e) {
if (opts.logger) {
opts.logger.error("cant parse apidoc.json");
}
}
initialize({
apiDoc: _genApiDoc("Backend API", "1.0.0", opts.basePath, _definition),
app,
paths: "./dist/open-api",
routesGlob: "**/*.{ts,js}",
routesIndexFileRegExp: /(?:index)?\.[tj]s$/,
dependencies: {
_dispatcher,
},
});
app.use(((err, req, res, next) => {
res.status(err.status).json(err);
}) as express.ErrorRequestHandler);
const server = app.listen(opts.port);
const accessor = getBackendAccesors(app);
if (options.logger) {
options.logger.info(
"Server Running on http://localhost:" +
opts.port.toString() +
opts.basePath
);
options.logger.info(
"API Documentation available on http://localhost:" +
opts.port.toString() +
opts.basePath +
"/api-docs"
);
options.logger.debug("Checkout http://localhost:3000/docs");
}
return {
app,
// Accessor for the Server
accessor,
// Function to extract the Definitions.
definitionUri: opts.basePath + "/api-docs",
// Function to Close the Server
close() {
server.close();
},
};
}

4529
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,19 @@
{
"name": "nope",
"version": "1.0.1",
"description": "NoPE Runtime",
"browser": "build/nope.js",
"main": "dist/index.nodejs.js",
"version": "1.0.7",
"description": "NoPE Runtime for Nodejs. For Browser-Support please use nope-browser",
"files": [
"build",
"dist",
"node_modules",
"README.md",
"package.json"
"dist-nodejs/**/*",
"lib/**/*",
"bin/*"
],
"bin": {
"nope-js": "./bin/nope"
},
"scripts": {
"test": "mocha",
"compile-nodejs": "tsc -p ./tsconfig.json",
"compile": "tsc -p ./tsconfig.browser.json",
"compile-browser": "tsc -p ./tsconfig.browser.json",
"build": "npx webpack -c webpack-typescript.config.js",
"doc": "npx jsdoc ./dist/**/* -d docs",
"dev": "NODE_OPTIONS='--inspect' next dev",
"start": "node ./dist/lib/cli/nope.js",
"start": "node ./dist/cli/repl.js",
"prettier-format": "run-script-os",
"prettier-format:win32": "prettier \"./lib/**/*.ts\" --write",
"prettier-format:darwin:linux": "prettier 'lib/**/*.ts' --write",
@ -60,7 +52,6 @@
"mathjs": "^10.0.2",
"mqtt": "^4.3.4",
"mqtt-pattern": "^1.2.0",
"next": "^12.0.7",
"npm": "^8.3.0",
"npx": "^10.2.2",
"reflect-metadata": "^0.1.13",
@ -74,11 +65,10 @@
"websocket-stream": "^5.5.2"
},
"devDependencies": {
"@babel/preset-typescript": "^7.16.7",
"@types/async": "^3.2.12",
"@types/chai": "^4.3.0",
"@types/lodash": "^4.14.178",
"@types/node": "^17.0.8",
"@types/node": "^17.0.9",
"@types/socket.io": "^3.0.1",
"@types/socket.io-client": "^1.4.36",
"chai": "^4.3.4",
@ -96,5 +86,9 @@
"typescript": "^4.5.4",
"webpack": "^4.46.0",
"webpack-cli": "^4.8.0"
}
},
"bin": {
"nope-js": "./bin/nope"
},
"main": "dist-nodejs/index.nodejs.js"
}

99
package.json.bak Normal file
View File

@ -0,0 +1,99 @@
{
"name": "nope",
"version": "1.0.3",
"description": "NoPE Runtime for Nodejs. For Browser-Support please use nope-browser",
"browser": "build/nope.js",
"main": "dist-nodejs/index.nodejs.js",
"files": [
"build/**/*",
"dist-nodejs/**/*",
"lib/**/*",
"bin/*"
],
"bin": {
"nope-js": "./bin/nope"
},
"scripts": {
"test": "mocha",
"compile-nodejs": "tsc -p ./tsconfig.json",
"compile": "tsc -p ./tsconfig.browser.json",
"build": "npx webpack -c webpack-typescript.config.js",
"doc": "npx jsdoc ./dist/**/* -d docs",
"dev": "NODE_OPTIONS='--inspect' next dev",
"start": "node ./dist/lib/cli/nope.js",
"prettier-format": "run-script-os",
"prettier-format:win32": "prettier \"./lib/**/*.ts\" --write",
"prettier-format:darwin:linux": "prettier 'lib/**/*.ts' --write",
"prettier-format:default": "prettier 'lib/**/*.ts' --write",
"prettier-watch": "run-script-os",
"prettier-watch:win32": "onchange \"lib/**/*.ts\" -- prettier --write {{changed}}",
"prettier-watch:darwin:linux": "onchange 'lib/**/*.ts' -- prettier --write {{changed}}",
"prettier-watch:default": "onchange 'lib/**/*.ts' -- prettier --write {{changed}}"
},
"mocha": {
"reporter": "spec",
"spec": "dist/**/*.spec.js"
},
"repository": {
"type": "git",
"url": "git+https://git.zema.de/tfs/ZISS/_git/nope-js"
},
"keywords": [],
"author": "Martin Karkowski",
"license": "MIT",
"bugs": {
"url": "https://git.zema.de/tfs/ZISS/_git/nope-js/issues"
},
"homepage": "https://git.zema.de/tfs/ZISS/_git/nope-js#readme",
"dependencies": {
"async": "^3.2.2",
"comment-parser": "^1.3.0",
"cors": "^2.8.5",
"handlebars": "^4.7.7",
"inquirer": "^8.2.0",
"inquirer-fuzzy-path": "^2.3.0",
"inquirer-search-list": "^1.2.6",
"inversify": "^6.0.1",
"js-logger": "^1.6.1",
"lodash": "^4.17.21",
"mathjs": "^10.0.2",
"mqtt": "^4.3.4",
"mqtt-pattern": "^1.2.0",
"next": "^12.0.7",
"npm": "^8.3.0",
"npx": "^10.2.2",
"reflect-metadata": "^0.1.13",
"run-script-os": "^1.1.6",
"rxjs": "^7.5.1",
"socket.io": "^4.4.1",
"socket.io-client": "^4.4.1",
"ts-morph": "^13.0.2",
"typescript-json-schema": "^0.52.0",
"uuid": "^8.3.2",
"websocket-stream": "^5.5.2"
},
"devDependencies": {
"@babel/preset-typescript": "^7.16.7",
"@types/async": "^3.2.12",
"@types/chai": "^4.3.0",
"@types/lodash": "^4.14.178",
"@types/node": "^17.0.8",
"@types/socket.io": "^3.0.1",
"@types/socket.io-client": "^1.4.36",
"chai": "^4.3.4",
"dts-bundle": "^0.7.3",
"dts-bundle-webpack": "^1.0.2",
"eslint": "^8.6.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-prettier": "^4.0.0",
"mocha": "^9.1.3",
"npm-check-updates": "^12.1.0",
"onchange": "^7.1.0",
"prettier": "2.5.1",
"typedoc": "^0.22.10",
"typescript": "^4.5.4",
"webpack": "^4.46.0",
"webpack-cli": "^4.8.0"
}
}

View File

@ -12,15 +12,13 @@
"moduleResolution": "node",
"noFallthroughCasesInSwitch": false,
"noImplicitReturns": true,
"outDir": "./dist",
"outDir": "./dist-browser",
"pretty": false,
"removeComments": true,
"rootDir": "./",
"stripInternal": true,
"downlevelIteration": true,
"noImplicitAny": false,
"declaration": true,
"noEmitOnError": true
},
"include": [
"lib"
@ -28,6 +26,7 @@
"exclude": [
"node_modules",
"temp",
"dist"
"dist-nodejs",
"dist-browser"
]
}

View File

@ -12,7 +12,7 @@
"moduleResolution": "node",
"noFallthroughCasesInSwitch": false,
"noImplicitReturns": true,
"outDir": "./dist",
"outDir": "./dist-nodejs",
"pretty": false,
"removeComments": false,
"stripInternal": true,
@ -32,6 +32,7 @@
"exclude": [
"node_modules",
"temp",
"dist"
"dist-nodejs",
"dist-browser"
]
}

View File

@ -3,12 +3,12 @@ const DtsBundleWebpack = require("dts-bundle-webpack");
module.exports = {
mode: "production",
entry: path.resolve(__dirname, "dist", "index.browser.js"),
entry: path.resolve(__dirname, "dist-browser", "index.browser.js"),
devtool: "inline-source-map",
output: {
path: path.resolve(__dirname, "build"),
filename: "nope.js",
library: "nope_browser",
library: "nope-browser",
libraryTarget: "commonjs2",
},
// resolve: {
@ -16,8 +16,8 @@ module.exports = {
// },
plugins: [
new DtsBundleWebpack({
name: "nope_browser",
main: path.resolve(__dirname, "dist", "index.browser.d.ts"),
name: "nope-browser",
main: path.resolve(__dirname, "dist-browser", "index.browser.d.ts"),
baseDir: path.resolve(__dirname),
out: path.resolve(__dirname, "build", "nope.d.ts"),
// baseDir: path.resolve(__dirname, "dist"),

View File

@ -0,0 +1,64 @@
# Getting started
---
## Installation:
### Using https://npm.zema.de/
Use the following code: `npm --registry https://npm.zema.de/ install nope`
### Use this Libary locally:
1. Clone the repo: `git clone -b lib https://git.zema.de/tfs/ZISS/_git/nope-js`
2. Install the depencies by typing `npm install`
3. Go to your desired folder and create a local link `npm link` _``path to the cloned package`_
---
## Documentation
The Documentation is contained in here. Alternative you can create a Documentation using `npm run-script doc`. This will create the Documentation under `docs`.
You'll additional help under `wiki`
---
## Contribute
To contribute to the Project, please perform the following steps:
0. Perform the Steps in `PREPARE_VSCODE.md`
1. Assign a new Version under `contribute/VERSION`
2. Fillout the Change Log in the `CHANGELOG.md`
3. Implement Your Changes and **Test-Cases**:
1. For Testing the Library [`mocha`](https://mochajs.org/) is used (click [here](https://mochajs.org/) for more details).
2. name your tests `*.spec.ts`
3. run the tests with `npm test`
4. If the Test are successfully proceed, otherwise perform your Bugfixes
5. Run the Code-Formater: `npm run-script prettier-format`
6. Push the Code to the Git
---
### Commiting Changes
For simpler usage, you can use the following helpers:
- `00-compile.bat`, which will compile the library for the browser and nodejs
- `10-push-to-npm.bat`, which will push the library to the npm registry.
#### Browser
1. Compile the code: `npm run-script compile-browser`
2. Build the Library; `npm run-script build`
3. Switch the Package Defintion to `browser` by `node ./contribute/toBrowser.js`
4. Publish the Code to `https://npm.zema.de/` using `npm publish --registry https://npm.zema.de/`
#### Nodejs
1. Compile the code: `npm run-script compile-nodejs`
2. Switch the Package Defintion to `nodejs` by `node ./contribute/toNodejs.js`
3. Publish the Code to `https://npm.zema.de/` using `npm publish --registry https://npm.zema.de/`