Skip to content

Commit

Permalink
feat: improve types
Browse files Browse the repository at this point in the history
  • Loading branch information
v1rtl committed Sep 23, 2021
1 parent 576f02f commit 301d7dc
Show file tree
Hide file tree
Showing 43 changed files with 590 additions and 559 deletions.
3 changes: 2 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ examples/dev-server/public/sosseDevSocketClient/main.umd.js
benchmark
site/static/js/index.js
examples/aws/.build
examples/firebase-functions/lib
examples/firebase-functions/lib
build
12 changes: 3 additions & 9 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,10 @@
},
"env": {
"node": true,
"es6": true
"es6": true,
"browser": true
},
"rules": {
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/ban-ts-comment": "off",
"no-unused-vars": "off",
"no-console": "off",
"no-undef": "off"
"@typescript-eslint/ban-ts-comment": "warn"
}
}
2 changes: 1 addition & 1 deletion examples/deta/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ app.put('/todos', async (req, res) => {
})

app.delete('/todos', async (req, res) => {
const { key } = req.body
const { key, task } = req.body
await db.delete(key)
res.send(`Task ${task} has been updated!`)
})
Expand Down
1 change: 1 addition & 0 deletions examples/react-ssr/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-undef */
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(React.createElement)

Expand Down
22 changes: 11 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,31 @@
"@changesets/cli": "2.17.0",
"@commitlint/cli": "13.1.0",
"@commitlint/config-conventional": "13.1.0",
"@jest/globals": "27.1.1",
"@jest/globals": "27.2.1",
"@rollup/plugin-typescript": "8.2.5",
"@types/jest": "27.0.1",
"@types/node": "16.9.1",
"@typescript-eslint/eslint-plugin": "4.31.0",
"@typescript-eslint/parser": "4.31.0",
"colorette": "1.4.0",
"@types/jest": "27.0.2",
"@types/node": "16.9.6",
"@typescript-eslint/eslint-plugin": "4.31.2",
"@typescript-eslint/parser": "4.31.2",
"colorette": "2.0.8",
"decache": "4.6.0",
"dirname-filename-esm": "1.1.1",
"enhanced-resolve": "5.8.2",
"enhanced-resolve": "5.8.3",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-prettier": "4.0.0",
"eta": "1.12.3",
"husky": "7.0.2",
"jest": "27.1.1",
"jest": "27.2.1",
"jsonwebtoken": "8.5.1",
"prettier": "2.4.0",
"prettier": "2.4.1",
"range-parser": "1.2.1",
"regexparam": "2.0.0",
"rollup": "2.56.3",
"rollup": "2.57.0",
"supertest-fetch": "1.4.3",
"ts-jest": "27.0.5",
"tslib": "2.3.1",
"typescript": "4.3.5"
"typescript": "4.4.3"
},
"scripts": {
"prerelease": "pnpm lint && pnpm build && pnpm test",
Expand Down
20 changes: 10 additions & 10 deletions packages/app/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export class App<
* @param setting setting name
* @param value setting value
*/
set(setting: string, value: any) {
set(setting: string, value: any): this {
this.settings[setting] = value

return this
Expand All @@ -124,7 +124,7 @@ export class App<
* Enable app setting
* @param setting Setting name
*/
enable(setting: string) {
enable(setting: string): this {
this.settings[setting] = true

return this
Expand All @@ -134,7 +134,7 @@ export class App<
* Disable app setting
* @param setting
*/
disable(setting: string) {
disable(setting: string): this {
this.settings[setting] = false

return this
Expand All @@ -152,7 +152,7 @@ export class App<
data: Record<string, any> = {},
cb: (err: unknown, html: unknown) => void,
options: TemplateEngineOptions<RenderOptions> = {}
) {
): this {
options.viewsFolder = options.viewsFolder || `${process.cwd()}/views`
options.ext = options.ext || file.slice(file.lastIndexOf('.') + 1) || 'ejs'

Expand All @@ -172,7 +172,7 @@ export class App<

return this
}
use(...args: UseMethodParams<Req, Res, App>) {
use(...args: UseMethodParams<Req, Res, App>): this {
const base = args[0]

const fns = args.slice(1).flat()
Expand Down Expand Up @@ -233,12 +233,12 @@ export class App<
})
}

return this // chainable
return this
}
/**
* Register a template engine with extension
*/
engine(ext: string, fn: TemplateFunc<RenderOptions>) {
engine(ext: string, fn: TemplateFunc<RenderOptions>): this {
this.engines[ext] = fn

return this
Expand All @@ -252,7 +252,7 @@ export class App<
return app
}

find(url: string) {
find(url: string): Middleware<Req, Res>[] {
return this.middleware.filter((m) => {
m.regex = m.regex || rg(m.path, m.type === 'mw')

Expand All @@ -271,7 +271,7 @@ export class App<
* @param req Req object
* @param res Res object
*/
handler(req: Req, res: Res, next?: NextFunction) {
handler(req: Req, res: Res, next?: NextFunction): void {
/* Set X-Powered-By header */
const { xPoweredBy } = this.settings
if (xPoweredBy) res.setHeader('X-Powered-By', typeof xPoweredBy === 'string' ? xPoweredBy : 'tinyhttp')
Expand Down Expand Up @@ -314,7 +314,7 @@ export class App<
})

const handle = (mw: Middleware) => async (req: Req, res: Res, next?: NextFunction) => {
const { path, handler, type, regex } = mw
const { path, handler, regex } = mw

const params = regex ? getURLParams(regex, pathname) : {}

Expand Down
12 changes: 6 additions & 6 deletions packages/content-disposition/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ const getlatin1 = (val: unknown) => {

export class ContentDisposition {
type: string
parameters: Record<any, any>
constructor(type: string, parameters: Record<any, any>) {
parameters: Record<string, any>
constructor(type: string, parameters: Record<string, any>) {
this.type = type
this.parameters = parameters
}
Expand All @@ -55,7 +55,7 @@ function format({
parameters,
type
}: Partial<{
parameters: Record<any, any>
parameters: Record<string, any>
type: string | boolean | undefined
}>) {
if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) throw new TypeError('invalid type')
Expand All @@ -81,7 +81,7 @@ function createParams(filename?: string, fallback?: string | boolean) {
if (filename === undefined) return

const params: Partial<
Record<string, any> & {
Record<string, string> & {
filename: string
}
> = {}
Expand Down Expand Up @@ -126,7 +126,7 @@ export function contentDisposition(
type: string
fallback: string | boolean
}> = {}
) {
): string {
// format into string
return format(new ContentDisposition(options.type || 'attachment', createParams(filename, options.fallback)))
}
Expand Down Expand Up @@ -161,7 +161,7 @@ function decodefield(str: string) {
* Parse Content-Disposition header string.
* @param string string
*/
export function parse(string: string) {
export function parse(string: string): ContentDisposition {
let match = DISPOSITION_TYPE_REGEXP.exec(string)

if (!match) throw new TypeError('invalid type format')
Expand Down
4 changes: 2 additions & 2 deletions packages/cookie-signature/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { createHmac, timingSafeEqual } from 'crypto'
/**
* Sign the given `val` with `secret`.
*/
export const sign = (val: string, secret: string) =>
export const sign = (val: string, secret: string): string =>
`${val}.${createHmac('sha256', secret).update(val).digest('base64').replace(/=+$/, '')}`

/**
* Unsign and decode the given `val` with `secret`,
* returning `false` if the signature is invalid.
*/
export const unsign = (val: string, secret: string) => {
export const unsign = (val: string, secret: string): string | boolean => {
const str = val.slice(0, val.lastIndexOf('.')),
mac = sign(str, secret),
macBuffer = Buffer.from(mac),
Expand Down
2 changes: 1 addition & 1 deletion packages/cookie/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export type SerializeOptions = Partial<{
expires: Date
}>

export function serialize(name: string, val: string, opt: SerializeOptions = {}) {
export function serialize(name: string, val: string, opt: SerializeOptions = {}): string {
if (!opt.encode) opt.encode = encodeURIComponent

if (!fieldContentRegExp.test(name)) throw new TypeError('argument name is invalid')
Expand Down
10 changes: 4 additions & 6 deletions packages/etag/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { createHash } from 'crypto'
import { Stats } from 'fs'

const entityTag = (entity: string | Buffer) => {
const entityTag = (entity: string | Buffer): string => {
if (entity.length === 0) {
// fast-path empty
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
Expand All @@ -20,14 +20,12 @@ const entityTag = (entity: string | Buffer) => {
}
}

const statTag = ({ mtime, size }: Stats) => {
const statTag = ({ mtime, size }: Stats): string => {
return '"' + mtime.getTime().toString(16) + '-' + size.toString(16) + '"'
}

export const eTag = (entity: string | Buffer | Stats, options?: { weak: boolean }) => {
if (entity == null) {
throw new TypeError('argument entity is required')
}
export const eTag = (entity: string | Buffer | Stats, options?: { weak: boolean }): string => {
if (entity == null) throw new TypeError('argument entity is required')

const weak = options?.weak || entity instanceof Stats

Expand Down
6 changes: 3 additions & 3 deletions packages/forwarded/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { IncomingMessage } from 'http'
/**
* Get all addresses in the request, using the `X-Forwarded-For` header.
*/
export function forwarded(req: Pick<IncomingMessage, 'headers' | 'connection'>) {
export function forwarded(req: Pick<IncomingMessage, 'headers' | 'connection'>): string[] {
// simple header parsing
const proxyAddrs = parse((req.headers['x-forwarded-for'] as string) || '')
const socketAddr = req.connection.remoteAddress
Expand All @@ -15,9 +15,9 @@ export function forwarded(req: Pick<IncomingMessage, 'headers' | 'connection'>)
/**
* Parse the X-Forwarded-For header.
*/
export function parse(header: string) {
export function parse(header: string): string[] {
let end = header.length
const list = []
const list: string[] = []
let start = header.length

// gather addresses, backwards
Expand Down
1 change: 1 addition & 0 deletions packages/jsonp/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Request, Response } from '@tinyhttp/app'

export type JSONPOptions = Partial<{
Expand Down
16 changes: 8 additions & 8 deletions packages/proxy-addr/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const IP_RANGES = {
function alladdrs(
req: Pick<IncomingMessage, 'headers' | 'connection'>,
trust: ((...args: any[]) => any) | any[] | string[] | string
) {
): string[] {
// get addresses

const addrs = forwarded(req)
Expand All @@ -43,10 +43,10 @@ function alladdrs(
*
* @param val
*/
function compile(val: string | string[] | number[]) {
let trust
function compile(val: string | string[] | number[]): (addr: string) => boolean {
let trust: string[]
if (typeof val === 'string') trust = [val]
else if (Array.isArray(val)) trust = val.slice()
else if (Array.isArray(val)) trust = val.slice() as string[]
else throw new TypeError('unsupported trust argument')

for (let i = 0; i < trust.length; i++) {
Expand All @@ -64,7 +64,7 @@ function compile(val: string | string[] | number[]) {
/**
* Compile `arr` elements into range subnets.
*/
function compileRangeSubnets(arr: any[]) {
function compileRangeSubnets(arr: string[]) {
const rangeSubnets = new Array(arr.length)
for (let i = 0; i < arr.length; i++) rangeSubnets[i] = parseIPNotation(arr[i])

Expand All @@ -75,7 +75,7 @@ function compileRangeSubnets(arr: any[]) {
*
* @param rangeSubnets
*/
function compileTrust(rangeSubnets: any[]) {
function compileTrust(rangeSubnets: (IPv4 | IPv6)[]) {
// Return optimized function based on length
const len = rangeSubnets.length
return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets)
Expand All @@ -86,7 +86,7 @@ function compileTrust(rangeSubnets: any[]) {
* @param {String} note
* @private
*/
export function parseIPNotation(note: string) {
export function parseIPNotation(note: string): [IPv4 | IPv6, string | number] {
const pos = note.lastIndexOf('/')
const str = pos !== -1 ? note.substring(0, pos) : note

Expand Down Expand Up @@ -133,7 +133,7 @@ function parseNetmask(netmask: string) {
export function proxyaddr(
req: Pick<IncomingMessage, 'headers' | 'connection'>,
trust: ((...args: any[]) => any) | any[] | string[] | string
) {
): string {
const addrs = alladdrs(req, trust)

return addrs[addrs.length - 1]
Expand Down
8 changes: 4 additions & 4 deletions packages/rate-limit/src/memory-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,20 @@ export class MemoryStore implements Store {
callback(null, this.hits[key], this.resetTime)
}

decrement(key: string) {
decrement(key: string): void {
if (this.hits[key]) this.hits[key]--
}

resetAll = () => {
resetAll = (): void => {
this.hits = {}
this.resetTime = this.calculateNextResetTime(this.windowMs)
}

resetKey(key: string) {
resetKey(key: string): void {
delete this.hits[key]
}

calculateNextResetTime(windowMs) {
calculateNextResetTime(windowMs: number): Date {
const nextResetDate = new Date()
nextResetDate.setMilliseconds(nextResetDate.getMilliseconds() + windowMs)
return nextResetDate
Expand Down
Loading

0 comments on commit 301d7dc

Please sign in to comment.