Initial commit

This code serves as an application framework of sorts and is totally not
stolen from some of my other projects.
This commit is contained in:
Wolvan 2021-12-28 21:11:19 +01:00
commit 8bc3f7fe36
20 changed files with 4691 additions and 0 deletions

7
.editorconfig Normal file
View file

@ -0,0 +1,7 @@
root = true
[*]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true

3
.eslintignore Normal file
View file

@ -0,0 +1,3 @@
dist/
node_modules/
utils/todo-finder.js

44
.eslintrc.json Normal file
View file

@ -0,0 +1,44 @@
{
"env": {
"browser": false,
"commonjs": false,
"es6": true,
"node": true
},
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"mocha",
"chai-expect"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:mocha/recommended",
"plugin:chai-expect/recommended"
],
"parserOptions": {
"ecmaFeatures": {
"impliedStrict": true
},
"sourceType": "module"
},
"rules": {
"no-const-assign": "warn",
"no-this-before-super": "warn",
"no-undef": "warn",
"no-unreachable": "warn",
"semi-spacing": "warn",
"constructor-super": "warn",
"valid-typeof": "warn",
"default-case": "warn",
"array-bracket-spacing": "warn",
"brace-style": "warn",
"camelcase": "warn",
"no-fallthrough": "warn",
"@typescript-eslint/semi": "warn",
"@typescript-eslint/no-explicit-any": "off"
}
}

113
.gitignore vendored Normal file
View file

@ -0,0 +1,113 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Testing directory
testing/
# SQLite database file
*.sqlite
*.sqlite3
*.db
*.db3

8
.mocharc.json Normal file
View file

@ -0,0 +1,8 @@
{
"extension": ["ts"],
"spec": "test/**/*.spec.ts",
"require": [
"ts-node/register",
"test/setup.ts"
]
}

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 NodeJSBots
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

32
README.md Normal file
View file

