Skip to content
Myr

html.ts

This file

Path

src/utils/html.ts

182 lines · 5.0 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–182why, one step back
1/**
2 * @module3 * HTML utility.4 */56export const HtmlEscapedCallbackPhase = {7 Stringify: 1,8 BeforeStream: 2,9 Stream: 3,10} as const11type HtmlEscapedCallbackOpts = {12 buffer?: [string]13 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]14 context: Readonly<object> // An object unique to each JSX tree. This object is used as the WeakMap key.15}16export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined17export type HtmlEscaped = {18 isEscaped: true19 callbacks?: HtmlEscapedCallback[]20}21export type HtmlEscapedString = string & HtmlEscaped2223/**24 * StringBuffer contains string and Promise<string> alternately25 * The length of the array will be odd, the odd numbered element will be a string,26 * and the even numbered element will be a Promise<string>.27 * When concatenating into a single string, it must be processed from the tail.28 * @example29 * [30 * 'framework.',31 * Promise.resolve('ultra fast'),32 * 'a ',33 * Promise.resolve('is '),34 * 'Hono',35 * ]36 */37export type StringBuffer = (string | Promise<string>)[]38export type StringBufferWithCallbacks = StringBuffer & { callbacks: HtmlEscapedCallback[] }3940export const raw = (value: unknown, callbacks?: HtmlEscapedCallback[]): HtmlEscapedString => {41 const escapedString = new String(value) as HtmlEscapedString42 escapedString.isEscaped = true43 escapedString.callbacks = callbacks4445 return escapedString46}4748// The `escapeToBuffer` implementation is based on code from the MIT licensed `react-dom` package.49// https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/server/escapeTextForBrowser.js5051const escapeRe = /[&<>'"]/5253export const stringBufferToString = async (54 buffer: StringBuffer,55 callbacks: HtmlEscapedCallback[] | undefined56): Promise<HtmlEscapedString> => {57 let str = ''58 callbacks ||= []59 const resolvedBuffer = await Promise.all(buffer)60 for (let i = resolvedBuffer.length - 1; ; i--) {61 str += resolvedBuffer[i]62 i--63 if (i < 0) {64 break65 }6667 let r = resolvedBuffer[i]68 if (typeof r === 'object') {69 callbacks.push(...((r as HtmlEscapedString).callbacks || []))70 }7172 const isEscaped = (r as HtmlEscapedString).isEscaped73 r = await (typeof r === 'object' ? (r as HtmlEscapedString).toString() : r)74 if (typeof r === 'object') {75 callbacks.push(...((r as HtmlEscapedString).callbacks || []))76 }7778 if ((r as HtmlEscapedString).isEscaped ?? isEscaped) {79 str += r80 } else {81 const buf = [str]82 escapeToBuffer(r, buf)83 str = buf[0]84 }85 }8687 return raw(str, callbacks)88}8990export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {91 const match = str.search(escapeRe)92 if (match === -1) {93 buffer[0] += str94 return95 }9697 let escape98 let index99 let lastIndex = 0100101 for (index = match; index < str.length; index++) {102 switch (str.charCodeAt(index)) {103 case 34: // "104 escape = '&quot;'105 break106 case 39: // '107 escape = '&#39;'108 break109 case 38: // &110 escape = '&amp;'111 break112 case 60: // <113 escape = '&lt;'114 break115 case 62: // >116 escape = '&gt;'117 break118 default:119 continue120 }121122 buffer[0] += str.substring(lastIndex, index) + escape123 lastIndex = index + 1124 }125126 buffer[0] += str.substring(lastIndex, index)127}128129export const resolveCallbackSync = (str: string | HtmlEscapedString): string => {130 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]131 if (!callbacks?.length) {132 return str133 }134 const buffer: [string] = [str]135 const context = {}136137 callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }))138139 return buffer[0]140}141142export const resolveCallback = async (143 str: string | HtmlEscapedString | Promise<string>,144 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],145 preserveCallbacks: boolean,146 context: object,147 buffer?: [string]148): Promise<string> => {149 if (typeof str === 'object' && !(str instanceof String)) {150 if (!((str as unknown) instanceof Promise)) {151 str = (str as unknown as string).toString() // HtmlEscapedString object to string152 }153 if ((str as string | Promise<string>) instanceof Promise) {154 str = await (str as unknown as Promise<string>)155 }156 }157158 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]159 if (!callbacks?.length) {160 return Promise.resolve(str)161 }162 if (buffer) {163 buffer[0] += str164 } else {165 buffer = [str as string]166 }167168 const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>169 Promise.all(170 res171 // eslint-disable-next-line @typescript-eslint/no-explicit-any172 .filter<string>(Boolean as any)173 .map((str) => resolveCallback(str, phase, false, context, buffer))174 ).then(() => (buffer as [string])[0])175 )176177 if (preserveCallbacks) {178 return raw(await resStr, callbacks)179 } else {180 return resStr181 }182}