repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/App.tsx
import { Helmet } from "react-helmet"; import { MainPageComponent } from "./components/mainPage/mainPage.component"; import React from "react"; const App: React.FC = () => { return ( <div className="App"> <Helmet> <title>{"Valheim Management Dashboard"}</title> </Helmet> <MainPageComponent /> </div> ); }; export default App;
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/shared/errorHandler.tsx
<gh_stars>0 export const onError = (err: Error): void => { console.error("failed to load data"); console.error(err); };
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/mainPage.ui.tsx
import { Fragment, FunctionComponent } from "react"; // import styled from "styled-components"; import { ServerStatusDto } from "./serverStatus.dto"; import { Button, Grid, makeStyles, Typography } from "@material-ui/core"; import { ServerStatusUi } from "./serverStatus.ui"; type Props = { serverStatus: ServerStatusDto; onServerStatusUpdateClicked: () => unknown; onHostStartClicked: () => unknown; onHostStopClicked: () => unknown; serverIp: string; serverPassword: string; }; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, maxWidth: "sm", padding: theme.spacing(9), }, grid: { justify: "center", alignItems: "center", paddingBottom: theme.spacing(5), }, controlGridItem: { justify: "center", alignItems: "center", }, })); export const MainPageUi: FunctionComponent<Props> = (props) => { const classes = useStyles(); return ( <Fragment> <div className={classes.root}> <Grid className={classes.grid} container spacing={3}> <Grid item> <Button variant="contained" onClick={props.onServerStatusUpdateClicked}> refresh </Button> </Grid> <Grid item> <Button variant="contained" color="primary" onClick={props.onHostStartClicked}> start </Button> </Grid> <Grid item> <Button variant="contained" color="secondary" onClick={props.onHostStopClicked}> stop </Button> </Grid> </Grid> <Grid className={classes.grid} container spacing={3}> <div> <Typography>{`server IP: ${props.serverIp}`}</Typography> <Typography>{`server password: ${props.serverPassword}`}</Typography> </div> </Grid> <Grid className={classes.grid} container spacing={3}> <ServerStatusUi serverStatus={props.serverStatus} /> </Grid> </div> </Fragment> ); };
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/serverStatus.service.ts
import { ServerStatusDto } from "./serverStatus.dto"; import { Config } from "../../shared/config"; import axios from "axios"; import { validate } from "class-validator"; import { plainToClassFromExist } from "class-transformer"; import { get } from "lodash"; export class ServerStatusService { private serverStatusDto = new ServerStatusDto(); getStatus(): ServerStatusDto { return this.serverStatusDto; } async syncStatus(): Promise<void> { console.log("refresh status"); await this.syncHostStatus().catch((err) => { console.error("failed to sync host status: ", err); this.serverStatusDto.host = new ServerStatusDto().host; }); await this.syncGameServerStatus().catch((err) => { console.error("failed to sync server status: ", err); this.serverStatusDto.server = new ServerStatusDto().server; }); this.serverStatusDto.syncTimestamp = new Date(); } private async syncGameServerStatus(): Promise<void> { const statusCheckUrl = Config.STATUS_CHECK_URL; const res = await axios.get(statusCheckUrl, { timeout: 10000 }); const dto = plainToClassFromExist(this.serverStatusDto, { server: get(res.data, "server"), }); await validate(dto); this.serverStatusDto = dto; } private async syncHostStatus(): Promise<void> { const statusCheckUrl = Config.EC2_STATUS_URL; const res = await axios.get(statusCheckUrl, { timeout: 10000 }); const dto = plainToClassFromExist(this.serverStatusDto, { host: res.data, }); await validate(dto); this.serverStatusDto = dto; } async startHost(): Promise<void> { const url = Config.EC2_START_URL; const { data } = await axios.get(url, { timeout: 10000 }); console.log(data); } async stopHost(): Promise<void> { const url = Config.EC2_STOP_URL; const { data } = await axios.get(url, { timeout: 10000 }); console.log(data); } } export const serverStatusService = new ServerStatusService();
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/infoCard.ui.tsx
import { FunctionComponent } from "react"; import { Card, CardContent, CardProps, makeStyles, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ card: { padding: theme.spacing(1), height: 220, width: 220, }, })); type Props = CardProps & { title: string; content: string; }; export const InfoCard: FunctionComponent<Props> = (props) => { const classes = useStyles(); return ( <Card className={classes.card}> <CardContent> <Typography variant="h5" component="p" gutterBottom> {props.title} </Typography> <Typography variant="h6" component="p"> {props.content} </Typography> </CardContent> </Card> ); };
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/serverStatus.dto.ts
<filename>packages/ui/src/components/mainPage/serverStatus.dto.ts import { IsInt } from "class-validator"; export class ServerStatusDto { host?: Host; server?: Server; serverUp?: boolean; syncTimestamp?: Date; } class Host { status = "N/A"; } class Server { name = ""; version = ""; @IsInt() players = NaN; @IsInt() max_players = NaN; map = ""; }
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/components/mainPage/mainPage.component.tsx
import { MainPageUi } from "./mainPage.ui"; import { FunctionComponent, useEffect, useState } from "react"; import { serverStatusService } from "./serverStatus.service"; import { Config } from "../../shared/config"; import { cloneDeep } from "lodash"; import { onError } from "../../shared/errorHandler"; export const MainPageComponent: FunctionComponent = () => { const [serverStatus, setServerStatus] = useState(serverStatusService.getStatus()); const { GAME_SERVER_CONNECTION, GAME_SERVER_PASSWORD } = Config; useEffect(() => { console.log("loading data"); handleUpdateServerStatus().catch(onError); }, []); const handleUpdateServerStatus = async () => { await serverStatusService.syncStatus(); console.log("update UI"); setServerStatus(cloneDeep(serverStatusService.getStatus())); // todo: make it immutable in a proper way }; const handleStartHost = async () => { console.log("start host"); await serverStatusService.startHost(); await handleUpdateServerStatus().catch(onError); }; const handleStopHost = async () => { console.log("stop host"); await serverStatusService.stopHost(); await handleUpdateServerStatus().catch(onError); }; return ( <MainPageUi serverStatus={serverStatus} onServerStatusUpdateClicked={handleUpdateServerStatus} onHostStartClicked={handleStartHost} onHostStopClicked={handleStopHost} serverIp={GAME_SERVER_CONNECTION} serverPassword={<PASSWORD>} /> ); };
Jarvie8176/valheim-ec2-dashboard
packages/ui/src/shared/config/index.ts
<filename>packages/ui/src/shared/config/index.ts import { decodeDto } from "@ansik/sdk/lib/utils"; import { string } from "io-ts"; export const Config = { EC2_START_URL: decodeDto(string, process.env.REACT_APP_EC2_START_URL), EC2_STOP_URL: decodeDto(string, process.env.REACT_APP_EC2_STOP_URL), EC2_STATUS_URL: decodeDto(string, process.env.REACT_APP_EC2_STATUS_URL), STATUS_CHECK_URL: decodeDto(string, process.env.REACT_APP_STATUS_CHECK_URL), API_AUTH_TOKEN: decodeDto(string, process.env.REACT_APP_API_AUTH_TOKEN), GAME_SERVER_CONNECTION: decodeDto(string, process.env.REACT_APP_SERVER_CONNECTION), GAME_SERVER_PASSWORD: decodeDto(string, process.env.REACT_APP_SERVER_PASSWORD), };
ibrahimusluu/network-operators
network-operator-dialog/network-operator-dialog.component.ts
import { Component, OnInit, Inject } from "@angular/core"; import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog"; import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core'; import { MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter'; import * as moment from 'moment'; export const MY_FORMATS = { parse: { dateInput: 'DD.MM.YYYY', }, display: { dateInput: 'DD.MM.YYYY', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'DD', monthYearA11yLabel: 'MMM YYYY', }, }; @Component({ selector: 'app-network-operator-dialog', templateUrl: './network-operator-dialog.component.html', styleUrls: ['./network-operator-dialog.component.css'], providers: [ // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your // application's root module. We provide it at the component level here, due to limitations of // our example generation script. { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS] }, { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }, { provide: MAT_DATE_LOCALE, useValue: 'de_DE' }, ] }) export class NetworkOperatorDialogComponent implements OnInit { files: File[] = []; constructor(public dialogRef: MatDialogRef<NetworkOperatorDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { } save() { const tmp = this.data.copy; let success = true; let addFiles = false; this.data.editFields.forEach(function (item) { if (item.hasOwnProperty('required')) { if (!tmp[item.index] && item.required) { success = false; } } if (item.hasOwnProperty('inputType')) { if (item.inputType === 'dropbox') { addFiles = true; } } }); // @ts-ignore if (addFiles === true) { this.data.copy.icon = this.files; } if (success === true) { this.dialogRef.close(this.data.copy); } } saveTariff() { let tmp = this.data.copy; let success = true; // let addFiles = false; this.data.editFields.forEach(function (item) { if (item.hasOwnProperty('required')) { if (!tmp[item.index] && item.required) { success = false; } } if (item.hasOwnProperty('inputType')) { if (item.inputType === 'dropbox') { // addFiles = true; } } }); this.data.copy.all = 1; // @ts-ignore // if (addFiles === true) { // this.data.copy.icon = this.files; // } if (success === true) { this.dialogRef.close(this.data.copy); } } saveContract() { let tmp = this.data.copy; let success = true; this.data.editFields.forEach(function (item) { if (item.hasOwnProperty('required')) { if (!tmp[item.index] && item.required) { success = false; } } if (item.hasOwnProperty('inputType')) { if (item.inputType === 'dropbox') { // addFiles = true; } } }); this.data.copy.all = 2; // @ts-ignore // if (addFiles === true) { // this.data.copy.icon = this.files; // } if (success === true) { this.dialogRef.close(this.data.copy); } } /** * copies input start date in end date Input */ fillEndDate() { this.data.copy.bhour_to_date = this.data.copy.bhour_from_date; } onSelect(event) { this.files.push(...event.addedFiles); } onRemove(event) { this.files.splice(this.files.indexOf(event), 1); } selectDuration(minutes) { let end; if (moment.isMoment(this.data.copy.bhour_to_date)) { end = moment(moment(this.data.copy.bhour_to_date).format('YYYY-MM-DD') + ' ' + this.data.copy.endTime); } else { end = moment(this.data.copy.bhour_to_date + ' ' + this.data.copy.endTime); } const start = end.subtract(minutes, 'minutes'); this.data.copy.bhour_from_date = start.format('YYYY-MM-DD'); this.data.copy.startTime = start.format('HH:mm'); } ngOnInit() { console.log("data: ", this.data); // this.onNoClick(); } }
ibrahimusluu/network-operators
network-operator.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; @Injectable({ providedIn: 'root' }) export class NetworkOperatorService { constructor(private http: HttpClient) { } /** * gibt ein JSON Objekt mit allen Netzbetreibern zurück / returns a JSON object with all network operators * (id,name) * @returns{any} */ // not used getNetworkOperator(): any { return this.http.get('/apiV2/netzbetreiber'); } // get all Network Operators getNetworkOperators(data: any): any { return this.http.get('/apiV2/netzbetreiber/getAll', data); } getNetworkOperatorNames(data: any): any { return this.http.get('/apiV2/netzbetreiber/getAllNames', data); } // Contracts getNetworkOperatorContracts(data: any): any { return this.http.post('/apiV2/netzbetreiberr/getAllContracts', data); } addNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/createNetworkOperator', data); } editNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/updateNetworkOperator', data); } deleteNetworkOperator(id: string): any { return this.http.get('/apiV2/netzbetreiber/deleteNetworkOperator/' + id); } activateNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/activate', data); } inActivateNetworkOperator(data: any): any { return this.http.post('/apiV2/netzbetreiber/deactivate', data); } getNetworkOperatorStores(data: any): any { return this.http.get('/apiV2/netzbetreiberr/getAllStores', data); } }
ibrahimusluu/network-operators
network-operator/network-operator.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { MatPaginator } from '@angular/material/paginator'; import { MatSnackBar } from '@angular/material/snack-bar'; import { MatTableDataSource } from '@angular/material/table'; import { NetworkOperatorService } from '../services/network-operator.service'; import { NetworkOperatorDialogComponent } from '../network-operator-dialog/network-operator-dialog.component'; @Component({ selector: 'app-network-operator', templateUrl: './network-operator.component.html', styleUrls: ['./network-operator.component.css'] }) export class NetworkOperatorComponent implements OnInit { contentLoading = true; admin: string; // Determine which columns should be visible in the table // 'abgeschlossen', 'del' displayedColumns: string[] = ['edit', 'name', 'vvl', 'contract', 'existingTariff', 'tariff', 'activate']; dataSource = new MatTableDataSource(); @ViewChild(MatPaginator, { static: true }) set matPaginator(paginator: MatPaginator) { this.dataSource.paginator = paginator; } public inputValue: string; constructor(private _networkOperatorService: NetworkOperatorService, private dialog: MatDialog, private snackBar: MatSnackBar ) { } ngOnInit() { this.getAll(); this.admin = localStorage.getItem('user'); this.admin = JSON.parse(this.admin).admin; } getAll() { this._networkOperatorService.getNetworkOperators({}).subscribe(data => { if (data['status'] === 'success') { this.dataSource.data = data['data']; } this.contentLoading = false; }); } showEditDialogAsAdd() { const editFields = [ { inputLabel: 'Name', inputType: 'text', index: 'netz_name', required: true } ]; const copy = { 'netz_name': '' }; const dialogRef = this.dialog.open(NetworkOperatorDialogComponent, { data: { title: 'Neuer Netzbetreiber', copy, editFields } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.confirmAdd(result); } }); } confirmAdd(networkOperator) { const changeEntry = { 'netz_name': networkOperator.netz_name }; this._networkOperatorService.addNetworkOperator(changeEntry).subscribe(result => { if (result['status'] === 'success') { this.openSnackBar('Netzbetreiber erfolgreich hinzugefügt', ''); this.getAll(); } }); } showEditDialog(networkOperator) { console.log("networkOperator:(showEditDialog start here) ", networkOperator); const editFields = [ { inputLabel: 'Name', inputType: 'text', index: 'netz_name' }, { inputLabel: 'Vertragsdauer', inputType: 'text', index: 'netz_vertragsdauer' }, { inputLabel: 'VVL-berechtigt', inputType: 'text', index: 'netz_vvl' }, { inputLabel: 'Kürzel', inputType: 'text', index: 'netz_kurz' }, { inputLabel: 'VO Nummer', inputType: 'text', index: 'netz_vo' }, { inputLabel: 'Notiz', inputType: 'textarea', index: 'netz_bemerkung' }, { inputLabel: 'Keine Marge für Mitarbeiter berechnen', inputType: 'checkbox', index: 'netz_nomitmarge' } ]; const copy = JSON.parse(JSON.stringify(networkOperator)); console.log("copy: ", copy); const dialogRef = this.dialog.open(NetworkOperatorDialogComponent, { data: { title: 'Netzbetreiber bearbeiten', copy, editFields } }); dialogRef.afterClosed().subscribe(result => { console.log("result: ", result); if (result) { this.confirmEdit(result); } }); } confirmEdit(networkOperator) { console.log("networkOperator:(confirmEdit start here) ", networkOperator); const changeEntry = { 'netz_name': networkOperator.netz_name, 'netz_vertragsdauer': networkOperator.netz_vertragsdauer, 'netz_vvl': networkOperator.netz_vvl, 'netz_kurz': networkOperator.netz_kurz, 'netz_vo': networkOperator.netz_vo, 'netz_bemerkung': networkOperator.netz_bemerkung, 'netz_nomitmarge': networkOperator.netz_nomitmarge, 'all': networkOperator.all, 'id': networkOperator.netz_id }; console.log("changeEntry: ", changeEntry); this._networkOperatorService.editNetworkOperator(changeEntry).subscribe(result => { console.log("we are here!"); console.log("confirmEdit result: ", result); if (result['status'] === 'success') { this.openSnackBar('Netzbetreiber erfolgreich geändert', ''); this.getAll(); } }); } // zeigt kleines info Fenster unten an / shows little info window below openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 5000 }); } clickButton(data) { const changeEntry = { 'id': data.netz_id }; // if it is 1 we will deactivate, if it is 0 we will activate if (data.active == 0) { this._networkOperatorService.activateNetworkOperator(changeEntry).subscribe(result => { if (result['status'] === 'success') { this.openSnackBar(data.netz_name + ' activated', ''); } }); } else { this._networkOperatorService.inActivateNetworkOperator(changeEntry).subscribe(result => { if (result['status'] === 'success') { this.openSnackBar(data.netz_name + ' deactivated', ''); } }); } } }
1-EXON/star-battle
app/src/models/users.ts
<reponame>1-EXON/star-battle import User from '../data/User' export let user1: User = new User('', 0, 0) export let user2: User = new User('', 0, 0)
1-EXON/star-battle
app/src/data/User.ts
<reponame>1-EXON/star-battle<gh_stars>1-10 export default class User { name: string stars: number followers: number constructor(name: string, stars: number, followers: number) { this.name = name this.stars = stars this.followers = followers } public Reset(name: string, stars: number, followers: number) { this.name = name this.stars = stars this.followers = followers } }
1-EXON/star-battle
app/src/components/UserContent.tsx
import React, { Component } from 'react' class UserContent extends Component { public render() { return ( <div className="users"> <table> <thead> <tr> <th id="user1"></th> <th id="user2"></th> </tr> </thead> <tbody> <th> <td>star<p id="star1"></p></td><br/> <td>followers<p id="followers1"></p></td><br/> {/* <td>commits<p id="commits1"></p></td><br/> */} </th> <th> <td>star<p id="star2"></p></td><br/> <td>followers<p id="followers2"></p></td><br/> {/* <td>commits<p id="commits2"></p></td><br/> */} </th> </tbody> </table> </div> ) } } export default UserContent
1-EXON/star-battle
app/src/components/Main.tsx
import React, { Component } from 'react' import { getStar as getUserStar } from '../data/GetStar' import { getFollowers as getUserFollowers } from '../data/GetFollowers' import { user1, user2 } from '../models/users' import UserContent from './UserContent' const Selector = (param: string) => { return document.querySelector(param) } class UserInput extends Component { public state = { first: '', second: '' } public handleSubmit(e: React.FormEvent<HTMLFormElement>) { e.preventDefault() } public handleChangeFirst(e: React.ChangeEvent<HTMLInputElement>) { this.setState({ first: e.target.value }) } public handleChangeSecond(e: React.ChangeEvent<HTMLInputElement>) { this.setState({ second: e.target.value }) } public async search() { user1.Reset(this.state.first, await getUserStar(this.state.first), await getUserFollowers(this.state.first)) user2.Reset(this.state.second, await getUserStar(this.state.second), await getUserFollowers(this.state.second)) Selector('#user1')!.innerHTML = user1.name Selector('#user2')!.innerHTML = user2.name Selector('#star1')!.innerHTML = user1.stars?.toString() Selector('#star2')!.innerHTML = user2.stars?.toString() Selector('#followers1')!.innerHTML = user1.followers?.toString() Selector('#followers2')!.innerHTML = user2.followers?.toString() } public render() { return ( <div className="search"> <form onSubmit={this.handleSubmit.bind(this)}> <input placeholder="Github Id" onChange={this.handleChangeFirst.bind(this)}></input> <input placeholder="Github Id" onChange={this.handleChangeSecond.bind(this)}></input> <button onClick={this.search.bind(this)}>검색</button> </form> <br/> <UserContent /> </div> ) } } export default UserInput
1-EXON/star-battle
app/src/App.tsx
import React from 'react' import './css/App.css' import Main from './components/Main' function App() { return ( <div className="App"> <header className="App-header"> <div className="head"> <h1>Github Star Battle</h1> <p>깃허브 스타 대결 사이트!</p> </div> <Main /> </header> </div> ) } export default App
1-EXON/star-battle
app/src/data/GetStar.ts
<gh_stars>1-10 export async function getStar(name: string) { const repos = await fetch(`https://api.github.com/users/${name}/repos`).then(resp => resp.json()) return repos.reduce((acc: any, cur: { stargazers_count: any }) => acc += cur.stargazers_count, 0) }
ickeep/think-mail
src/think-mail.ts
<gh_stars>0 // @ts-ignore import { think, Context } from 'thinkjs' export interface IConf { apiUser: string, apiKey: string, from: string, captchaTemplate?: string, logDb?: string, logTable?: string, } export interface ISendTemplateOpt { to: string[], sub: { '%action%': string[], '%code%': Array<string | number>, '%minute%': Array<string | number> } } export default class extends think.Service { conf: { [key: string]: any } constructor(conf = {}) { super() const dfOpts = { apiUser: '', apiKey: '', from: '', captchaTemplate: 'captcha', logDb: 'log', logTable: 'mail', } const dfConf = think.config('mail') this.conf = Object.assign(dfOpts, dfConf, conf) } async send(sendOpts: any, apiUrl: string, ctx: Context) { const url = apiUrl || 'http://api.sendcloud.net/apiv2/mail/send' const opts = Object.assign(this.conf, sendOpts) const postConf: any = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } const sendData = await think.httpPost(url, opts, postConf) const { code, msg, status, data } = sendData if (code === 0 && data.statusCode !== 200) { sendData.code = data.statusCode // http 请求成功 sendCloud 返回错误 sendData.msg = data.message think.logger.error(sendData.msg) } const { logTable, logDb, to, xsmtpapi, apiKey, ...args } = opts if (logTable && logDb) { think.model(logTable, logDb).add({ mail: to || xsmtpapi, opt: JSON.stringify(args), result: JSON.stringify({ code, msg, status, data }), time: Math.floor(new Date().getTime() / 1000), ip: ctx.ip }) } return sendData } sendTemplate(name: string, sendOpt: ISendTemplateOpt, ctx: Context) { const opts = Object.assign(this.conf, { templateInvokeName: name, xsmtpapi: JSON.stringify(sendOpt) }) return this.send(opts, 'http://api.sendcloud.net/apiv2/mail/sendtemplate', ctx) } sendCaptcha(mail: string, action: string, code: string | number, minute: any, ctx: Context) { const actionNameMap = { login: '登录', join: '注册', bind: '绑定', reset: '重置' } const actionName = actionNameMap[action] || '' const sendOpt = { to: [mail], sub: { '%action%': [actionName], '%code%': [code], '%minute%': [minute] } } return this.sendTemplate(this.conf.captchaTemplate, sendOpt, ctx) } }
andrefillypesilva/clever-weather
src/app/models/interfaces/weather-forecast.interface.ts
<reponame>andrefillypesilva/clever-weather<gh_stars>0 // Interfaces import { ConsolidatedWeather } from "./consolidated-weather.interface"; import { WeatherParent } from "./weather-parent.interface"; import { WeatherSource } from "./weather-source.interface"; export interface WeatherForecast { consolidated_weather: ConsolidatedWeather[], time: string, sun_rise: string, sun_set: string, timezone_name: string, parent: WeatherParent, sources: WeatherSource[], title: string, location_type: string, woeid: number, latt_long: string, timezone: string }
andrefillypesilva/clever-weather
src/app/shared/components/weather-box/weather-box.component.ts
<reponame>andrefillypesilva/clever-weather import { Component, Input, OnInit } from '@angular/core'; // Interfaces import { ConsolidatedWeather } from 'src/app/models/interfaces/consolidated-weather.interface'; @Component({ selector: 'app-weather-box', templateUrl: './weather-box.component.html', styleUrls: ['./weather-box.component.scss'] }) export class WeatherBoxComponent implements OnInit { @Input() public consolidatedWeather: ConsolidatedWeather[]; constructor() { } ngOnInit(): void { } }
andrefillypesilva/clever-weather
src/app/models/enums/local-storage.config.enum.ts
export enum LOCALSTORAGECONFIG { FIRST_ACCESS = 'FE__first' }
andrefillypesilva/clever-weather
src/app/models/interfaces/weather-source.interface.ts
export interface WeatherSource { title: string; slug: string; url: string; crawl_rate: number; }
andrefillypesilva/clever-weather
src/app/shared/services/local-storage.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LocalStorageService { constructor() { } public setItem(key: string, value: any): boolean { try { localStorage.setItem(key, JSON.stringify(value)); return true; } catch { return false; } } public getItem(key: string): any { try { return JSON.parse(localStorage.getItem(key)); } catch { return null; } } public clearLocalStorage(): void { localStorage.clear(); } }
andrefillypesilva/clever-weather
src/app/shared/shared.module.ts
<filename>src/app/shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; // Components import { WeatherBoxComponent } from './components/weather-box/weather-box.component'; import { WeatherCardComponent } from './components/weather-card/weather-card.component'; import { OnboardingCardComponent } from './components/onboarding-card/onboarding-card.component'; @NgModule({ declarations: [ WeatherBoxComponent, WeatherCardComponent, OnboardingCardComponent ], imports: [ CommonModule, HttpClientModule ], exports: [ WeatherBoxComponent, OnboardingCardComponent ] }) export class SharedModule { }
andrefillypesilva/clever-weather
src/app/models/interfaces/consolidated-weather.interface.ts
export interface ConsolidatedWeather { id: number; weather_state_name: string; weather_state_abbr: string; wind_direction_compass: string; created: string; applicable_date: string; min_temp: number; max_temp: number; the_temp: number; wind_speed: number; wind_direction: number; air_pressure: number; humidity: number; visibility: number; predictability: number; }
andrefillypesilva/clever-weather
src/app/shared/interceptors/request.interceptor.ts
<filename>src/app/shared/interceptors/request.interceptor.ts<gh_stars>0 import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders, } from '@angular/common/http'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; @Injectable() export class RequestInterceptor implements HttpInterceptor { constructor() {} intercept( req: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { let headers = new HttpHeaders() .set('Content-Type', environment.contentType) .set('Access-Control-Allow-Origin', '*') .set('Access-Control-Allow-Methods', 'GET,POST,PATCH,DELETE,PUT,OPTIONS') .set('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, content-type') .set("X-Requested-With", "XMLHttpRequest"); const request = req.clone({ headers }); return next.handle(request); } }
andrefillypesilva/clever-weather
src/app/core/home/home.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { Router } from '@angular/router'; // Interfaces import { Place } from 'src/app/models/interfaces/place.interface'; import { ConsolidatedWeather } from 'src/app/models/interfaces/consolidated-weather.interface'; // Services import { WeatherService } from 'src/app/shared/services/weather.service'; import { LocalStorageService } from 'src/app/shared/services/local-storage.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { public place: string; public consolidatedWeather$: Observable<ConsolidatedWeather[]>; public formGroup: FormGroup; constructor( private readonly weatherService: WeatherService, private readonly fb: FormBuilder, private readonly localStorageService: LocalStorageService, private readonly router: Router ) { this.formGroup = this.fb.group({ query: [null] }); } ngOnInit(): void { navigator.geolocation.getCurrentPosition(position => { let lat = position.coords.latitude; let long = position.coords.longitude; this.weatherService.getPlace(lat, long).subscribe((data: Place[]) => { this.place = `${data[0].title} <span>(based on your geolocation)</span>`; this.consolidatedWeather$ = this.weatherService.getWeather(data[0].woeid); }); }, () => { this.forceGeolocationAccess(); }); } search(): void { this.weatherService.getPlaceByName(this.formGroup.get('query').value).subscribe((data: Place[]) => { this.place = `${data[0].title} <span>(based on the search you have done)</span>`; this.consolidatedWeather$ = this.weatherService.getWeather(data[0].woeid); }); } private forceGeolocationAccess(): void { alert('To use this app, you need to allow geolocation.'); this.localStorageService.clearLocalStorage(); this.router.navigate(['/']); } }
andrefillypesilva/clever-weather
src/app/shared/services/local-storage.service.spec.ts
<reponame>andrefillypesilva/clever-weather<filename>src/app/shared/services/local-storage.service.spec.ts import { TestBed } from '@angular/core/testing'; // Enums import { LOCALSTORAGECONFIG } from 'src/app/models/enums/local-storage.config.enum'; // Services import { LocalStorageService } from './local-storage.service'; describe('LocalStorageService', () => { let service: LocalStorageService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(LocalStorageService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should to set an item into local-storage', () => { const before = service.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS); const response = service.setItem(LOCALSTORAGECONFIG.FIRST_ACCESS, false); expect(response).toBe(true); expect(before).not.toBe(service.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS)); }); it('should to return [null] for a non-existing item', () => { service.clearLocalStorage(); expect(service.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS)).toBeNull(); }); });
andrefillypesilva/clever-weather
src/app/shared/services/weather.service.ts
<reponame>andrefillypesilva/clever-weather<filename>src/app/shared/services/weather.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { pluck } from 'rxjs/operators'; // Interfaces import { Place } from 'src/app/models/interfaces/place.interface'; import { ConsolidatedWeather } from 'src/app/models/interfaces/consolidated-weather.interface'; @Injectable({ providedIn: 'root', }) export class WeatherService { constructor( private readonly http: HttpClient ) {} public getPlace(lat: number, long: number): Observable<Place[]> { return this.http.get<Place[]>(`/api/location/search/?lattlong=${lat},${long}`); } public getPlaceByName(title: string): Observable<Place[]> { return this.http.get<Place[]>(`/api/location/search/?query=${title}`); } public getWeather(woeid: number): Observable<ConsolidatedWeather[]> { return this.http.get<ConsolidatedWeather[]>(`/api/location/${woeid}/`) .pipe( pluck('consolidated_weather') ); } }
andrefillypesilva/clever-weather
src/app/models/enums/weather-card-type.enum.ts
<filename>src/app/models/enums/weather-card-type.enum.ts export enum WEATHERCARDTYPE { MAIN = 'main__card', SUPPORT = 'support__card' }
andrefillypesilva/clever-weather
src/app/core/core.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; // Routing import { CoreRoutingModule } from './core-routing.module'; // Modules import { SharedModule } from '../shared/shared.module'; // Components import { HomeComponent } from './home/home.component'; import { OnboardingComponent } from './onboarding/onboarding.component'; @NgModule({ declarations: [HomeComponent, OnboardingComponent], imports: [ CommonModule, CoreRoutingModule, FormsModule, ReactiveFormsModule, SharedModule ] }) export class CoreModule { }
andrefillypesilva/clever-weather
src/app/core/onboarding/onboarding.component.spec.ts
import { HttpClientModule } from '@angular/common/http'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; // Components import { OnboardingCardComponent } from 'src/app/shared/components/onboarding-card/onboarding-card.component'; import { OnboardingComponent } from './onboarding.component'; // Services import { LocalStorageService } from 'src/app/shared/services/local-storage.service'; // Enums import { LOCALSTORAGECONFIG } from 'src/app/models/enums/local-storage.config.enum'; describe('OnboardingComponent', () => { let onboarding: OnboardingComponent; let fixture: ComponentFixture<OnboardingComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ HttpClientModule, RouterTestingModule ], declarations: [ OnboardingComponent, OnboardingCardComponent ], providers: [ LocalStorageService ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OnboardingComponent); onboarding = fixture.componentInstance; fixture.detectChanges(); onboarding.testingAskForGeolocationAccess(); }); it('should create', () => { expect(onboarding).toBeTruthy(); }); it('should increment [step] value', () => { const stepInitial = onboarding.step; onboarding.next(); expect(onboarding.step).toBeGreaterThan(stepInitial); }); it('should to set first-access into local storage', () => { const firstAccess = localStorage.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS); onboarding.testingSetLocalStorageFinished(); expect(JSON.parse(localStorage.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS))).toBe(true); expect(localStorage.getItem(LOCALSTORAGECONFIG.FIRST_ACCESS)).not.toBe(firstAccess); }); it('should render [Perfect Weather Explorer] in the first card of onboarding', () => { const compiled = fixture.nativeElement; const text = compiled.querySelector('.secondary-heading'); expect(text.textContent).toContain('Perfect Weather Explorer'); }); });
andrefillypesilva/clever-weather
src/app/shared/services/weather.service.spec.ts
<filename>src/app/shared/services/weather.service.spec.ts import { HttpClientModule } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController, } from '@angular/common/http/testing'; import { getTestBed, TestBed } from '@angular/core/testing'; // Test Mocks import { MOCK__PLACES } from 'src/app/test-mocks/mock-places.mock'; import { MOCK__CONSOLIDATED_WEATHER } from 'src/app/test-mocks/mock-consolidated-weather.mock'; // Services import { WeatherService } from './weather.service'; describe('WeatherService', () => { let service: WeatherService; let injector: TestBed; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientModule, HttpClientTestingModule], providers: [WeatherService], }); injector = getTestBed(); service = injector.inject(WeatherService); httpMock = injector.inject(HttpTestingController); }); afterEach(() => { httpMock.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return an object of [Place] with Lisbon data', () => { service.getPlaceByName('lisbon').subscribe((places) => { expect(places.length).toBe(1); expect(places[0].woeid).toBe(742676); // Code for Lisbon city expect(MOCK__PLACES).toBe(places); }); const req = httpMock.expectOne('/api/location/search/?query=lisbon'); req.flush(MOCK__PLACES); }); it('should return an object of [ConsolidatedWeather] with Lisbon data', () => { service.getWeather(742676).subscribe((consolidatedWeather) => { expect(consolidatedWeather.length).toBe(1); expect(consolidatedWeather[0].the_temp).toBeGreaterThanOrEqual(-2); // Lowest temperature has ever registered for Lisbon in history expect(MOCK__CONSOLIDATED_WEATHER).toBe(consolidatedWeather); }); const req = httpMock.expectOne('/api/location/742676/'); req.flush(MOCK__CONSOLIDATED_WEATHER); }); });
andrefillypesilva/clever-weather
src/app/core/onboarding/onboarding.component.ts
<filename>src/app/core/onboarding/onboarding.component.ts import { animate, style, transition, trigger } from '@angular/animations'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; // Enums import { LOCALSTORAGECONFIG } from 'src/app/models/enums/local-storage.config.enum'; // Interfaces import { Onboarding } from 'src/app/models/interfaces/onboarding.interface'; // Services import { LocalStorageService } from 'src/app/shared/services/local-storage.service'; @Component({ selector: 'app-onboarding', templateUrl: './onboarding.component.html', animations: [ trigger( 'inOutAnimation', [ transition( ':enter', [ style({ height: 0, opacity: 0 }), animate('.6s ease-out', style({ height: 300, opacity: 1 })) ] ), transition( ':leave', [ style({ height: 300, opacity: 1 }), animate('.1s ease-in', style({ height: 0, opacity: 0 })) ] ) ] ) ] }) export class OnboardingComponent implements OnInit { public step: number; public onboardingList: Onboarding[]; constructor( private readonly localStorageService: LocalStorageService, private readonly router: Router ) { } ngOnInit(): void { this.step = 0; this.onboardingList = [ { icon: 'map', title: 'Perfect Weather Explorer', description: 'Here you can find everything about weather around the world!', step: 0 }, { icon: 'mobile', title: 'Any city in your hand!', description: 'Search the city you want to know about the weather and have fun!', step: 1 }, { icon: 'unlock', title: 'Allow us to know where you are', description: 'We need to know where you are for give you the weather forecast of your region!', step: 2 } ]; } public next(): void { this.step++; } public finish(): void { this.askForGeolocationAccess(); } // For Unit Tests: setLocalStorageFinished() public testingSetLocalStorageFinished(): void { this.setLocalStorageFinished(); } private setLocalStorageFinished(): boolean { let response = this.localStorageService.setItem(LOCALSTORAGECONFIG.FIRST_ACCESS, true); return response; } // For Unit Tests: askForGeolocationAccess() public testingAskForGeolocationAccess(): void { this.askForGeolocationAccess(); } private askForGeolocationAccess(): void { navigator.geolocation.getCurrentPosition(() => { if (this.setLocalStorageFinished()) { this.router.navigate(['/home']); } else { alert('Something went wrong! We can not save your local storage first access.'); } }, () => { alert('To use this app, you need to allow geolocation.'); }); } }
andrefillypesilva/clever-weather
src/app/test-mocks/mock-places.mock.ts
export const MOCK__PLACES = [ { title: 'Lisbon', location_type: 'City', woeid: 742676, latt_long: '38.725670,-9.150370', }, ];
andrefillypesilva/clever-weather
src/app/shared/components/onboarding-card/onboarding-card.component.ts
<reponame>andrefillypesilva/clever-weather import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; // Interfaces import { Onboarding } from 'src/app/models/interfaces/onboarding.interface'; @Component({ selector: 'app-onboarding-card', templateUrl: './onboarding-card.component.html', styleUrls: ['./onboarding-card.component.scss'] }) export class OnboardingCardComponent implements OnInit { @Input() public onboarding: Onboarding; @Output() public onNext: EventEmitter<boolean> = new EventEmitter(); @Output() public onFinish: EventEmitter<boolean> = new EventEmitter(); constructor() { } ngOnInit(): void { } next = (): void => this.onNext.emit(true); finish = (): void => this.onFinish.emit(true); }
andrefillypesilva/clever-weather
src/app/shared/components/weather-card/weather-card.component.ts
import { Component, Input, OnInit } from '@angular/core'; // Interfaces import { ConsolidatedWeather } from 'src/app/models/interfaces/consolidated-weather.interface'; @Component({ selector: 'app-weather-card', templateUrl: './weather-card.component.html', styleUrls: ['./weather-card.component.scss'], }) export class WeatherCardComponent implements OnInit { @Input() public weather: ConsolidatedWeather; @Input() public isShare = false; constructor() {} ngOnInit(): void {} share(): void { if (navigator.share) { navigator .share({ title: 'CleverWeather', text: 'Everything about weather in your city.', url: 'https://localhost:4201', }) .then(() => console.log('Successful share')) .catch((error) => console.log('Error sharing', error)); } else { console.log('It is not possible share content in this device.'); } } }
andrefillypesilva/clever-weather
src/app/test-mocks/mock-consolidated-weather.mock.ts
<gh_stars>0 export const MOCK__CONSOLIDATED_WEATHER = [ { id: 5740829197991936, weather_state_name: 'Heavy Cloud', weather_state_abbr: 'hc', wind_direction_compass: 'NW', created: '2021-03-07T19:40:49.698125Z', applicable_date: '2021-03-07', min_temp: 10.745000000000001, max_temp: 16.64, the_temp: 16.675, wind_speed: 5.240507905853813, wind_direction: 313.35680085430624, air_pressure: 1019, humidity: 69, visibility: 13.553969816272966, predictability: 71, }, ];
andrefillypesilva/clever-weather
src/app/shared/interceptors/index.ts
import { HTTP_INTERCEPTORS } from "@angular/common/http"; // Interceptors import { RequestInterceptor } from "./request.interceptor"; export const httpInterceptorProviders = [ { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }, ];
chaos7theory/polecat
src/services/users/users.class.ts
<reponame>chaos7theory/polecat import { Params } from '@feathersjs/feathers'; import { Service, NedbServiceOptions } from 'feathers-nedb'; import { Application } from '../../declarations'; export interface UserData { _id?: string; email?: string; discordId: string; name?: string; avatar?: string; } export class Users extends Service<UserData> { //eslint-disable-next-line @typescript-eslint/no-unused-vars constructor(options: Partial<NedbServiceOptions>, app: Application) { super(options); } create(data: UserData, params?: Params): Promise<any> { const { email, discordId, name, avatar } = data; const userData = { email, discordId, name, avatar }; return super.create(userData, params); } }
chaos7theory/polecat
test/users.helper.ts
import {UserData} from '../src/services/users/users.class'; import app from '../src/app'; // An example account that's not used for anything beyond testing export const userInfo = { email: '<EMAIL>', discordId: '823737099332616216', avatar: 'https://cdn.discordapp.com/avatars/823737099332616216/3936a0db6677ea8679da89a9e4c614ca.png', name: 'Len#8486' }; export async function get_user(): Promise<UserData> { const result = await app.service('users').find({$limit: 1, query: {discordId: userInfo.discordId}}); // Check for pagination const [user] = 'data' in result ? result.data : result; return user; } export async function create_user(): Promise<void> { try { await app.service('users').create(userInfo); } catch (error) { // Do nothing, it just means the user already exists and can be tested } } export async function remove_user(): Promise<void> { try { const user = await get_user(); if(user._id) { await app.service('users').remove(user._id); } } catch (error) { // Do nothing, it just means the user already exists and can be tested } }
chaos7theory/polecat
test/authentication.test.ts
<reponame>chaos7theory/polecat import assert from 'assert'; import app from '../src/app'; describe('authentication', () => { it('registered the authentication service', () => { assert.ok(app.service('authentication')); }); // describe('discord strategy', () => { // before(async () => { // await create_user(); // }); // // it('authenticates user and creates accessToken', async () => { // const {user, accessToken} = await app.service('authentication').create({ // strategy: 'discord', // ...userInfo // }, {}); // // assert.ok(accessToken, 'Created access token for user'); // assert.ok(user, 'Includes user in authentication data'); // }); // }); });
chaos7theory/polecat
src/authentication.ts
<gh_stars>0 import { Params, ServiceAddons } from '@feathersjs/feathers'; import { AuthenticationRequest, AuthenticationService, JWTStrategy } from '@feathersjs/authentication'; import { expressOauth, OAuthProfile, OAuthStrategy } from '@feathersjs/authentication-oauth'; import { Application } from './declarations'; import axios, { AxiosRequestConfig } from 'axios'; declare module './declarations' { interface ServiceTypes { 'authentication': AuthenticationService & ServiceAddons<any>; } } class DiscordStrategy extends OAuthStrategy { async getEntityData(profile: OAuthProfile, existing: any, params: Params) { const baseData = await super.getEntityData(profile, existing, params); if (profile.avatar) { const isGif = profile.avatar.startsWith('a_'); profile.avatar = `https://cdn.discordapp.com/avatars/${profile['id']}/${profile['avatar']}.${isGif ? 'gif' : 'png'}`; } else { // TODO: Replace with default Polecat icon instead profile.avatar = 'https://cdn.discordapp.com/embed/avatars/0.png'; } return { ...baseData, name: `${profile.username}#${profile.discriminator}`, email: profile.email, avatar: profile.avatar, }; } async getProfile(authResult: AuthenticationRequest) { const accessToken = authResult.access_token; const userOptions: AxiosRequestConfig = { method: 'GET', headers: { 'Authorization': `Bearer ${accessToken}` }, url: 'https://discord.com/api/users/@me' }; const { data } = await axios(userOptions); return data; } } export default function (app: Application): void { const authentication = new AuthenticationService(app); authentication.register('jwt', new JWTStrategy()); authentication.register('discord', new DiscordStrategy()); app.use('/authentication', authentication); app.configure(expressOauth({})); }
chaos7theory/polecat
src/services/messages/messages.hooks.ts
<reponame>chaos7theory/polecat import * as authentication from '@feathersjs/authentication'; import { alterItems, disallow, iff, isProvider, keep, populate, required, setNow, stashBefore, validate } from 'feathers-hooks-common'; import {HookContext} from '@feathersjs/feathers'; // Don't remove this comment. It's needed to format import lines nicely. const { authenticate } = authentication.hooks; const userSchema = { include: { service: 'users', nameAs: 'user', parentField: 'userId', childField: '_id' } }; function msgValidator(values: any, context: HookContext) : { [key: string]: string } | null { if(values.text.length > 10000) { return { 'text': 'Message too long.' }; } return null; } export default { before: { all: [ authenticate('jwt'), required('text'), validate(msgValidator) ], find: [], get: [], create: [ keep('text'), alterItems((msg, context) => msg.userId = context.params.user?._id), setNow('createdAt', 'updatedAt') ], update: [ disallow('external') ], patch: [ stashBefore('msg'), iff(context => context.params.user?._id != context.params.msg.userId, disallow()), iff(isProvider('external'), keep('text')), setNow('updatedAt') ], remove: [ stashBefore('msg'), iff(context => context.params.user?._id != context.params.msg.userId, disallow()) ] }, after: { all: [ populate({schema: userSchema}) ], find: [], get: [], create: [], update: [], patch: [], remove: [] }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] } };
chaos7theory/polecat
src/models/characters.model.ts
import NeDB from 'nedb'; import path from 'path'; import { Application } from '../declarations'; export default function (app: Application): NeDB<any> { const dbPath = app.get('nedb'); const Model = new NeDB({ filename: path.join(dbPath, 'characters.db'), autoload: true }); return Model; }
chaos7theory/polecat
test/services/users.test.ts
import assert from 'assert'; import app from '../../src/app'; import {remove_user, userInfo} from '../users.helper'; describe('\'users\' service', () => { beforeEach(async () => { await remove_user(); }); it('registered the service', () => { const service = app.service('users'); assert.ok(service, 'Registered the service'); }); it('creates a user', async () => { const user = await app.service('users').create(userInfo); // Verify Gravatar has been set as we'd expect // assert.strictEqual(user.avatar, 'https://s.gravatar.com/avatar/55502f40dc8b7c769880b10874abc9d0?s=60'); // // Makes sure the password got encrypted // assert.ok(user.password !== '<PASSWORD>'); assert.ok(user, 'Created a user successfully'); assert.strictEqual(user['email'], userInfo.email); assert.strictEqual(user['discordId'], userInfo.discordId); assert.strictEqual(user['avatar'], userInfo.avatar); assert.strictEqual(user['name'], userInfo.name); }); // it('removes password for external requests', async () => { // // Setting `provider` indicates an external request // const params = { provider: 'rest' }; // // const user = await app.service('users').create({ // email: '<EMAIL>', // password: '<PASSWORD>' // }, params); // // // Make sure password has been removed // assert.ok(!user.password); // }); });
chaos7theory/polecat
test/services/messages.test.ts
<filename>test/services/messages.test.ts import assert from 'assert'; import app from '../../src/app'; import {create_user, get_user} from '../users.helper'; describe('\'messages\' service', () => { beforeEach(async () => { await create_user(); }); it('registered the service', () => { const service = app.service('messages'); assert.ok(service, 'Registered the service'); }); it('creates and processes message, adds user information', async () => { const user = await get_user(); // The messages service call params (with the user we just created) const params = {user}; const message = await app.service('messages').create({ text: 'a test', additional: 'should be removed' }, params); assert.strictEqual(message.text, 'a test'); // `userId` should be set to passed users it assert.strictEqual(message.userId, user._id); // Additional property has been removed assert.ok(!message.additional); // `user` has been populated assert.deepStrictEqual(message.user, user); }); it('attempts to create a message that\'s too large', async () => { const user = await get_user(); // The messages service call params (with the user we just created) const params = {user}; const text = '#'.repeat(10001); console.log(text.length); await assert.rejects(app.service('messages').create({ text: text }, params), 'Create message service failed to reject.'); }); });
danielcondemarin/rust-lambda-test
deployment/bin/stack.ts
import * as cdk from "@aws-cdk/core"; import { LambdaStack } from "../lib/lambda-stack"; import * as pkg from "../../package.json"; // Allow appending a randomized benchmark number. const { BENCHMARK_SUFFIX } = process.env; const STACK_NAME = BENCHMARK_SUFFIX ? `${pkg.name}-${BENCHMARK_SUFFIX}` : pkg.name; /** * Construct for the Serverless Application. * * NOTE: We export the our construct so that it's possible to stitch it into a larger deployment. */ export default class Stack { public lambdaStack: LambdaStack; constructor(app: cdk.App) { // Set up our Lambda Stack. this.lambdaStack = new LambdaStack(app, `${STACK_NAME}`, {}); } } const app = new cdk.App(); new Stack(app);
danielcondemarin/rust-lambda-test
benchmark/benchmark.ts
import { LambdaClient, GetFunctionConfigurationCommand, UpdateFunctionConfigurationCommand, UpdateFunctionConfigurationCommandInput, InvokeCommand, InvokeCommandInput, } from "@aws-sdk/client-lambda"; import { XRayClient, GetTraceSummariesCommand, GetTraceSummariesCommandInput, BatchGetTracesCommand, BatchGetTracesCommandInput, TraceSummary, Trace, } from "@aws-sdk/client-xray"; import * as fs from "fs"; import * as pkg from "../package.json"; import * as benchmarkPayload from "./benchmark-payload.json"; const chartistSvg = require("svg-chartist"); /** * Benchmark configuration values. */ const COLD_STARTS = 50; const WARM_STARTS = 50; const MEMORY_SIZES = [128, 256, 512, 1024, 2048, 3072, 4096]; /** * Dynamic benchmark variables. The stack name is generated by taking the package name * and appending the random number generated in the benchmark suffix. */ const { BENCHMARK_SUFFIX, DRY_RUN } = process.env; const STACK_NAME = BENCHMARK_SUFFIX ? `${pkg.name}-${BENCHMARK_SUFFIX}` : pkg.name; /** * Map of memory configuration and their benchmark results. */ interface MemoryTimes { memorySize: number; times: BenchmarkResults; } /** * The benchmark numbers. */ interface BenchmarkResults { overallTimes: BenchmarkAggregateMetrics; traceTimes: BenchmarkSingleInvocationMetric[]; } /** * All aggregate benchmark metrics. */ interface BenchmarkAggregateMetrics { avgWarmMs: number | undefined; avgColdMs: number | undefined; fastestWarmMs: number | undefined; fastestColdMs: number | undefined; slowestWarmMs: number | undefined; slowestColdMs: number | undefined; } /** * The metrics for a single invocation, extract from XRay. */ interface BenchmarkSingleInvocationMetric { id: string | undefined; totalTime: number | undefined; initTime: number | undefined; invocTime: number | undefined; overheadTime: number | undefined; } /** * Map of memory configuration and the traces extracted. */ interface MemoryTraces { memorySize: number; traces: MinimalTrace[]; } /** * The minimal trace information we require for processing. */ type MinimalTrace = Pick<Trace, "Id"> & { Segments: SegmentDocument[] }; /** * The layout of the XRay segments. */ interface SegmentDocument { origin?: string; end_time: number; start_time: number; subsegments?: SubSegment[]; } /** * The layout of the XRay sub-segments. */ interface SubSegment { name?: string; end_time: number; start_time: number; } /** * Run the benchmark by: * - Iterating through memory configurations. * - Updating the Lambda with each memory configuration. * - Invoking the Lambda for n cold starts and m warm starts. * - Extract all XRay traces. * - Process the traces to get the benchmark results. * - Output a markdown table and two charts. * * If you just want to reprocess the results, run the benchmark with `DRY_RUN`, * e.g. `DRY_RUN=true npm run benchmark`. This will skip deployment, teardown, invocations, and * fetching of XRay traces, and instead load the existing traces from `traces.json` and generate * the output again. */ const main = async (functionName: string) => { const memoryTimes: MemoryTimes[] = []; if (DRY_RUN === "true") { // If we are running a dry run, we only need to load in the existing traces and process them. const memoryTraces = JSON.parse(fs.readFileSync("./benchmark/traces.json").toString()); memoryTraces.forEach(({ memorySize, traces: traceBatches }: MemoryTraces) => { const times = processXRayTraces(traceBatches); memoryTimes.push({ memorySize, times, }); }); } else { // For each memory configuration, run through all invocations first. const benchmarkStartTimes: Date[] = []; for (let i = 0; i < MEMORY_SIZES.length; i++) { const benchmarkStartTime = new Date(); benchmarkStartTimes.push(benchmarkStartTime); const memorySize = MEMORY_SIZES[i]; await invokeFunctions(functionName, memorySize); await sleep(1000); } // The XRay traces should now be ready for us to fetch. const memoryTraces: MemoryTraces[] = []; for (let i = 0; i < MEMORY_SIZES.length; i++) { const benchmarkStartTime = benchmarkStartTimes[i]; const memorySize = MEMORY_SIZES[i]; const traceSummaries = await fetchXRayTraceSummaries(functionName, benchmarkStartTime); const traceBatches = await fetchXRayTraceBatches(traceSummaries); memoryTraces.push({ memorySize, traces: traceBatches, }); const times = processXRayTraces(traceBatches); memoryTimes.push({ memorySize, times, }); } fs.writeFileSync("./benchmark/traces.json", JSON.stringify(memoryTraces)); } outputBenchmarkMarkdown(memoryTimes); outputBenchmarkChart(memoryTimes); }; /** * Sleep for the specified time. */ const sleep = (ms: number) => { return new Promise((resolve) => { setTimeout(resolve, ms); }); }; /** * Run the actual benchmark, performing a series of invocations to the Lambda. To ensure cold * starts, we trigger an update on the functions environment variables before invoking it. We * then invoke it a number of times afterwards to gather warm startup data as well. * * The `memorySize` configuration sets the Lambda memory size, allowing easy scale up and down. */ const invokeFunctions = async (functionName: string, memorySize: number) => { const lambdaClient = new LambdaClient({}); const baseConfiguration = await lambdaClient.send( new GetFunctionConfigurationCommand({ FunctionName: functionName, }) ); // We generate the update configuration on the fly to always provide a unique // benchmark run time. const updateConfiguration: () => UpdateFunctionConfigurationCommandInput = () => ({ FunctionName: functionName, MemorySize: memorySize, Environment: { Variables: { ...baseConfiguration.Environment?.Variables, BENCHMARK_RUN_TIME: `${new Date().toISOString()}-${Math.random()}`, }, }, }); const testPayload: () => InvokeCommandInput = () => { // Dynamically replace placeholders in the payload, so we can generate unique // test data per invocation. const payload = JSON.stringify(benchmarkPayload) .replace("##DATE##", new Date().toISOString()) .replace("##NUM##", `${Math.floor(Math.random() * 10000)}`); return { FunctionName: functionName, Payload: Buffer.from(payload), }; }; for (let cI = 0; cI < COLD_STARTS; cI++) { console.log("[BENCHMARK] Updating the function to ensure a cold start."); await lambdaClient.send(new UpdateFunctionConfigurationCommand(updateConfiguration())); const s = Date.now(); await lambdaClient.send(new InvokeCommand(testPayload())); console.log(`[BENCHMARK] Invoked cold-start function: ${Date.now() - s}ms.`); await sleep(500); } for (let wI = 0; wI < WARM_STARTS; wI++) { const s = Date.now(); await lambdaClient.send(new InvokeCommand(testPayload())); console.log(`[BENCHMARK] Invoked warm-start function: ${Date.now() - s}ms.`); await sleep(500); } }; /** * Fetch all XRay trace summaries, which contain the trace IDs we will need to get the detailed information. We * limit the information we search for by filtering on the `functionName` and on service type of AWS:Lambda. Additionally, * we only look in the period between the `benchmarkStartTime` time and the time that this function is called. * * Since XRay trace can take some time to appear, we also gracefully handle waiting if we don't see at least 90% of * the traces in the results. */ const fetchXRayTraceSummaries = async (functionName: string, benchmarkStartTime: Date): Promise<TraceSummary[]> => { const benchmarkEndTime = new Date(); const xRayClient = new XRayClient({}); const traceSummaries: TraceSummary[] = []; let nextTokenSummary: string | undefined; let retries = 0; let retry = true; while (retry) { const traceInput: GetTraceSummariesCommandInput = { StartTime: benchmarkStartTime, EndTime: benchmarkEndTime, FilterExpression: `service(id(name: "${functionName}", type: "AWS::Lambda"))`, NextToken: nextTokenSummary, }; const traceSummariesRes = await xRayClient.send(new GetTraceSummariesCommand(traceInput)); nextTokenSummary = traceSummariesRes.NextToken; traceSummaries.push(...(traceSummariesRes.TraceSummaries ?? [])); // Make sure we've fetched all our traces. We only require 90% to have been gathered, since // XRay is sampling our requests. if ((traceSummariesRes.TraceSummaries?.length ?? 0) + traceSummaries.length < (COLD_STARTS + WARM_STARTS) * 0.8) { if (retries >= 40) { throw new Error( `[TEARDOWN] Failed to get all traces for the invocations, was only able to find '${traceSummariesRes.TraceSummaries?.length}' traces.` ); } console.log("[TRACES] Traces has still not appeared, waiting 1 seconds and trying again..."); await sleep(1000); retries++; } else { retry = false; } if (!retry && nextTokenSummary === undefined) { break; } } console.log("[TRACES] Fetched trace summaries, fetching detailed trace information."); return traceSummaries; }; /** * Split an array into chunks based on the `size`. */ const chunkArray = (arr: any[], size: number) => { var results = []; while (arr.length) { results.push(arr.splice(0, size)); } return results; }; /** * Once we have a list of trace IDs, we can get the detailed trace information which contain the breakdown * of the different stages the Lambda function went through. * * Because the XRay API is limited to fetching 5 traces at a time, we divide all the trace IDs into chunks of * 5. Additionally, we re-request traces if we detect any that are unprocessed. * * NOTE: To avoid leaking information, all traces are stripped of information and only a whitelist is saved. */ const fetchXRayTraceBatches = async (traceSummaries: Pick<TraceSummary, "Id">[]): Promise<MinimalTrace[]> => { const xRayClient = new XRayClient({}); const batchTraces: MinimalTrace[] = []; // We can only request 5 traces at a time, so we split the summary IDs into chunks. const batchSummaryChunks = chunkArray(traceSummaries, 5); let nextTokenBatch: string | undefined; for (let i = 0; i < batchSummaryChunks.length; i++) { const batchSummaryChunk = batchSummaryChunks[i]; while (true) { const batchInput: BatchGetTracesCommandInput = { TraceIds: [...new Set(batchSummaryChunk.filter((t) => t.Id).map((t) => t.Id!))], NextToken: nextTokenBatch, }; const batchTracesRes = await xRayClient.send(new BatchGetTracesCommand(batchInput)); // Check if there are any unprocessed traces. If there are, we wait 1 second and retry the loop. if ((batchTracesRes.UnprocessedTraceIds?.length ?? 0) > 0) { console.log("[TRACES] Detailed traces are still being processed, waiting 1 second and trying again..."); await sleep(1000); continue; } // Only store the relevant parts of the traces, so we can't accidentally leak information. const minimalTraces: MinimalTrace[] = (batchTracesRes.Traces ?? []).map((t) => ({ Id: t.Id, Segments: (t.Segments ?? []) .filter((s) => s.Document !== undefined) .map((s: any) => { const seg: SegmentDocument = JSON.parse(s.Document!); const cleanedSeg: SegmentDocument = { origin: seg.origin, end_time: seg.end_time, start_time: seg.start_time, subsegments: seg.subsegments?.map((subSeg) => ({ name: subSeg.name, end_time: subSeg.end_time, start_time: subSeg.start_time, })), }; return cleanedSeg; }), })); batchTraces.push(...minimalTraces); nextTokenBatch = batchTracesRes.NextToken; if (nextTokenBatch === undefined) { break; } } } return batchTraces; }; /** * Process a list of XRay detailed traces, extracting the timings for the various * segments, along with overall metrics. */ const processXRayTraces = (traces: MinimalTrace[]): BenchmarkResults => { console.log("[TRACES] Processing trace information."); // Gather overall metrics. let avgWarmMs: number | undefined; let avgColdMs: number | undefined; let fastestWarmMs: number | undefined; let fastestColdMs: number | undefined; let slowestWarmMs: number | undefined; let slowestColdMs: number | undefined; // Gather per-trace metrics. const traceTimes: BenchmarkSingleInvocationMetric[] = []; traces.map((trace) => { let totalTime: number | undefined; let initTime: number | undefined; let invocTime: number | undefined; let overheadTime: number | undefined; // Piece together the segment timings into one measurement. trace.Segments?.map((seg) => { if (seg.origin === "AWS::Lambda") { totalTime = seg.end_time - seg.start_time; } else if (seg.origin === "AWS::Lambda::Function") { seg.subsegments?.map((subSeg) => { if (subSeg.name === "Initialization") { initTime = subSeg.end_time - subSeg.start_time; } else if (subSeg.name === "Invocation") { invocTime = subSeg.end_time - subSeg.start_time; } else if (subSeg.name === "Overhead") { overheadTime = subSeg.end_time - subSeg.start_time; } }); } }); const isColdStart = initTime ? true : false; // XRay validation (see https://github.com/codetalkio/patterns-serverless-rust-minimal/issues/5 for context): // 1. XRay can sometimes hand us back invalid traces where the total time is less than the // sum of its elements. We discard these traces. const otherTime = (initTime || 0) + (invocTime || 0) + (overheadTime || 0); if (totalTime! < otherTime) { console.error( `[TRACES] Invalid trace with total time '${totalTime}' less than sum of other times '${otherTime}'. ID = ${trace.Id}.` ); return; } // 2. Similarly, XRay sometimes only catches the Lambda service part, but not the function metrics // themselves. We are then unable to tell if it was a cold start or not. if (!invocTime) { console.error(`[TRACES] Invalid trace with missing invocation time. ID = ${trace.Id}.`); return; } traceTimes.push({ id: trace.Id, totalTime, initTime, invocTime, overheadTime, }); // Keep track of overall metrics. if (!isColdStart) { avgWarmMs = !avgWarmMs ? totalTime : (avgWarmMs + totalTime!) / 2; fastestWarmMs = !fastestWarmMs || totalTime! < fastestWarmMs ? totalTime : fastestWarmMs; slowestWarmMs = !slowestWarmMs || totalTime! > slowestWarmMs ? totalTime : slowestWarmMs; } else if (isColdStart) { avgColdMs = !avgColdMs ? totalTime : (avgColdMs + totalTime!) / 2; fastestColdMs = !fastestColdMs || totalTime! < fastestColdMs ? totalTime : fastestColdMs; slowestColdMs = !slowestColdMs || totalTime! > slowestColdMs ? totalTime : slowestColdMs; } }); return { overallTimes: { avgWarmMs, avgColdMs, fastestWarmMs, slowestWarmMs, fastestColdMs, slowestColdMs, }, traceTimes, }; }; /** * Output the results to the `response-times.md` markdown file by manually piecing together the * markdown content. */ const outputBenchmarkMarkdown = async (memoryTimes: MemoryTimes[]) => { console.log("[OUTPUT] Saving benchmark times to 'response-times.md'."); // Generate the measurement tables for each memory configuration section. let benchmarkData = ""; memoryTimes.map(({ memorySize, times }) => { benchmarkData += ` ## Results for ${memorySize} MB`; benchmarkData += ` | Measurement (${memorySize} MB) | Time (ms) | |-------------|------| | Average warm start response time | ${Math.floor(times.overallTimes.avgWarmMs! * 10000) / 10} ms | | Average cold start response time | ${Math.floor(times.overallTimes.avgColdMs! * 10000) / 10} ms | | Fastest warm response time | ${Math.floor(times.overallTimes.fastestWarmMs! * 10000) / 10} ms | | Slowest warm response time | ${Math.floor(times.overallTimes.slowestWarmMs! * 10000) / 10} ms | | Fastest cold response time | ${Math.floor(times.overallTimes.fastestColdMs! * 10000) / 10} ms | | Slowest cold response time | ${Math.floor(times.overallTimes.slowestColdMs! * 10000) / 10} ms | `; benchmarkData += ` | Response time | Initialization | Invocation | Overhead | Cold/ Warm Start | Memory Size | Trace ID | |---------------|----------------|------------|----------|------------------|-------------|----------|`; times.traceTimes.map((time) => { const isColdStart = !!time.initTime; const totalTimeMs = time.totalTime ? `${Math.floor(time.totalTime * 10000) / 10} ms` : ""; const initTimeMs = time.initTime ? `${Math.floor(time.initTime * 10000) / 10} ms` : ""; const invocTimeMs = time.invocTime ? `${Math.floor(time.invocTime * 10000) / 10} ms` : ""; const overheadTimeMs = time.overheadTime ? `${Math.floor(time.overheadTime * 10000) / 10} ms` : ""; const coldOrWarmStart = isColdStart ? "🥶" : "🥵"; benchmarkData += ` | ${totalTimeMs} | ${initTimeMs} | ${invocTimeMs} | ${overheadTimeMs} | ${coldOrWarmStart} | ${memorySize} MB | ${time.id} |`; }); }); // Set up the page, including the generated charts. const header = ` # Benchmark: Response Times The following are the response time results from AWS XRay, generated after running \`npm run benchmark\`. ![Average Cold/Warm Response Times](./response-times-average.svg) - 🔵: Average cold startup times - 🔴: Average warm startup times ![Fastest and Slowest Response Times](./response-times-extremes.svg) - 🔵: Fastest warm response time - 🔴: Slowest warm response time - 🟡: Fastest cold response time - 🟠: Slowest cold response time `; // Provide a table of contents for quick access to the different measurements. let tableOfContents = ` ## Overview `; memoryTimes.map(({ memorySize }) => { tableOfContents += ` - [Results for ${memorySize} MB](#results-for-${memorySize}-mb)`; }); // Include generic XRay trace examples in the bottom of the page. const footer = ` ## XRay Example of a Cold Start <img width="1476" alt="Screenshot 2020-10-07 at 23 01 40" src="https://user-images.githubusercontent.com/1189998/95387505-178a1d00-08f1-11eb-83a7-7bc32eee48e2.png"> ## XRay Example of a Warm Start <img width="1479" alt="Screenshot 2020-10-07 at 23 01 23" src="https://user-images.githubusercontent.com/1189998/95387509-1953e080-08f1-11eb-8d46-ac25efa235e4.png"> `; const markdown = [header, tableOfContents, benchmarkData, footer].join("\n"); fs.writeFileSync("./benchmark/response-times.md", markdown); }; /** * Output two charts based on the data, showing the behaviour and performance of the AWS Lambda: * - response-times-average.svg: Shows average cold start and warm starts, for each memory configuration. * - response-times-extremes.svg: Shows the fastest and slowests response times for both cold and warm * starts, for each memory configuration. */ const outputBenchmarkChart = async (memoryTimes: MemoryTimes[]) => { console.log("[OUTPUT] Charting benchmark times to 'response-times.svg'."); const opts = { options: { width: 700, height: 300, axisX: { showLabel: true, showGrid: false, }, axisY: { labelInterpolationFnc: function (value: any) { return value + "ms"; }, scaleMinSpace: 15, }, }, title: { height: 50, fill: "#4A5572", }, css: `.ct-series-a .ct-bar, .ct-series-a .ct-line, .ct-series-a .ct-point, .ct-series-a .ct-slice-donut{ stroke: #4A5572 }`, }; const labels: string[] = []; const avgSeries: number[][] = [ [], // Avg. Cold [], // Avg. Warm ]; const extremesSeries: number[][] = [ [], // Fastest Warm [], // Slowest Warm [], // Fastest Cold [], // Slowest Cold ]; memoryTimes.map(({ memorySize, times }) => { labels.push(`${memorySize}MB`); // Add the average data to the first chart series. avgSeries[0].push(Math.floor(times.overallTimes.avgColdMs! * 10000) / 10); avgSeries[1].push(Math.floor(times.overallTimes.avgWarmMs! * 10000) / 10); // Add the extremes data to the second chart series. extremesSeries[0].push(Math.floor(times.overallTimes.fastestWarmMs! * 10000) / 10); extremesSeries[1].push(Math.floor(times.overallTimes.slowestWarmMs! * 10000) / 10); extremesSeries[2].push(Math.floor(times.overallTimes.fastestColdMs! * 10000) / 10); extremesSeries[3].push(Math.floor(times.overallTimes.slowestColdMs! * 10000) / 10); }); const avgSeriesData = { title: "Average Cold/Warm Response Times Across Memory Configurations", labels, series: avgSeries, }; const extremesSeriesData = { title: "Fastest and Slowest Response Times Across Memory Configurations", labels, series: extremesSeries, }; chartistSvg("bar", avgSeriesData, opts).then((html: any) => { fs.writeFileSync("./benchmark/response-times-average.svg", html); }); chartistSvg("bar", extremesSeriesData, opts).then((html: any) => { fs.writeFileSync("./benchmark/response-times-extremes.svg", html); }); }; (async () => { const functionName = `${STACK_NAME}-main`; console.log(`[SETUP] BENCHMARK_SUFFIX = ${BENCHMARK_SUFFIX}`); console.log(`[SETUP] Stack Name = ${functionName}`); if (!BENCHMARK_SUFFIX) { console.error("No 'BENCHMARK_SUFFIX' was set!"); process.exit(1); } try { await main(functionName); } catch (err) { console.error("[ERROR] Benchmark failed unexpectedly:", err); process.exit(1); } })();
powerpool-finance/snapshot.js
dist/index.d.ts
declare const _default: { plugins: { aragon: typeof import("./plugins/aragon").default; gnosis: typeof import("./plugins/gnosis").default; }; strategies: { balancer: typeof import("./strategies/balancer").strategy; 'erc20-received': typeof import("./strategies/erc20-received").strategy; 'contract-call': typeof import("./strategies/contract-call").strategy; 'eth-received': typeof import("./strategies/eth-received").strategy; 'eth-philanthropy': typeof import("./strategies/eth-philanthropy").strategy; 'ens-domains-owned': typeof import("./strategies/ens-domains-owned").strategy; 'erc20-balance-of': typeof import("./strategies/erc20-balance-of").strategy; 'erc20-balance-of-fixed-total': typeof import("./strategies/erc20-balance-of-fixed-total").strategy; 'erc20-balance-of-cv': typeof import("./strategies/erc20-balance-of-cv").strategy; 'erc20-balance-of-coeff': typeof import("./strategies/erc20-balance-of-coeff").strategy; 'erc20-with-balance': typeof import("./strategies/erc20-with-balance").strategy; 'erc20-balance-of-delegation': typeof import("./strategies/erc20-balance-of-delegation").strategy; 'balance-of-with-min': typeof import("./strategies/balance-of-with-min").strategy; 'balancer-delegation': typeof import("./strategies/balancer-delegation").strategy; 'eth-balance': typeof import("./strategies/eth-balance").strategy; 'eth-wallet-age': typeof import("./strategies/eth-wallet-age").strategy; 'maker-ds-chief': typeof import("./strategies/maker-ds-chief").strategy; uni: typeof import("./strategies/uni").strategy; 'frax-finance': typeof import("./strategies/frax-finance").strategy; 'yearn-vault': typeof import("./strategies/yearn-vault").strategy; moloch: typeof import("./strategies/moloch").strategy; masterchef: typeof import("./strategies/masterchef").strategy; sushiswap: typeof import("./strategies/sushiswap").strategy; uniswap: typeof import("./strategies/uniswap").strategy; pancake: typeof import("./strategies/pancake").strategy; synthetix: typeof import("./strategies/synthetix").strategy; ctoken: typeof import("./strategies/ctoken").strategy; cream: typeof import("./strategies/cream").strategy; 'staked-uniswap': typeof import("./strategies/staked-uniswap").strategy; esd: typeof import("./strategies/esd").strategy; 'esd-delegation': typeof import("./strategies/esd-delegation").strategy; piedao: typeof import("./strategies/piedao").strategy; 'xdai-stake': typeof import("./strategies/xdai-stake").strategy; 'xdai-stake-delegation': typeof import("./strategies/xdai-stake-delegation").strategy; defidollar: typeof import("./strategies/defidollar").strategy; aavegotchi: typeof import("./strategies/aavegotchi").strategy; mithcash: typeof import("./strategies/mithcash").strategy; stablexswap: typeof import("./strategies/stablexswap").strategy; dittomoney: typeof import("./strategies/dittomoney").strategy; 'staked-keep': typeof import("./strategies/staked-keep").strategy; 'balancer-unipool': typeof import("./strategies/balancer-unipool").strategy; typhoon: typeof import("./strategies/typhoon").strategy; delegation: typeof import("./strategies/delegation").strategy; ticket: typeof import("./strategies/ticket").strategy; work: typeof import("./strategies/work").strategy; 'ticket-validity': typeof import("./strategies/ticket-validity").strategy; opium: typeof import("./strategies/opium").strategy; 'ocean-marketplace': typeof import("./strategies/ocean-marketplace").strategy; 'the-graph-balance': typeof import("./strategies/the-graph-balance").strategy; 'the-graph-delegation': typeof import("./strategies/the-graph-delegation").strategy; 'the-graph-indexing': typeof import("./strategies/the-graph-indexing").strategy; whitelist: typeof import("./strategies/whitelist").strategy; powerpool: typeof import("./strategies/powerpool").strategy; tokenlon: typeof import("./strategies/tokenlon").strategy; rebased: typeof import("./strategies/rebased").strategy; }; schemas: { space: { title: string; type: string; properties: { name: { type: string; title: string; minLength: number; maxLength: number; }; private: { type: string; }; network: { type: string; title: string; minLength: number; maxLength: number; }; symbol: { type: string; title: string; minLength: number; maxLength: number; }; skin: { type: string; title: string; maxLength: number; }; domain: { type: string; title: string; maxLength: number; }; strategies: { type: string; minItems: number; maxItems: number; items: { type: string; properties: { name: { type: string; maxLength: number; title: string; }; params: { type: string; title: string; }; }; required: string[]; additionalProperties: boolean; }; title: string; }; members: { type: string; items: { type: string; maxLength: number; }; title: string; }; filters: { type: string; properties: { defaultTab: { type: string; }; minScore: { type: string; minimum: number; }; onlyMembers: { type: string; }; invalids: { type: string; items: { type: string; maxLength: number; }; title: string; }; }; additionalProperties: boolean; }; plugins: { type: string; }; }; required: string[]; additionalProperties: boolean; }; }; utils: { call: typeof import("./utils").call; multicall: typeof import("./utils").multicall; subgraphRequest: typeof import("./utils").subgraphRequest; ipfsGet: typeof import("./utils").ipfsGet; sendTransaction: typeof import("./utils").sendTransaction; getScores: typeof import("./utils").getScores; validateSchema: typeof import("./utils").validateSchema; getProvider: typeof import("./utils/provider").default; decodeContenthash: typeof import("./utils/contentHash").decodeContenthash; validateContent: typeof import("./utils/contentHash").validateContent; isValidContenthash: typeof import("./utils/contentHash").isValidContenthash; encodeContenthash: typeof import("./utils/contentHash").encodeContenthash; resolveENSContentHash: typeof import("./utils/contentHash").resolveENSContentHash; resolveContent: typeof import("./utils/contentHash").resolveContent; signMessage: typeof import("./utils/web3").signMessage; getBlockNumber: typeof import("./utils/web3").getBlockNumber; Multicaller: typeof import("./utils/multicaller").default; }; }; export default _default;
powerpool-finance/snapshot.js
src/strategies/powerpool/index.ts
import {formatUnits, parseUnits} from '@ethersproject/units'; import {getBlockNumber} from '../../utils/web3'; import {multicall, call} from '../../utils'; export const author = 'powerpool'; export const version = '0.1.0'; const abi = [ { constant: true, inputs: [ { internalType: 'address', name: '', type: 'address' } ], name: 'balanceOf', outputs: [{internalType: 'uint256', name: '', type: 'uint256'}], payable: false, stateMutability: 'view', type: 'function' }, { inputs: [], name: 'totalSupply', outputs: [ { internalType: 'uint256', name: '', type: 'uint256' } ], stateMutability: 'view', type: 'function' }, { "inputs": [ { "internalType": "uint256", "name": "", "type": "uint256" }, { "internalType": "address", "name": "", "type": "address" } ], "name": "users", "outputs": [ { "internalType": "uint32", "name": "lastUpdateBlock", "type": "uint32" }, { "internalType": "uint32", "name": "vestingBlock", "type": "uint32" }, { "internalType": "uint96", "name": "pendedCvp", "type": "uint96" }, { "internalType": "uint96", "name": "cvpAdjust", "type": "uint96" }, { "internalType": "uint256", "name": "lptAmount", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0xb9d02df4" }, { "inputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "name": "pools", "outputs": [ { "internalType": "contract IERC20", "name": "lpToken", "type": "address" }, { "internalType": "bool", "name": "votesEnabled", "type": "bool" }, { "internalType": "uint8", "name": "poolType", "type": "uint8" }, { "internalType": "uint32", "name": "allocPoint", "type": "uint32" }, { "internalType": "uint32", "name": "lastUpdateBlock", "type": "uint32" }, { "internalType": "uint256", "name": "accCvpPerLpt", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0xac4afa38" }, { "inputs": [], "name": "poolLength", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0x081e3eda" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "members", "outputs": [ { "internalType": "bool", "name": "active", "type": "bool" }, { "internalType": "bool", "name": "transferred", "type": "bool" }, { "internalType": "uint96", "name": "alreadyClaimedVotes", "type": "uint96" }, { "internalType": "uint96", "name": "alreadyClaimedTokens", "type": "uint96" } ], "stateMutability": "view", "type": "function", "signature": "0x08ae4b0c" }, { "inputs": [], "name": "startV", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0x5cfa7d02" }, { "inputs": [], "name": "durationV", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0x51771f40" }, { "inputs": [], "name": "endT", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function", "signature": "0xa8b7d824" }, { "inputs": [], "name": "amountPerMember", "outputs": [ { "internalType": "uint96", "name": "", "type": "uint96" } ], "stateMutability": "view", "type": "function", "signature": "0x5e6a1dd8" }, { "inputs": [{"internalType": "uint256", "name": "", "type": "uint256"}, { "internalType": "address", "name": "", "type": "address" }], "name": "usersPoolBoost", "outputs": [{"internalType": "uint256", "name": "balance", "type": "uint256"}, { "internalType": "uint32", "name": "lastUpdateBlock", "type": "uint32" }], "stateMutability": "view", "type": "function" } ]; export async function strategy( space, network, provider, addresses, options, snapshot ) { const blockTag = typeof snapshot === 'number' ? snapshot : await getBlockNumber(provider); const results = await Promise.all([ // @ts-ignore cvpBalanceOf(network, provider, addresses, options, blockTag), cvpMiningLP(network, provider, addresses, options, blockTag), cvpVestingOf(network, provider, addresses, options, blockTag), ]); return results.reduce((balance, result) => { for (const [userAddress, userBalance] of Object.entries(result)) { balance[userAddress] = (balance[userAddress] || 0) + userBalance; } return balance; }, {}); } async function cvpVestingOf(network, provider, addresses, options, snapshot) { const blockTag = typeof snapshot === 'number' ? snapshot : 'latest'; let [startV, durationV, endT, amountPerMember] = await multicall(network, provider, abi, [ [options.vesting, 'startV', []], [options.vesting, 'durationV', []], [options.vesting, 'endT', []], [options.vesting, 'amountPerMember', []] ], {blockTag}).then(data => data.map(d => d.toString())); startV = parseInt(startV); durationV = parseInt(durationV); endT = parseInt(endT); amountPerMember = formatUnits(amountPerMember); const amountPerSecond = amountPerMember / durationV; const block = await provider.getBlock(snapshot); const currentVotesAmount = block.timestamp >= endT ? 0 : (block.timestamp - startV) * amountPerSecond; const calls: any = addresses.map((address) => [ options.vesting, 'members', [address] ]); const members = await multicall(network, provider, abi, calls, {blockTag}); return Object.fromEntries( addresses.map((address, i) => [address, members[i].active ? currentVotesAmount : 0]) ); } async function cvpBalanceOf(network, provider, addresses, options, snapshot) { const blockTag = typeof snapshot === 'number' ? snapshot : 'latest'; const calls: any = addresses.map((address) => [ options.token, 'balanceOf', [address] ]); const balances = await multicall(network, provider, abi, calls, {blockTag}); return Object.fromEntries( addresses.map((address, i) => { return [address, parseFloat(formatUnits(balances[i].toString()))]; }) ); } async function cvpMiningLP( network, provider, addresses, options, snapshot ) { const blockTag = typeof snapshot === 'number' ? snapshot : 'latest'; const poolLength = await call(provider, abi, [options.mining, 'poolLength', []]).then(l => parseInt(l.toString())); const poolsCalls = []; for (let i = 0; i < poolLength; i++) { if (i > 11) { break; } // @ts-ignore poolsCalls.push([options.mining, 'pools', [i]]); } const pools = await multicall(network, provider, abi, poolsCalls, {blockTag}); const votesByAddress = {}; const votesPools = pools.map((p, i) => ({pid: i, token: p.lpToken})); for (let i = 0; i < votesPools.length; i++) { const pool = votesPools[i]; const response = await multicall( network, provider, abi, [ [options.token, 'balanceOf', [pool.token]], [pool.token, 'totalSupply'], ...addresses.map((address: any) => [ pool.token, 'balanceOf', [address] ]), ...addresses.map((address: any) => [ options.mining, 'users', [pool.pid, address] ]), ...addresses.map((address: any) => [ options.mining, 'usersPoolBoost', [pool.pid, address] ]) ], {blockTag} ); const cvpPerLP = parseUnits(response[0][0].toString(), 18).div(response[1][0]); const lpBalances = response.slice(2, addresses.length + 2); const stakedUserInfo = response.slice( addresses.length + 2, addresses.length * 2 + 2 ); const boostUserInfo = response.slice( addresses.length * 2 + 2, addresses.length * 3 + 2 ); addresses.forEach((a, k) => { const lpBalance = lpBalances[k][0].add(stakedUserInfo[k]['lptAmount']); let cvpLpBalance = lpBalance .mul(cvpPerLP) .div(parseUnits('1', 18)); cvpLpBalance = cvpLpBalance.add(boostUserInfo[k]['balance']) if (!votesByAddress[a]) { votesByAddress[a] = 0; } votesByAddress[a] += parseFloat(formatUnits(cvpLpBalance, 18)); }) } return votesByAddress; }
powerpool-finance/snapshot.js
dist/utils/multicaller.d.ts
import { JsonRpcProvider } from '@ethersproject/providers'; export default class Multicaller { network: string; provider: JsonRpcProvider; abi: any[]; options: any; calls: any[]; paths: any[]; constructor(network: string, provider: JsonRpcProvider, abi: any[], options?: any); call(path: any, address: any, fn: any, params?: any): Multicaller; execute(from?: any): Promise<any>; }
powerpool-finance/snapshot.js
dist/strategies/the-graph-indexing/indexers.d.ts
import { GraphAccountScores } from '../the-graph/graphUtils'; export declare function indexersStrategy(_space: any, network: any, _provider: any, addresses: any, options: any, snapshot: any): Promise<GraphAccountScores>;
powerpool-finance/snapshot.js
dist/schemas/index.d.ts
<filename>dist/schemas/index.d.ts declare const _default: { space: { title: string; type: string; properties: { name: { type: string; title: string; minLength: number; maxLength: number; }; private: { type: string; }; network: { type: string; title: string; minLength: number; maxLength: number; }; symbol: { type: string; title: string; minLength: number; maxLength: number; }; skin: { type: string; title: string; maxLength: number; }; domain: { type: string; title: string; maxLength: number; }; strategies: { type: string; minItems: number; maxItems: number; items: { type: string; properties: { name: { type: string; maxLength: number; title: string; }; params: { type: string; title: string; }; }; required: string[]; additionalProperties: boolean; }; title: string; }; members: { type: string; items: { type: string; maxLength: number; }; title: string; }; filters: { type: string; properties: { defaultTab: { type: string; }; minScore: { type: string; minimum: number; }; onlyMembers: { type: string; }; invalids: { type: string; items: { type: string; maxLength: number; }; title: string; }; }; additionalProperties: boolean; }; plugins: { type: string; }; }; required: string[]; additionalProperties: boolean; }; }; export default _default;
powerpool-finance/snapshot.js
dist/utils/provider.d.ts
export default function getProvider(network: string): any;
powerpool-finance/snapshot.js
dist/utils/contentHash.d.ts
<reponame>powerpool-finance/snapshot.js<gh_stars>0 import { Provider } from '@ethersproject/abstract-provider'; export declare function decodeContenthash(encoded: any): { protocolType: any; decoded: any; error?: undefined; } | { protocolType: any; decoded: any; error: any; }; export declare function validateContent(encoded: any): any; export declare function isValidContenthash(encoded: any): boolean; export declare function encodeContenthash(text: any): any; /** * Fetches and decodes the result of an ENS contenthash lookup on mainnet to a URI * @param ensName to resolve * @param provider provider to use to fetch the data */ export declare function resolveENSContentHash(ensName: string, provider: Provider): Promise<string>; export declare function resolveContent(provider: any, name: any): Promise<{ protocolType: any; decoded: any; error?: undefined; } | { protocolType: any; decoded: any; error: any; }>;
powerpool-finance/snapshot.js
dist/strategies/the-graph/utils.d.ts
import { BigNumber } from '@ethersproject/bignumber'; export declare const GRAPH_NETWORK_SUBGRAPH_URL: { 1: string; 4: string; }; export declare const WEI = "1000000000000000000"; export interface GraphAccountScores { [key: string]: number; } export declare function bdMulBn(bd: string, bn: string): BigNumber; export declare function calcNonStakedTokens(totalSupply: string, totalTokensStaked: string, totalDelegatedTokens: string): number;
dorzey/vscode-dbt-language
src/dbtDefinitionProvider.ts
<gh_stars>1-10 import * as vscode from 'vscode'; import { Uri, Range, ProviderResult, Definition, DefinitionLink, Location } from 'vscode'; import { DBTManifestCacheInstance } from './dbtManifestCache'; export const DBT_MODE = { language: 'jinja-sql', scheme: 'file' }; class RefDefinitionProvider { private static readonly IS_REF = /(ref)[^}]*/; private static readonly REF_FUNC_CALL = /^(ref)[^}]*/ig; private static readonly GET_DBT_MODEL = /('|")([^('|")]*)('|")/ig; static provideDefinition(document: vscode.TextDocument, position: vscode.Position): Definition | undefined { const word = document.getText(document.getWordRangeAtPosition(position, RefDefinitionProvider.IS_REF)); const fullRefFuncCall = word.match(RefDefinitionProvider.REF_FUNC_CALL); if (fullRefFuncCall && fullRefFuncCall.length === 1) { const dbtModel = fullRefFuncCall[0].match(RefDefinitionProvider.GET_DBT_MODEL); if (dbtModel && dbtModel.length === 1) { const name = RefDefinitionProvider.removeQuotes(dbtModel); return DBTManifestCacheInstance.getDefinitionFor(name); } } return undefined; } private static removeQuotes(dbtModel: RegExpMatchArray): string { return dbtModel[0].replace(/[']/g, '').replace(/["]/g, ''); } } export class DbtDefinitionProvider implements vscode.DefinitionProvider { provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): ProviderResult<Definition | DefinitionLink[]> { return new Promise((resolve, reject) => { const definition = RefDefinitionProvider.provideDefinition(document, position); if (definition) { resolve(definition); } else { reject(); } }); } }
dorzey/vscode-dbt-language
src/extension.ts
<filename>src/extension.ts import * as vscode from 'vscode'; import { DbtDefinitionProvider, DBT_MODE } from './dbtDefinitionProvider'; import { DbtDocumentHighlightProvider } from './dbtDocumentHighlightProvider'; export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.languages.registerDefinitionProvider(DBT_MODE, new DbtDefinitionProvider()), vscode.languages.registerDocumentHighlightProvider(DBT_MODE, new DbtDocumentHighlightProvider()) ); } export function deactivate() { }
dorzey/vscode-dbt-language
src/dbtDocumentHighlightProvider.ts
<reponame>dorzey/vscode-dbt-language<filename>src/dbtDocumentHighlightProvider.ts import * as vscode from 'vscode'; export class DbtDocumentHighlightProvider implements vscode.DocumentHighlightProvider { provideDocumentHighlights(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.ProviderResult<vscode.DocumentHighlight[]> { return new Promise((resolve, reject) => { const word = document.getText(document.getWordRangeAtPosition(position)); const lines: string[] = document.getText().split(/\r?\n/g); const highlights = this.getHighlights(lines, word, document); resolve(highlights); }); } private getHighlights(lines: string[], word: string, document: vscode.TextDocument): vscode.DocumentHighlight[] { let highlights: vscode.DocumentHighlight[] = []; for (let lineNumber = 0; lineNumber < lines.length; lineNumber++) { const match = (new RegExp(word)).exec(lines[lineNumber]); if (match) { const startPosition = new vscode.Position(lineNumber, match.index); const endPosition = new vscode.Position(lineNumber, match.index + match[0].length); const wordToHightLight = document.getText(document.getWordRangeAtPosition(startPosition)); if (word === wordToHightLight) { const range = new vscode.Range(startPosition, endPosition); highlights.push(new vscode.DocumentHighlight(range)); } } } return highlights; } }
dorzey/vscode-dbt-language
src/dbtManifestCache.ts
<gh_stars>1-10 import * as vscode from 'vscode'; import { Location, Uri, Range, Definition } from 'vscode'; const fs = require('fs'); class DBTManifestCache { modelToLocationMap: Map<String, String> = new Map(); constructor() { let dbtManifastLocation = vscode.workspace.getConfiguration().get<string>('dbt.manifestLocation', '/target/manifest.json'); let dataFile = fs.readFileSync(vscode.workspace.rootPath + dbtManifastLocation); let stringData = JSON.parse(dataFile); for (var key in stringData.nodes) { this.modelToLocationMap.set(stringData.nodes[key].name, stringData.nodes[key].original_file_path); } } public getDefinitionFor(name: string): Definition | undefined { const location = this.modelToLocationMap.get(name); if (vscode.workspace.rootPath && location) { return new Location( Uri.file(vscode.workspace.rootPath + '/' + location), new Range(0, 0, 0, 0) ); } return undefined; } } export var DBTManifestCacheInstance = new DBTManifestCache();
kundanb/ninjahost
index.d.ts
<reponame>kundanb/ninjahost export default function hello(dir: string, port?: number = 1123): number;
cremalab/boilerplate-app-web
src/components/App/App.test.tsx
<reponame>cremalab/boilerplate-app-web import { render, screen } from "@testing-library/react" import { App } from "./App" describe("App", () => { it("renders expected text", () => { // Arrange const text = "Learn React" // Act render(<App />) const received = screen.getByText(text) // Assert expect(received).toBeDefined() }) })
cremalab/boilerplate-app-web
.storybook/preview.ts
import "../src/index.css" export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, }
Allisone/dstruct
lib/ArrayUtilities.ts
export function clear(array: any[]) { while (array.length > 0) { array.pop(); } }
Allisone/dstruct
lib/structures/trees/RedBlackTree.ts
import Interfaces = require("../../Interfaces"); import RedBlackTreeHelpers = require("./RedBlackTreeHelpers"); import Error = require("../../Error"); import MapHelpers = require("../maps/MapHelpers") // TODO: this could use a lot of improvements. Look at CLR more and the gnu opensource implementation // https://www.opensource.apple.com/source/gcc/gcc-5484/libjava/java/util/TreeMap.java // TODO: ensure the insert check to replace the value guarantees uniqueness! class RedBlackTree<K extends Interfaces.IComparableBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.ITree<K, V> { private nodeCount = 0; private root: RedBlackTreeHelpers.Node<K, V> = null; constructor() { } equals(): boolean { Error.notImplemented(); return null; } hashCode(): number { Error.notImplemented(); return null; } // inserts a node with the given key and value // if a node with the given key exists, the value will be overwritten with the given value // TODO: Return value? insert(key: K, value: V) { Error.checkNotNull(key); Error.checkNotNull(value); var returnValue = false; if (this.root === null) { // empty tree this.root = new RedBlackTreeHelpers.Node<K, V>(key, value); returnValue = true; this.nodeCount++; } else { var head = new RedBlackTreeHelpers.Node<K, V>(); // fake tree root var direction = false; var last = false; //TODO: bad name! // setup var grandParent: RedBlackTreeHelpers.Node<K, V> = null; var grandParentParent = head; var parent: RedBlackTreeHelpers.Node<K, V> = null; var node = this.root; grandParentParent.right = this.root; // search down while (true) { if (node === null) { // insert new node at the bottom node = new RedBlackTreeHelpers.Node<K, V>(key, value); parent.setChild(direction, node); returnValue = true; this.nodeCount++; } else if (this.isRed(node.left) && this.isRed(node.right)) { // color flip node.red = true; node.left.red = false; node.right.red = false; } // fix red violation if (this.isRed(node) && this.isRed(parent)) { //TODO: dir2 is a terrible name, what is this? var dir2 = grandParentParent.right === grandParent; if (node === parent.getChild(last)) { grandParentParent.setChild(dir2, this.singleRotate(!last, grandParent)); } else { grandParentParent.setChild(dir2, this.doubleRotate(!last, grandParent)); } } var cmp = node.key.compareTo(key); // stop if found if (cmp === 0) { node.value = value; break; } last = direction; direction = cmp < 0; // update helpers if (grandParent !== null) { grandParentParent = grandParent; } grandParent = parent; parent = node; node = node.getChild(direction); } // update root this.root = head.right; } // make root black this.root.red = false; return returnValue; } //TODO: return value? remove(key: K): V { Error.checkNotNull(key); if (this.root === null) { return null; } var head = new RedBlackTreeHelpers.Node<K, V>(); // fake tree root var node = head; node.right = this.root; var parent: RedBlackTreeHelpers.Node<K, V> = null; var grandParent: RedBlackTreeHelpers.Node<K, V> = null; var found: RedBlackTreeHelpers.Node<K, V> = null; var directionRight = true; while (node.getChild(directionRight) !== null) { var last = directionRight; // update helpers grandParent = parent; parent = node; node = node.getChild(directionRight); var cmp = key.compareTo(node.key); directionRight = cmp > 0; // save found node if (cmp === 0) { found = node; } // push the red node down if (!this.isRed(node) && !this.isRed(node.getChild(directionRight))) { if (this.isRed(node.getChild(!directionRight))) { var sr = this.singleRotate(directionRight, node); parent.setChild(last, sr); parent = sr; } else if (!this.isRed(node.getChild(!directionRight))) { var sibling = parent.getChild(!last); if (sibling !== null) { if (!this.isRed(sibling.getChild(!last)) && !this.isRed(sibling.getChild(last))) { // color flip parent.red = false; sibling.red = true; node.red = true; } else { var dir2 = grandParent.right === parent; if (this.isRed(sibling.getChild(last))) { grandParent.setChild(dir2, this.doubleRotate(last, parent)); } else if (this.isRed(sibling.getChild(!last))) { grandParent.setChild(dir2, this.singleRotate(last, parent)); } // ensure correct coloring var gpc = grandParent.getChild(dir2); gpc.red = true; node.red = true; gpc.left.red = false; gpc.right.red = false; } } } } } // replace and remove if found if (found !== null) { found.key = node.key; parent.setChild(parent.right === node, node.getChild(node.left === null)); this.nodeCount--; } // update root and make it black this.root = head.right; if (this.root !== null) { this.root.red = false; } return found.value; } size(): number { return this.nodeCount; } isEmpty(): boolean { return this.size() === 0; } keys(): Interfaces.IIterator<K> { return new RedBlackTreeHelpers.Iterator<K>(this.root, this.size(), function (node) { return node.key; }); } values(): Interfaces.IIterator<V> { return new RedBlackTreeHelpers.Iterator<V>(this.root, this.size(), function (node) { return node.value; }); } clear(): void { this.root = null; this.nodeCount = 0; } // return null get(key: K): V { Error.checkNotNull(key); var res = this.root; while (res !== null) { var comparatorValue = key.compareTo(res.key); if (comparatorValue === 0) { return res.value; } else { res = res.getChild(comparatorValue > 0); } } return null; } // calls cb on each node's data, in order // TODO: Type forEach(callback: any): void { MapHelpers.forEach(<any>this, callback); } // returns a null iterator // call next() or prev() to point to an element __iterator__(): Interfaces.IIterator<K> { return this.keys(); } private isRed(node: RedBlackTreeHelpers.Node<K, V>): boolean { return node !== null && node.red; } private doubleRotate(right: boolean, root: RedBlackTreeHelpers.Node<K, V>): RedBlackTreeHelpers.Node<K, V> { root.setChild(!right, this.singleRotate(!right, root.getChild(!right))); return this.singleRotate(right, root); } private singleRotate(right: boolean, root: RedBlackTreeHelpers.Node<K, V>): RedBlackTreeHelpers.Node<K, V> { var save = root.getChild(!right); root.setChild(!right, save.getChild(right)); save.setChild(right, root); root.red = true; save.red = false; return save; } } export = RedBlackTree;
Allisone/dstruct
lib/structures/maps/biMaps/HashBiMap.ts
import Interfaces = require("../../../Interfaces"); import MapHelpers = require("../MapHelpers"); import Error = require("../../../Error"); import IterableHelpers = require("../../IterableHelpers"); import HashMap = require("../HashMap"); class HashBiMap<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.IBiMap<K, V> { constructor(private map: HashMap<K, V> = new HashMap<K, V>(), private inverseMap: HashMap<V, K> = new HashMap<V, K>()) { } containsKey(key: K): boolean { return this.map.containsKey(key); } hashCode(): number { Error.notImplemented(); return null; } equals(biMap: Interfaces.IBiMap<K, V>): boolean { return MapHelpers.equals(this, biMap); } get(key: K): V { return this.map.get(key); } remove(key: K): V { Error.checkNotNull(key); // Check for the key/value pair, return null if not found var value = this.map.get(key); if (!value) { return null; } this.map.remove(key); this.inverseMap.remove(value); return value; } set(key: K, value: V): V { this.inverseMap.set(value, key); return this.map.set(key, value); } size(): number { return this.map.size(); } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } inverse(): Interfaces.IBiMap<V, K> { // TODO: return a copy, or immutable/protected? return new HashBiMap<V, K>(this.inverseMap, this.map); } clear(): void { this.map.clear(); this.inverseMap.clear(); } forEach(callback: Interfaces.IForEachMapCallback<K, V>): void { this.map.forEach(callback); } keys(): Interfaces.IIterator<K> { return this.map.keys(); } values(): Interfaces.IIterator<V> { return this.map.values(); } __iterator__(): Interfaces.IIterator<K> { return this.map.keys(); } } export = HashBiMap;
Allisone/dstruct
lib/structures/maps/TreeMap.ts
import Interfaces = require("../../Interfaces"); import Error = require("../../Error"); import MapHelpers = require("./MapHelpers"); import RedBlackTree = require("../trees/RedBlackTree"); import IterableHelpers = require("../IterableHelpers"); class TreeMap<K extends Interfaces.IComparableBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.ISortedMap<K, V> { private tree: Interfaces.ITree<K, V>; constructor() { this.tree = new RedBlackTree<K, V>(); } clear(): void { this.tree.clear(); } containsKey(key: K): boolean { return this.get(key) !== null; } hashCode(): number { Error.notImplemented(); return null; } equals(map: Interfaces.IMap<K, V>): boolean { return MapHelpers.equals(this, map); } forEach(callback: Interfaces.IForEachMapCallback<K, V>): void { this.tree.forEach(callback); } get(key: K): V { return this.tree.get(key); } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } keys(): Interfaces.IIterator<K> { return this.tree.keys(); } remove(key: K): V { return this.tree.remove(key); } set(key: K, value: V): V { this.tree.insert(key, value); return null; //TODO! } size(): number { return this.tree.size(); } values(): Interfaces.IIterator<V> { return this.tree.values(); } // not to be used directly __iterator__(): Interfaces.IIterator<K> { return this.keys(); } } export = TreeMap;
Allisone/dstruct
lib/structures/maps/ES6Helpers.ts
<filename>lib/structures/maps/ES6Helpers.ts import * as Interfaces from '../../Interfaces'; /** * Based on the MDN ES6 documentation of the upcoming ES6 Map proposal. * Not necessarily complete, only the methods used within the library are part of the interface. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_BaseObjects/Map */ export interface IMap<K, V> { size: number; clear(): void; delete(key: K): boolean; // TODO: entries? forEach(callback: Interfaces.IForEachMapCallback<K, V>): void; get(key: K): V; has(key: K): boolean; keys(): Iterator<K>; set(key: K, value: V): void; values(): Iterator<V>; } export interface IEntry<K, V> { key: K; value: V; next: IEntry<K, V>; // TODO: consider using a singly linkedlist? } export class Iterator<E> implements Interfaces.IIterator<E> { private currentEntry: IEntry<any, any>; private done = false; constructor(private iterator: Interfaces.IIterator<IEntry<any, any>>, private valueCallback: (entry: IEntry<any, any>) => any) { } next(): Interfaces.IIteratorReturn<E> { // Check if there is an entry to return if (this.currentEntry === null || this.currentEntry.next === null) { // Get next entry, assign done value and current entry. var next = this.iterator.next(); this.done = next.done; this.currentEntry = next.value; } return { value: this.valueCallback(this.currentEntry), // Check if there is a current entry, and if this is the last key and return true. // Else return false. done: !!(this.currentEntry.next === null && this.done) }; } }
Allisone/dstruct
lib/structures/maps/MapHelpers.ts
import * as Interfaces from '../../Interfaces'; import * as Error from '../../Error'; export function equals<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject>(map: Interfaces.IMap<K, V>, otherMap: Interfaces.IMap<K, V>): boolean { return false; // TODO! implement /* return iterableEquals<K>(map, otherMap, (mapIterator) => { var mapKey = <any>mapIterator.next(); //TODO: remove any var mapValue = <any>map.get(mapKey.value); var otherMapValue = <any>otherMap.get(mapKey.value); return mapValue.value.equals(otherMapValue.value); })*/ } export function forEach<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject>(map: Interfaces.IMap<K, V>, callback: Interfaces.IForEachMapCallback<K, V>): void { Error.checkNotNull(map); Error.checkNotNull(callback); if (map.size() > 0) { var keys = map.keys(); var values = map.values(); var key: Interfaces.IIteratorReturn<K>; do { key = keys.next(); var value = values.next(); callback(value.value, key.value); } while (!key.done); } }
Allisone/dstruct
lib/structures/tables/MapBasedTable.ts
import * as Interfaces from '../../Interfaces'; import * as Error from '../../Error'; // TODO: attempt implementation without two maps. export class MapBasedTable<R extends Interfaces.IBaseObject, C extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.ITable<R, C, V> { constructor(private rows: Interfaces.IMap<R, Interfaces.IMap<C, V>>, private columns: Interfaces.IMap<C, Interfaces.IMap<R, V>>) { } clear(): void { this.rows.clear(); this.columns.clear(); } column(columnKey: C): Interfaces.IMap<R, V> { return this.columns.get(columnKey); } columnKeys(): Interfaces.IIterator<C> { return this.columns.keys(); } columnMap(): Interfaces.IMap<C, Interfaces.IMap<R, V>> { return this.columns; } contains(rowKey: R, columnKey: C): boolean { return this.get(rowKey, columnKey) !== null; } containsColumn(columnKey: C): boolean { return this.column(columnKey) !== null; } containsRow(rowKey: R): boolean { return this.row(rowKey) !== null; } containsValue(value: V): boolean { Error.notImplemented(); return false; } equals(table: Interfaces.ITable<R, C, V>): boolean { Error.notImplemented(); return false; } get(rowKey: R, columnKey: C): V { var row = this.rows.get(rowKey); return row ? row.get(columnKey) : null; } hashCode(): number { Error.notImplemented(); return null; } isEmpty(): boolean { Error.notImplemented(); return false; } put(rowKey: R, columnKey: C, value: V): V { return null; } // putAll remove(rowKey: R, columnKey: C): V { var row = this.rows.get(rowKey); if (row) { row.remove(columnKey); } var column = this.columns.get(columnKey); if (column) { return column.remove(rowKey); } return null; } row(rowKey: R): Interfaces.IMap<C, V> { Error.notImplemented(); return null; } rowKeys(): Interfaces.IIterator<R> { Error.notImplemented(); return null; } rowMap(): Interfaces.IMap<R, Interfaces.IMap<C, V>> { Error.notImplemented(); return null; } size(): number { Error.notImplemented(); return null; } values(): Interfaces.IIterator<V> { Error.notImplemented(); return null; } }
Allisone/dstruct
lib/structures/sets/MapSet.ts
import Interfaces = require("../../Interfaces"); import Error = require("../../Error"); import IterableHelpers = require("../IterableHelpers"); class MapSet<E extends Interfaces.IBaseObject> implements Interfaces.ISet<E> { constructor(private map: Interfaces.IMap<E, boolean>) { } add(element: E): boolean { this.map.set(element, true); return false; //TODO! } clear(): void { this.map.clear(); } remove(element: E): boolean { this.map.remove(element); //TODO! return false; } hashCode(): number { Error.notImplemented(); return null; } equals(set: Interfaces.ISet<E>): boolean { return IterableHelpers.equals<E>(this, set); } forEach(callback: Interfaces.IForEachCollectionCallback<E>): void { IterableHelpers.forEach(this, callback); } has(element: E): boolean { return this.map.containsKey(element); } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } size(): number { return this.map.size(); } toArray(): E[] { return IterableHelpers.toArray<E>(this); } values(): Interfaces.IIterator<E> { //TODO return null; } __iterator__(): Interfaces.IIterator<E> { return this.map.keys(); } } export = MapSet;
Allisone/dstruct
lib/structures/lists/DoublyLinkedListHelpers.ts
<reponame>Allisone/dstruct<gh_stars>0 import Interfaces = require("../../Interfaces"); export class Node<E extends Interfaces.IBaseObject> { constructor(public value: E, public prev?: Node<E>, public next?: Node<E>) { } } // Circular doubly linked export class Iterator<E extends Interfaces.IBaseObject> implements Interfaces.IIterator<E> { constructor(private currentNode: Node<E>) { } next(): Interfaces.IIteratorReturn<E> { if (this.currentNode && this.currentNode !== undefined) { var next = { value: this.currentNode.value, done: false }; this.currentNode = this.currentNode.next; return next; } else { return { value: null, done: true } } } }
Allisone/dstruct
lib/structures/maps/WeakHashMap.ts
import Interfaces = require("../../Interfaces"); import ES6BaseMap = require("./ES6BaseMap"); class WeakHashMap<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject> extends ES6BaseMap<K, V> { constructor() { super(<any>new WeakMap()); } } export = WeakHashMap;
Allisone/dstruct
lib/structures/multiSets/TreeMultiSet.ts
<gh_stars>0 import Interfaces = require("../../Interfaces"); import TreeMap = require("../maps/TreeMap"); import BaseMultiSet = require("./BaseMultiSet"); // TODO: create SortedMultiSet interface! class TreeMultiSet<E extends Interfaces.IComparableBaseObject> extends BaseMultiSet<E> { constructor() { super(new TreeMap<E, number>()); } } export = TreeMultiSet;
Allisone/dstruct
lib/structures/trees/RedBlackTreeHelpers.ts
import Interfaces = require("../../Interfaces"); //TODO: interface?! export class Node<K extends Interfaces.IComparableBaseObject, V extends Interfaces.IBaseObject> { public red = true; constructor(public key: K = null, public value: V = null, public left: Node<K, V> = null, public right: Node<K, V> = null) { } getChild(right: boolean): Node<K, V> { return right ? this.right : this.left; } // TODO: change to comparator value! setChild(right: boolean, node: Node<K,V>) { if (right) { this.right = node; } else { this.left = node; } } } // TODO: Ensure comparator is used! // TODO: Properly type export class Iterator<E extends Interfaces.IBaseObject> implements Interfaces.IIterator<E> { // consider protected? private ancestors = []; private cursor: any; //Node<K, V>; private index: number = -1; // TODO: replace treebase with interface? constructor(private root: any, private size: number, private nodeValue: (node: any) => E) { } next(): Interfaces.IIteratorReturn<E> { this.index++; if (!this.cursor) { var root = this.root; if (root !== null) { this.minNode(root); } } else { if (this.cursor.right === null) { // no greater node in subtree, go up to parent // if coming from a right child, continue up the stack var save; do { save = this.cursor; if (this.ancestors.length) { this.cursor = this.ancestors.pop(); } else { this.cursor = null; break; } } while (this.cursor.right === save); } else { // get the next node from the subtree this.ancestors.push(this.cursor); this.minNode(this.cursor.right); } } //TODO: done! return {value: this.nodeValue(this.cursor), done: this.index >= this.size - 1}; } // TODO: Consider returning the node, and assignign it to curors? private minNode(start: any): void { while (start.left !== null) { this.ancestors.push(start); start = start.left; } this.cursor = start; } }
Allisone/dstruct
lib/structures/IterableHelpers.ts
import * as Interfaces from '../Interfaces'; import * as Error from '../Error'; // TODO: generic equals for maps may be different that lists since keys, and values must be comparaed! export function equals<E extends Interfaces.IBaseObject>( iterable: Interfaces.IIterable<E>, otherIterable: Interfaces.IIterable<E>): boolean { Error.checkNotNull(iterable); Error.checkNotNull(otherIterable); if (iterable.size() !== otherIterable.size()) { return false; } if (iterable.size() === otherIterable.size() && iterable.size() === 0) { return true; } // Get each element // TODO rewrite to use the .next var collectionIterator = iterable.__iterator__(); var otherCollectionIterator = otherIterable.__iterator__(); var index = 0; while (index < iterable.size()) { var collectionNext = collectionIterator.next(); var otherCollectionNext = otherCollectionIterator.next(); if (!collectionNext.value.equals(otherCollectionNext.value)) { return false; } index++; } return true; } export function toArray<E extends Interfaces.IBaseObject>(iterable: Interfaces.IIterable<E>): E[] { Error.checkNotNull(iterable); var array = new Array(iterable.size()); iterable.forEach((value: E) => { array.push(value); }); return array; } export function isEmpty(iterable: Interfaces.IIterable<any>) { return iterable.size() === 0; } export function forEach<E extends Interfaces.IBaseObject>( iterable: Interfaces.IIterable<E>, callback: Interfaces.IForEachCollectionCallback<E>): void { Error.checkNotNull(iterable); var collectionIterator = iterable.__iterator__(); var collectionNext = collectionIterator.next(); while (!collectionNext.done) { callback(collectionNext.value); collectionNext = collectionIterator.next(); } } export function indexOf<E extends Interfaces.IBaseObject>(iterable: Interfaces.IIterable<E>, value: E) { Error.checkNotNull(iterable); Error.checkNotNull(value); var index = 0; var collectionIterator = iterable.__iterator__(); var collectionNext = collectionIterator.next(); while (!collectionNext.done) { if (value.equals(collectionNext.value)) { return index; } collectionNext = collectionIterator.next(); index++; } // Return -1 if no element is found return -1; }
Allisone/dstruct
lib/structures/sets/HashSet.ts
<filename>lib/structures/sets/HashSet.ts<gh_stars>0 import Interfaces = require("../../Interfaces"); import MapSet = require("./MapSet"); import HashMap = require("../maps/HashMap"); class HashSet<E extends Interfaces.IBaseObject> extends MapSet<E> implements Interfaces.ISet<E> { constructor() { super(new HashMap<E, boolean>()); } } export = HashSet;
Allisone/dstruct
lib/structures/multiSets/BaseMultiSet.ts
<reponame>Allisone/dstruct<gh_stars>0 import Interfaces = require("../../Interfaces"); import Error = require("../../Error"); import IterableHelpers = require("../IterableHelpers"); interface MultiSet<E> { } //TODO: Create an interface for MultiSets! class BaseMultiSet<E extends Interfaces.IBaseObject> { constructor(private map: Interfaces.IMap<E, number>) { } size(): number { return this.map.size(); } /** * Adds a number of occurrences to this multiset * @param element Element to add a number of occurrences of. * @param occurrences Number of occurrences to add. */ add(element: E, occurrences: number = 1): number { return this.setCount(element, this.count(element) + occurrences); } /** * Returns the number of occurrences of the specified element. * @param element Element to retrieve the occurrences of. * @returns The number of occurrences of the element in this multiset. */ count(element: E): number { var count = this.map.get(element); return count ? count : 0; } has(element: E): boolean { return this.count(element) > 0; } clear(): void { this.map.clear(); } hashCode(): number { Error.notImplemented(); return null; } equals(set: Interfaces.ISet<E>): boolean { Error.notImplemented(); return null; } remove(element: E, occurrences: number = 1): number { return this.setCount(element, this.count(element) - occurrences); } setCount(element: E, occurrences: number): number { Error.checkArgument(occurrences >= 0); return occurrences < 0 ? this.map.remove(element) : this.map.set(element, occurrences); } forEach(callback: Interfaces.IForEachCollectionCallback<E>): void { Error.notImplemented(); //TODO: Use map foreach to repliate collection for each //this.map.forEach(callback); } values(): Interfaces.IIterator<E> { return this.map.keys(); } isEmpty(): boolean { return this.size() === 0; } toArray(): E[] { return IterableHelpers.toArray<E>(this); } __iterator__(): Interfaces.IIterator<E> { return this.values(); } } export = BaseMultiSet
Allisone/dstruct
lib/dsa.ts
<reponame>Allisone/dstruct<filename>lib/dsa.ts import Interfaces = require("./Interfaces"); // FOR BROWSER USERS // Configure this file with the data structures and algorithms you require // for your project. Remove any require statements and exports you do not use. // Lists import ArrayList = require("./structures/lists/ArrayList"); import DoublyLinkedList = require("./structures/lists/DoublyLinkedList"); // Maps import HashMap = require("./structures/maps/HashMap"); import TreeMap = require("./structures/maps/TreeMap"); // WeakHashMap cannot be implemented until ES6 is implemented. This is because the implementation // requires low level access to memory. Uncomment when using in a ES6 environment. //import WeakHashMap = require("./structures/maps/WeakHashMap"); // BiMaps import HashBiMap = require("./structures/maps/biMaps/HashBiMap"); // MultiSets import HashMultiSet = require("./structures/multiSets/HashMultiSet"); import TreeMultiSet = require("./structures/multiSets/TreeMultiSet"); // Queues import LinkedListQueue = require("./structures/queues/LinkedListQueue"); // Sets import HashSet = require("./structures/sets/HashSet"); import TreeSet = require("./structures/sets/TreeSet"); // Stacks import ArrayStack = require("./structures/stacks/ArrayStack"); // Tables // TODO! - Not ready for production // Trees // TODO! - Not ready for production var dsa = { 'Lists': { 'ArrayList': ArrayList, 'DoublyLinkedList': DoublyLinkedList }, 'Maps': { 'HashMap': HashMap, 'TreeMap': TreeMap }, 'BiMaps': { 'HashBiMap': HashBiMap }, 'MultiSet': { 'HashMultiSet': HashMultiSet, 'TreeMultiSet': TreeMultiSet }, 'Queues': { 'LinkedListQueue': LinkedListQueue }, 'Sets': { 'HashSet': HashSet, 'TreeSet': TreeSet }, 'Stacks': { 'ArrayStack': ArrayStack } }; export = dsa;
Allisone/dstruct
lib/Primitive.ts
<reponame>Allisone/dstruct<filename>lib/Primitive.ts interface Number { hashCode(): number; equals(otherNumber: Number); compareTo(otherNumber: Number): number; } interface String { hashCode(): number; equals(otherString: String); compareTo(otherString: String): number; } interface Boolean { hashCode(): number; equals(otherBoolean: Boolean); compareTo(otherBoolean: Boolean): number; } // TODO: make these non enumerable. String.prototype.hashCode = function () { var hash = 0, i, chr, len; if (this.length == 0) return hash; for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; String.prototype.equals = function (otherString) { return this.valueOf() === otherString; }; String.prototype.compareTo = function (otherString) { return DefaultComparator(this.valueOf(), otherString); }; Number.prototype.hashCode = function () { return this.valueOf(); }; Number.prototype.equals = function (otherNumber) { return this.valueOf() === otherNumber; }; Number.prototype.compareTo = function (otherNumber) { return DefaultComparator(this.valueOf(), otherNumber); }; Boolean.prototype.hashCode = function () { return this.valueOf() ? 1 : 0; //TODO }; Boolean.prototype.equals = function (otherBoolean) { return this.valueOf() === otherBoolean; }; Boolean.prototype.compareTo = function (otherBoolean) { return this.valueOf() === otherBoolean ? 0 : -1; }; // TODO: only works for base types. Ensure not used in new classes. function DefaultComparator(item1: any, item2: any): number { if (item1 === item2) { return 0; } else if (!item1 || item1 < item2) { return -1; } else if (!item2 || item1 > item2) { return 1; } } /* String.prototype.equals = function (otherString: string): boolean { //TODO: test this implementation return this.compareTo(otherString) === 0; }; String.prototype.compareTo = function (otherString: String): number { return dsa.structs.DefaultComparator(this, otherString); }; */
Allisone/dstruct
lib/structures/lists/ArrayList.ts
// import Interfaces = require("../../Interfaces"); import * as Interfaces from '../../Interfaces'; import * as Error from '../../Error'; import * as IterableHelpers from '../IterableHelpers'; import { ArrayListIterator } from './ArrayListIterator'; import * as ArrayUtilities from '../../ArrayUtilities'; /** * Resizable-array implementation of the List interface */ export class ArrayList<E extends Interfaces.IBaseObject> implements Interfaces.IList<E> { private array: E[]; constructor(initialCapacity?: number) { this.array = new Array(initialCapacity || 0); } __iterator__(): Interfaces.IIterator<E> { return new ArrayListIterator(this.array); } add(element: E): boolean { //TODO: should it default add at 0? this.addAtIndex(this.size(), element); //TODO: return true? return true; } addAtIndex(index: number, element: E): void { Error.checkNotNull(element); if (index === this.size()) { this.array.push(element); } else { this.array.splice(index, 0, element); } } clear(): void { ArrayUtilities.clear(this.array); } removeAtIndex(index: number): E { Error.checkNotNull(index); Error.checkIndex(index, this.size()); var element = this.get(index); this.array.splice(index, 1); return element; } remove(element: E): boolean { Error.checkNotNull(element); var index = this.indexOf(element); if (index >= 0) { this.array.splice(index, 1); return true; } else { return false; } } hashCode(): number { Error.notImplemented(); return null; } equals(collection: Interfaces.ICollection<E>): boolean { return IterableHelpers.equals<E>(this, collection); } forEach(callback: Interfaces.IForEachCollectionCallback<E>): void { //TODO forEach? this.forEach(callback); } get(index: number): E { Error.checkNotNull(index); Error.checkIndex(index, this.size()); return this.array[index]; } has(element: E): boolean { return this.indexOf(element) >= 0; } indexOf(value: E): number { return IterableHelpers.indexOf(this, value); } set(index: number, element: E): E { Error.checkNotNull(element); var currentValue = this.get(index); this.array[index] = element; return currentValue; } size(): number { return this.array.length; } toArray(): E[] { // TODO: type properly return IterableHelpers.toArray<E>(this); } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } }
Allisone/dstruct
lib/Error.ts
// Exceptions export class BaseException { error: Error; name: string; constructor(message?: string) { this.error = new Error(message); this.error.name = this.name + 'Exception'; //TODO: adding exception necesary? } } export class IllegalArgument extends BaseException { name = 'IllegalArgument'; constructor(message?: string) { super(message); } } export class IllegalState extends BaseException { name = 'IllegalState'; constructor(message?: string) { super(message); } } export class NullPointer extends BaseException { name = 'NullPointer'; constructor(message?: string) { super(message); } } export class IndexOutOfBounds extends BaseException { name = 'IndexOutOfBounds'; constructor(message?: string) { super(message); } } export class NotImplemented extends BaseException { name = 'NotImplemented'; constructor(message?: string) { super(message); } } // Precondition helpers export function notImplemented() { throw new NotImplemented().error; } export function checkNotNull(argument: any, message?: string): void { if (argument === null || argument === undefined) { throw new NullPointer(message || 'argument is null.').error; } } export function checkArgument(condition: boolean, message?: string): void { if (condition) { throw new IllegalArgument(message).error; } } export function checkIndex(index: number, size: number, message?: string): void { if (index < 0 || index > size) { throw new IndexOutOfBounds(message).error; } } export function checkIndexRange(startIndex: number, endIndex: number, size: number, message?: string): void { if (startIndex > endIndex || startIndex < 0 || endIndex >= size) { throw new IndexOutOfBounds(message).error; } }
Allisone/dstruct
lib/structures/sets/TreeSet.ts
import Interfaces = require("../../Interfaces"); import MapSet = require("./MapSet"); import TreeMap = require("../maps/TreeMap"); class TreeSet<E extends Interfaces.IComparableBaseObject> extends MapSet<E> implements Interfaces.ISortedSet<E> { constructor() { super(new TreeMap<E, boolean>()); } } export = TreeSet;
Allisone/dstruct
lib/structures/maps/HashMap.ts
<reponame>Allisone/dstruct import * as Interfaces from '../../Interfaces'; import {ES6BaseMap} from './ES6BaseMap'; export class HashMap<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject> extends ES6BaseMap<K, V> { constructor() { super(<any>new Map()); } }
Allisone/dstruct
lib/structures/stacks/ArrayStack.ts
<filename>lib/structures/stacks/ArrayStack.ts import Interfaces = require("../../Interfaces"); import ArrayList = require("../lists/ArrayList"); class ArrayStack<E extends Interfaces.IBaseObject> extends ArrayList<E> implements Interfaces.IStack<E> { peek(): E { return this.get(this.size() - 1); } pop(): E { return this.removeAtIndex(this.size() - 1); } push(element: E): void { this.add(element); } } export = ArrayStack;
Allisone/dstruct
lib/structures/queues/LinkedListQueue.ts
<filename>lib/structures/queues/LinkedListQueue.ts import Interfaces = require("../../Interfaces"); import DoublyLinkedList = require("../lists/DoublyLinkedList"); class LinkedListQueue<E extends Interfaces.IBaseObject> extends DoublyLinkedList<E> implements Interfaces.IQueue<E> { peek(): E { return this.get(0); } pop(): E { return this.removeAtIndex(0); } push(element: E): void { this.add(element); } } export = LinkedListQueue;
Allisone/dstruct
lib/search/Search.d.ts
declare module dsa.search { /* export interface Search<E> { search(list: dsa.structs.List<E>, value: E, comparator?: dsa.structs.Comparator<E> = dsa.structs.DefaultComparator) } */ }
Allisone/dstruct
lib/structures/lists/DoublyLinkedList.ts
import Interfaces = require("../../Interfaces"); import DoublyLinkedListHelpers = require("./DoublyLinkedListHelpers"); import Error = require("../../Error"); import IterableHelpers = require("../IterableHelpers"); import Node = DoublyLinkedListHelpers.Node; class DoublyLinkedList<E extends Interfaces.IBaseObject> implements Interfaces.IList<E> { private rootNode: Node<E>; private lastNode: Node<E>; private count = 0; constructor() { } __iterator__(): Interfaces.IIterator<E> { return new DoublyLinkedListHelpers.Iterator(this.rootNode); } add(element: E): boolean { this.addAtIndex(this.size(), element); return true; } addAtIndex(index: number, element: E): void { Error.checkNotNull(element); Error.checkIndex(index, this.size()); // TODO: handle at n index if (this.size() === 0) { this.rootNode = this.lastNode = new Node<E>(element); } else if (this.size() === 1) { if (index === 0) { // Assign the root to the new element node, link the root to last. this.rootNode = new Node<E>(element); this.rootNode.next = this.lastNode; this.lastNode.prev = this.rootNode; } else { this.lastNode = new Node<E>(element); this.rootNode.next = this.lastNode; this.lastNode.prev = this.rootNode; } } else if (index === 0) { // Store the current root in a temporary variable, and reassign the root to the element. var previousRootNode = this.rootNode; this.rootNode = new Node<E>(element); // Reassign rootNode next, and previousRoot to link the element in the list. this.rootNode.next = previousRootNode; previousRootNode.prev = this.rootNode; } else if (index === this.size()) { var previousLastNode = this.lastNode; this.lastNode = new Node<E>(element); // Assign the new last node.prev to the previousLastNode. // previousLastNode.next is assigned to the new lastNode. this.lastNode.prev = previousLastNode; previousLastNode.next = this.lastNode; } else { // Handles the n index case, where n is not the end or beginning of the list. var node = this.getNodeByIndex(index); var previousNode = node.prev; node.prev = new Node<E>(element, node, previousNode); previousNode.next = node.prev; } this.count++; } clear(): void { this.rootNode = this.lastNode = null; this.count = 0; } remove(element: E): boolean { Error.checkNotNull(element); if (this.size() === 0) { return false; } else if (this.size() == 1) { return this.removeAtIndex(0) !== null; } if (this.rootNode.value.equals(element)) { return this.removeAtIndex(0) !== null; } else if (this.lastNode.value.equals(element)) { return this.removeAtIndex(this.size() - 1) !== null; } else { var node = this.getNodeByElement(element); if (node) { node.prev.next = node.next; node.next.prev = node.prev; this.count--; return true; } } return false; } removeAtIndex(index: number): E { Error.checkNotNull(index); Error.checkIndex(index, this.size() - 1); // TODO, handle n case, and 0 case. if (this.size() === 1) { var element = this.rootNode.value; this.clear(); return element; } else if (index === 0) { var element = this.rootNode.value; this.rootNode = this.rootNode.next; this.count--; return element; } else if (this.size() - 1 === index) { return this.removeLastNode(); } else { //TODO: handle n index case. } } hashCode(): number { Error.notImplemented(); return null; } equals(collection: Interfaces.ICollection<E>): boolean { return IterableHelpers.equals<E>(this, collection); } forEach(callback: Interfaces.IForEachCollectionCallback<E>): void { IterableHelpers.forEach(this, callback); } get(index: number): E { Error.checkNotNull(index); Error.checkIndex(index, this.size() - 1); return this.getNodeByIndex(index).value; } has(element: E): boolean { return this.indexOf(element) >= 0; } indexOf(value: E): number { return IterableHelpers.indexOf(this, value); } set(index: number, element: E): E { Error.checkNotNull(element); return this.getNodeByIndex(index).value = element; } size(): number { return this.count; } toArray(): E[] { return IterableHelpers.toArray<E>(this); } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } private getNodeByElement(element: E): Node<E> { var node = this.rootNode; while (node) { if (element.equals(node.value)) { return node; } node = node.next; } return null; } private getNodeByIndex(index: number): Node<E> { var node = this.rootNode; var i = 0; while (node) { if (i === index) { return node; } if (i > index) { return null; } node = node.next; i++; } return null; } private removeLastNode(): E { var element = this.rootNode.value; this.lastNode = this.lastNode.prev; this.lastNode.next = this.rootNode; this.rootNode.prev = this.lastNode; this.count--; return element; } } export = DoublyLinkedList;
Allisone/dstruct
lib/Interfaces.d.ts
declare module Interfaces { /** * An object which can be compared for equality and hashed. All objects * used with the collections and algorithms must implement this algorithm. * Primitive types are modified in "Primitive" to implement this interface. */ export interface IBaseObject { hashCode(): number; equals(otherBaseObject: IBaseObject); } /** * An object which can be compared with another comparable. */ export interface IComparable { compareTo(otherComparable: IComparable): number; } /** * An object which implements BaseObject and Comparable. * * NOTE: This class is only necessary because TypeScript has problems with * multiple interfaces for generic arguments */ export interface IComparableBaseObject extends IBaseObject, IComparable { } // Use in for ( element in Iterator ) { .. } export interface IIterator<E> { next(): IIteratorReturn<E>; } export interface IIteratorReturn<E> { value: E; done: boolean; } /** * A set of elements that can be iterated over. */ export interface IIterable<E> extends IBaseObject { // Todo, fix this typing forEach(callback: any): void; size(): number; __iterator__(): IIterator<E>; // not to be used directly, for es6 spec } export interface IForEachCollectionCallback<E extends IBaseObject> { (value: E): void; } /** * A group of elements. No guarantees of order or allowing duplicates. */ export interface ICollection<E extends IBaseObject> extends IIterable<E> { /** * Adds a single occurrence of the specified element to this collection * @param element Element to add one occurrence of. */ add(element: E): boolean; clear(): void; // If multiple element, first one is removed. remove(element: E): boolean; // TODO: should equals be a collection member, or a utility function? leaning towards utility for ease. equals(collection: ICollection<E>):boolean; forEach(callback: IForEachCollectionCallback<E>): void; // TODO: mixin or abstract class for shared has logic? has(element: E): boolean; // TODO: mixin or abstract class for shared isEmpty logic? isEmpty(): boolean; // Although a readonly property would be better, typescript does not support this for interfaces. toArray(): E[]; __iterator__(): IIterator<E>; // TODO: all methods //addAll(collection: Collection<E>); //deleteAll(collection: Collection<E>); //hasAll(collection: Collection<E>); } /** * An ordered collection of elements. Permits random access, insertion, and deletion. * Allows duplicate and null elements. */ export interface IList<E extends IBaseObject> extends ICollection<E> { indexOf(element: E): number; get(index: number): E; set(index: number, Element: E): E; addAtIndex(index: number, element: E):void; removeAtIndex(index: number): E; } export interface IForEachMapCallback<K, V> { (value: V, key: K): void; } /** * An object that maps keys to values. Duplicate keys are prohibited. Each key * must map to one value. Duplicate values are allowed. */ export interface IMap<K extends IBaseObject, V extends IBaseObject> extends IIterable<K> { clear(): void; containsKey(key: K): boolean; equals(map: IMap<K, V>):boolean; forEach(callback: IForEachMapCallback<K, V>): void; get(key: K): V; isEmpty(): boolean; keys(): IIterator<K>; remove(key: K): V; set(key: K, value: V): V; values(): IIterator<V>; __iterator__(): IIterator<K>; } /** * A sorted version of a Map. Keys are maintained in sorted order. All other * Map conditions apply. */ export interface ISortedMap<K extends IComparableBaseObject, V extends IBaseObject> extends IMap<K, V> { } /** * A map that maintains the uniqueness of its values as well as the keys. This * allows an inverse view of the map where values are mapped to keys. */ export interface IBiMap<K extends IBaseObject, V extends IBaseObject> extends IMap<K ,V> { inverse(): IBiMap<V, K>; } /** * A collection that contains no duplicate elements. */ export interface ISet<E extends IBaseObject> extends ICollection<E> { values(): IIterator<E>; } /** * A set which maintains the sorted order of elements. */ export interface ISortedSet<E extends IBaseObject> extends ISet<E> { } /** * */ export interface IStack<E extends IBaseObject> extends ICollection<E> { peek(): E; pop(): E; push(element: E): void; } export interface IQueue<E extends IBaseObject> extends ICollection<E> { peek():E; pop():E; push(element: E):void; } // TODO: does this need to extend anything? export interface ITable<R extends IBaseObject, C extends IBaseObject, V extends IBaseObject> { clear(): void; column(columnKey: C): Interfaces.IMap<R, V>; columnKeys(): IIterator<C>; columnMap(): Interfaces.IMap<C, Interfaces.IMap<R, V>>; contains(rowKey: R, columnKey: C): boolean; containsColumn(columnKey: C): boolean; containsRow(rowKey: R): boolean; containsValue(value: V): boolean; equals(table: ITable<R, C, V>): boolean; get(row: R, column: C): V; hashCode(): number; isEmpty(): boolean; put(rowKey: R, columnKey: C, value: V): V; remove(rowKey: R, columnKey: C): V; row(rowKey: R); rowKeys(): IIterator<R>; rowMap(): Interfaces.IMap<R, Interfaces.IMap<C, V>> size(): number; values(): IIterator<V>; } export interface ITree<K extends IComparableBaseObject, V extends IBaseObject> extends IIterable<K> { clear(): void; forEach(callback: IForEachMapCallback<K, V>): void; get(key: K): V; isEmpty(): boolean; keys(): IIterator<K>; values(): IIterator<V>; remove(key: K): V; insert(key: K, value: V): void; // TODO: add these //values(): Iterator<V>; //equals(tree: Tree<E, V>):boolean; } export interface IGraph<K extends IComparableBaseObject, V extends IBaseObject> extends IIterable<K> { add(key: K, value?: V, weight?: number): boolean; remove(key: K): boolean; isAdjacent(key: K): boolean; neighbors(key: K): IList<K>; } } export = Interfaces;
Allisone/dstruct
lib/sort/InsertionSort.ts
/** * Created by codystebbins on 4/13/14. */ /* //best, average, worst // O(n), O(n^2), O(n^2) function insertionSort(array) { for (var i = 1; i < array.length; i++) { insert(array, i, array[i]); } } function insert(array, position, value) { var i = position - 1; while (i >= 0 && array[i] > value) { array[i + 1] = array[i]; i--; } array[i + 1] = value; } */
Allisone/dstruct
lib/search/BinarySearch.ts
/* module dsa.search { export function BinarySearch<E>( list: dsa.structs.List<E>, value: E, comparator: dsa.structs.Comparator<E> = dsa.structs.DefaultComparator) { var minIndex = 0; var maxIndex = list.size() - 1; var midIndex: number; var midValue: E; //Check for sorted condition? // Return two's compliment https://pay.reddit.com/r/javascript/comments/1fx4od/searching_javascript_arrays_with_a_binary_search/caeo5is while (minIndex <= maxIndex) { midIndex = (minIndex + maxIndex)/2 | 0; midValue = list.get(midIndex); if (comparator(midValue, value) < 0) { minIndex = midIndex + 1; } else if (comparator(midValue, value) > 0) { maxIndex = midIndex - 1; } else { return midIndex; } } return ~maxIndex; } } */
Allisone/dstruct
lib/structures/multiSets/HashMultiSet.ts
import Interfaces = require("../../Interfaces"); import HashMap = require("../maps/HashMap"); import BaseMultiSet = require("./BaseMultiSet"); class HashMultiSet<E extends Interfaces.IBaseObject> extends BaseMultiSet<E> { constructor() { super(new HashMap<E, number>()); } } export = HashMultiSet;
Allisone/dstruct
lib/structures/maps/ES6BaseMap.ts
<filename>lib/structures/maps/ES6BaseMap.ts<gh_stars>0 import {IIterator} from '../../Interfaces'; import * as Interfaces from '../../Interfaces'; import * as Error from '../../Error'; import {IEntry} from './ES6Helpers'; import * as MapHelpers from './MapHelpers'; import * as IterableHelpers from '../IterableHelpers'; import * as ES6Helpers from './ES6Helpers'; // TODO: benchmark this solution compared to actually implementing a HashMap with an array. export class ES6BaseMap<K extends Interfaces.IBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.IMap<K, V> { private keyCount = 0; constructor(private map: Map<number, ES6Helpers.IEntry<K, V>>) { } clear(): void { this.map.clear(); } containsKey(key: K): boolean { Error.checkNotNull(key); return this.get(key) !== null; } equals(map: Interfaces.IMap<K, V>): boolean { return MapHelpers.equals(this, map); } hashCode(): number { Error.notImplemented(); return null; } forEach(callback: Interfaces.IForEachMapCallback<K, V>): void { Error.checkNotNull(callback); this.map.forEach(function (entry) { while (entry !== null) { callback(entry.value, entry.key); entry = entry.next; } }); } get(key: K): V { if (this.map.size === 0) { return null; } if (key === null) { var entry = this.map.get(null); } else { var entry = this.map.get(key.hashCode()); } if (!entry) { return null; } // Check if an entry with the key exists in the bucket while (entry !== null) { if (entry.key.equals(key)) { return entry.value; } entry = entry.next; } return null; } isEmpty(): boolean { return IterableHelpers.isEmpty(this); } keys(): Interfaces.IIterator<K> { return new ES6Helpers.Iterator<K>(this.map.values() as IIterator<IEntry<any, any>>, (currentEntry) => { return currentEntry.key; }); } remove(key: K): V { Error.checkNotNull(key); var hashCode = key.hashCode(); // Check if the bucket exists var entry = this.map.get(hashCode); if (!entry) { return null; } // Check if the first entry is the key if (entry.key.equals(key)) { this.keyCount--; if (entry.next) { // Map hashCode to entry.next if it exist s this.map.set(hashCode, entry.next); } else { // Remove the hashCode mapping else this.map.delete(hashCode); } return entry.value; } // Check if the next entry has the key and remove it from the bucket and set. while (entry.next !== null) { if (entry.next.key.equals(key)) { this.keyCount--; var removedEntry = entry.next; entry.next = entry.next.next; return removedEntry.value; } entry = entry.next; } return null; } set(key: K, value: V): V { Error.checkNotNull(key); Error.checkNotNull(value); // Check if the bucket exists var hashCode = key.hashCode(); var entry = this.map.get(hashCode); if (!entry) { this.keyCount++; // Map the hashCode to a new bucket if no bucket exists. this.map.set(hashCode, { key: key, value: value, next: null }); return null; } // Check if an entry with the key exists in the bucket while (entry.next !== null) { if (entry.key.equals(key)) { return this.swapEntryValue(entry, key, value); } entry = entry.next; } // Check if the last entry has the key. Else add it. if (entry.key.equals(key)) { return this.swapEntryValue(entry, key, value); } else { this.keyCount++; entry.next = { key: key, value: value, next: null }; } return null; } size(): number { return this.keyCount; } values(): Interfaces.IIterator<V> { return new ES6Helpers.Iterator<V>(this.map.values() as IIterator<IEntry<any, any>>, (currentEntry) => { return currentEntry.value; }); } __iterator__(): Interfaces.IIterator<K> { return this.keys(); } private swapEntryValue(entry: ES6Helpers.IEntry<K, V>, key: K, value: V) { // Swap value var oldValue = entry.value; entry.value = value; return oldValue; } }
Allisone/dstruct
lib/sort/MergeSort.ts
<gh_stars>0 /** * An implementation for Mergesort. Less efficient * than Quicksort. Again, you'd just use Array.sort * but if you found yourself unable to use that * there's always this option. * * Tests with: * * var array = []; * for(var i = 0; i < 20; i++) { * array.push(Math.round(Math.random() * 100)); * } * * Mergesort.sort(array); * * @author <NAME> */ //var Mergesort = (function() { /** * Sorts the array by breaking it down * into smaller chunks. * * @param {Array} array The array to sort */ /* function sort(array) { var length = array.length, mid = Math.floor(length * 0.5), left = array.slice(0, mid), right = array.slice(mid, length); if(length === 1) { return array; } return merge(sort(left), sort(right)); }*/ /** * Merges two sublists back together. * Shift either left or right onto * the result depending on which is * lower (assuming both exist), and simply * pushes on a list if the other doesn't * exist. * * @param {Array} left The left hand sublist * @param {Array} right The right hand sublist */ /* function merge(left, right) { var result = []; while(left.length || right.length) { if(left.length && right.length) { if(left[0] < right[0]) { result.push(left.shift()); } else { result.push(right.shift()); } } else if (left.length) { result.push(left.shift()); } else { result.push(right.shift()); } } return result; } return { sort: sort }; })(); */
Allisone/dstruct
lib/sort/QuickSort.ts
<reponame>Allisone/dstruct /** * Partitions the (sub)array into values less than and greater * than the pivot value * * @param {Array} array The target array * @param {int} pivot The index of the pivot * @param {int} left The index of the leftmost element * @param {int} left The index of the rightmost element * / function partition(array, pivot, left, right) { var storeIndex = left, pivotValue = array[pivot]; // put the pivot on the right swap(array, pivot, right); // go through the rest for(var v = left; v < right; v++) { // if the value is less than the pivot's // value put it to the left of the pivot // point and move the pivot point along one if(array[v] < pivotValue) { swap(array, v, storeIndex); storeIndex++; } } // finally put the pivot in the correct place swap(array, right, storeIndex); return storeIndex; } /** * Sorts the (sub-)array * * @param {Array} array The target array * @param {int} left The index of the leftmost element, defaults 0 * @param {int} left The index of the rightmost element, defaults array.length-1 * / function sort(array, left, right) { var pivot = null; if(typeof left !== 'number') { left = 0; } if(typeof right !== 'number') { right = array.length - 1; } // effectively set our base // case here. When left == right // we'll stop if(left < right) { // pick a pivot between left and right // and update it once we've partitioned // the array to values < than or > than // the pivot value pivot = left + Math.ceil((right - left) * 0.5); var newPivot = partition(array, pivot, left, right); // recursively sort to the left and right sort(array, left, newPivot - 1); sort(array, newPivot + 1, right); } } /** * Swaps two values in the heap * * @param {int} indexA Index of the first item to be swapped * @param {int} indexB Index of the second item to be swapped * / function swap(array, indexA, indexB) { var temp = array[indexA]; array[indexA] = array[indexB]; array[indexB] = temp; } /// BEtter solution // FROM! http://en.literateprograms.org/Quicksort_%28JavaScript%29 function partition(array, begin, end, pivot) { var pivotValue = array[pivot]; swap(array, pivot, end-1); var store=begin; var index; for(index = begin; index<end-1; ++index) { if(array[index]<=pivotValue) { swap(array, store, index); store++; } } swap(array, end-1, store); return store; } function qsort(array, begin, end) { if(end-1>begin) { var pivot = randomPivot(begin, end); pivot = partition(array, begin, end, pivot); qsort(array, begin, pivot); qsort(array, pivot+1, end); } } function QuickSort(array) { qsort(array, 0, array.length); } function randomPivot(begin, end) { return begin+Math.floor(Math.random()*(end-begin)) } */
Allisone/dstruct
lib/structures/lists/ArrayListIterator.ts
import * as Interfaces from '../../Interfaces'; export class ArrayListIterator<E extends Interfaces.IBaseObject> implements Interfaces.IIterator<E> { private index = 0; constructor(private array: E[]) { } next(): Interfaces.IIteratorReturn<E> { var next = this.index < this.array.length ? {value: this.array[this.index], done: false} : {value: null, done: true}; this.index++; return next; } }
samjeyam/nestjs-passport-clientcert-demo
src/helloworld/helloworld.controller.ts
import { Controller, Get, Query, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport' @Controller('helloworld') export class HelloworldController { // https://localhost:443/helloworld/ - no client cert auth enforcement @Get() getHello(): string { return "hello world" } // https://localhost:443/helloworld/greetings - client cert auth enforcement // with whitelisting based on config process.env.WHITELISTED_CN @UseGuards(AuthGuard('client-cert')) @Get('/greetings') getGreetings(@Query() query): string { return `Hello ${query.name}`; } }
samjeyam/nestjs-passport-clientcert-demo
src/main.ts
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app/app.module'; import { NestApplicationOptions } from '@nestjs/common'; import * as path from "path"; const fs = require("fs"); function getFileContent(path) { if (!path) { return null; } return fs.readFileSync(path); } const certPath = path.join(__dirname, '/../certs/data'); const serverKey = getFileContent(path.join(certPath, 'server.key')).toString('utf8'); const serverCert = getFileContent(path.join(certPath, 'server.crt')).toString('utf8'); const serverCa = getFileContent(path.join(certPath, 'ca.crt')).toString('utf8'); async function bootstrap() { let nestOptions : NestApplicationOptions = {}; nestOptions.httpsOptions = { key: serverKey, cert: serverCert, ca: serverCa, requestCert: true, rejectUnauthorized: false }; const app = await NestFactory.create(AppModule, nestOptions); await app.listen(443); } bootstrap();
samjeyam/nestjs-passport-clientcert-demo
src/auth/auth.module.ts
<reponame>samjeyam/nestjs-passport-clientcert-demo import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config' import {ClientCertStrategy} from "./client-cert.strategy"; @Module({ imports: [ConfigModule], providers: [ClientCertStrategy], exports: [ClientCertStrategy] }) export class AuthModule {}