Skip to content
Myr

refactor: use `#` for private methods to reduce the minified file size (#3596)

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

* refactor: use `#` for private methods to reduce the bundle size * use `#` for routers * defined `#newResponse` with a method style * Swap c.#newResponse and c.newResponse * make `#newResponse` as `#method() {}` style

authored by Yusuke Wada · committed by GitHub · parent e43f203 · Browse files · 6 files+71 added−67 removed
This commit

State

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

Diff stats

6 files+71 added−67 removed

  • other:+71 added−67 removed

6 files+71 added−67 removed

modified:src/router/pattern-router/router.ts+4 added-4 removed
modified:src/router/reg-exp-router/router.ts+4 added-4 removed
205 unmodified lines
206207 match(method: string, path: string): Result<T> {208 clearWildcardRegExpCache() // no longer used.209210 const matchers = this.buildAllMatchers()210 const matchers = this.#buildAllMatchers()211212 this.match = (method, path) => {213 const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher<T>214
13 unmodified lines
228229 return this.match(method, path)230 }231232 private buildAllMatchers(): Record<string, Matcher<T> | null> {232 #buildAllMatchers(): Record<string, Matcher<T> | null> {233 const matchers: Record<string, Matcher<T> | null> = Object.create(null)234235 Object.keys(this.routes!)236 .concat(Object.keys(this.middleware!))237 .forEach((method) => {238 matchers[method] ||= this.buildMatcher(method)238 matchers[method] ||= this.#buildMatcher(method)239 })240241 // Release cache242 this.middleware = this.routes = undefined243244 return matchers245 }246247 private buildMatcher(method: string): Matcher<T> | null {247 #buildMatcher(method: string): Matcher<T> | null {248 const routes: [string, HandlerWithMetadata<T>[]][] = []249250 let hasOwnRoute = method === METHOD_NAME_ALL251
24 unmodified lines
modified:src/router/trie-router/node.ts+9 added-7 removed
80 unmodified lines
81 return curNode82 }8384 // getHandlerSets85 private gHSets(85 #gHSets(86 node: Node<T>,87 method: string,88 nodeParams: Record<string, string>,89 params: Record<string, string>
42 unmodified lines
132 if (isLast) {133 // '/hello/*' => match '/hello'134 if (nextNode.children['*']) {135 handlerSets.push(136 ...this.gHSets(nextNode.children['*'], method, node.params, Object.create(null))136 ...this.#gHSets(nextNode.children['*'], method, node.params, Object.create(null))137 )138 }139 handlerSets.push(...this.gHSets(nextNode, method, node.params, Object.create(null)))139 handlerSets.push(...this.#gHSets(nextNode, method, node.params, Object.create(null)))140 } else {141 tempNodes.push(nextNode)142 }143 }
7 unmodified lines
151 // '/hello/*/foo' => match /hello/bar/foo152 if (pattern === '*') {153 const astNode = node.children['*']154 if (astNode) {155 handlerSets.push(...this.gHSets(astNode, method, node.params, Object.create(null)))155 handlerSets.push(...this.#gHSets(astNode, method, node.params, Object.create(null)))156 tempNodes.push(astNode)157 }158 continue159 }
9 unmodified lines
169 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js170 const restPathString = parts.slice(i).join('/')171 if (matcher instanceof RegExp && matcher.test(restPathString)) {172 params[name] = restPathString173 handlerSets.push(...this.gHSets(child, method, node.params, params))173 handlerSets.push(...this.#gHSets(child, method, node.params, params))174 continue175 }176177 if (matcher === true || matcher.test(part)) {178 if (typeof key === 'string') {179 params[name] = part180 if (isLast) {181 handlerSets.push(...this.gHSets(child, method, params, node.params))181 handlerSets.push(...this.#gHSets(child, method, params, node.params))182 if (child.children['*']) {183 handlerSets.push(...this.gHSets(child.children['*'], method, params, node.params))183 handlerSets.push(184 ...this.#gHSets(child.children['*'], method, params, node.params)185 )186 }187 } else {188 child.params = params189 tempNodes.push(child)
15 unmodified lines
modified:src/context.ts+13 added-11 removed
621 unmodified lines
622 }623 return Object.fromEntries(this.#var)624 }625626 newResponse: NewResponse = (626 #newResponse(627 data: Data | null,628 arg?: StatusCode | ResponseInit,629 headers?: HeaderRecord630 ): Response => {630 ): Response {631 // Optimized632 if (this.#isFresh && !headers && !arg && this.#status === 200) {633 return new Response(data, {634 headers: this.#preparedHeaders,
53 unmodified lines
688 headers: this.#headers,689 })690 }691692 newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))693694 /**695 * `.body()` can return the HTTP response.696 * You can set headers with `.header()` and set HTTP status code with `.status`.697 * This can also be set in `.text()`, `.json()` and so on.
19 unmodified lines
717 arg?: StatusCode | ResponseInit,718 headers?: HeaderRecord719 ): Response => {720 return typeof arg === 'number'719 ? this.newResponse(data, arg, headers)720 : this.newResponse(data, arg)721 ? this.#newResponse(data, arg, headers)722 : this.#newResponse(data, arg)723 }724725 /**726 * `.text()` can render text as `Content-Type:text/plain`.
23 unmodified lines
750 }751 this.#preparedHeaders['content-type'] = TEXT_PLAIN752 // @ts-expect-error `Response` due to missing some types-only keys753 return typeof arg === 'number'752 ? this.newResponse(text, arg, headers)753 : this.newResponse(text, arg)754 ? this.#newResponse(text, arg, headers)755 : this.#newResponse(text, arg)756 }757758 /**759 * `.json()` can render JSON as `Content-Type:application/json`.
19 unmodified lines
779 this.#preparedHeaders ??= {}780 this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'781 /* eslint-disable @typescript-eslint/no-explicit-any */782 return (781 typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)783 typeof arg === 'number' ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg)784 ) as any785 }786787 html: HTMLRespond = (
6 unmodified lines
794795 if (typeof html === 'object') {796 return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html) => {797 return typeof arg === 'number'796 ? this.newResponse(html, arg, headers)797 : this.newResponse(html, arg)798 ? this.#newResponse(html, arg, headers)799 : this.#newResponse(html, arg)800 })801 }802803 return typeof arg === 'number'802 ? this.newResponse(html as string, arg, headers)803 : this.newResponse(html as string, arg)804 ? this.#newResponse(html as string, arg, headers)805 : this.#newResponse(html as string, arg)806 }807808 /**809 * `.redirect()` can Redirect, default status code is 302.
39 unmodified lines
modified:src/hono-base.ts+29 added-29 removed
128 unmodified lines
129 this[method] = (args1: string | H, ...args: H[]) => {130 if (typeof args1 === 'string') {131 this.#path = args1132 } else {133 this.addRoute(method, this.#path, args1)133 this.#addRoute(method, this.#path, args1)134 }135 args.forEach((handler) => {136 if (typeof handler !== 'string') {137 this.addRoute(method, this.#path, handler)137 this.#addRoute(method, this.#path, handler)138 }139 })140 return this as any141 }
4 unmodified lines
146 for (const p of [path].flat()) {147 this.#path = p148 for (const m of [method].flat()) {149 handlers.map((handler) => {150 this.addRoute(m.toUpperCase(), this.#path, handler)150 this.#addRoute(m.toUpperCase(), this.#path, handler)151 })152 }153 }154 return this as any
7 unmodified lines
162 this.#path = '*'163 handlers.unshift(arg1)164 }165 handlers.forEach((handler) => {166 this.addRoute(METHOD_NAME_ALL, this.#path, handler)166 this.#addRoute(METHOD_NAME_ALL, this.#path, handler)167 })168 return this as any169 }170
2 unmodified lines
173 Object.assign(this, options)174 this.getPath = strict ? options.getPath ?? getPath : getPathNoStrict175 }176177 private clone(): Hono<E, S, BasePath> {177 #clone(): Hono<E, S, BasePath> {178 const clone = new Hono<E, S, BasePath>({179 router: this.router,180 getPath: this.getPath,181 })182 clone.routes = this.routes183 return clone184 }185186 private notFoundHandler: NotFoundHandler = notFoundHandler187 private errorHandler: ErrorHandler = errorHandler186 #notFoundHandler: NotFoundHandler = notFoundHandler187 #errorHandler: ErrorHandler = errorHandler188189 /**190 * `.route()` allows grouping other Hono instance in routes.191 *
23 unmodified lines
215 ): Hono<E, MergeSchemaPath<SubSchema, MergePath<BasePath, SubPath>> | S, BasePath> {216 const subApp = this.basePath(path)217 app.routes.map((r) => {218 let handler219 if (app.errorHandler === errorHandler) {219 if (app.#errorHandler === errorHandler) {220 handler = r.handler221 } else {222 handler = async (c: Context, next: Next) =>223 (await compose<Context>([], app.errorHandler)(c, () => r.handler(c, next))).res223 (await compose<Context>([], app.#errorHandler)(c, () => r.handler(c, next))).res224 ;(handler as any)[COMPOSED_HANDLER] = r.handler225 }226227 subApp.addRoute(r.method, r.path, handler)227 subApp.#addRoute(r.method, r.path, handler)228 })229 return this230 }231
10 unmodified lines
242 * const api = new Hono().basePath('/api')243 * ```244 */245 basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {246 const subApp = this.clone()246 const subApp = this.#clone()247 subApp._basePath = mergePath(this._basePath, path)248 return subApp249 }250
13 unmodified lines
264 * })265 * ```266 */267 onError = (handler: ErrorHandler<E>): Hono<E, S, BasePath> => {268 this.errorHandler = handler268 this.#errorHandler = handler269 return this270 }271272 /**
11 unmodified lines
284 * })285 * ```286 */287 notFound = (handler: NotFoundHandler<E>): Hono<E, S, BasePath> => {288 this.notFoundHandler = handler288 this.#notFoundHandler = handler289 return this290 }291292 /**
76 unmodified lines
369 }370371 await next()372 }373 this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)373 this.#addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)374 return this375 }376377 private addRoute(method: string, path: string, handler: H) {377 #addRoute(method: string, path: string, handler: H) {378 method = method.toUpperCase()379 path = mergePath(this._basePath, path)380 const r: RouterRoute = { path: path, method: method, handler: handler }381 this.router.add(method, path, [handler, r])382 this.routes.push(r)383 }384385 private handleError(err: unknown, c: Context<E>) {385 #handleError(err: unknown, c: Context<E>) {386 if (err instanceof Error) {387 return this.errorHandler(err, c)387 return this.#errorHandler(err, c)388 }389 throw err390 }391392 private dispatch(392 #dispatch(393 request: Request,394 executionCtx: ExecutionContext | FetchEventLike | undefined,395 env: E['Bindings'],396 method: string397 ): Response | Promise<Response> {398 // Handle HEAD method399 if (method === 'HEAD') {400 return (async () =>401 new Response(null, await this.dispatch(request, executionCtx, env, 'GET')))()401 new Response(null, await this.#dispatch(request, executionCtx, env, 'GET')))()402 }403404 const path = this.getPath(request, { env })405 const matchResult = this.router.match(method, path)
2 unmodified lines
408 path,409 matchResult,410 env,411 executionCtx,412 notFoundHandler: this.notFoundHandler,412 notFoundHandler: this.#notFoundHandler,413 })414415 // Do not `compose` if it has only one handler416 if (matchResult[0].length === 1) {417 let res: ReturnType<H>418 try {419 res = matchResult[0][0][0][0](c, async () => {420 c.res = await this.notFoundHandler(c)420 c.res = await this.#notFoundHandler(c)421 })422 } catch (err) {423 return this.handleError(err, c)423 return this.#handleError(err, c)424 }425426 return res instanceof Promise427 ? res428 .then(429 (resolved: Response | undefined) =>430 resolved || (c.finalized ? c.res : this.notFoundHandler(c))430 resolved || (c.finalized ? c.res : this.#notFoundHandler(c))431 )432 .catch((err: Error) => this.handleError(err, c))433 : res ?? this.notFoundHandler(c)432 .catch((err: Error) => this.#handleError(err, c))433 : res ?? this.#notFoundHandler(c)434 }435436 const composed = compose<Context>(matchResult[0], this.errorHandler, this.notFoundHandler)436 const composed = compose<Context>(matchResult[0], this.#errorHandler, this.#notFoundHandler)437438 return (async () => {439 try {440 const context = await composed(c)
4 unmodified lines
445 }446447 return context.res448 } catch (err) {449 return this.handleError(err, c)449 return this.#handleError(err, c)450 }451 })()452 }453
12 unmodified lines
466 request: Request,467 Env?: E['Bindings'] | {},468 executionCtx?: ExecutionContext469 ) => Response | Promise<Response> = (request, ...rest) => {470 return this.dispatch(request, rest[1], rest[0], request.method)470 return this.#dispatch(request, rest[1], rest[0], request.method)471 }472473 /**474 * `.request()` is a useful method for testing.
35 unmodified lines
510 fire = (): void => {511 // eslint-disable-next-line @typescript-eslint/ban-ts-comment512 // @ts-ignore513 addEventListener('fetch', (event: FetchEventLike): void => {514 event.respondWith(this.dispatch(event.request, event, undefined, event.request.method))514 event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method))515 })516 }517}518
1 unmodified line
modified:src/request.ts+12 added-12 removed
89 unmodified lines
90 ): string | undefined91 param(key: string): string | undefined92 param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>93 param(key?: string): unknown {94 return key ? this.getDecodedParam(key) : this.getAllDecodedParams()94 return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()95 }9697 private getDecodedParam(key: string): string | undefined {97 #getDecodedParam(key: string): string | undefined {98 const paramKey = this.#matchResult[0][this.routeIndex][1][key]99 const param = this.getParamValue(paramKey)99 const param = this.#getParamValue(paramKey)100 return param ? (/\%/.test(param) ? tryDecodeURIComponent(param) : param) : undefined101 }102103 private getAllDecodedParams(): Record<string, string> {103 #getAllDecodedParams(): Record<string, string> {104 const decoded: Record<string, string> = {}105106 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])107 for (const key of keys) {108 const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key])108 const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])109 if (value && typeof value === 'string') {110 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value111 }112 }113114 return decoded115 }116117 private getParamValue(paramKey: any): string | undefined {117 #getParamValue(paramKey: any): string | undefined {118 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey119 }120121 /**
85 unmodified lines
207 async parseBody(options?: Partial<ParseBodyOptions>) {208 return (this.bodyCache.parsedBody ??= await parseBody(this, options))209 }210211 private cachedBody = (key: keyof Body) => {211 #cachedBody = (key: keyof Body) => {212 const { bodyCache, raw } = this213 const cachedBody = bodyCache[key]214215 if (cachedBody) {
25 unmodified lines
241 * })242 * ```243 */244 json<T = any>(): Promise<T> {245 return this.cachedBody('json')245 return this.#cachedBody('json')246 }247248 /**249 * `.text()` can parse Request body of type `text/plain`
7 unmodified lines
257 * })258 * ```259 */260 text(): Promise<string> {261 return this.cachedBody('text')261 return this.#cachedBody('text')262 }263264 /**265 * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
7 unmodified lines
273 * })274 * ```275 */276 arrayBuffer(): Promise<ArrayBuffer> {277 return this.cachedBody('arrayBuffer')277 return this.#cachedBody('arrayBuffer')278 }279280 /**281 * Parses the request body as a `Blob`.
5 unmodified lines
287 * ```288 * @see https://hono.dev/docs/api/request#blob289 */290 blob(): Promise<Blob> {291 return this.cachedBody('blob')291 return this.#cachedBody('blob')292 }293294 /**295 * Parses the request body as `FormData`.
5 unmodified lines
301 * ```302 * @see https://hono.dev/docs/api/request#formdata303 */304 formData(): Promise<FormData> {305 return this.cachedBody('formData')305 return this.#cachedBody('formData')306 }307308 /**309 * Adds validated data to the request.
97 unmodified lines