initial commit

This commit is contained in:
Evert Prants 2022-04-02 16:45:07 +03:00
commit 2ed837f60a
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
23 changed files with 18653 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
dist/
node_modules/
/*.png
/*.db
/config.toml

4
.prettierrc Normal file
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@ -0,0 +1,17 @@
--------------------------------------------------------------------------------
-- Up
--------------------------------------------------------------------------------
CREATE TABLE Placement (
ts INTEGER NOT NULL,
x INTEGER NOT NULL,
y INTEGER NOT NULL,
color INTEGER NOT NULL,
user TEXT NOT NULL
);
--------------------------------------------------------------------------------
-- Down
--------------------------------------------------------------------------------
DROP TABLE Placement;

17412
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

48
package.json Normal file
View File

@ -0,0 +1,48 @@
{
"name": "icydraw",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"connect-redis": "^6.1.3",
"express": "^4.17.3",
"express-session": "^1.17.2",
"jimp": "^0.16.1",
"passport": "^0.5.2",
"passport-icynet": "^0.0.1",
"redis": "^3.1.2",
"socket.io": "^4.4.1",
"sqlite": "^4.0.25",
"sqlite3": "^5.0.2",
"toml": "^3.0.0"
},
"devDependencies": {
"@babel/preset-env": "^7.16.11",
"@babel/preset-typescript": "^7.16.7",
"@types/connect-redis": "^0.0.18",
"@types/express-session": "^1.17.4",
"@types/passport": "^1.0.7",
"@types/sqlite3": "^3.1.8",
"@types/three": "^0.139.0",
"@types/webpack-dev-server": "^4.7.2",
"babel-loader": "^8.2.4",
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.6.0",
"nodemon": "^2.0.15",
"prettier": "^2.6.1",
"sass": "^1.49.10",
"sass-loader": "^12.6.0",
"socket.io-client": "^4.4.1",
"typescript": "^4.6.3",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
}

240
src/client/canvas.ts Normal file
View File

@ -0,0 +1,240 @@
import { convertHex } from '../common/convert';
import { clamp } from '../common/helper';
import { Placement } from '../common/types/canvas';
import { IcyNetUser } from '../server/types/user';
import { Picker } from './picker';
import { $ } from './utils/dom';
export class ViewCanvas {
public picker = new Picker();
private _user?: IcyNetUser;
private _fn?: (placement: Placement) => void;
private _canvas = $('<canvas class="canvas">') as HTMLCanvasElement;
private _ctx = this._canvas.getContext('2d');
private _wrapper = $('<div class="canvas__wrapper">');
private _container = $('<div class="canvas__container">');
private _cursor = $('<div class="canvas__cursor">');
private _size = 1000;
private _viewWidth = 0;
private _viewHeight = 0;
private _posx = 0;
private _posy = 0;
private _zoom = this._size;
private _mousex = 0;
private _mousey = 0;
private _relmousex = 0;
private _relmousey = 0;
private _cursorx = 0;
private _cursory = 0;
private _relcursorx = 0;
private _relcursory = 0;
private _dragging = false;
constructor() {}
public moveCanvas(): void {
const zoomLength = this._size / this._zoom;
// Snap the canvas coordinates to pixels, using the zoom level as the size of one pixel
const snapx = Math.floor(this._posx / zoomLength) * zoomLength;
const snapy = Math.floor(this._posy / zoomLength) * zoomLength;
this._canvas.style.top = `${snapy}px`;
this._canvas.style.left = `${snapx}px`;
this._canvas.style.transform = `scale(${zoomLength})`;
}
public center(): void {
const offsetWidth = this._viewWidth - this._size;
const offsetHeight = this._viewHeight - this._size;
this._posx = offsetWidth / 2;
this._posy = offsetHeight / 2;
this.moveCanvas();
this.moveCursor();
}
public moveCursor(): void {
// Zoom multiplier
const pixelSize = this._size / this._zoom;
// Apparent size of the canvas after scaling it
const realSize = pixelSize * this._size;
// The difference between the real canvas size and apparent size
const scale = this._size / 2 - realSize / 2;
const screenX = this._posx + scale;
const screenY = this._posy + scale;
// Position of the on-screen cursor, snapped
// Relative to top left of screen
this._cursorx =
Math.ceil(
clamp(this._viewWidth / 2, screenX, screenX + realSize) / pixelSize,
) * pixelSize;
this._cursory =
Math.ceil(
clamp(this._viewHeight / 2, screenY, screenY + realSize) / pixelSize,
) * pixelSize;
// Position of the cursor on the canvas
this._relcursorx = Math.floor((this._cursorx - screenX) / pixelSize);
this._relcursory = Math.floor((this._cursory - screenY) / pixelSize);
this._cursor.style.top = `${this._cursory - pixelSize / 2}px`;
this._cursor.style.left = `${this._cursorx - pixelSize / 2}px`;
this._cursor.style.transform = `scale(${pixelSize})`;
}
public initialize(): void {
this.picker.initialize();
this._container.append(this._canvas);
this._container.append(this._cursor);
this._wrapper.append(this._container);
this._wrapper.append(this.picker.element);
document.body.append(this._wrapper);
this._container.addEventListener('pointermove', (ev: MouseEvent) => {
const currentX = this._mousex;
const currentY = this._mousey;
this._mousex = ev.clientX;
this._mousey = ev.clientY;
const offsetX = currentX - this._mousex;
const offsetY = currentY - this._mousey;
if (this._dragging) {
this._posx -= offsetX;
this._posy -= offsetY;
}
if (this._dragging) {
this.moveCanvas();
this.moveCursor();
}
});
this._container.addEventListener('pointerdown', (ev: MouseEvent) => {
this._mousex = ev.clientX;
this._mousey = ev.clientY;
this._dragging = true;
});
this._container.addEventListener('pointerup', (ev: MouseEvent) => {
this._dragging = false;
});
this._container.addEventListener('pointerleave', (ev: MouseEvent) => {
this._dragging = false;
});
this._container.addEventListener('wheel', (ev: WheelEvent) => {
ev.preventDefault();
this._mousex = ev.clientX;
this._mousey = ev.clientY;
const delta = Math.ceil(ev.deltaY / 2) * 2;
this._zoom = clamp((this._zoom += delta), 8, this._size);
this.moveCanvas();
this.moveCursor();
});
this.picker.registerOnPlace((color) => {
if (this._fn) {
this._fn({
x: this._relcursorx,
y: this._relcursory,
c: color,
t: Date.now(),
});
}
});
this.setView();
window.addEventListener('resize', () => this.setView());
window.addEventListener('keyup', (ev: KeyboardEvent) => {
const numeral = parseInt(ev.key, 10);
if (ev.key && !Number.isNaN(numeral)) {
this.picker.pickPalette(numeral === 0 ? 9 : numeral - 1);
return;
}
if (
!['ArrowLeft', 'ArrowRight', 'ArrowDown', 'ArrowUp', ' '].includes(
ev.key,
)
) {
return;
}
const pixelSize = this._size / this._zoom;
if (ev.key === 'ArrowLeft') {
this._posx += pixelSize;
} else if (ev.key === 'ArrowRight') {
this._posx -= pixelSize;
}
if (ev.key === 'ArrowUp') {
this._posy += pixelSize;
} else if (ev.key === 'ArrowDown') {
this._posy -= pixelSize;
}
if (ev.key === ' ') {
this.picker.place();
return;
}
this.moveCanvas();
this.moveCursor();
});
}
public setView() {
this._viewWidth = document.body.clientWidth;
this._viewHeight = document.body.clientHeight;
this.center();
}
public fill(size: number, canvas: number[]) {
this._size = size;
this._canvas.width = this._size;
this._canvas.height = this._size;
const data = this._ctx!.getImageData(0, 0, this._size, this._size);
for (let row = 0; row < this._size; row++) {
for (let col = 0; col < this._size; col++) {
const index = col + row * this._size;
const pixel = canvas[index];
const { r, g, b } = convertHex(pixel);
data.data[4 * index] = r;
data.data[4 * index + 1] = g;
data.data[4 * index + 2] = b;
data.data[4 * index + 3] = 255;
}
}
this._ctx!.putImageData(data, 0, 0);
}
public setPixel(x: number, y: number, pixel: number) {
const { r, g, b } = convertHex(pixel);
this._ctx!.fillStyle = `rgb(${r},${g},${b})`;
this._ctx!.fillRect(x, y, 1, 1);
}
public registerOnPlace(fn: (placement: Placement) => void): void {
this._fn = fn;
}
public setUser(user: IcyNetUser): void {
this._user = user;
this.picker.setLoggedIn(user);
}
}

37
src/client/index.ts Normal file
View File

@ -0,0 +1,37 @@
import SocketIO from 'socket.io-client';
import { CanvasRecord, Placement } from '../common/types/canvas';
import { ViewCanvas } from './canvas';
const socket = SocketIO();
const canvas = new ViewCanvas();
canvas.initialize();
socket.on('connect', () => {
console.log('connected');
});
socket.on('me', (user) => {
console.log(user);
canvas.setUser(user);
});
socket.on('plane', (plane) => {
canvas.fill(plane.size, plane.canvas);
});
socket.on('changes', (changes: CanvasRecord[]) => {
console.log(changes);
changes
.sort((a, b) => a.ts - b.ts)
.forEach((change) => {
canvas.setPixel(change.x, change.y, change.color);
});
});
socket.on('colorack', ({ x, y, c }: Placement) => {
canvas.setPixel(x, y, c);
});
canvas.registerOnPlace((placement) => {
socket.emit('color', placement);
});

147
src/client/picker.ts Normal file
View File

@ -0,0 +1,147 @@
import { hexToString, storeHex } from '../common/convert';
import { IcyNetUser } from '../server/types/user';
import { $ } from './utils/dom';
export class Picker {
private _fn?: (color: number) => void;
private _color: number = 0x000000;
private _colorHistory: number[] = [];
private _wrapper = $('<div class="controls__wrapper">');
private _content = $('<div class="controls">');
private _colorsEl = $('<div class="controls__colors">');
private _colorHistoryEl = $('<div class="controls__colors-history">');
private _user = $('<a href="/login">');
private _colorInput = $('<input type="color">') as HTMLInputElement;
private _placebtn = $('<button class="btn btn-primary btn-place">');
private _palettebtn = $('<button class="btn btn-palette">');
private _clearbtn = $('<button class="btn btn-palette">');
get element() {
return this._wrapper;
}
public place() {
if (this._fn) {
this._storeColor(this._color);
this._fn(this._color);
}
}
public pickPalette(index: number) {
if (this._colorHistory && this._colorHistory.length) {
this._setColor(this._colorHistory[index]);
}
}
public initialize() {
this._placebtn.innerText = 'Place';
this._palettebtn.innerText = '>>';
this._clearbtn.innerText = 'Clear';
this._user.innerText = 'Log in';
this._wrapper.append(this._content);
this._content.append(this._colorsEl);
this._colorsEl.append(this._colorInput);
this._colorsEl.append(this._palettebtn);
this._colorsEl.append(this._colorHistoryEl);
this._colorsEl.append(this._clearbtn);
this._content.append(this._placebtn);
this._content.append(this._user);
this._placebtn.setAttribute('disabled', 'true');
this._placebtn.addEventListener('click', (ev) => {
ev.preventDefault();
this.place();
});
this._colorInput.addEventListener('input', (ev) => {
this._color = storeHex(this._colorInput.value);
});
this._palettebtn.addEventListener('click', () => {
this._storeColor(this._color);
});
this._clearbtn.addEventListener('click', () => {
this._colorHistory.length = 0;
this._colorHistoryEl.innerHTML = '';
this._preserveHistory();
});
this._colorHistory = this._getHistory();
if (this._colorHistory.length) {
this._setColor(this._colorHistory[0]);
this._drawColorList();
}
}
public setLoggedIn(user: IcyNetUser): void {
if (!user) {
return;
}
this._placebtn.removeAttribute('disabled');
this._user.innerText = `Logged in as ${user.username}, click here to log out`;
this._user.setAttribute('href', '/logout');
}
public registerOnPlace(fn: (color: number) => void): void {
this._fn = fn;
}
private _setColor(color: number): void {
this._color = color;
this._colorInput.value = hexToString(color);
}
private _drawColorList(): void {
this._colorHistoryEl.innerHTML = '';
this._colorHistory.map((item) => {
const str = hexToString(item);
const colEl = $(
`<div class="btn controls__color" style="background-color: ${str};">`,
);
colEl.addEventListener('click', () => {
this._colorInput.value = str;
this._color = item;
});
this._colorHistoryEl.append(colEl);
});
}
private _storeColor(color: number): void {
if (this._colorHistory.includes(color)) {
return;
}
this._colorHistory.unshift(color);
if (this._colorHistory.length > 10) {
this._colorHistory.length = 10;
}
this._drawColorList();
this._preserveHistory();
}
private _preserveHistory(): void {
if (window.localStorage) {
if (!this._colorHistory.length) {
window.localStorage.removeItem('colors');
return;
}
window.localStorage.setItem('colors', this._colorHistory.join('|'));
}
}
private _getHistory(): number[] {
if (window.localStorage) {
const list = window.localStorage.getItem('colors')?.split('|');
if (list?.length) {
return list.map((item) => Number(item));
}
}
return [];
}
}

107
src/client/scss/index.scss Normal file

File diff suppressed because one or more lines are too long

31
src/client/utils/dom.ts Normal file
View File

@ -0,0 +1,31 @@
export const $ = ($selector: string): HTMLElement => {
let element: HTMLElement | null = null;
if ($selector.includes('<')) {
const elementName = $selector.match(/^<([^\s>]*)/);
if (!elementName?.length) {
throw new Error('Could not select element');
}
element = document.createElement(elementName[1]);
const attrs = $selector.match(/([^=\s]*="[^">]*")/g);
if (attrs?.length) {
const propMap = attrs
.map((item) => item.split('='))
.reduce<Record<string, any>>(
(obj, arr) => ({ ...obj, [arr[0]]: arr[1].replace(/"/g, '').trim() }),
{},
);
if (propMap && Object.keys(propMap).length) {
Object.keys(propMap).forEach((attr) => {
element?.setAttribute(attr, propMap[attr]);
});
}
}
} else {
element = document.querySelector($selector);
}
if (element === null) {
throw new Error('Could not select element');
}
return element;
};

28
src/common/convert.ts Normal file
View File

@ -0,0 +1,28 @@
export function convertHex(hex: number): { r: number; g: number; b: number } {
return {
r: (hex >> 16) & 255,
g: (hex >> 8) & 255,
b: hex & 255,
};
}
export function hexToString(hex: number): string {
const { r, g, b } = convertHex(hex);
return `#${r.toString(16).padStart(2, '0')}${g
.toString(16)
.padStart(2, '0')}${b.toString(16).padStart(2, '0')}`;
}
export function to2D(index: number, size: number): { x: number; y: number } {
const y = index / size;
const x = index % size;
return { x, y };
}
export function to1D(x: number, y: number, size: number): number {
return y * size + x;
}
export function storeHex(hex: string): number {
return Number(hex.replace('#', '0x'));
}

3
src/common/helper.ts Normal file
View File

@ -0,0 +1,3 @@
export function clamp(x: number, min: number, max: number): number {
return Math.min(Math.max(x, min), max);
}

View File

@ -0,0 +1,14 @@
export interface CanvasRecord {
user: string;
color: number;
x: number;
y: number;
ts: number;
}
export interface Placement {
c: number;
t: number;
x: number;
y: number;
}

7
src/server/config.ts Normal file
View File

@ -0,0 +1,7 @@
import toml from 'toml';
import fs from 'fs';
import { join } from 'path';
export const config = toml.parse(
fs.readFileSync(join(__dirname, '..', '..', 'config.toml'), 'utf-8'),
);

9
src/server/express.d.ts vendored Normal file
View File

@ -0,0 +1,9 @@
import { IcyNetUser } from './types/user';
declare global {
namespace Express {
export interface Request {
user: IcyNetUser;
}
}
}

164
src/server/index.ts Normal file
View File

@ -0,0 +1,164 @@
import express, { RequestHandler } from 'express';
import session from 'express-session';
import passport from 'passport';
import * as redis from 'redis';
import * as icynetstrat from 'passport-icynet';
import connectRedis from 'connect-redis';
import http from 'http';
import { join } from 'path';
import { Server, Socket } from 'socket.io';
import { IcyNetUser } from './types/user';
import { Canvas } from './object/canvas';
import { CanvasRecord, Placement } from '../common/types/canvas';
import { config } from './config';
const RedisStore = connectRedis(session);
const redisClient = redis.createClient();
const sessionMiddleware = session({
secret: config.server.sessionSecret,
resave: false,
saveUninitialized: false,
cookie: { secure: process.env.NODE_ENV === 'production', sameSite: 'strict' },
store: new RedisStore({ client: redisClient }),
});
// todo: store less info in session
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((obj: IcyNetUser, done) => {
done(null, obj);
});
passport.use(
new icynetstrat.Strategy(
{
clientID: config.auth.clientID,
clientSecret: config.auth.clientSecret,
callbackURL: config.auth.callbackURL,
scope: [],
},
function (
accessToken: string,
refreshToken: string,
profile: any,
done: Function,
) {
console.log(profile);
process.nextTick(function () {
return done(null, profile);
});
},
),
);
const app = express();
if (process.env.NODE_ENV === 'production') {
app.enable('trust proxy');
}
const server = http.createServer(app);
const io = new Server(server);
const checkAuth: RequestHandler = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.send('not logged in :(');
};
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.get(
'/login',
passport.authenticate('icynet', { scope: [] }),
(req, res) => {},
);
app.get(
'/callback',
passport.authenticate('icynet', { failureRedirect: '/?login=false' }),
(req, res) => {
res.redirect('/?login=true');
}, // auth success
);
app.get('/logout', (req, res) => {
req.logout();
res.redirect('/');
});
app.get('/info', checkAuth, (req, res) => {
res.json(req.user);
});
app.use(express.static(join(__dirname, '..', 'public')));
///
const canvas = new Canvas(config.game.boardSize);
const connections: Socket[] = [];
const changes: CanvasRecord[] = [];
io.use((socket, next) =>
sessionMiddleware(socket.request as any, {} as any, next as any),
);
io.on('connection', (socket) => {
const session = (socket.request as any).session;
const user = session?.passport?.user as IcyNetUser;
connections.push(socket);
socket.emit(
'me',
user
? {
username: user.username,
display_name: user.display_name,
}
: null,
);
socket.emit('plane', {
size: canvas.size,
canvas: Object.values(canvas.getFullPlane()),
});
socket.on('color', ({ c, x, y, t }: Placement) => {
if (!user || c > 0xffffff || c < 0) {
return;
}
canvas.setPixelAt(c, x, y, user.username);
socket.emit('colorack', { c, x, y, t });
});
socket.on('disconnect', () => {
connections.splice(connections.indexOf(socket), 1);
});
});
canvas.registerChangeHandler((record) => {
changes.push(record);
});
setInterval(() => {
if (changes.length && connections.length) {
connections.forEach((socket) => socket.emit('changes', changes));
changes.length = 0;
}
}, 1000);
///
canvas.initialize().then(() =>
server.listen(config.server.port, 'localhost', () => {
console.log(`Listening at http://localhost:${config.server.port}/`);
}),
);

View File

@ -0,0 +1,65 @@
import { storeHex, to1D } from '../../common/convert';
import { CanvasRecord } from '../../common/types/canvas';
import { History } from './history';
import { Imager } from './imager';
export class Canvas {
private _fn?: (change: CanvasRecord) => void;
private _canvas!: Uint32Array;
private _history = new History();
private _imager = new Imager(this.size);
constructor(public size = 1000) {}
public async initialize(): Promise<void> {
this._imager.registerGetCanvas(() => this._canvas);
await this._history.initialize();
const image = await this._imager.load();
if (!image) {
this._canvas = new Uint32Array(this.size * this.size).fill(0xffffff);
return;
}
this._canvas = image;
}
public setPixelAt(
pixel: string | number,
x: number,
y: number,
user: string,
) {
if (x > this.size || y > this.size || x < 0 || y < 0) {
return;
}
const color = typeof pixel === 'string' ? storeHex(pixel) : pixel;
const index = to1D(x, y, this.size);
const record = {
user,
color,
x,
y,
ts: Date.now(),
};
this._history.insert(record);
this._canvas[index] = color;
if (this._fn) {
this._fn(record);
}
this._imager.save();
}
public getFullPlane(): Uint32Array {
return this._canvas;
}
public registerChangeHandler(handler: (change: CanvasRecord) => void) {
this._fn = handler;
}
}

View File

@ -0,0 +1,38 @@
import { join } from 'path';
import sqlite3 from 'sqlite3';
import { open, Database } from 'sqlite';
import { CanvasRecord } from '../../common/types/canvas';
export class History {
private db!: Database;
constructor(
private _store = join(__dirname, '..', '..', '..', 'canvas.db'),
) {}
async initialize(): Promise<void> {
this.db = await open({
filename: this._store,
driver: sqlite3.cached.Database,
});
await this.db.migrate();
}
async insert(record: CanvasRecord): Promise<void> {
await this.db.run(
`INSERT INTO Placement (user, x, y, ts, color) VALUES (?,?,?,?,?)`,
record.user,
record.x,
record.y,
record.ts,
record.color,
);
}
async getUserPlacements(user: string): Promise<CanvasRecord[]> {
return this.db.all<CanvasRecord[]>(
`SELECT * FROM Placement WHERE user = ?`,
user,
);
}
}

113
src/server/object/imager.ts Normal file
View File

@ -0,0 +1,113 @@
import Jimp from 'jimp';
import { to1D } from '../../common/convert';
import fs from 'fs/promises';
import { join } from 'path';
export class Imager {
private _saveTimer?: any;
private _saving = false;
private _lastSave = 0;
private _getCanvas?: () => Uint32Array;
constructor(
private _size: number,
private _store = join(__dirname, '..', '..', '..', 'canvas.png'),
private _debounce = 5000,
) {}
async toImage(array: Uint32Array): Promise<Buffer> {
return new Promise((resolve, reject) => {
new Jimp(this._size, this._size, (err, image) => {
if (err) {
return reject(err);
}
// Read data from array
for (let x = 0; x < this._size; x++) {
for (let y = 0; y < this._size; y++) {
const pixel = array[to1D(x, y, this._size)];
image.setPixelColor(pixel * 256 + 255, x, y);
}
}
image.getBuffer(Jimp.MIME_PNG, (err, buffer) => {
if (err) {
return reject(err);
}
resolve(buffer);
});
});
});
}
async fromImage(buffer: Buffer): Promise<Uint32Array> {
const image = await Jimp.read(buffer);
const uint = new Uint32Array(this._size * this._size);
for (let x = 0; x < this._size; x++) {
for (let y = 0; y < this._size; y++) {
const id = to1D(x, y, this._size);
uint[id] = (image.getPixelColor(x, y) - 255) / 256;
}
}
return uint;
}
save(force = false): void {
if (!this._getCanvas) {
return;
}
clearTimeout(this._saveTimer);
if (this._saving) {
this._saveTimer = setTimeout(() => this.save(force), 1000);
return;
}
const saveFn = async () => {
this._saving = true;
console.log('Saving canvas to disk');
const start = Date.now();
const array = this._getCanvas!();
const save = await this.toImage(array);
await fs.writeFile(this._store, save);
const end = (Date.now() - start) / 1000;
console.log(`saved in ${end}s`);
this._saving = false;
this._lastSave = Date.now();
};
if (force || this._lastSave < Date.now() - this._debounce * 2) {
saveFn().catch((e) => console.error(e));
return;
}
this._saveTimer = setTimeout(
() => saveFn().catch((e) => console.error(e)),
this._debounce,
);
}
async load(): Promise<Uint32Array | null> {
try {
await fs.stat(this._store);
console.log('loading canvas from disk');
const start = Date.now();
const loadFile = await fs.readFile(this._store);
const imgData = await this.fromImage(loadFile);
const end = (Date.now() - start) / 1000;
console.log(`loaded in ${end}s`);
return imgData;
} catch (e) {
return null;
}
}
public registerGetCanvas(fn: () => Uint32Array) {
this._getCanvas = fn;
}
}

24
src/server/passport-icynet.d.ts vendored Normal file
View File

@ -0,0 +1,24 @@
declare module 'passport-icynet' {
declare class Strategy {
name?: string | undefined;
authenticate(
this: StrategyCreated<this>,
req: express.Request,
options?: any,
): any;
constructor(
options: {
clientID: string;
clientSecret: string;
callbackURL: string;
scope?: string[];
},
callback: (
accessToken: string,
refreshToken: string,
profile: any,
done: Function,
) => void,
);
}
}

7
src/server/types/user.ts Normal file
View File

@ -0,0 +1,7 @@
export interface IcyNetUser {
id: number;
uuid: string;
username: string;
display_name: string;
accessToken: string;
}

99
tsconfig.json Normal file
View File

@ -0,0 +1,99 @@
{
"include": [
"src/server/**/*.ts"
],
"exclude": [
"src/client/**/*.ts"
],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

34
webpack.config.js Normal file
View File

@ -0,0 +1,34 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: ['./src/client/index.ts', './src/client/scss/index.scss'],
module: {
rules: [
{
test: /\.(ts|js)?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-typescript'],
},
},
},
{
test: /\.(css|scss)/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [new HtmlWebpackPlugin(), new MiniCssExtractPlugin()],
output: {
path: path.resolve(__dirname, 'dist', 'public'),
filename: 'bundle.js',
},
devtool: 'source-map'
};