Skip to content
Myr

perf(types): add type annotations (#2663)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(jsr): reduce slow types (#2369) * feat(jsr): reduce slow types * fix: use allow function * chore: format code * chore: denoify * use `fn = () => {}` syntax for backwards compatible * add type annotations and denoify * add type annotations for helpers and denoify * tweak ---------

authored by Yusuke Wada · committed by GitHub · parent 6db1cc6 · Browse files · 50 files+228 added−114 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Shotaro Nakamura <79000684+nakasyou@users.noreply.github.com>

Diff stats

50 files+228 added−114 removed

  • other:+228 added−114 removed

50 files+228 added−114 removed

modified:deno_dist/helper/accepts/accepts.ts+3 added-3 removed
modified:deno_dist/helper/adapter/index.ts+1 added-1 removed
modified:deno_dist/helper/cookie/index.ts+1 added-1 removed
116 unmodified lines
117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): string | undefined => {122 const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124 return deletedCookie125}
modified:deno_dist/helper/css/common.ts+8 added-8 removed
1 unmodified line
2export const PSEUDO_GLOBAL_SELECTOR = ':-hono-global'3export const isPseudoGlobalSelectorRe = new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`)4export const DEFAULT_STYLE_ID = 'hono-css'56export const SELECTOR = Symbol()7export const CLASS_NAME = Symbol()8export const STYLE_STRING = Symbol()9export const SELECTORS = Symbol()10export const EXTERNAL_CLASS_NAMES = Symbol()11const CSS_ESCAPED = Symbol()6export const SELECTOR: unique symbol = Symbol()7export const CLASS_NAME: unique symbol = Symbol()8export const STYLE_STRING: unique symbol = Symbol()9export const SELECTORS: unique symbol = Symbol()10export const EXTERNAL_CLASS_NAMES: unique symbol = Symbol()11const CSS_ESCAPED: unique symbol = Symbol()1213export interface CssClassName {14 [SELECTOR]: string15 [CLASS_NAME]: string
32 unmodified lines
48 }49 return 'css-' + out50}5152const cssStringReStr = [52const cssStringReStr: string = [53 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54 // eslint-disable-next-line quotes55 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56].join('|')57const minifyCssRe = new RegExp(57const minifyCssRe: RegExp = new RegExp(58 [59 '(' + cssStringReStr + ')', // $1: quoted string6061 '(?:' +
182 unmodified lines
modified:deno_dist/helper/css/index.ts+40 added-13 removed
22 unmodified lines
23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25]2627interface CssType {28 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>29}3031interface CxType {32 (33 ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]34 ): Promise<string>35}3637interface KeyframesType {38 (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon39}4041interface ViewTransitionType {42 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>43 (content: Promise<string>): Promise<string>44 (): Promise<string>45}4647interface StyleType {48 (args?: { children?: Promise<string> }): HtmlEscapedString49}5051/**52 * @experimental53 * `createCssContext` is an experimental feature.54 * The API might be changed.55 */32export const createCssContext = ({ id }: { id: Readonly<string> }) => {56export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {57 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })5859 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()60
68 unmodified lines
129 promise.toString = cssJsxDomObject.toString130 return promise131 }132109 const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {133 const css: CssType = (strings, ...values) => {134 return newCssClassNameObject(cssCommon(strings, values))135 }136113 const cx = (114 ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]115 ): Promise<string> => {137 const cx: CxType = (...args) => {138 // eslint-disable-next-line @typescript-eslint/no-explicit-any139 args = cxCommon(args as any) as any140 // eslint-disable-next-line @typescript-eslint/no-explicit-any141 return css(Array(args.length).fill('') as any, ...args)142 }143144 const keyframes = keyframesCommon145124 type ViewTransitionType = {125 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>126 (content: Promise<string>): Promise<string>127 (): Promise<string>128 }146 const viewTransition: ViewTransitionType = ((147 strings: TemplateStringsArray | Promise<string> | undefined,148 ...values: CssVariableType[]132 ): Promise<string> => {149 ) => {150 // eslint-disable-next-line @typescript-eslint/no-explicit-any151 return newCssClassNameObject(viewTransitionCommon(strings as any, values))152 }) as ViewTransitionType153137 const Style = ({ children }: { children?: Promise<string> } = {}) =>154 const Style: StyleType = ({ children } = {}) =>155 children156 ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)157 : raw(`<style id="${id}"></style>`)158 // eslint-disable-next-line @typescript-eslint/no-explicit-any
7 unmodified lines
166 Style,167 }168}169153const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })170interface DefaultContextType {171 css: CssType172 cx: CxType173 keyframes: KeyframesType174 viewTransition: ViewTransitionType175 Style: StyleType176}177178const defaultContext: DefaultContextType = createCssContext({179 id: DEFAULT_STYLE_ID,180})181182/**183 * @experimental184 * `css` is an experimental feature.185 * The API might be changed.
30 unmodified lines
modified:deno_dist/helper/dev/index.ts+2 added-2 removed
13 unmodified lines
14 name: string15 isMiddleware: boolean16}1718const handlerName = (handler: Function) => {18const handlerName = (handler: Function): string => {19 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')20}2122export const inspectRoutes = <E extends Env>(hono: Hono<E>): RouteData[] => {
44 unmodified lines
67 })68 })69}7071export const getRouterName = <E extends Env>(app: Hono<E>) => {71export const getRouterName = <E extends Env>(app: Hono<E>): string => {72 app.router.match('GET', '/')73 return app.router.name74}
modified:deno_dist/helper/factory/index.ts+3 added-3 removed
214 unmodified lines
215 /**216 * @experimental217 * `createApp` is an experimental feature.218 */219 createApp = () => {219 createApp = (): Hono<E> => {220 const app = new Hono<E>()221 if (this.initApp) {222 this.initApp(app)223 }
9 unmodified lines
233}234235export const createFactory = <E extends Env = any, P extends string = any>(init?: {236 initApp?: InitApp<E>237}) => new Factory<E, P>(init)237}): Factory<E, P> => new Factory<E, P>(init)238239export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(240 middleware: MiddlewareHandler<E, P, I>241) => createFactory<E, P>().createMiddleware<I>(middleware)241): MiddlewareHandler<E, P, I> => createFactory<E, P>().createMiddleware<I>(middleware)
modified:deno_dist/helper/streaming/sse.ts+1 added-1 removed
60 unmodified lines
61export const streamSSE = (62 c: Context,63 cb: (stream: SSEStreamingApi) => Promise<void>,64 onError?: (e: Error, stream: SSEStreamingApi) => Promise<void>65) => {65): Response => {66 const { readable, writable } = new TransformStream()67 const stream = new SSEStreamingApi(writable, readable)6869 c.header('Transfer-Encoding', 'chunked')
8 unmodified lines
modified:deno_dist/helper/testing/index.ts+3 added-1 removed
1import { hc } from '../../client/index.ts'2import type { Client } from '../../client/types.ts'3import type { ExecutionContext } from '../../context.ts'4import type { Hono } from '../../hono.ts'5import type { UnionToIntersection } from '../../utils/types.ts'67// eslint-disable-next-line @typescript-eslint/no-explicit-any8type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never9
1 unmodified line
11export const testClient = <T extends Hono<any, any, any>>(12 app: T,13 Env?: ExtractEnv<T>['Bindings'] | {},14 executionCtx?: ExecutionContext13) => {15): UnionToIntersection<Client<T>> => {16 const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {17 return app.request(input, init, Env, executionCtx)18 }19
2 unmodified lines
modified:deno_dist/jsx/dom/context.ts+1 added-1 removed
3 unmodified lines
4import { globalContexts } from '../context.ts'5import { Fragment } from './jsx-runtime.ts'6import { setInternalTagFlag } from './utils.ts'78export const createContextProviderFunction = <T>(values: T[]) =>8export const createContextProviderFunction = <T>(values: T[]): Function =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }
42 unmodified lines
modified:deno_dist/jsx/dom/css.ts+10 added-1 removed
54 unmodified lines
55 }56 return result57}5859interface CreateCssJsxDomObjectsType {60 (args: { id: Readonly<string> }): readonly [61 {62 toString(this: CssClassName): string63 },64 FC<PropsWithChildren<void>>65 ]66}6759export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {68export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => {69 let styleSheet: CSSStyleSheet | null | undefined = undefined70 const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {71 if (!styleSheet) {72 styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)
148 unmodified lines
modified:deno_dist/jsx/dom/jsx-dev-runtime.ts+1 added-1 removed
26 unmodified lines
27 JSXNodeCompatPrototype28 ) as JSXNode29}3031export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)31export const Fragment = (props: Record<string, unknown>): JSXNode => jsxDEV('', props, undefined)
modified:deno_dist/jsx/dom/utils.ts+1 added-1 removed
1import { DOM_INTERNAL_TAG } from '../constants.ts'23export const setInternalTagFlag = (fn: Function) => {3export const setInternalTagFlag = (fn: Function): Function => {4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5 ;(fn as any)[DOM_INTERNAL_TAG] = true6 return fn7}
modified:deno_dist/jsx/hooks/index.ts+4 added-1 removed
16 unmodified lines
17 (() => void) | undefined, // cleanup18 (() => void) | undefined // effect19]2021const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21const resolvedPromiseValueMap: WeakMap<Promise<unknown>, unknown> = new WeakMap<22 Promise<unknown>,23 unknown24>()2526const isDepsChanged = (27 prevDeps: readonly unknown[] | undefined,28 deps: readonly unknown[] | undefined
394 unmodified lines
modified:deno_dist/jsx/jsx-runtime.ts+5 added-1 removed
1export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime.ts'2export { jsxDEV as jsxs } from './jsx-dev-runtime.ts'34import { raw, html } from '../helper/html/index.ts'5import type { HtmlEscapedString } from '../utils/html.ts'6export { html as jsxTemplate }6export const jsxAttr = (name: string, value: string | Promise<string>) =>7export const jsxAttr = (8 name: string,9 value: string | Promise<string>10): HtmlEscapedString | Promise<HtmlEscapedString> =>11 typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`12export const jsxEscape = (value: string) => value
modified:deno_dist/middleware/jsx-renderer/index.ts+3 added-1 removed
1 unmodified line
2import type { Context, PropsForRenderer } from '../../context.ts'3import { html, raw } from '../../helper/html/index.ts'4import { jsx, createContext, useContext, Fragment } from '../../jsx/index.ts'5import type { FC, PropsWithChildren, JSXNode } from '../../jsx/index.ts'6import type { Context as JSXContext } from '../../jsx/index.ts'7import { renderToReadableStream } from '../../jsx/streaming.ts'8import type { Env, Input, MiddlewareHandler } from '../../types.ts'9import type { HtmlEscapedString } from '../../utils/html.ts'1010export const RequestContext = createContext<Context | null>(null)11export const RequestContext: JSXContext<Context<any, any, {}> | null> =12 createContext<Context | null>(null)1314type RendererOptions = {15 docType?: boolean | string16 stream?: boolean | Record<string, string>
79 unmodified lines
modified:deno_dist/middleware/timing/index.ts+1 added-1 removed
22 unmodified lines
23 autoEnd: boolean24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25}2627const getTime = () => {27const getTime = (): number => {28 try {29 return performance.now()30 } catch {}31 return Date.now()
108 unmodified lines
modified:deno_dist/router/smart-router/router.ts+1 added-1 removed
57 unmodified lines
5859 return res as Result<T>60 }6162 get activeRouter() {62 get activeRouter(): Router<T> {63 if (this.routes || this.routers.length !== 1) {64 throw new Error('No active router has been determined yet.')65 }66
3 unmodified lines
modified:deno_dist/utils/jwt/utf8.ts+2 added-2 removed
1export const utf8Encoder = new TextEncoder()2export const utf8Decoder = new TextDecoder()1export const utf8Encoder: TextEncoder = new TextEncoder()2export const utf8Decoder: TextDecoder = new TextDecoder()
modified:deno_dist/utils/buffer.ts+4 added-1 removed
46 unmodified lines
47 }48 return buffer49}5051export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {51export const bufferToFormData = (52 arrayBuffer: ArrayBuffer,53 contentType: string54): Promise<FormData> => {55 const response = new Response(arrayBuffer, {56 headers: {57 'Content-Type': contentType,58 },
3 unmodified lines
modified:deno_dist/utils/color.ts+1 added-1 removed
1export function getColorEnabled() {1export function getColorEnabled(): boolean {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any45 const isNoColor =
9 unmodified lines
modified:deno_dist/utils/stream.ts+3 added-3 removed
28 unmodified lines
29 },30 })31 }3233 async write(input: Uint8Array | string) {33 async write(input: Uint8Array | string): Promise<StreamingApi> {34 try {35 if (typeof input === 'string') {36 input = this.encoder.encode(input)37 }
3 unmodified lines
41 }42 return this43 }4445 async writeln(input: string) {45 async writeln(input: string): Promise<StreamingApi> {46 await this.write(input + '\n')47 return this48 }4950 sleep(ms: number) {50 sleep(ms: number): Promise<unknown> {51 return new Promise((res) => setTimeout(res, ms))52 }5354 async close() {
17 unmodified lines
modified:deno_dist/context.ts+10 added-3 removed
1import type { HonoRequest } from './request.ts'2import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'3import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html.ts'2import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types.ts'3import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html.ts'4import type { RedirectStatusCode, StatusCode } from './utils/http-status.ts'5import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types.ts'67type HeaderRecord = Record<string, string | string[]>
215 unmodified lines
223 * @see https://hono.dev/api/context#render-setrenderer224 */225 render: Renderer = (...args) => this.renderer(...args)226227 setLayout = (layout: Layout<PropsForRenderer & { Layout: Layout }>) => (this.layout = layout)227 setLayout = (228 layout: Layout<PropsForRenderer & { Layout: Layout }>229 ): Layout<230 PropsForRenderer & {231 Layout: Layout232 }233 > => (this.layout = layout)234235 getLayout = () => this.layout236237 /**238 * `.setRenderer()` can set the layout in the custom middleware.
334 unmodified lines
modified:deno_dist/hono-base.ts+3 added-3 removed
231 unmodified lines
232 * return c.text('Custom Error Message', 500)233 * })234 * ```235 */236 onError = (handler: ErrorHandler<E>) => {236 onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath> => {237 this.errorHandler = handler238 return this239 }240
5 unmodified lines
246 * })247 * ```248 * @see https://hono.dev/api/hono#not-found249 */250 notFound = (handler: NotFoundHandler<E>) => {250 notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath> => {251 this.notFoundHandler = handler252 return this253 }254
140 unmodified lines
395 input: RequestInfo | URL,396 requestInit?: RequestInit,397 Env?: E['Bindings'] | {},398 executionCtx?: ExecutionContext399 ) => {399 ): Response | Promise<Response> => {400 if (input instanceof Request) {401 if (requestInit !== undefined) {402 input = new Request(input, requestInit)403 }
24 unmodified lines
modified:deno_dist/request.ts+2 added-2 removed
287 unmodified lines
288 * })289 * ```290 * @see https://hono.dev/api/request#url291 */292 get url() {292 get url(): string {293 return this.raw.url294 }295296 /**
5 unmodified lines
302 * })303 * ```304 * @see https://hono.dev/api/request#method305 */306 get method() {306 get method(): string {307 return this.raw.method308 }309310 /**
38 unmodified lines
modified:src/helper/accepts/accepts.ts+3 added-3 removed
23 unmodified lines
24export interface acceptsOptions extends acceptsConfig {25 match?: (accepts: Accept[], config: acceptsConfig) => string26}2728export const parseAccept = (acceptHeader: string) => {28export const parseAccept = (acceptHeader: string): Accept[] => {29 // Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.830 const accepts = acceptHeader.split(',') // ['text/html', 'application/xhtml+xml', 'application/xml;q=0.9', 'image/webp', '*/*;q=0.8']31 return accepts.map((accept) => {32 const [type, ...params] = accept.trim().split(';') // ['application/xml', 'q=0.9']
8 unmodified lines
41 }42 })43}4445export const defaultMatch = (accepts: Accept[], config: acceptsConfig) => {45export const defaultMatch = (accepts: Accept[], config: acceptsConfig): string => {46 const { supports, default: defaultSupport } = config47 const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type))48 return accept ? accept.type : defaultSupport49}
10 unmodified lines
60 * })61 * })62 * ```63 */64export const accepts = (c: Context, options: acceptsOptions) => {64export const accepts = (c: Context, options: acceptsOptions): string => {65 const acceptHeader = c.req.header(options.header)66 if (!acceptHeader) {67 return options.default68 }
5 unmodified lines
modified:src/helper/adapter/index.ts+1 added-1 removed
28 unmodified lines
2930 return runtimeEnvHandlers[runtime]()31}3233export const getRuntimeKey = () => {33export const getRuntimeKey = (): Runtime => {34 // eslint-disable-next-line @typescript-eslint/no-explicit-any35 const global = globalThis as any3637 if (global?.Deno !== undefined) {
20 unmodified lines
modified:src/helper/cookie/index.ts+1 added-1 removed
116 unmodified lines
117 }118 c.header('set-cookie', cookie, { append: true })119}120121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions) => {121export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): string | undefined => {122 const deletedCookie = getCookie(c, name)123 setCookie(c, name, '', { ...opt, maxAge: 0 })124 return deletedCookie125}
modified:src/helper/css/common.ts+8 added-8 removed
1 unmodified line
2export const PSEUDO_GLOBAL_SELECTOR = ':-hono-global'3export const isPseudoGlobalSelectorRe = new RegExp(`^${PSEUDO_GLOBAL_SELECTOR}{(.*)}$`)4export const DEFAULT_STYLE_ID = 'hono-css'56export const SELECTOR = Symbol()7export const CLASS_NAME = Symbol()8export const STYLE_STRING = Symbol()9export const SELECTORS = Symbol()10export const EXTERNAL_CLASS_NAMES = Symbol()11const CSS_ESCAPED = Symbol()6export const SELECTOR: unique symbol = Symbol()7export const CLASS_NAME: unique symbol = Symbol()8export const STYLE_STRING: unique symbol = Symbol()9export const SELECTORS: unique symbol = Symbol()10export const EXTERNAL_CLASS_NAMES: unique symbol = Symbol()11const CSS_ESCAPED: unique symbol = Symbol()1213export interface CssClassName {14 [SELECTOR]: string15 [CLASS_NAME]: string
32 unmodified lines
48 }49 return 'css-' + out50}5152const cssStringReStr = [52const cssStringReStr: string = [53 '"(?:(?:\\\\[\\s\\S]|[^"\\\\])*)"', // double quoted string54 // eslint-disable-next-line quotes55 "'(?:(?:\\\\[\\s\\S]|[^'\\\\])*)'", // single quoted string56].join('|')57const minifyCssRe = new RegExp(57const minifyCssRe: RegExp = new RegExp(58 [59 '(' + cssStringReStr + ')', // $1: quoted string6061 '(?:' +
182 unmodified lines
modified:src/helper/css/index.ts+40 added-13 removed
22 unmodified lines
23 Record<string, string>, // class name to add24 Record<string, true> // class name already added25]2627interface CssType {28 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>29}3031interface CxType {32 (33 ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]34 ): Promise<string>35}3637interface KeyframesType {38 (strings: TemplateStringsArray, ...values: CssVariableType[]): CssClassNameCommon39}4041interface ViewTransitionType {42 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>43 (content: Promise<string>): Promise<string>44 (): Promise<string>45}4647interface StyleType {48 (args?: { children?: Promise<string> }): HtmlEscapedString49}5051/**52 * @experimental53 * `createCssContext` is an experimental feature.54 * The API might be changed.55 */32export const createCssContext = ({ id }: { id: Readonly<string> }) => {56export const createCssContext = ({ id }: { id: Readonly<string> }): DefaultContextType => {57 const [cssJsxDomObject, StyleRenderToDom] = createCssJsxDomObjects({ id })5859 const contextMap: WeakMap<object, usedClassNameData> = new WeakMap()60
68 unmodified lines
129 promise.toString = cssJsxDomObject.toString130 return promise131 }132109 const css = (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string> => {133 const css: CssType = (strings, ...values) => {134 return newCssClassNameObject(cssCommon(strings, values))135 }136113 const cx = (114 ...args: (CssClassName | Promise<string> | string | boolean | null | undefined)[]115 ): Promise<string> => {137 const cx: CxType = (...args) => {138 // eslint-disable-next-line @typescript-eslint/no-explicit-any139 args = cxCommon(args as any) as any140 // eslint-disable-next-line @typescript-eslint/no-explicit-any141 return css(Array(args.length).fill('') as any, ...args)142 }143144 const keyframes = keyframesCommon145124 type ViewTransitionType = {125 (strings: TemplateStringsArray, ...values: CssVariableType[]): Promise<string>126 (content: Promise<string>): Promise<string>127 (): Promise<string>128 }146 const viewTransition: ViewTransitionType = ((147 strings: TemplateStringsArray | Promise<string> | undefined,148 ...values: CssVariableType[]132 ): Promise<string> => {149 ) => {150 // eslint-disable-next-line @typescript-eslint/no-explicit-any151 return newCssClassNameObject(viewTransitionCommon(strings as any, values))152 }) as ViewTransitionType153137 const Style = ({ children }: { children?: Promise<string> } = {}) =>154 const Style: StyleType = ({ children } = {}) =>155 children156 ? raw(`<style id="${id}">${(children as unknown as CssClassName)[STYLE_STRING]}</style>`)157 : raw(`<style id="${id}"></style>`)158 // eslint-disable-next-line @typescript-eslint/no-explicit-any
7 unmodified lines
166 Style,167 }168}169153const defaultContext = createCssContext({ id: DEFAULT_STYLE_ID })170interface DefaultContextType {171 css: CssType172 cx: CxType173 keyframes: KeyframesType174 viewTransition: ViewTransitionType175 Style: StyleType176}177178const defaultContext: DefaultContextType = createCssContext({179 id: DEFAULT_STYLE_ID,180})181182/**183 * @experimental184 * `css` is an experimental feature.185 * The API might be changed.
30 unmodified lines
modified:src/helper/dev/index.ts+2 added-2 removed
13 unmodified lines
14 name: string15 isMiddleware: boolean16}1718const handlerName = (handler: Function) => {18const handlerName = (handler: Function): string => {19 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')20}2122export const inspectRoutes = <E extends Env>(hono: Hono<E>): RouteData[] => {
44 unmodified lines
67 })68 })69}7071export const getRouterName = <E extends Env>(app: Hono<E>) => {71export const getRouterName = <E extends Env>(app: Hono<E>): string => {72 app.router.match('GET', '/')73 return app.router.name74}
modified:src/helper/factory/index.ts+3 added-3 removed
214 unmodified lines
215 /**216 * @experimental217 * `createApp` is an experimental feature.218 */219 createApp = () => {219 createApp = (): Hono<E> => {220 const app = new Hono<E>()221 if (this.initApp) {222 this.initApp(app)223 }
9 unmodified lines
233}234235export const createFactory = <E extends Env = any, P extends string = any>(init?: {236 initApp?: InitApp<E>237}) => new Factory<E, P>(init)237}): Factory<E, P> => new Factory<E, P>(init)238239export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(240 middleware: MiddlewareHandler<E, P, I>241) => createFactory<E, P>().createMiddleware<I>(middleware)241): MiddlewareHandler<E, P, I> => createFactory<E, P>().createMiddleware<I>(middleware)
modified:src/helper/streaming/sse.ts+1 added-1 removed
60 unmodified lines
61export const streamSSE = (62 c: Context,63 cb: (stream: SSEStreamingApi) => Promise<void>,64 onError?: (e: Error, stream: SSEStreamingApi) => Promise<void>65) => {65): Response => {66 const { readable, writable } = new TransformStream()67 const stream = new SSEStreamingApi(writable, readable)6869 c.header('Transfer-Encoding', 'chunked')
8 unmodified lines
modified:src/helper/testing/index.ts+3 added-1 removed
1import { hc } from '../../client'2import type { Client } from '../../client/types'3import type { ExecutionContext } from '../../context'4import type { Hono } from '../../hono'5import type { UnionToIntersection } from '../../utils/types'67// eslint-disable-next-line @typescript-eslint/no-explicit-any8type ExtractEnv<T> = T extends Hono<infer E, any, any> ? E : never9
1 unmodified line
11export const testClient = <T extends Hono<any, any, any>>(12 app: T,13 Env?: ExtractEnv<T>['Bindings'] | {},14 executionCtx?: ExecutionContext13) => {15): UnionToIntersection<Client<T>> => {16 const customFetch = (input: RequestInfo | URL, init?: RequestInit) => {17 return app.request(input, init, Env, executionCtx)18 }19
2 unmodified lines
modified:src/jsx/dom/context.ts+1 added-1 removed
3 unmodified lines
4import { globalContexts } from '../context'5import { Fragment } from './jsx-runtime'6import { setInternalTagFlag } from './utils'78export const createContextProviderFunction = <T>(values: T[]) =>8export const createContextProviderFunction = <T>(values: T[]): Function =>9 setInternalTagFlag(({ value, children }: { value: T; children: Child[] }) => {10 if (!children) {11 return undefined12 }
42 unmodified lines
modified:src/jsx/dom/css.ts+10 added-1 removed
54 unmodified lines
55 }56 return result57}5859interface CreateCssJsxDomObjectsType {60 (args: { id: Readonly<string> }): readonly [61 {62 toString(this: CssClassName): string63 },64 FC<PropsWithChildren<void>>65 ]66}6759export const createCssJsxDomObjects = ({ id }: { id: Readonly<string> }) => {68export const createCssJsxDomObjects: CreateCssJsxDomObjectsType = ({ id }) => {69 let styleSheet: CSSStyleSheet | null | undefined = undefined70 const findStyleSheet = (): [CSSStyleSheet, Set<string>] | [] => {71 if (!styleSheet) {72 styleSheet = document.querySelector<HTMLStyleElement>(`style#${id}`)
148 unmodified lines
modified:src/jsx/dom/jsx-dev-runtime.ts+1 added-1 removed
26 unmodified lines
27 JSXNodeCompatPrototype28 ) as JSXNode29}3031export const Fragment = (props: Record<string, unknown>) => jsxDEV('', props, undefined)31export const Fragment = (props: Record<string, unknown>): JSXNode => jsxDEV('', props, undefined)
modified:src/jsx/dom/utils.ts+1 added-1 removed
1import { DOM_INTERNAL_TAG } from '../constants'23export const setInternalTagFlag = (fn: Function) => {3export const setInternalTagFlag = (fn: Function): Function => {4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5 ;(fn as any)[DOM_INTERNAL_TAG] = true6 return fn7}
modified:src/jsx/hooks/index.ts+4 added-1 removed
16 unmodified lines
17 (() => void) | undefined, // cleanup18 (() => void) | undefined // effect19]2021const resolvedPromiseValueMap = new WeakMap<Promise<unknown>, unknown>()21const resolvedPromiseValueMap: WeakMap<Promise<unknown>, unknown> = new WeakMap<22 Promise<unknown>,23 unknown24>()2526const isDepsChanged = (27 prevDeps: readonly unknown[] | undefined,28 deps: readonly unknown[] | undefined
394 unmodified lines
modified:src/jsx/jsx-runtime.ts+5 added-1 removed
1export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime'2export { jsxDEV as jsxs } from './jsx-dev-runtime'34import { raw, html } from '../helper/html'5import type { HtmlEscapedString } from '../utils/html'6export { html as jsxTemplate }6export const jsxAttr = (name: string, value: string | Promise<string>) =>7export const jsxAttr = (8 name: string,9 value: string | Promise<string>10): HtmlEscapedString | Promise<HtmlEscapedString> =>11 typeof value === 'string' ? raw(name + '="' + html`${value}` + '"') : html`${name}="${value}"`12export const jsxEscape = (value: string) => value
modified:src/middleware/jsx-renderer/index.ts+3 added-1 removed
1 unmodified line
2import type { Context, PropsForRenderer } from '../../context'3import { html, raw } from '../../helper/html'4import { jsx, createContext, useContext, Fragment } from '../../jsx'5import type { FC, PropsWithChildren, JSXNode } from '../../jsx'6import type { Context as JSXContext } from '../../jsx'7import { renderToReadableStream } from '../../jsx/streaming'8import type { Env, Input, MiddlewareHandler } from '../../types'9import type { HtmlEscapedString } from '../../utils/html'1010export const RequestContext = createContext<Context | null>(null)11export const RequestContext: JSXContext<Context<any, any, {}> | null> =12 createContext<Context | null>(null)1314type RendererOptions = {15 docType?: boolean | string16 stream?: boolean | Record<string, string>
79 unmodified lines
modified:src/middleware/timing/index.ts+1 added-1 removed
22 unmodified lines
23 autoEnd: boolean24 crossOrigin: boolean | string | ((c: Context) => boolean | string)25}2627const getTime = () => {27const getTime = (): number => {28 try {29 return performance.now()30 } catch {}31 return Date.now()
108 unmodified lines
modified:src/router/smart-router/router.ts+1 added-1 removed
57 unmodified lines
5859 return res as Result<T>60 }6162 get activeRouter() {62 get activeRouter(): Router<T> {63 if (this.routes || this.routers.length !== 1) {64 throw new Error('No active router has been determined yet.')65 }66
3 unmodified lines
modified:src/utils/jwt/utf8.ts+2 added-2 removed
1export const utf8Encoder = new TextEncoder()2export const utf8Decoder = new TextDecoder()1export const utf8Encoder: TextEncoder = new TextEncoder()2export const utf8Decoder: TextDecoder = new TextDecoder()
modified:src/utils/buffer.ts+4 added-1 removed
46 unmodified lines
47 }48 return buffer49}5051export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {51export const bufferToFormData = (52 arrayBuffer: ArrayBuffer,53 contentType: string54): Promise<FormData> => {55 const response = new Response(arrayBuffer, {56 headers: {57 'Content-Type': contentType,58 },
3 unmodified lines
modified:src/utils/color.ts+1 added-1 removed
1export function getColorEnabled() {1export function getColorEnabled(): boolean {2 // eslint-disable-next-line @typescript-eslint/no-explicit-any3 const { process, Deno } = globalThis as any45 const isNoColor =
9 unmodified lines
modified:src/utils/stream.ts+3 added-3 removed
28 unmodified lines
29 },30 })31 }3233 async write(input: Uint8Array | string) {33 async write(input: Uint8Array | string): Promise<StreamingApi> {34 try {35 if (typeof input === 'string') {36 input = this.encoder.encode(input)37 }
3 unmodified lines
41 }42 return this43 }4445 async writeln(input: string) {45 async writeln(input: string): Promise<StreamingApi> {46 await this.write(input + '\n')47 return this48 }4950 sleep(ms: number) {50 sleep(ms: number): Promise<unknown> {51 return new Promise((res) => setTimeout(res, ms))52 }5354 async close() {
17 unmodified lines
modified:src/context.ts+10 added-3 removed
1import type { HonoRequest } from './request'2import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'3import { resolveCallback, HtmlEscapedCallbackPhase } from './utils/html'2import type { Env, FetchEventLike, Input, NotFoundHandler, TypedResponse } from './types'3import { HtmlEscapedCallbackPhase, resolveCallback } from './utils/html'4import type { RedirectStatusCode, StatusCode } from './utils/http-status'5import type { JSONValue, JSONParsed, IsAny, Simplify } from './utils/types'67type HeaderRecord = Record<string, string | string[]>
215 unmodified lines
223 * @see https://hono.dev/api/context#render-setrenderer224 */225 render: Renderer = (...args) => this.renderer(...args)226227 setLayout = (layout: Layout<PropsForRenderer & { Layout: Layout }>) => (this.layout = layout)227 setLayout = (228 layout: Layout<PropsForRenderer & { Layout: Layout }>229 ): Layout<230 PropsForRenderer & {231 Layout: Layout232 }233 > => (this.layout = layout)234235 getLayout = () => this.layout236237 /**238 * `.setRenderer()` can set the layout in the custom middleware.
334 unmodified lines
modified:src/hono-base.ts+3 added-3 removed
231 unmodified lines
232 * return c.text('Custom Error Message', 500)233 * })234 * ```235 */236 onError = (handler: ErrorHandler<E>) => {236 onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath> => {237 this.errorHandler = handler238 return this239 }240
5 unmodified lines
246 * })247 * ```248 * @see https://hono.dev/api/hono#not-found249 */250 notFound = (handler: NotFoundHandler<E>) => {250 notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath> => {251 this.notFoundHandler = handler252 return this253 }254
140 unmodified lines
395 input: RequestInfo | URL,396 requestInit?: RequestInit,397 Env?: E['Bindings'] | {},398 executionCtx?: ExecutionContext399 ) => {399 ): Response | Promise<Response> => {400 if (input instanceof Request) {401 if (requestInit !== undefined) {402 input = new Request(input, requestInit)403 }
24 unmodified lines
modified:src/request.ts+2 added-2 removed
287 unmodified lines
288 * })289 * ```290 * @see https://hono.dev/api/request#url291 */292 get url() {292 get url(): string {293 return this.raw.url294 }295296 /**
5 unmodified lines
302 * })303 * ```304 * @see https://hono.dev/api/request#method305 */306 get method() {306 get method(): string {307 return this.raw.method308 }309310 /**
38 unmodified lines