refactor(`utils/html`): rename `Buffer` to `StringBuffer` (#449)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent fefba4f · Browse files · 12 files·+314 added−115 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+314 added−115 removed
- tests:+72 added−8 removed
- other:+242 added−107 removed
Provenance
- Commit
9f2a270- Tree
067670d- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
fefba4f
12 files changed+314 added−115 removed
modified:deno_dist/middleware/html/index.ts+15 added-11 removed
112334456789101113121314161516171819202121222323242425262728292630313233303435323637import { escape } from '../../utils/html.ts'import { escapeToBuffer } from '../../utils/html.ts'import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'
export type HtmlEscapedString = string & { isEscaped: true }
export const raw = (value: any): HtmlEscapedString => { const escapedString = new String(value) as HtmlEscapedString escapedString.isEscaped = true
return escapedString}
export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => { let result = '' const buffer: StringBuffer = ['']
for (let i = 0, len = strings.length - 1; i < len; i++) { result += strings[i] buffer[0] += strings[i]
const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]] for (let i = 0, len = children.length; i < len; i++) { const child = children[i] if (typeof child === 'string') { escapeToBuffer(child, buffer) if (typeof child === 'boolean' || child === null || child === undefined) { } else if (typeof child === 'boolean' || child === null || child === undefined) { continue } else if (typeof child === 'object' && (child as any).isEscaped) { result += child } else if ( (typeof child === 'object' && (child as HtmlEscaped).isEscaped) || typeof child === 'number' ) { buffer[0] += child } else { result += escape(child.toString()) escapeToBuffer(child.toString(), buffer) } } } result += strings[strings.length - 1] buffer[0] += strings[strings.length - 1]
return raw(result) return raw(buffer[0])}modified:deno_dist/middleware/jsx/index.test.tsx+67 added-5 removed
1 import { Hono } from '../../hono.ts'2+import { html } from '../html/index.ts'3 import { jsx, memo, Fragment } from './index.ts'4 5+interface SiteData {6+ title: string7+ children?: any8+}9+10 describe('JSX middleware', () => {5- const app = new Hono()11+ let app: Hono12 13+ beforeEach(() => {14+ app = new Hono()15+ })16+17 it('Should render HTML strings', async () => {18 app.get('/', (c) => {19 return c.html(<h1>Hello</h1>)20 })1 unmodified line22 expect(res.status).toBe(200)23 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24 expect(await res.text()).toBe('<h1>Hello</h1>')25 })26+27+ it('Should be able to be used with html middleware', async () => {28+ const Layout = (props: SiteData) => html`<!DOCTYPE html>29+ <html>30+ <head>31+ <title>${props.title}</title>32+ </head>33+ <body>34+ ${props.children}35+ </body>36+ </html>`37+38+ const Content = (props: { siteData: SiteData; name: string }) => (39+ <Layout {...props.siteData}>40+ <h1>{props.name}</h1>41+ </Layout>42+ )43+44+ app.get('/', (c) => {45+ const props = {46+ name: 'JSX',47+ siteData: {48+ title: 'with html middleware',49+ },50+ }51+ return c.html(<Content {...props} />)52+ })53+ const res = await app.request('http://localhost/')54+ expect(res.status).toBe(200)55+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56+ expect(await res.text()).toBe(`<!DOCTYPE html>57+ <html>58+ <head>59+ <title>with html middleware</title>60+ </head>61+ <body>62+ <h1>JSX</h1>63+ </body>64+ </html>`)65+ })66 })67 68 describe('render to string', () => {69 it('Nested array', () => {28 unmodified lines98 expect(template.toString()).toBe('<span>" is allowed here</span>')99 })100 101 it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {52- expect(() => (53- <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>54- )).toThrow()102+ expect(() =>103+ (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104+ ).toThrow()105 })106 })107 108 // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored15 unmodified lines124 expect(template.toString()).toBe('<span data-hello="true">Hello</span>')125 })126 })127 78- describe('Special case for input boolean params', () => {128+ // https://html.spec.whatwg.org/#attributes-3129+ describe('Boolean attribute', () => {130 it('default prop value for checked', () => {131 const template = <input type='checkbox' checked />132 expect(template.toString()).toBe('<input type="checkbox" checked=""/>')133 })95 unmodified lines229 it('should render "false" value properly for other non-defined keys', () => {230 const template = <input type='checkbox' testkey={false} />231 expect(template.toString()).toBe('<input type="checkbox" testkey="false"/>')232 })233+234+ it('should support attributes for elements other than input', () => {235+ const template = (236+ <video controls autoplay>237+ <source src='movie.mp4' type='video/mp4' />238+ </video>239+ )240+ expect(template.toString()).toBe(241+ '<video controls="" autoplay=""><source src="movie.mp4" type="video/mp4"/></video>'242+ )243+ })244 })245 246 // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children247 describe('Functions as Children', () => {109 unmodified linesmodified:deno_dist/middleware/jsx/index.ts+135 added-55 removed
1-import { escape } from '../../utils/html.ts'2-import type { HtmlEscapedString } from '../../utils/html.ts'1+import { escapeToBuffer } from '../../utils/html.ts'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'3 4 declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {19 unmodified lines26 'source',27 'track',28 'wbr',29 ]30-const booleanAttributes = ['checked', 'selected', 'disabled', 'readonly', 'multiple']30+const booleanAttributes = [31+ 'allowfullscreen',32+ 'async',33+ 'autofocus',34+ 'autoplay',35+ 'checked',36+ 'controls',37+ 'default',38+ 'defer',39+ 'disabled',40+ 'formnovalidate',41+ 'hidden',42+ 'inert',43+ 'ismap',44+ 'itemscope',45+ 'loop',46+ 'multiple',47+ 'muted',48+ 'nomodule',49+ 'novalidate',50+ 'open',51+ 'playsinline',52+ 'readonly',53+ 'required',54+ 'reversed',55+ 'selected',56+]57 32-const newHtmlEscapedString = (str: string): HtmlEscapedString => {33- const escapedString = new String(str) as HtmlEscapedString34- escapedString.isEscaped = true35- return escapedString58+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {59+ for (let i = 0, len = children.length; i < len; i++) {60+ const child = children[i]61+ if (typeof child === 'string') {62+ escapeToBuffer(child, buffer)63+ } else if (typeof child === 'boolean' || child === null || child === undefined) {64+ continue65+ } else if (child instanceof JSXNode) {66+ child.toStringToBuffer(buffer)67+ } else if (typeof child === 'number' || (child as any).isEscaped) {68+ buffer[0] += child69+ } else {70+ // `child` type is `Child[]`, so stringify recursively71+ childrenToStringToBuffer(child, buffer)72+ }73+ }74 }75 38-export { jsxFn as jsx }39-const jsxFn = (40- tag: string | Function,41- props: Record<string, any>,42- ...children: (string | HtmlEscapedString)[]43-): HtmlEscapedString => {44- if (typeof tag === 'function') {45- return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })76+type Child = string | number | JSXNode | Child[]77+export class JSXNode implements HtmlEscaped {78+ tag: string | Function79+ props: Record<string, any>80+ children: Child[]81+ isEscaped: true = true82+ constructor(tag: string | Function, props: Record<string, any>, children: Child[]) {83+ this.tag = tag84+ this.props = props85+ this.children = children86 }87 48- let result = tag !== '' ? `<${tag}` : ''88+ toString(): string {89+ const buffer: StringBuffer = ['']90+ this.toStringToBuffer(buffer)91+ return buffer[0]92+ }93 50- const propsKeys = Object.keys(props || {})94+ toStringToBuffer(buffer: StringBuffer): void {95+ const tag = this.tag as string96+ const props = this.props97+ let { children } = this98 99+ buffer[0] += `<${tag}`100+101+ const propsKeys = Object.keys(props || {})102+103+ for (let i = 0, len = propsKeys.length; i < len; i++) {104+ const v = props[propsKeys[i]]52- for (let i = 0, len = propsKeys.length; i < len; i++) {53- const v = props[propsKeys[i]]54- if (typeof v === 'string') {55- result += ` ${propsKeys[i]}="${escape(v)}"`56- } else if (typeof v === 'number') {57- result += ` ${propsKeys[i]}="${v}"`58- } else if (v === null || v === undefined) {59- // Do nothing60- } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {61- if (v) {62- result += ` ${propsKeys[i]}=""`105+ if (typeof v === 'string') {106+ buffer[0] += ` ${propsKeys[i]}="`107+ escapeToBuffer(v, buffer)108+ buffer[0] += '"'109+ } else if (typeof v === 'number') {110+ buffer[0] += ` ${propsKeys[i]}="${v}"`111+ } else if (v === null || v === undefined) {112+ // Do nothing113+ } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {114+ if (v) {115+ buffer[0] += ` ${propsKeys[i]}=""`116+ }117+ } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {118+ if (children.length > 0) {119+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'120+ }121+122+ const escapedString = new String(v.__html) as HtmlEscapedString123+ escapedString.isEscaped = true124+ children = [escapedString]125+ } else {126+ buffer[0] += ` ${propsKeys[i]}="`127+ escapeToBuffer(v.toString(), buffer)128+ buffer[0] += '"'129 }64- } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {65- if (children.length > 0) {66- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'67- }130+ }131 69- children = [newHtmlEscapedString(v.__html)]70- } else {71- result += ` ${propsKeys[i]}="${escape(v.toString())}"`132+ if (emptyTags.includes(tag as string)) {133+ buffer[0] += '/>'134+ return135 }73- }136 75- if (emptyTags.includes(tag)) {76- result += '/>'77- return newHtmlEscapedString(result)78- }137+ buffer[0] += '>'138 80- if (tag !== '') {81- result += '>'139+ childrenToStringToBuffer(children, buffer)140+141+ buffer[0] += `</${tag}>`142 }143+}144 84- const flattenChildren = children.flat(Infinity)85- for (let i = 0, len = flattenChildren.length; i < len; i++) {86- const child = flattenChildren[i]87- if (typeof child === 'boolean' || child === null || child === undefined) {88- continue89- } else if (typeof child === 'object' && (child as any).isEscaped) {90- result += child145+class JSXFunctionNode extends JSXNode {146+ toStringToBuffer(buffer: StringBuffer): void {147+ const { children } = this148+149+ const res = (this.tag as Function).call(null, {150+ ...this.props,151+ children: children.length <= 1 ? children[0] : children,152+ })153+154+ if (res instanceof JSXNode) {155+ res.toStringToBuffer(buffer)156+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {157+ buffer[0] += res158 } else {92- result += escape(child.toString())159+ escapeToBuffer(res, buffer)160 }161 }162+}163 96- if (tag !== '') {97- result += `</${tag}>`164+class JSXFragmentNode extends JSXNode {165+ toStringToBuffer(buffer: StringBuffer): void {166+ childrenToStringToBuffer(this.children, buffer)167 }168+}169 100- return newHtmlEscapedString(result)170+export { jsxFn as jsx }171+const jsxFn = (172+ tag: string | Function,173+ props: Record<string, any>,174+ ...children: (string | HtmlEscapedString)[]175+): JSXNode => {176+ if (typeof tag === 'function') {177+ return new JSXFunctionNode(tag, props, children)178+ } else {179+ return new JSXNode(tag, props, children)180+ }181 }182 183 type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString184 31 unmodified lines216 return (computed ||= component(props))217 }) as FC<T>218 }219 140-export const Fragment = (props: { key?: string; children?: any }): HtmlEscapedString => {141- return jsxFn('', {}, ...(props.children || []))220+export const Fragment = (props: { key?: string; children?: any }): JSXNode => {221+ return new JSXFragmentNode('', {}, props.children || [])222 }modified:deno_dist/middleware/jsx/jsx-dev-runtime.ts+2 added-2 removed
1123445678import type { HtmlEscapedString } from '../html/index.ts'import { jsx } from './index.ts'import type { JSXNode } from './index.ts'
export function jsxDEV(tag: string | Function, props: Record<string, any>): HtmlEscapedString {export function jsxDEV(tag: string | Function, props: Record<string, any>): JSXNode { const children = props.children ?? [] delete props['children'] return jsx(tag, props, children)}modified:deno_dist/middleware/jwt/index.ts+19 added-13 removed
1234566789102 unmodified lines13141516171817181920212223242519202122232425262728293031323334282935363738394 unmodified lines4445464742484950515213 unmodified linesimport type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import { Jwt } from '../../utils/jwt/index.ts'import type { AlgorithmTypes } from '../../utils/jwt/types.ts'
export const jwt = (options: { secret: string; alg?: string }) => {export const jwt = (options: { secret: string; cookie?: string; alg?: string }) => { if (!options) { throw new Error('JWT auth middleware requires options for "secret') }
2 unmodified lines }
return async (ctx: Context, next: Next) => { const credentials = ctx.req.headers.get('Authorization') let token if (credentials) {
if (!credentials) { ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`, }, }) return const parts = credentials.split(/\s+/) if (parts.length !== 2) { ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`, }, }) return } else { token = parts[1] } } else if (options.cookie) { token = ctx.req.cookie(options.cookie) }
const parts = credentials.split(/\s+/) if (parts.length !== 2) { if (!token) { ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,4 unmodified lines
let authorized = false let msg = '' try { authorized = await Jwt.verify(parts[1], options.secret, options.alg as AlgorithmTypes) authorized = await Jwt.verify(token, options.secret, options.alg as AlgorithmTypes) } catch (e) { msg = `${e}` } if (!authorized) {13 unmodified linesmodified:deno_dist/utils/body.ts+3 added-3 removed
123123456719 unmodified linesexport const parseBody = async ( r: Request | Response): Promise<string | object | Record<string, string | File>> => {export type Body = string | object | Record<string, string | File>
export const parseBody = async (r: Request | Response): Promise<Body> => { const contentType = r.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) { let body = {}19 unmodified linesmodified:deno_dist/utils/html.ts+54 added-10 removed
112343456789105678910121112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657export type HtmlEscapedString = string & { isEscaped: true }export type HtmlEscaped = { isEscaped: true }export type HtmlEscapedString = string & HtmlEscapedexport type StringBuffer = [string]
const entityMap: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"',}const escapeRe = new RegExp(`[${Object.keys(entityMap).join('')}]`, 'g')const replaceFn = (m: string) => entityMap[m]// The `escape` and `escapeToBuffer` implementations are based on code from the MIT licensed `react-dom` package.// https://github.com/facebook/react/blob/main/packages/react-dom/src/server/escapeTextForBrowser.js
const escapeRe = /[&<>"]/
export const escape = (str: string): string => { return str.replace(escapeRe, replaceFn) // This function is an alias for `escapeToBuffer`, // but returns immediately if `str` does not contain the character to be escaped. const match = str.search(escapeRe) if (match === -1) { return str }
const buffer: StringBuffer = [''] escapeToBuffer(str, buffer) return buffer[0]}
export const escapeToBuffer = (str: string, buffer: StringBuffer): void => { const match = str.search(escapeRe) if (match === -1) { buffer[0] += str return }
let escape let index let lastIndex = 0
for (index = match; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"' break case 38: // & escape = '&' break case 60: // < escape = '<' break case 62: // > escape = '>' break default: continue }
buffer[0] += str.substring(lastIndex, index) + escape lastIndex = index + 1 }
buffer[0] += str.substring(lastIndex, index)}modified:deno_dist/request.ts+3 added-2 removed
1 import { parseBody } from './utils/body.ts'2+import type { Body } from './utils/body.ts'3 import type { Cookie } from './utils/cookie.ts'4 import { parse } from './utils/cookie.ts'5 6 declare global {18 unmodified lines25 cookie: {26 (name: string): string27 (): Cookie28 }28- parsedBody?: Promise<any>29+ parsedBody?: Promise<Body>30 parseBody: {30- (): Promise<any>31+ (): Promise<Body>32 }33 }34 }35 73 unmodified linesmodified:src/middleware/html/index.ts+2 added-2 removed
1 import { escapeToBuffer } from '../../utils/html'2-import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3 4 export const raw = (value: any): HtmlEscapedString => {5 const escapedString = new String(value) as HtmlEscapedString6 escapedString.isEscaped = true1 unmodified line8 return escapedString9 }10 11 export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => {12- const buffer: Buffer = ['']12+ const buffer: StringBuffer = ['']13 14 for (let i = 0, len = strings.length - 1; i < len; i++) {15 buffer[0] += strings[i]16 21 unmodified linesmodified:src/middleware/jsx/index.ts+6 added-6 removed
1 import { escapeToBuffer } from '../../utils/html'2-import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'2+import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3 4 declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {47 unmodified lines54 'reversed',55 'selected',56 ]57 58-const childrenToStringToBuffer = (children: Child[], buffer: Buffer): void => {58+const childrenToStringToBuffer = (children: Child[], buffer: StringBuffer): void => {59 for (let i = 0, len = children.length; i < len; i++) {60 const child = children[i]61 if (typeof child === 'string') {62 escapeToBuffer(child, buffer)22 unmodified lines85 this.children = children86 }87 88 toString(): string {89- const buffer: Buffer = ['']89+ const buffer: StringBuffer = ['']90 this.toStringToBuffer(buffer)91 return buffer[0]92 }93 94- toStringToBuffer(buffer: Buffer): void {94+ toStringToBuffer(buffer: StringBuffer): void {95 const tag = this.tag as string96 const props = this.props97 let { children } = this98 43 unmodified lines142 }143 }144 145 class JSXFunctionNode extends JSXNode {146- toStringToBuffer(buffer: Buffer): void {146+ toStringToBuffer(buffer: StringBuffer): void {147 const { children } = this148 149 const res = (this.tag as Function).call(null, {150 ...this.props,10 unmodified lines161 }162 }163 164 class JSXFragmentNode extends JSXNode {165- toStringToBuffer(buffer: Buffer): void {165+ toStringToBuffer(buffer: StringBuffer): void {166 childrenToStringToBuffer(this.children, buffer)167 }168 }169 53 unmodified linesmodified:src/utils/html.test.ts+5 added-3 removed
1 import { escape, escapeToBuffer } from './html'2-import type { Buffer } from './html'2+import type { StringBuffer } from './html'3 4 describe('HTML utilities', () => {5 describe('escape', () => {6 it('Should escape special characters', () => {7- expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.')7+ expect(escape('I <b>think</b> this is good.')).toBe(8+ 'I <b>think</b> this is good.'9+ )10 expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith')11 })12 })13 14 describe('escapeToBuffer', () => {15 it('Should escape special characters', () => {14- let buffer: Buffer = ['']16+ let buffer: StringBuffer = ['']17 escapeToBuffer('I <b>think</b> this is good.', buffer)18 expect(buffer[0]).toBe('I <b>think</b> this is good.')19 20 buffer = ['']5 unmodified linesmodified:src/utils/html.ts+3 added-3 removed
1 export type HtmlEscaped = { isEscaped: true }2 export type HtmlEscapedString = string & HtmlEscaped3-export type Buffer = [string]3+export type StringBuffer = [string]4 5 // The `escape` and `escapeToBuffer` implementations are based on code from the MIT licensed `react-dom` package.6 // https://github.com/facebook/react/blob/main/packages/react-dom/src/server/escapeTextForBrowser.js7 6 unmodified lines14 if (match === -1) {15 return str16 }17 18- const buffer: Buffer = ['']18+ const buffer: StringBuffer = ['']19 escapeToBuffer(str, buffer)20 return buffer[0]21 }22 23-export const escapeToBuffer = (str: string, buffer: Buffer): void => {23+export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {24 const match = str.search(escapeRe)25 if (match === -1) {26 buffer[0] += str27 return30 unmodified lines