@ -0,0 +1,32 @@
# Poll.horse
### Simple polling service for public polls
With strawpoll being somewhat very broken I decided to implement my own. Let's go!
## What is this
If you have never used strawpoll, in short this is a website to easily make small polls without a fuss.
## Contributing
The core is written in TypeScript, a typed superset to Javascript and executed with NodeJS. Pull Requests welcome.
Before cloning this repository, make sure you have [Node](https://www.nodejs.org/) installed.
Then clone this repository, open a terminal/command prompt and type `npm i` to install the required dependencies.
`ts-node` is recommended to test during development, install it with `npm i -g ts-node typescript`.
## Directory Structure
- `./dist` - The finalized and compiled files that can be used with node
- `./src` - The source files of the project
- `./test` - Files required for unit testing, aka test setup/teardown and test spec files
- `./utils` - Various utility scripts not part of the main source code
## Scripts
Execute the scripts with `npm run <script>`
- `find-todo` - Finds remaining `TODO:` in the code and warns the developer that there are still things that are unfinished
- `mocha` - Runs the unit tests in the `/test` directory
- `lint` - Runs `eslint` and checks for code styling problems
- `build` - Compile the TypeScript Source to `dist/`
- `test` - Runs `lint`, `find-todo` and `mocha` in order
- `start` - Run `test` and `build`, then try and execute the `./dist/main.js` in the `./dist` directory to test

4114
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

57
package.json Normal file
View file

@ -0,0 +1,57 @@
{
"name": "poll-horse",
"version": "0.1.0",
"description": "Make polls to vote on easily",
"main": "dist/main.js",
"types": "dist/main.d.ts",
"scripts": {
"find-todo": "node utils/todo-finder.js .",
"mocha": "mocha",
"lint": "eslint .",
"build": "rimraf ./dist && tsc",
"test": "npm run lint && npm run find-todo && npm run mocha",
"start": "npm test && npm run build && node ./dist/main.js",
"prepublish": "npm test && npm run build"
},
"repository": {
"type": "git",
"url": "git+https://Wolvan@github.com/Wolvan/poll.horse.git"
},
"keywords": [
"voting",
"polls",
"democracy"
],
"author": "Wolvan",
"license": "MIT",
"bugs": {
"url": "https://github.com/Wolvan/poll.horse/issues"
},
"files": [
"/dist"
],
"homepage": "https://github.com/Wolvan/poll.horse#readme",
"devDependencies": {
"@types/chai": "^4.2.22",
"@types/chai-as-promised": "^7.1.4",
"@types/fs-extra": "^9.0.13",
"@types/mocha": "^9.0.0",
"@types/node": "^16.11.10",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"chai": "^4.3.4",
"chai-as-promised": "^7.1.1",
"eslint": "^8.3.0",
"eslint-plugin-chai-expect": "^3.0.0",
"eslint-plugin-mocha": "^9.0.0",
"fs-extra": "^10.0.0",
"klaw": "^4.0.1",
"mocha": "^9.1.3",
"rimraf": "^3.0.2",
"ts-node": "^10.4.0",
"typescript": "^4.5.2"
},
"dependencies": {
"commander": "^8.3.0"
}
}

24
src/config-handlers.ts Normal file
View file

@ -0,0 +1,24 @@
"use strict";
import env from "./config-handlers/env";
import file from "./config-handlers/file";
import secret from "./config-handlers/secret";
const replacers = {
env,
file,
secret
};
function replaceArguments(commanderValues: { [key: string]: any }): void {
Object.keys(commanderValues).forEach(key => {
if (key.startsWith("_") || !commanderValues[key] || typeof commanderValues[key] !== "string") return;
Object.entries(replacers).forEach(([replaceKey, replacer]) => {
const value = commanderValues[key];
if (value.match(new RegExp(`^${replaceKey}:`, "i")))
commanderValues[key] = replacer(value.split(":")[1]);
});
});
}
export default replaceArguments;

View file

@ -0,0 +1,8 @@
"use strict";
function get(environmentVariable: string) : (string | null) {
const envVar = process.env[environmentVariable];
return typeof envVar === "string" ? envVar : null;
}
export default get;

View file

@ -0,0 +1,14 @@
"use strict";
import fs from "fs";
import { resolve } from "path";
function get(filename: string) : (string | null) {
try {
return fs.readFileSync(resolve(filename), "utf8").trim();
} catch (error) {
return null;
}
}
export default get;

View file

@ -0,0 +1,14 @@
"use strict";
import fs from "fs";
import { resolve } from "path";
function get(secret: string) : (string | null) {
try {
return fs.readFileSync(resolve("/run/secrets", secret), "utf8").trim();
} catch (error) {
return null;
}
}
export default get;

70
src/config-loader.ts Normal file
View file

@ -0,0 +1,70 @@
"use strict";
import { resolve } from "path";
import { homedir } from "os";
import fs from "fs-extra";
import { Command, program } from "commander";
import replaceArguments from "./config-handlers";
type CommanderOption = [flags: string, description: string, defaultValueOrHandler?: (((...args:any[]) => any) | any), defaultValue?: any];
const configCommander = new Command();
configCommander
.allowUnknownOption()
.option("-c, --config-path <path>", "Path to the configuration file to load", "../config")
.option("-h, --help", "Don't. Just don't.")
.parse(process.argv);
async function loadPackageJSONVersion(): Promise<string> {
try {
const packageJSON = await fs.readFile(resolve(__dirname, "../package.json"), "utf8");
const packageJSONObject = JSON.parse(packageJSON);
return packageJSONObject.version || "0.0.0";
} catch (error) {
console.error(error);
console.warn("Failed to load package.json version");
return "0.0.0";
}
}
async function loadConfig(options: CommanderOption[] = [], homedirConfigFilename: (string | null) = null): Promise<void> {
const config = await (async () => {
try {
const opts = configCommander.opts();
const config = await import(opts.configPath || "../config");
console.log(`Loaded config from ${opts.configPath || "../config"}`);
return config;
} catch (error) {
try {
if (!homedirConfigFilename) throw new Error("homedir config file disabled");
const config = await import(resolve(homedir(), homedirConfigFilename));
console.log(`Loaded config from ${resolve(homedir(), homedirConfigFilename)}`);
return config;
} catch (error) {
try {
const config = await import(resolve(__dirname, "config"));
console.log(`Loaded config from ${resolve(__dirname, "config")}`);
return config;
} catch (error) {
return {};
}
}
}
})();
const version = await loadPackageJSONVersion();
program
.version(version)
.option("-c, --config-path <path>", "Path to the configuration file to load", "./config");
options.forEach(([name, description, handler, defaultValue]) => program.option(name, description, handler, defaultValue));
Object.keys(program.opts()).forEach(option => {
if (config[option]) program.opts()[option] = config[option];
});
program.parse(process.argv);
replaceArguments(program.opts());
}
export default loadConfig;

13
src/main.ts Normal file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env node
"use strict";
import loadConfig from "./config-loader";
import { program } from "commander";
async function main(): Promise<void> {
await loadConfig([
], ".poll-horse-config");
const opts = program.opts();
}
main();

9
test/const.ts Normal file
View file

@ -0,0 +1,9 @@
"use strict";
import { resolve } from "path";
const TEST_DIRECTORY = resolve(__dirname, "../testing");
export {
TEST_DIRECTORY
};

4
test/dummy.spec.ts Normal file
View file

@ -0,0 +1,4 @@
/*
This spec is only there so mocha finds at least a single
spec file and doesn't throw an error on `npm install`
*/

17
test/setup.ts Normal file
View file

@ -0,0 +1,17 @@
"use strict";
import fs from "fs-extra";
import { TEST_DIRECTORY } from "./const";
console.log("Setting up Mocha Tests");
export async function mochaGlobalSetup(): Promise<void> {
console.log(`Setting up TEST_DIRECTORY '${TEST_DIRECTORY}'`);
await fs.remove(TEST_DIRECTORY);
await fs.mkdirp(TEST_DIRECTORY);
}
export async function mochaGlobalTeardown(): Promise<void> {
console.log(`Cleaning up TEST_DIRECTORY '${TEST_DIRECTORY}'`);
await fs.remove(TEST_DIRECTORY);
}

73
tsconfig.json Normal file
View file

@ -0,0 +1,73 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["es6"], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist/", /* Redirect output structure to the directory. */
"rootDir": "src/", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"resolveJsonModule": true, /* Include modules imported with '.json' extension */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"src/**/*"
]
}

46
utils/todo-finder.js Normal file
View file

@ -0,0 +1,46 @@
"use strict";
const fs = require("fs-extra");
const path = require("path");
const readline = require("readline");
const klaw = require("klaw");
const WritableStream = require("stream").Writable;
const outstream = new WritableStream();
if (!process.argv[2]) throw new Error("No path to check given");
let found = 0;
klaw(process.argv[2], {
filter: p => !path.relative(process.argv[2], p).includes("node_modules") && p !== __filename
})
.on("data", async item => {
if (item.stats.isFile()) {
if (![
".js",
".ts",
".mjs",
".cjs"
].includes(path.parse(item.path).ext.toLowerCase())) return;
const rl = readline.createInterface({
input: fs.createReadStream(item.path),
output: outstream,
terminal: false
});
let lnCnt = 0;
rl.on("line", line => {
lnCnt++;
const index = line.search(/TODO:/);
if (index !== -1) {
console.log(`${path.relative(process.argv[2], item.path)}:${lnCnt}:${index + 1}\t${line}`);
found++;
}
});
}
})
.on("end", () => {
if (found) {
console.error(`${found} TODO: have been found in the code`);
process.exit(1);
}
});