refactor(SSG): separate middleware logic (#2315)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* move to middleware * move core logic * denoify
authored by watany · committed by GitHub · parent 47f5c54 · Browse files · 8 files·+1232 added−1228 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+1232 added−1228 removed
- tests:+500 added−508 removed
- other:+732 added−720 removed
Provenance
- Commit
8ef9b7b- Tree
b3b4cdb- Author
watany <76135106+watany-dev@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
47f5c54
8 files changed+1232 added−1228 removed
modified:deno_dist/helper/ssg/index.ts+2 added-360 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936012import { replaceUrlParam } from '../../client/utils.ts'import type { Context } from '../../context.ts'import type { Hono } from '../../hono.ts'import type { Env, MiddlewareHandler, Schema } from '../../types.ts'import { createPool } from '../../utils/concurrent.ts'import { getExtension } from '../../utils/mime.ts'import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'
const SSG_CONTEXT = 'HONO_SSG_CONTEXT'export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })
const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg
/** * @experimental * `FileSystemModule` is an experimental feature. * The API might be changed. */export interface FileSystemModule { writeFile(path: string, data: string | Uint8Array): Promise<void> mkdir(path: string, options: { recursive: boolean }): Promise<void | string>}
/** * @experimental * `ToSSGResult` is an experimental feature. * The API might be changed. */export interface ToSSGResult { success: boolean files: string[] error?: Error}
const generateFilePath = (routePath: string, outDir: string, mimeType: string) => { const extension = determineExtension(mimeType)
if (routePath.endsWith(`.${extension}`)) { return joinPaths(outDir, routePath) }
if (routePath === '/') { return joinPaths(outDir, `index.${extension}`) } if (routePath.endsWith('/')) { return joinPaths(outDir, routePath, `index.${extension}`) } return joinPaths(outDir, `${routePath}.${extension}`)}
const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => { const contentType = response.headers.get('Content-Type')
try { if (contentType?.includes('text') || contentType?.includes('json')) { return await response.text() } else { return await response.arrayBuffer() } } catch (error) { throw new Error( `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}` ) }}
const determineExtension = (mimeType: string): string => { switch (mimeType) { case 'text/html': return 'html' case 'text/xml': case 'application/xml': return 'xml' default: { return getExtension(mimeType) || 'html' } }}
interface SSGParam { [key: string]: string}type SSGParams = SSGParam[]
interface SSGParamsMiddleware { <E extends Env = Env>( generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams> ): MiddlewareHandler<E> <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>}
type AddedSSGDataRequest = Request & { ssgParams?: SSGParams}/** * Define SSG Route */export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => { ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c) await next()}
export type BeforeRequestHook = (req: Request) => Request | falseexport type AfterResponseHook = (res: Response) => Response | falseexport type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>
export interface ToSSGOptions { dir?: string beforeRequestHook?: BeforeRequestHook afterResponseHook?: AfterResponseHook afterGenerateHook?: AfterGenerateHook concurrency?: number}
/** * @experimental * `fetchRoutesContent` is an experimental feature. * The API might be changed. */export const fetchRoutesContent = function* < E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>( app: Hono<E, S, BasePath>, beforeRequestHook?: BeforeRequestHook, afterResponseHook?: AfterResponseHook, concurrency?: number): Generator< Promise< | Generator< Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined> > | undefined >> { const baseURL = 'http://localhost' const pool = createPool({ concurrency })
for (const route of filterStaticGenerateRoutes(app)) { // GET Route Info const thisRouteBaseURL = new URL(route.path, baseURL).toString()
let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest if (beforeRequestHook) { const maybeRequest = beforeRequestHook(forGetInfoURLRequest) if (!maybeRequest) { continue } forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest }
// eslint-disable-next-line no-async-promise-executor yield new Promise(async (resolveGetInfo, rejectGetInfo) => { try { await pool.run(() => app.fetch(forGetInfoURLRequest))
if (!forGetInfoURLRequest.ssgParams) { if (isDynamicRoute(route.path)) { resolveGetInfo(undefined) return } forGetInfoURLRequest.ssgParams = [{}] }
const requestInit = { method: forGetInfoURLRequest.method, headers: forGetInfoURLRequest.headers, }
resolveGetInfo( (function* () { for (const param of forGetInfoURLRequest.ssgParams as SSGParams) { // eslint-disable-next-line no-async-promise-executor yield new Promise(async (resolveReq, rejectReq) => { try { const replacedUrlParam = replaceUrlParam(route.path, param) let response = await pool.run(() => app.request(replacedUrlParam, requestInit, { [SSG_CONTEXT]: true, }) ) if (response === SSG_DISABLED_RESPONSE) { resolveReq(undefined) return } if (afterResponseHook) { const maybeResponse = afterResponseHook(response) if (!maybeResponse) { resolveReq(undefined) return } response = maybeResponse } const mimeType = response.headers.get('Content-Type')?.split(';')[0] || 'text/plain' const content = await parseResponseContent(response) resolveReq({ routePath: replacedUrlParam, mimeType, content, }) } catch (error) { rejectReq(error) } }) } })() ) } catch (error) { rejectGetInfo(error) } }) }}
const isDynamicRoute = (path: string): boolean => { return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))}
/** * @experimental * `saveContentToFile` is an experimental feature. * The API might be changed. */const createdDirs: Set<string> = new Set()export const saveContentToFile = async ( data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>, fsModule: FileSystemModule, outDir: string): Promise<string | undefined> => { const awaitedData = await data if (!awaitedData) { return } const { routePath, content, mimeType } = awaitedData const filePath = generateFilePath(routePath, outDir, mimeType) const dirPath = dirname(filePath)
if (!createdDirs.has(dirPath)) { await fsModule.mkdir(dirPath, { recursive: true }) createdDirs.add(dirPath) } if (typeof content === 'string') { await fsModule.writeFile(filePath, content) } else if (content instanceof ArrayBuffer) { await fsModule.writeFile(filePath, new Uint8Array(content)) } return filePath}
/** * @experimental * `ToSSGInterface` is an experimental feature. * The API might be changed. */export interface ToSSGInterface { ( // eslint-disable-next-line @typescript-eslint/no-explicit-any app: Hono<any, any, any>, fsModule: FileSystemModule, options?: ToSSGOptions ): Promise<ToSSGResult>}
/** * @experimental * `ToSSGAdaptorInterface` is an experimental feature. * The API might be changed. */export interface ToSSGAdaptorInterface< E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'> { (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>}
/** * @experimental * `toSSG` is an experimental feature. * The API might be changed. */export const toSSG: ToSSGInterface = async (app, fs, options) => { let result: ToSSGResult | undefined = undefined const getInfoPromises: Promise<unknown>[] = [] const savePromises: Promise<string | undefined>[] = [] try { const outputDir = options?.dir ?? './static' const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY
const getInfoGen = fetchRoutesContent( app, options?.beforeRequestHook, options?.afterResponseHook, concurrency ) for (const getInfo of getInfoGen) { getInfoPromises.push( getInfo.then((getContentGen) => { if (!getContentGen) { return } for (const content of getContentGen) { savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e)) } }) ) } await Promise.all(getInfoPromises) const files: string[] = [] for (const savePromise of savePromises) { const fileOrError = await savePromise if (typeof fileOrError === 'string') { files.push(fileOrError) } else if (fileOrError) { throw fileOrError } } result = { success: true, files } } catch (error) { const errorObj = error instanceof Error ? error : new Error(String(error)) result = { success: false, files: [], error: errorObj } } await options?.afterGenerateHook?.(result) return result}
/** * @experimental * `isSSGContext` is an experimental feature. * The API might be changed. */export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]
/** * @experimental * `disableSSG` is an experimental feature. * The API might be changed. */export const disableSSG = (): MiddlewareHandler => async function disableSSG(c, next) { if (isSSGContext(c)) { return SSG_DISABLED_RESPONSE } await next() }
/** * @experimental * `onlySSG` is an experimental feature. * The API might be changed. */export const onlySSG = (): MiddlewareHandler => async function onlySSG(c, next) { if (!isSSGContext(c)) { return c.notFound() } await next() }export * from './ssg.ts'export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware.ts'added:deno_dist/helper/ssg/middleware.ts+62 added
1+import type { Context } from '../../context.ts'2+import type { Env, MiddlewareHandler } from '../../types.ts'3+4+export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })6+7+interface SSGParam {8+ [key: string]: string9+}10+export type SSGParams = SSGParam[]11+12+interface SSGParamsMiddleware {13+ <E extends Env = Env>(14+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15+ ): MiddlewareHandler<E>16+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17+}18+19+export type AddedSSGDataRequest = Request & {20+ ssgParams?: SSGParams21+}22+23+/**24+ * Define SSG Route25+ */26+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28+ await next()29+}30+31+/**32+ * @experimental33+ * `isSSGContext` is an experimental feature.34+ * The API might be changed.35+ */36+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]37+38+/**39+ * @experimental40+ * `disableSSG` is an experimental feature.41+ * The API might be changed.42+ */43+export const disableSSG = (): MiddlewareHandler =>44+ async function disableSSG(c, next) {45+ if (isSSGContext(c)) {46+ return SSG_DISABLED_RESPONSE47+ }48+ await next()49+ }50+51+/**52+ * @experimental53+ * `onlySSG` is an experimental feature.54+ * The API might be changed.55+ */56+export const onlySSG = (): MiddlewareHandler =>57+ async function onlySSG(c, next) {58+ if (!isSSGContext(c)) {59+ return c.notFound()60+ }61+ await next()62+ }added:deno_dist/helper/ssg/ssg.ts+302 added
1+import { replaceUrlParam } from '../../client/utils.ts'2+import type { Hono } from '../../hono.ts'3+import type { Env, Schema } from '../../types.ts'4+import { createPool } from '../../utils/concurrent.ts'5+import { getExtension } from '../../utils/mime.ts'6+import type { AddedSSGDataRequest, SSGParams } from './middleware.ts'7+import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware.ts'8+import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'9+10+const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg11+12+/**13+ * @experimental14+ * `FileSystemModule` is an experimental feature.15+ * The API might be changed.16+ */17+export interface FileSystemModule {18+ writeFile(path: string, data: string | Uint8Array): Promise<void>19+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20+}21+22+/**23+ * @experimental24+ * `ToSSGResult` is an experimental feature.25+ * The API might be changed.26+ */27+export interface ToSSGResult {28+ success: boolean29+ files: string[]30+ error?: Error31+}32+33+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34+ const extension = determineExtension(mimeType)35+36+ if (routePath.endsWith(`.${extension}`)) {37+ return joinPaths(outDir, routePath)38+ }39+40+ if (routePath === '/') {41+ return joinPaths(outDir, `index.${extension}`)42+ }43+ if (routePath.endsWith('/')) {44+ return joinPaths(outDir, routePath, `index.${extension}`)45+ }46+ return joinPaths(outDir, `${routePath}.${extension}`)47+}48+49+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50+ const contentType = response.headers.get('Content-Type')51+52+ try {53+ if (contentType?.includes('text') || contentType?.includes('json')) {54+ return await response.text()55+ } else {56+ return await response.arrayBuffer()57+ }58+ } catch (error) {59+ throw new Error(60+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61+ )62+ }63+}64+65+const determineExtension = (mimeType: string): string => {66+ switch (mimeType) {67+ case 'text/html':68+ return 'html'69+ case 'text/xml':70+ case 'application/xml':71+ return 'xml'72+ default: {73+ return getExtension(mimeType) || 'html'74+ }75+ }76+}77+78+export type BeforeRequestHook = (req: Request) => Request | false79+export type AfterResponseHook = (res: Response) => Response | false80+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>81+82+export interface ToSSGOptions {83+ dir?: string84+ beforeRequestHook?: BeforeRequestHook85+ afterResponseHook?: AfterResponseHook86+ afterGenerateHook?: AfterGenerateHook87+ concurrency?: number88+}89+90+/**91+ * @experimental92+ * `fetchRoutesContent` is an experimental feature.93+ * The API might be changed.94+ */95+export const fetchRoutesContent = function* <96+ E extends Env = Env,97+ S extends Schema = {},98+ BasePath extends string = '/'99+>(100+ app: Hono<E, S, BasePath>,101+ beforeRequestHook?: BeforeRequestHook,102+ afterResponseHook?: AfterResponseHook,103+ concurrency?: number104+): Generator<105+ Promise<106+ | Generator<107+ Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108+ >109+ | undefined110+ >111+> {112+ const baseURL = 'http://localhost'113+ const pool = createPool({ concurrency })114+115+ for (const route of filterStaticGenerateRoutes(app)) {116+ // GET Route Info117+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()118+119+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120+ if (beforeRequestHook) {121+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122+ if (!maybeRequest) {123+ continue124+ }125+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126+ }127+128+ // eslint-disable-next-line no-async-promise-executor129+ yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130+ try {131+ await pool.run(() => app.fetch(forGetInfoURLRequest))132+133+ if (!forGetInfoURLRequest.ssgParams) {134+ if (isDynamicRoute(route.path)) {135+ resolveGetInfo(undefined)136+ return137+ }138+ forGetInfoURLRequest.ssgParams = [{}]139+ }140+141+ const requestInit = {142+ method: forGetInfoURLRequest.method,143+ headers: forGetInfoURLRequest.headers,144+ }145+146+ resolveGetInfo(147+ (function* () {148+ for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149+ // eslint-disable-next-line no-async-promise-executor150+ yield new Promise(async (resolveReq, rejectReq) => {151+ try {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await pool.run(() =>154+ app.request(replacedUrlParam, requestInit, {155+ [SSG_CONTEXT]: true,156+ })157+ )158+ if (response === SSG_DISABLED_RESPONSE) {159+ resolveReq(undefined)160+ return161+ }162+ if (afterResponseHook) {163+ const maybeResponse = afterResponseHook(response)164+ if (!maybeResponse) {165+ resolveReq(undefined)166+ return167+ }168+ response = maybeResponse169+ }170+ const mimeType =171+ response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172+ const content = await parseResponseContent(response)173+ resolveReq({174+ routePath: replacedUrlParam,175+ mimeType,176+ content,177+ })178+ } catch (error) {179+ rejectReq(error)180+ }181+ })182+ }183+ })()184+ )185+ } catch (error) {186+ rejectGetInfo(error)187+ }188+ })189+ }190+}191+192+const isDynamicRoute = (path: string): boolean => {193+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194+}195+196+/**197+ * @experimental198+ * `saveContentToFile` is an experimental feature.199+ * The API might be changed.200+ */201+const createdDirs: Set<string> = new Set()202+export const saveContentToFile = async (203+ data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204+ fsModule: FileSystemModule,205+ outDir: string206+): Promise<string | undefined> => {207+ const awaitedData = await data208+ if (!awaitedData) {209+ return210+ }211+ const { routePath, content, mimeType } = awaitedData212+ const filePath = generateFilePath(routePath, outDir, mimeType)213+ const dirPath = dirname(filePath)214+215+ if (!createdDirs.has(dirPath)) {216+ await fsModule.mkdir(dirPath, { recursive: true })217+ createdDirs.add(dirPath)218+ }219+ if (typeof content === 'string') {220+ await fsModule.writeFile(filePath, content)221+ } else if (content instanceof ArrayBuffer) {222+ await fsModule.writeFile(filePath, new Uint8Array(content))223+ }224+ return filePath225+}226+227+/**228+ * @experimental229+ * `ToSSGInterface` is an experimental feature.230+ * The API might be changed.231+ */232+export interface ToSSGInterface {233+ (234+ // eslint-disable-next-line @typescript-eslint/no-explicit-any235+ app: Hono<any, any, any>,236+ fsModule: FileSystemModule,237+ options?: ToSSGOptions238+ ): Promise<ToSSGResult>239+}240+241+/**242+ * @experimental243+ * `ToSSGAdaptorInterface` is an experimental feature.244+ * The API might be changed.245+ */246+export interface ToSSGAdaptorInterface<247+ E extends Env = Env,248+ S extends Schema = {},249+ BasePath extends string = '/'250+> {251+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252+}253+254+/**255+ * @experimental256+ * `toSSG` is an experimental feature.257+ * The API might be changed.258+ */259+export const toSSG: ToSSGInterface = async (app, fs, options) => {260+ let result: ToSSGResult | undefined = undefined261+ const getInfoPromises: Promise<unknown>[] = []262+ const savePromises: Promise<string | undefined>[] = []263+ try {264+ const outputDir = options?.dir ?? './static'265+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266+267+ const getInfoGen = fetchRoutesContent(268+ app,269+ options?.beforeRequestHook,270+ options?.afterResponseHook,271+ concurrency272+ )273+ for (const getInfo of getInfoGen) {274+ getInfoPromises.push(275+ getInfo.then((getContentGen) => {276+ if (!getContentGen) {277+ return278+ }279+ for (const content of getContentGen) {280+ savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281+ }282+ })283+ )284+ }285+ await Promise.all(getInfoPromises)286+ const files: string[] = []287+ for (const savePromise of savePromises) {288+ const fileOrError = await savePromise289+ if (typeof fileOrError === 'string') {290+ files.push(fileOrError)291+ } else if (fileOrError) {292+ throw fileOrError293+ }294+ }295+ result = { success: true, files }296+ } catch (error) {297+ const errorObj = error instanceof Error ? error : new Error(String(error))298+ result = { success: false, files: [], error: errorObj }299+ }300+ await options?.afterGenerateHook?.(result)301+ return result302+}deleted:src/helper/ssg/index.test.tsx-508 removed
1-import { beforeEach, describe, expect, it } from 'vitest'2-import { Hono } from '../../hono'3-// eslint-disable-next-line @typescript-eslint/no-unused-vars4-import { jsx } from '../../jsx'5-import { poweredBy } from '../../middleware/powered-by'6-import {7- SSG_DISABLED_RESPONSE,8- fetchRoutesContent,9- saveContentToFile,10- ssgParams,11- toSSG,12- isSSGContext,13- disableSSG,14- onlySSG,15-} from './index'16-import type {17- BeforeRequestHook,18- AfterResponseHook,19- AfterGenerateHook,20- FileSystemModule,21-} from './index'22-23-const resolveRoutesContent = async (res: ReturnType<typeof fetchRoutesContent>) => {24- const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()25- for (const getInfoPromise of res) {26- const getInfo = await getInfoPromise27- if (!getInfo) {28- continue29- }30- for (const dataPromise of getInfo) {31- const data = await dataPromise32- if (!data) {33- continue34- }35- htmlMap.set(data.routePath, {36- content: data.content,37- mimeType: data.mimeType,38- })39- }40- }41- return htmlMap42-}43-44-describe('toSSG function', () => {45- let app: Hono46- let fsMock: FileSystemModule47-48- const postParams = [{ post: '1' }, { post: '2' }]49-50- beforeEach(() => {51- app = new Hono()52- app.all('/', (c) => c.html('Hello, World!'))53- app.get('/about', (c) => c.html('About Page'))54- app.get('/about/some', (c) => c.text('About Page 2tier'))55- app.post('/about/some/thing', (c) => c.text('About Page 3tier'))56- app.get('/bravo', (c) => c.html('Bravo Page'))57- app.get('/Charlie', async (c, next) => {58- c.setRenderer((content, head) => {59- return c.html(60- <html>61- <head>62- <title>{head.title || ''}</title>63- </head>64- <body>65- <p>{content}</p>66- </body>67- </html>68- )69- })70- await next()71- })72- app.get('/Charlie', (c) => {73- return c.render('Hello!', { title: 'Charlies Page' })74- })75-76- // Included params77- app.get(78- '/post/:post',79- ssgParams(() => postParams),80- (c) => c.html(<h1>{c.req.param('post')}</h1>)81- )82-83- app.get(84- '/user/:user_id',85- ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),86- (c) => c.html(<h1>{c.req.param('user_id')}</h1>)87- )88-89- type Env = {90- Bindings: {91- FOO_DB: string92- }93- Variables: {94- FOO_VAR: string95- }96- }97-98- app.get(99- '/env-type-check',100- ssgParams<Env>((c) => {101- expectTypeOf<typeof c.env.FOO_DB>().toBeString()102- expectTypeOf<typeof c.var.FOO_VAR>().toBeString()103- return []104- })105- )106-107- fsMock = {108- writeFile: vi.fn(() => Promise.resolve()),109- mkdir: vi.fn(() => Promise.resolve()),110- }111- })112- it('Should correctly generate static HTML files for Hono routes', async () => {113- const writtenFiles: Record<string, string> = {}114- const fsMock: FileSystemModule = {115- writeFile: (path, data) => {116- writtenFiles[path] = typeof data === 'string' ? data : data.toString()117- return Promise.resolve()118- },119- mkdir: vi.fn(() => Promise.resolve()),120- }121-122- const result = await toSSG(app, fsMock, { dir: './static' })123-124- for (const postParam of postParams) {125- const html = writtenFiles[`static/post/${postParam.post}.html`]126- expect(html).toBe(`<h1>${postParam.post}</h1>`)127- }128-129- for (let i = 1; i <= 3; i++) {130- const html = writtenFiles[`static/user/${i}.html`]131- expect(html).toBe(`<h1>${i}</h1>`)132- }133-134- expect(result.files.length).toBe(10)135- expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {136- recursive: true,137- })138- })139-140- it('Should handle file system errors correctly in saveContentToFiles', async () => {141- const fsMock: FileSystemModule = {142- writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),143- mkdir: vi.fn(() => Promise.resolve()),144- }145-146- const result = await toSSG(app, fsMock, { dir: './static' })147- expect(result.success).toBe(false)148- expect(result.files).toStrictEqual([])149- expect(result.error?.message).toBe('Write error')150- })151-152- it('Should handle overall process errors correctly in toSSG', async () => {153- const fsMock: FileSystemModule = {154- writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),155- mkdir: vi.fn(() => Promise.resolve()),156- }157-158- const result = await toSSG(app, fsMock, { dir: './static' })159-160- expect(result.success).toBe(false)161- expect(result.error).toBeDefined()162- expect(result.files).toStrictEqual([])163- })164-165- it('Should correctly generate files with the expected paths', async () => {166- await toSSG(app, fsMock, { dir: './static' })167-168- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))169- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))170- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))171- expect(fsMock.writeFile).not.toHaveBeenCalledWith(172- 'static/about/some/thing.txt',173- expect.any(String)174- )175- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))176- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))177- expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))178- })179-180- it('should modify the request if the hook is provided', async () => {181- const beforeRequestHook: BeforeRequestHook = (req) => {182- if (req.method === 'GET') {183- return req184- }185- return false186- }187- const result = await toSSG(app, fsMock, { beforeRequestHook })188- expect(result.files).toHaveLength(10)189- })190-191- it('should skip the route if the request hook returns false', async () => {192- const beforeRequest: BeforeRequestHook = () => false193- const result = await toSSG(app, fsMock, { beforeRequestHook: beforeRequest })194- expect(result.success).toBe(true)195- expect(result.files).toStrictEqual([])196- })197-198- it('should modify the response if the hook is provided', async () => {199- const afterResponseHook: AfterResponseHook = (res) => {200- if (res.status === 200 || res.status === 500) {201- return res202- }203- return false204- }205- const result = await toSSG(app, fsMock, { afterResponseHook })206- expect(result.files).toHaveLength(10)207- })208-209- it('should skip the route if the response hook returns false', async () => {210- const afterResponse: AfterResponseHook = () => false211- const result = await toSSG(app, fsMock, { afterResponseHook: afterResponse })212- expect(result.success).toBe(true)213- expect(result.files).toStrictEqual([])214- })215-216- it('should execute additional processing using afterGenerateHook', async () => {217- const fsMock: FileSystemModule = {218- writeFile: vi.fn(() => Promise.resolve()),219- mkdir: vi.fn(() => Promise.resolve()),220- }221- const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {222- if (result.files) {223- result.files.forEach((file) => console.log(file))224- }225- })226-227- await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })228-229- expect(afterGenerateHookMock).toHaveBeenCalled()230- expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())231- })232-233- it('should avoid memory leak from `req.signal.addEventListener()`', async () => {234- const fsMock: FileSystemModule = {235- writeFile: vi.fn(() => Promise.resolve()),236- mkdir: vi.fn(() => Promise.resolve()),237- }238-239- const signalAddEventListener = vi.fn(() => {})240- const app = new Hono()241- app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>242- c.html(<h1>{c.req.param('post')}</h1>)243- )244- await toSSG(app, fsMock, {245- beforeRequestHook: (req) => {246- req.signal.addEventListener = signalAddEventListener247- return req248- },249- })250-251- expect(signalAddEventListener).not.toHaveBeenCalled()252- })253-})254-255-describe('fetchRoutesContent function', () => {256- let app: Hono257-258- beforeEach(() => {259- app = new Hono()260- app.get('/text', (c) => c.text('Text Response'))261- app.get('/html', (c) => c.html('<p>HTML Response</p>'))262- app.get('/json', (c) => c.json({ message: 'JSON Response' }))263- app.use('*', poweredBy())264- })265-266- it('should fetch the correct content and MIME type for each route', async () => {267- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))268-269- expect(htmlMap.get('/text')).toEqual({270- content: 'Text Response',271- mimeType: 'text/plain',272- })273- expect(htmlMap.get('/html')).toEqual({274- content: '<p>HTML Response</p>',275- mimeType: 'text/html',276- })277- expect(htmlMap.get('/json')).toEqual({278- content: '{"message":"JSON Response"}',279- mimeType: 'application/json',280- })281- })282-283- it('should skip middleware routes', async () => {284- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))285- expect(htmlMap.has('*')).toBeFalsy()286- })287-288- it('should handle errors correctly', async () => {289- vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))290- await expect(resolveRoutesContent(fetchRoutesContent(app))).rejects.toThrow('Network error')291- vi.restoreAllMocks()292- })293-})294-295-describe('saveContentToFile function', () => {296- // tar.gz, testdir/test.txt297- const gzFileBuffer = Buffer.from(298- 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',299- 'base64'300- )301- const gzFileArrayBuffer = gzFileBuffer.buffer.slice(302- gzFileBuffer.byteOffset,303- gzFileBuffer.byteLength + gzFileBuffer.byteOffset304- )305- // PNG, red dot (1x1)306- const pngFileBuffer = Buffer.from(307- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',308- 'base64'309- )310- const pngFileArrayBuffer = pngFileBuffer.buffer.slice(311- pngFileBuffer.byteOffset,312- pngFileBuffer.byteLength + pngFileBuffer.byteOffset313- )314-315- const fileData = [316- { routePath: '/', content: 'Home Page', mimeType: 'text/html' },317- { routePath: '/index.html', content: 'Home Page2', mimeType: 'text/html' },318- { routePath: '/about', content: 'About Page', mimeType: 'text/html' },319- { routePath: '/about/', content: 'About Page', mimeType: 'text/html' },320- { routePath: '/bravo/index.html', content: 'About Page', mimeType: 'text/html' },321- { routePath: '/bravo/release-4.0.0', content: 'Release 4.0.0', mimeType: 'text/html' },322- {323- routePath: '/bravo/2024.02.18-sweet-memories',324- content: 'Sweet Memories',325- mimeType: 'text/html',326- },327- { routePath: '/bravo/deep.dive.to.html', content: 'Deep Dive To HTML', mimeType: 'text/html' },328- { routePath: '/bravo/alert.js', content: 'alert("evil content")', mimeType: 'text/html' },329- { routePath: '/bravo.text/index.html', content: 'About Page', mimeType: 'text/html' },330- { routePath: '/bravo.text/', content: 'Bravo Page', mimeType: 'text/html' },331- {332- routePath: '/bravo/index.tar.gz',333- content: gzFileArrayBuffer,334- mimeType: 'application/gzip',335- },336- {337- routePath: '/bravo/dot.png',338- content: pngFileArrayBuffer,339- mimeType: 'image/png',340- },341- ]342-343- let fsMock: FileSystemModule344-345- beforeEach(() => {346- fsMock = {347- writeFile: vi.fn(() => Promise.resolve()),348- mkdir: vi.fn(() => Promise.resolve()),349- }350- })351-352- it('should correctly create files with the right content and paths', async () => {353- for (const data of fileData) {354- await saveContentToFile(Promise.resolve(data), fsMock, './static')355- }356-357- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')358- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')359- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')360- expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')361- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')362- expect(fsMock.writeFile).toHaveBeenCalledWith(363- 'static/bravo/release-4.0.0.html',364- 'Release 4.0.0'365- )366- expect(fsMock.writeFile).toHaveBeenCalledWith(367- 'static/bravo/deep.dive.to.html',368- 'Deep Dive To HTML'369- )370- expect(fsMock.writeFile).toHaveBeenCalledWith(371- 'static/bravo/2024.02.18-sweet-memories.html',372- 'Sweet Memories'373- )374- expect(fsMock.writeFile).toHaveBeenCalledWith(375- 'static/bravo/alert.js.html',376- 'alert("evil content")'377- )378- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')379- expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')380- // binary files381- expect(fsMock.writeFile).toHaveBeenCalledWith(382- 'static/bravo/index.tar.gz',383- new Uint8Array(gzFileArrayBuffer)384- )385- expect(fsMock.writeFile).toHaveBeenCalledWith(386- 'static/bravo/dot.png',387- new Uint8Array(pngFileArrayBuffer)388- )389- })390-391- it('should correctly create directories if they do not exist', async () => {392- await saveContentToFile(393- Promise.resolve({394- routePath: '/new-dir/index.html',395- content: 'New Page',396- mimeType: 'text/html',397- }),398- fsMock,399- './static'400- )401- expect(fsMock.mkdir).toHaveBeenCalledWith('static/new-dir', { recursive: true })402- })403-404- it('should handle file writing or directory creation errors', async () => {405- const fsMock: FileSystemModule = {406- writeFile: vi.fn(() => Promise.resolve()),407- mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),408- }409-410- await expect(411- saveContentToFile(412- Promise.resolve({413- routePath: '/error-dir/index.html',414- content: 'New Page',415- mimeType: 'text/html',416- }),417- fsMock,418- './static'419- )420- ).rejects.toThrow('File write error')421- })422- it('check extensions', async () => {423- for (const data of fileData) {424- await saveContentToFile(Promise.resolve(data), fsMock, './static-check-extensions')425- }426- expect(fsMock.mkdir).toHaveBeenCalledWith('static-check-extensions', { recursive: true })427- })428-})429-430-describe('Dynamic route handling', () => {431- let app: Hono432- beforeEach(() => {433- app = new Hono()434- app.get('/shops/:id', (c) => c.html('Shop Page'))435- app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))436- app.get('/foo/*', (c) => c.html('Foo Page'))437- app.get('/foo:bar', (c) => c.html('Foo Bar Page'))438- })439-440- it('should skip /shops/:id dynamic route', async () => {441- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))442- expect(htmlMap.has('/shops/:id')).toBeFalsy()443- })444-445- it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {446- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))447- expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()448- })449-450- it('should skip /foo/* dynamic route', async () => {451- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))452- expect(htmlMap.has('/foo/*')).toBeFalsy()453- })454-455- it('should not skip /foo:bar dynamic route', async () => {456- const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))457- expect(htmlMap.has('/foo:bar')).toBeTruthy()458- })459-})460-461-describe('isSSGContext()', () => {462- const app = new Hono()463- app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))464-465- const fsMock: FileSystemModule = {466- writeFile: vi.fn(() => Promise.resolve()),467- mkdir: vi.fn(() => Promise.resolve()),468- }469-470- it('Should not generate the page if disableSSG is set', async () => {471- await toSSG(app, fsMock, { dir: './static' })472- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', '<h1>SSG</h1>')473- })474-475- it('Should return 404 response if onlySSG() is set', async () => {476- const res = await app.request('/')477- expect(await res.text()).toBe('<h1>noSSG</h1>')478- })479-})480-481-describe('disableSSG/onlySSG middlewares', () => {482- const app = new Hono()483- app.get('/', (c) => c.html(<h1>Hello</h1>))484- app.get('/api', disableSSG(), (c) => c.text('an-api'))485- app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)486- app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))487-488- const fsMock: FileSystemModule = {489- writeFile: vi.fn(() => Promise.resolve()),490- mkdir: vi.fn(() => Promise.resolve()),491- }492-493- it('Should not generate the page if disableSSG is set', async () => {494- await toSSG(app, fsMock, { dir: './static' })495- expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))496- expect(fsMock.writeFile).toHaveBeenCalledWith('static/static-page.html', expect.any(String))497- expect(fsMock.writeFile).not.toHaveBeenCalledWith('static/api.html', expect.any(String))498- expect(fsMock.writeFile).not.toHaveBeenCalledWith(499- 'static/disable-by-response.html',500- expect.any(String)501- )502- })503-504- it('Should return 404 response if onlySSG() is set', async () => {505- const res = await app.request('/static-page')506- expect(res.status).toBe(404)507- })508-})modified:src/helper/ssg/index.ts+2 added-360 removed
1-import { replaceUrlParam } from '../../client/utils'2-import type { Context } from '../../context'3-import type { Hono } from '../../hono'4-import type { Env, MiddlewareHandler, Schema } from '../../types'5-import { createPool } from '../../utils/concurrent'6-import { getExtension } from '../../utils/mime'7-import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'8-9-const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10-export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })11-12-const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg13-14-/**15- * @experimental16- * `FileSystemModule` is an experimental feature.17- * The API might be changed.18- */19-export interface FileSystemModule {20- writeFile(path: string, data: string | Uint8Array): Promise<void>21- mkdir(path: string, options: { recursive: boolean }): Promise<void | string>22-}23-24-/**25- * @experimental26- * `ToSSGResult` is an experimental feature.27- * The API might be changed.28- */29-export interface ToSSGResult {30- success: boolean31- files: string[]32- error?: Error33-}34-35-const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {36- const extension = determineExtension(mimeType)37-38- if (routePath.endsWith(`.${extension}`)) {39- return joinPaths(outDir, routePath)40- }41-42- if (routePath === '/') {43- return joinPaths(outDir, `index.${extension}`)44- }45- if (routePath.endsWith('/')) {46- return joinPaths(outDir, routePath, `index.${extension}`)47- }48- return joinPaths(outDir, `${routePath}.${extension}`)49-}50-51-const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {52- const contentType = response.headers.get('Content-Type')53-54- try {55- if (contentType?.includes('text') || contentType?.includes('json')) {56- return await response.text()57- } else {58- return await response.arrayBuffer()59- }60- } catch (error) {61- throw new Error(62- `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`63- )64- }65-}66-67-const determineExtension = (mimeType: string): string => {68- switch (mimeType) {69- case 'text/html':70- return 'html'71- case 'text/xml':72- case 'application/xml':73- return 'xml'74- default: {75- return getExtension(mimeType) || 'html'76- }77- }78-}79-80-interface SSGParam {81- [key: string]: string82-}83-type SSGParams = SSGParam[]84-85-interface SSGParamsMiddleware {86- <E extends Env = Env>(87- generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>88- ): MiddlewareHandler<E>89- <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>90-}91-92-type AddedSSGDataRequest = Request & {93- ssgParams?: SSGParams94-}95-/**96- * Define SSG Route97- */98-export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {99- ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)100- await next()101-}102-103-export type BeforeRequestHook = (req: Request) => Request | false104-export type AfterResponseHook = (res: Response) => Response | false105-export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>106-107-export interface ToSSGOptions {108- dir?: string109- beforeRequestHook?: BeforeRequestHook110- afterResponseHook?: AfterResponseHook111- afterGenerateHook?: AfterGenerateHook112- concurrency?: number113-}114-115-/**116- * @experimental117- * `fetchRoutesContent` is an experimental feature.118- * The API might be changed.119- */120-export const fetchRoutesContent = function* <121- E extends Env = Env,122- S extends Schema = {},123- BasePath extends string = '/'124->(125- app: Hono<E, S, BasePath>,126- beforeRequestHook?: BeforeRequestHook,127- afterResponseHook?: AfterResponseHook,128- concurrency?: number129-): Generator<130- Promise<131- | Generator<132- Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>133- >134- | undefined135- >136-> {137- const baseURL = 'http://localhost'138- const pool = createPool({ concurrency })139-140- for (const route of filterStaticGenerateRoutes(app)) {141- // GET Route Info142- const thisRouteBaseURL = new URL(route.path, baseURL).toString()143-144- let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest145- if (beforeRequestHook) {146- const maybeRequest = beforeRequestHook(forGetInfoURLRequest)147- if (!maybeRequest) {148- continue149- }150- forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest151- }152-153- // eslint-disable-next-line no-async-promise-executor154- yield new Promise(async (resolveGetInfo, rejectGetInfo) => {155- try {156- await pool.run(() => app.fetch(forGetInfoURLRequest))157-158- if (!forGetInfoURLRequest.ssgParams) {159- if (isDynamicRoute(route.path)) {160- resolveGetInfo(undefined)161- return162- }163- forGetInfoURLRequest.ssgParams = [{}]164- }165-166- const requestInit = {167- method: forGetInfoURLRequest.method,168- headers: forGetInfoURLRequest.headers,169- }170-171- resolveGetInfo(172- (function* () {173- for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {174- // eslint-disable-next-line no-async-promise-executor175- yield new Promise(async (resolveReq, rejectReq) => {176- try {177- const replacedUrlParam = replaceUrlParam(route.path, param)178- let response = await pool.run(() =>179- app.request(replacedUrlParam, requestInit, {180- [SSG_CONTEXT]: true,181- })182- )183- if (response === SSG_DISABLED_RESPONSE) {184- resolveReq(undefined)185- return186- }187- if (afterResponseHook) {188- const maybeResponse = afterResponseHook(response)189- if (!maybeResponse) {190- resolveReq(undefined)191- return192- }193- response = maybeResponse194- }195- const mimeType =196- response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'197- const content = await parseResponseContent(response)198- resolveReq({199- routePath: replacedUrlParam,200- mimeType,201- content,202- })203- } catch (error) {204- rejectReq(error)205- }206- })207- }208- })()209- )210- } catch (error) {211- rejectGetInfo(error)212- }213- })214- }215-}216-217-const isDynamicRoute = (path: string): boolean => {218- return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))219-}220-221-/**222- * @experimental223- * `saveContentToFile` is an experimental feature.224- * The API might be changed.225- */226-const createdDirs: Set<string> = new Set()227-export const saveContentToFile = async (228- data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,229- fsModule: FileSystemModule,230- outDir: string231-): Promise<string | undefined> => {232- const awaitedData = await data233- if (!awaitedData) {234- return235- }236- const { routePath, content, mimeType } = awaitedData237- const filePath = generateFilePath(routePath, outDir, mimeType)238- const dirPath = dirname(filePath)239-240- if (!createdDirs.has(dirPath)) {241- await fsModule.mkdir(dirPath, { recursive: true })242- createdDirs.add(dirPath)243- }244- if (typeof content === 'string') {245- await fsModule.writeFile(filePath, content)246- } else if (content instanceof ArrayBuffer) {247- await fsModule.writeFile(filePath, new Uint8Array(content))248- }249- return filePath250-}251-252-/**253- * @experimental254- * `ToSSGInterface` is an experimental feature.255- * The API might be changed.256- */257-export interface ToSSGInterface {258- (259- // eslint-disable-next-line @typescript-eslint/no-explicit-any260- app: Hono<any, any, any>,261- fsModule: FileSystemModule,262- options?: ToSSGOptions263- ): Promise<ToSSGResult>264-}265-266-/**267- * @experimental268- * `ToSSGAdaptorInterface` is an experimental feature.269- * The API might be changed.270- */271-export interface ToSSGAdaptorInterface<272- E extends Env = Env,273- S extends Schema = {},274- BasePath extends string = '/'275-> {276- (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>277-}278-279-/**280- * @experimental281- * `toSSG` is an experimental feature.282- * The API might be changed.283- */284-export const toSSG: ToSSGInterface = async (app, fs, options) => {285- let result: ToSSGResult | undefined = undefined286- const getInfoPromises: Promise<unknown>[] = []287- const savePromises: Promise<string | undefined>[] = []288- try {289- const outputDir = options?.dir ?? './static'290- const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY291-292- const getInfoGen = fetchRoutesContent(293- app,294- options?.beforeRequestHook,295- options?.afterResponseHook,296- concurrency297- )298- for (const getInfo of getInfoGen) {299- getInfoPromises.push(300- getInfo.then((getContentGen) => {301- if (!getContentGen) {302- return303- }304- for (const content of getContentGen) {305- savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))306- }307- })308- )309- }310- await Promise.all(getInfoPromises)311- const files: string[] = []312- for (const savePromise of savePromises) {313- const fileOrError = await savePromise314- if (typeof fileOrError === 'string') {315- files.push(fileOrError)316- } else if (fileOrError) {317- throw fileOrError318- }319- }320- result = { success: true, files }321- } catch (error) {322- const errorObj = error instanceof Error ? error : new Error(String(error))323- result = { success: false, files: [], error: errorObj }324- }325- await options?.afterGenerateHook?.(result)326- return result327-}328-329-/**330- * @experimental331- * `isSSGContext` is an experimental feature.332- * The API might be changed.333- */334-export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]335-336-/**337- * @experimental338- * `disableSSG` is an experimental feature.339- * The API might be changed.340- */341-export const disableSSG = (): MiddlewareHandler =>342- async function disableSSG(c, next) {343- if (isSSGContext(c)) {344- return SSG_DISABLED_RESPONSE345- }346- await next()347- }348-349-/**350- * @experimental351- * `onlySSG` is an experimental feature.352- * The API might be changed.353- */354-export const onlySSG = (): MiddlewareHandler =>355- async function onlySSG(c, next) {356- if (!isSSGContext(c)) {357- return c.notFound()358- }359- await next()360- }1+export * from './ssg'2+export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'added:src/helper/ssg/middleware.ts+62 added
1+import type { Context } from '../../context'2+import type { Env, MiddlewareHandler } from '../../types'3+4+export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5+export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })6+7+interface SSGParam {8+ [key: string]: string9+}10+export type SSGParams = SSGParam[]11+12+interface SSGParamsMiddleware {13+ <E extends Env = Env>(14+ generateParams: (c: Context<E>) => SSGParams | Promise<SSGParams>15+ ): MiddlewareHandler<E>16+ <E extends Env = Env>(params: SSGParams): MiddlewareHandler<E>17+}18+19+export type AddedSSGDataRequest = Request & {20+ ssgParams?: SSGParams21+}22+23+/**24+ * Define SSG Route25+ */26+export const ssgParams: SSGParamsMiddleware = (params) => async (c, next) => {27+ ;(c.req.raw as AddedSSGDataRequest).ssgParams = Array.isArray(params) ? params : await params(c)28+ await next()29+}30+31+/**32+ * @experimental33+ * `isSSGContext` is an experimental feature.34+ * The API might be changed.35+ */36+export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]37+38+/**39+ * @experimental40+ * `disableSSG` is an experimental feature.41+ * The API might be changed.42+ */43+export const disableSSG = (): MiddlewareHandler =>44+ async function disableSSG(c, next) {45+ if (isSSGContext(c)) {46+ return SSG_DISABLED_RESPONSE47+ }48+ await next()49+ }50+51+/**52+ * @experimental53+ * `onlySSG` is an experimental feature.54+ * The API might be changed.55+ */56+export const onlySSG = (): MiddlewareHandler =>57+ async function onlySSG(c, next) {58+ if (!isSSGContext(c)) {59+ return c.notFound()60+ }61+ await next()62+ }added:src/helper/ssg/ssg.test.tsx+500 added
1+import { beforeEach, describe, expect, it } from 'vitest'2+import { Hono } from '../../hono'3+// eslint-disable-next-line @typescript-eslint/no-unused-vars4+import { jsx } from '../../jsx'5+import { poweredBy } from '../../middleware/powered-by'6+import { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'7+import { fetchRoutesContent, saveContentToFile, toSSG } from './ssg'8+import type {9+ BeforeRequestHook,10+ AfterResponseHook,11+ AfterGenerateHook,12+ FileSystemModule,13+} from './ssg'14+15+const resolveRoutesContent = async (res: ReturnType<typeof fetchRoutesContent>) => {16+ const htmlMap = new Map<string, { content: string | ArrayBuffer; mimeType: string }>()17+ for (const getInfoPromise of res) {18+ const getInfo = await getInfoPromise19+ if (!getInfo) {20+ continue21+ }22+ for (const dataPromise of getInfo) {23+ const data = await dataPromise24+ if (!data) {25+ continue26+ }27+ htmlMap.set(data.routePath, {28+ content: data.content,29+ mimeType: data.mimeType,30+ })31+ }32+ }33+ return htmlMap34+}35+36+describe('toSSG function', () => {37+ let app: Hono38+ let fsMock: FileSystemModule39+40+ const postParams = [{ post: '1' }, { post: '2' }]41+42+ beforeEach(() => {43+ app = new Hono()44+ app.all('/', (c) => c.html('Hello, World!'))45+ app.get('/about', (c) => c.html('About Page'))46+ app.get('/about/some', (c) => c.text('About Page 2tier'))47+ app.post('/about/some/thing', (c) => c.text('About Page 3tier'))48+ app.get('/bravo', (c) => c.html('Bravo Page'))49+ app.get('/Charlie', async (c, next) => {50+ c.setRenderer((content, head) => {51+ return c.html(52+ <html>53+ <head>54+ <title>{head.title || ''}</title>55+ </head>56+ <body>57+ <p>{content}</p>58+ </body>59+ </html>60+ )61+ })62+ await next()63+ })64+ app.get('/Charlie', (c) => {65+ return c.render('Hello!', { title: 'Charlies Page' })66+ })67+68+ // Included params69+ app.get(70+ '/post/:post',71+ ssgParams(() => postParams),72+ (c) => c.html(<h1>{c.req.param('post')}</h1>)73+ )74+75+ app.get(76+ '/user/:user_id',77+ ssgParams([{ user_id: '1' }, { user_id: '2' }, { user_id: '3' }]),78+ (c) => c.html(<h1>{c.req.param('user_id')}</h1>)79+ )80+81+ type Env = {82+ Bindings: {83+ FOO_DB: string84+ }85+ Variables: {86+ FOO_VAR: string87+ }88+ }89+90+ app.get(91+ '/env-type-check',92+ ssgParams<Env>((c) => {93+ expectTypeOf<typeof c.env.FOO_DB>().toBeString()94+ expectTypeOf<typeof c.var.FOO_VAR>().toBeString()95+ return []96+ })97+ )98+99+ fsMock = {100+ writeFile: vi.fn(() => Promise.resolve()),101+ mkdir: vi.fn(() => Promise.resolve()),102+ }103+ })104+ it('Should correctly generate static HTML files for Hono routes', async () => {105+ const writtenFiles: Record<string, string> = {}106+ const fsMock: FileSystemModule = {107+ writeFile: (path, data) => {108+ writtenFiles[path] = typeof data === 'string' ? data : data.toString()109+ return Promise.resolve()110+ },111+ mkdir: vi.fn(() => Promise.resolve()),112+ }113+114+ const result = await toSSG(app, fsMock, { dir: './static' })115+116+ for (const postParam of postParams) {117+ const html = writtenFiles[`static/post/${postParam.post}.html`]118+ expect(html).toBe(`<h1>${postParam.post}</h1>`)119+ }120+121+ for (let i = 1; i <= 3; i++) {122+ const html = writtenFiles[`static/user/${i}.html`]123+ expect(html).toBe(`<h1>${i}</h1>`)124+ }125+126+ expect(result.files.length).toBe(10)127+ expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {128+ recursive: true,129+ })130+ })131+132+ it('Should handle file system errors correctly in saveContentToFiles', async () => {133+ const fsMock: FileSystemModule = {134+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),135+ mkdir: vi.fn(() => Promise.resolve()),136+ }137+138+ const result = await toSSG(app, fsMock, { dir: './static' })139+ expect(result.success).toBe(false)140+ expect(result.files).toStrictEqual([])141+ expect(result.error?.message).toBe('Write error')142+ })143+144+ it('Should handle overall process errors correctly in toSSG', async () => {145+ const fsMock: FileSystemModule = {146+ writeFile: vi.fn(() => Promise.reject(new Error('Write error'))),147+ mkdir: vi.fn(() => Promise.resolve()),148+ }149+150+ const result = await toSSG(app, fsMock, { dir: './static' })151+152+ expect(result.success).toBe(false)153+ expect(result.error).toBeDefined()154+ expect(result.files).toStrictEqual([])155+ })156+157+ it('Should correctly generate files with the expected paths', async () => {158+ await toSSG(app, fsMock, { dir: './static' })159+160+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))161+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))162+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/some.txt', expect.any(String))163+ expect(fsMock.writeFile).not.toHaveBeenCalledWith(164+ 'static/about/some/thing.txt',165+ expect.any(String)166+ )167+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', expect.any(String))168+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.html', expect.any(String))169+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/Charlie.html', expect.any(String))170+ })171+172+ it('should modify the request if the hook is provided', async () => {173+ const beforeRequestHook: BeforeRequestHook = (req) => {174+ if (req.method === 'GET') {175+ return req176+ }177+ return false178+ }179+ const result = await toSSG(app, fsMock, { beforeRequestHook })180+ expect(result.files).toHaveLength(10)181+ })182+183+ it('should skip the route if the request hook returns false', async () => {184+ const beforeRequest: BeforeRequestHook = () => false185+ const result = await toSSG(app, fsMock, { beforeRequestHook: beforeRequest })186+ expect(result.success).toBe(true)187+ expect(result.files).toStrictEqual([])188+ })189+190+ it('should modify the response if the hook is provided', async () => {191+ const afterResponseHook: AfterResponseHook = (res) => {192+ if (res.status === 200 || res.status === 500) {193+ return res194+ }195+ return false196+ }197+ const result = await toSSG(app, fsMock, { afterResponseHook })198+ expect(result.files).toHaveLength(10)199+ })200+201+ it('should skip the route if the response hook returns false', async () => {202+ const afterResponse: AfterResponseHook = () => false203+ const result = await toSSG(app, fsMock, { afterResponseHook: afterResponse })204+ expect(result.success).toBe(true)205+ expect(result.files).toStrictEqual([])206+ })207+208+ it('should execute additional processing using afterGenerateHook', async () => {209+ const fsMock: FileSystemModule = {210+ writeFile: vi.fn(() => Promise.resolve()),211+ mkdir: vi.fn(() => Promise.resolve()),212+ }213+ const afterGenerateHookMock: AfterGenerateHook = vi.fn((result) => {214+ if (result.files) {215+ result.files.forEach((file) => console.log(file))216+ }217+ })218+219+ await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })220+221+ expect(afterGenerateHookMock).toHaveBeenCalled()222+ expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())223+ })224+225+ it('should avoid memory leak from `req.signal.addEventListener()`', async () => {226+ const fsMock: FileSystemModule = {227+ writeFile: vi.fn(() => Promise.resolve()),228+ mkdir: vi.fn(() => Promise.resolve()),229+ }230+231+ const signalAddEventListener = vi.fn(() => {})232+ const app = new Hono()233+ app.get('/post/:post', ssgParams([{ post: '1' }, { post: '2' }]), (c) =>234+ c.html(<h1>{c.req.param('post')}</h1>)235+ )236+ await toSSG(app, fsMock, {237+ beforeRequestHook: (req) => {238+ req.signal.addEventListener = signalAddEventListener239+ return req240+ },241+ })242+243+ expect(signalAddEventListener).not.toHaveBeenCalled()244+ })245+})246+247+describe('fetchRoutesContent function', () => {248+ let app: Hono249+250+ beforeEach(() => {251+ app = new Hono()252+ app.get('/text', (c) => c.text('Text Response'))253+ app.get('/html', (c) => c.html('<p>HTML Response</p>'))254+ app.get('/json', (c) => c.json({ message: 'JSON Response' }))255+ app.use('*', poweredBy())256+ })257+258+ it('should fetch the correct content and MIME type for each route', async () => {259+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))260+261+ expect(htmlMap.get('/text')).toEqual({262+ content: 'Text Response',263+ mimeType: 'text/plain',264+ })265+ expect(htmlMap.get('/html')).toEqual({266+ content: '<p>HTML Response</p>',267+ mimeType: 'text/html',268+ })269+ expect(htmlMap.get('/json')).toEqual({270+ content: '{"message":"JSON Response"}',271+ mimeType: 'application/json',272+ })273+ })274+275+ it('should skip middleware routes', async () => {276+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))277+ expect(htmlMap.has('*')).toBeFalsy()278+ })279+280+ it('should handle errors correctly', async () => {281+ vi.spyOn(app, 'fetch').mockRejectedValue(new Error('Network error'))282+ await expect(resolveRoutesContent(fetchRoutesContent(app))).rejects.toThrow('Network error')283+ vi.restoreAllMocks()284+ })285+})286+287+describe('saveContentToFile function', () => {288+ // tar.gz, testdir/test.txt289+ const gzFileBuffer = Buffer.from(290+ 'H4sIAAAAAAAAA+3SQQrCMBSE4aw9RU6gSc3LO0/FLgqukgj29qZgsQgqCEHE/9vMIoEMTMqQy3FMO9OQq1RkTq/i1rkwPkiMUXWvnXG+U/XGSstSi3MufbLWHIZ0mvLYP7v37vxHldv+c27LpbR4Yx44hvBi/3DfX3zdP0j9Eta1KPPoz/ef+mnz7Q4AAAAAAAAAAAAAAAAAPnMFqt1/BQAoAAA=',291+ 'base64'292+ )293+ const gzFileArrayBuffer = gzFileBuffer.buffer.slice(294+ gzFileBuffer.byteOffset,295+ gzFileBuffer.byteLength + gzFileBuffer.byteOffset296+ )297+ // PNG, red dot (1x1)298+ const pngFileBuffer = Buffer.from(299+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCCAAAALw',300+ 'base64'301+ )302+ const pngFileArrayBuffer = pngFileBuffer.buffer.slice(303+ pngFileBuffer.byteOffset,304+ pngFileBuffer.byteLength + pngFileBuffer.byteOffset305+ )306+307+ const fileData = [308+ { routePath: '/', content: 'Home Page', mimeType: 'text/html' },309+ { routePath: '/index.html', content: 'Home Page2', mimeType: 'text/html' },310+ { routePath: '/about', content: 'About Page', mimeType: 'text/html' },311+ { routePath: '/about/', content: 'About Page', mimeType: 'text/html' },312+ { routePath: '/bravo/index.html', content: 'About Page', mimeType: 'text/html' },313+ { routePath: '/bravo/release-4.0.0', content: 'Release 4.0.0', mimeType: 'text/html' },314+ {315+ routePath: '/bravo/2024.02.18-sweet-memories',316+ content: 'Sweet Memories',317+ mimeType: 'text/html',318+ },319+ { routePath: '/bravo/deep.dive.to.html', content: 'Deep Dive To HTML', mimeType: 'text/html' },320+ { routePath: '/bravo/alert.js', content: 'alert("evil content")', mimeType: 'text/html' },321+ { routePath: '/bravo.text/index.html', content: 'About Page', mimeType: 'text/html' },322+ { routePath: '/bravo.text/', content: 'Bravo Page', mimeType: 'text/html' },323+ {324+ routePath: '/bravo/index.tar.gz',325+ content: gzFileArrayBuffer,326+ mimeType: 'application/gzip',327+ },328+ {329+ routePath: '/bravo/dot.png',330+ content: pngFileArrayBuffer,331+ mimeType: 'image/png',332+ },333+ ]334+335+ let fsMock: FileSystemModule336+337+ beforeEach(() => {338+ fsMock = {339+ writeFile: vi.fn(() => Promise.resolve()),340+ mkdir: vi.fn(() => Promise.resolve()),341+ }342+ })343+344+ it('should correctly create files with the right content and paths', async () => {345+ for (const data of fileData) {346+ await saveContentToFile(Promise.resolve(data), fsMock, './static')347+ }348+349+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page')350+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', 'Home Page2')351+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about.html', 'About Page')352+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/about/index.html', 'About Page')353+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo/index.html', 'About Page')354+ expect(fsMock.writeFile).toHaveBeenCalledWith(355+ 'static/bravo/release-4.0.0.html',356+ 'Release 4.0.0'357+ )358+ expect(fsMock.writeFile).toHaveBeenCalledWith(359+ 'static/bravo/deep.dive.to.html',360+ 'Deep Dive To HTML'361+ )362+ expect(fsMock.writeFile).toHaveBeenCalledWith(363+ 'static/bravo/2024.02.18-sweet-memories.html',364+ 'Sweet Memories'365+ )366+ expect(fsMock.writeFile).toHaveBeenCalledWith(367+ 'static/bravo/alert.js.html',368+ 'alert("evil content")'369+ )370+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'About Page')371+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/bravo.text/index.html', 'Bravo Page')372+ // binary files373+ expect(fsMock.writeFile).toHaveBeenCalledWith(374+ 'static/bravo/index.tar.gz',375+ new Uint8Array(gzFileArrayBuffer)376+ )377+ expect(fsMock.writeFile).toHaveBeenCalledWith(378+ 'static/bravo/dot.png',379+ new Uint8Array(pngFileArrayBuffer)380+ )381+ })382+383+ it('should correctly create directories if they do not exist', async () => {384+ await saveContentToFile(385+ Promise.resolve({386+ routePath: '/new-dir/index.html',387+ content: 'New Page',388+ mimeType: 'text/html',389+ }),390+ fsMock,391+ './static'392+ )393+ expect(fsMock.mkdir).toHaveBeenCalledWith('static/new-dir', { recursive: true })394+ })395+396+ it('should handle file writing or directory creation errors', async () => {397+ const fsMock: FileSystemModule = {398+ writeFile: vi.fn(() => Promise.resolve()),399+ mkdir: vi.fn(() => Promise.reject(new Error('File write error'))),400+ }401+402+ await expect(403+ saveContentToFile(404+ Promise.resolve({405+ routePath: '/error-dir/index.html',406+ content: 'New Page',407+ mimeType: 'text/html',408+ }),409+ fsMock,410+ './static'411+ )412+ ).rejects.toThrow('File write error')413+ })414+ it('check extensions', async () => {415+ for (const data of fileData) {416+ await saveContentToFile(Promise.resolve(data), fsMock, './static-check-extensions')417+ }418+ expect(fsMock.mkdir).toHaveBeenCalledWith('static-check-extensions', { recursive: true })419+ })420+})421+422+describe('Dynamic route handling', () => {423+ let app: Hono424+ beforeEach(() => {425+ app = new Hono()426+ app.get('/shops/:id', (c) => c.html('Shop Page'))427+ app.get('/shops/:id/:comments([0-9]+)', (c) => c.html('Comments Page'))428+ app.get('/foo/*', (c) => c.html('Foo Page'))429+ app.get('/foo:bar', (c) => c.html('Foo Bar Page'))430+ })431+432+ it('should skip /shops/:id dynamic route', async () => {433+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))434+ expect(htmlMap.has('/shops/:id')).toBeFalsy()435+ })436+437+ it('should skip /shops/:id/:comments([0-9]+) dynamic route', async () => {438+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))439+ expect(htmlMap.has('/shops/:id/:comments([0-9]+)')).toBeFalsy()440+ })441+442+ it('should skip /foo/* dynamic route', async () => {443+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))444+ expect(htmlMap.has('/foo/*')).toBeFalsy()445+ })446+447+ it('should not skip /foo:bar dynamic route', async () => {448+ const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))449+ expect(htmlMap.has('/foo:bar')).toBeTruthy()450+ })451+})452+453+describe('isSSGContext()', () => {454+ const app = new Hono()455+ app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))456+457+ const fsMock: FileSystemModule = {458+ writeFile: vi.fn(() => Promise.resolve()),459+ mkdir: vi.fn(() => Promise.resolve()),460+ }461+462+ it('Should not generate the page if disableSSG is set', async () => {463+ await toSSG(app, fsMock, { dir: './static' })464+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', '<h1>SSG</h1>')465+ })466+467+ it('Should return 404 response if onlySSG() is set', async () => {468+ const res = await app.request('/')469+ expect(await res.text()).toBe('<h1>noSSG</h1>')470+ })471+})472+473+describe('disableSSG/onlySSG middlewares', () => {474+ const app = new Hono()475+ app.get('/', (c) => c.html(<h1>Hello</h1>))476+ app.get('/api', disableSSG(), (c) => c.text('an-api'))477+ app.get('/disable-by-response', () => SSG_DISABLED_RESPONSE)478+ app.get('/static-page', onlySSG(), (c) => c.html(<h1>Welcome to my site</h1>))479+480+ const fsMock: FileSystemModule = {481+ writeFile: vi.fn(() => Promise.resolve()),482+ mkdir: vi.fn(() => Promise.resolve()),483+ }484+485+ it('Should not generate the page if disableSSG is set', async () => {486+ await toSSG(app, fsMock, { dir: './static' })487+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/index.html', expect.any(String))488+ expect(fsMock.writeFile).toHaveBeenCalledWith('static/static-page.html', expect.any(String))489+ expect(fsMock.writeFile).not.toHaveBeenCalledWith('static/api.html', expect.any(String))490+ expect(fsMock.writeFile).not.toHaveBeenCalledWith(491+ 'static/disable-by-response.html',492+ expect.any(String)493+ )494+ })495+496+ it('Should return 404 response if onlySSG() is set', async () => {497+ const res = await app.request('/static-page')498+ expect(res.status).toBe(404)499+ })500+})added:src/helper/ssg/ssg.ts+302 added
1+import { replaceUrlParam } from '../../client/utils'2+import type { Hono } from '../../hono'3+import type { Env, Schema } from '../../types'4+import { createPool } from '../../utils/concurrent'5+import { getExtension } from '../../utils/mime'6+import type { AddedSSGDataRequest, SSGParams } from './middleware'7+import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware'8+import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'9+10+const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg11+12+/**13+ * @experimental14+ * `FileSystemModule` is an experimental feature.15+ * The API might be changed.16+ */17+export interface FileSystemModule {18+ writeFile(path: string, data: string | Uint8Array): Promise<void>19+ mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20+}21+22+/**23+ * @experimental24+ * `ToSSGResult` is an experimental feature.25+ * The API might be changed.26+ */27+export interface ToSSGResult {28+ success: boolean29+ files: string[]30+ error?: Error31+}32+33+const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34+ const extension = determineExtension(mimeType)35+36+ if (routePath.endsWith(`.${extension}`)) {37+ return joinPaths(outDir, routePath)38+ }39+40+ if (routePath === '/') {41+ return joinPaths(outDir, `index.${extension}`)42+ }43+ if (routePath.endsWith('/')) {44+ return joinPaths(outDir, routePath, `index.${extension}`)45+ }46+ return joinPaths(outDir, `${routePath}.${extension}`)47+}48+49+const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50+ const contentType = response.headers.get('Content-Type')51+52+ try {53+ if (contentType?.includes('text') || contentType?.includes('json')) {54+ return await response.text()55+ } else {56+ return await response.arrayBuffer()57+ }58+ } catch (error) {59+ throw new Error(60+ `Error processing response: ${error instanceof Error ? error.message : 'Unknown error'}`61+ )62+ }63+}64+65+const determineExtension = (mimeType: string): string => {66+ switch (mimeType) {67+ case 'text/html':68+ return 'html'69+ case 'text/xml':70+ case 'application/xml':71+ return 'xml'72+ default: {73+ return getExtension(mimeType) || 'html'74+ }75+ }76+}77+78+export type BeforeRequestHook = (req: Request) => Request | false79+export type AfterResponseHook = (res: Response) => Response | false80+export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>81+82+export interface ToSSGOptions {83+ dir?: string84+ beforeRequestHook?: BeforeRequestHook85+ afterResponseHook?: AfterResponseHook86+ afterGenerateHook?: AfterGenerateHook87+ concurrency?: number88+}89+90+/**91+ * @experimental92+ * `fetchRoutesContent` is an experimental feature.93+ * The API might be changed.94+ */95+export const fetchRoutesContent = function* <96+ E extends Env = Env,97+ S extends Schema = {},98+ BasePath extends string = '/'99+>(100+ app: Hono<E, S, BasePath>,101+ beforeRequestHook?: BeforeRequestHook,102+ afterResponseHook?: AfterResponseHook,103+ concurrency?: number104+): Generator<105+ Promise<106+ | Generator<107+ Promise<{ routePath: string; mimeType: string; content: string | ArrayBuffer } | undefined>108+ >109+ | undefined110+ >111+> {112+ const baseURL = 'http://localhost'113+ const pool = createPool({ concurrency })114+115+ for (const route of filterStaticGenerateRoutes(app)) {116+ // GET Route Info117+ const thisRouteBaseURL = new URL(route.path, baseURL).toString()118+119+ let forGetInfoURLRequest = new Request(thisRouteBaseURL) as AddedSSGDataRequest120+ if (beforeRequestHook) {121+ const maybeRequest = beforeRequestHook(forGetInfoURLRequest)122+ if (!maybeRequest) {123+ continue124+ }125+ forGetInfoURLRequest = maybeRequest as unknown as AddedSSGDataRequest126+ }127+128+ // eslint-disable-next-line no-async-promise-executor129+ yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130+ try {131+ await pool.run(() => app.fetch(forGetInfoURLRequest))132+133+ if (!forGetInfoURLRequest.ssgParams) {134+ if (isDynamicRoute(route.path)) {135+ resolveGetInfo(undefined)136+ return137+ }138+ forGetInfoURLRequest.ssgParams = [{}]139+ }140+141+ const requestInit = {142+ method: forGetInfoURLRequest.method,143+ headers: forGetInfoURLRequest.headers,144+ }145+146+ resolveGetInfo(147+ (function* () {148+ for (const param of forGetInfoURLRequest.ssgParams as SSGParams) {149+ // eslint-disable-next-line no-async-promise-executor150+ yield new Promise(async (resolveReq, rejectReq) => {151+ try {152+ const replacedUrlParam = replaceUrlParam(route.path, param)153+ let response = await pool.run(() =>154+ app.request(replacedUrlParam, requestInit, {155+ [SSG_CONTEXT]: true,156+ })157+ )158+ if (response === SSG_DISABLED_RESPONSE) {159+ resolveReq(undefined)160+ return161+ }162+ if (afterResponseHook) {163+ const maybeResponse = afterResponseHook(response)164+ if (!maybeResponse) {165+ resolveReq(undefined)166+ return167+ }168+ response = maybeResponse169+ }170+ const mimeType =171+ response.headers.get('Content-Type')?.split(';')[0] || 'text/plain'172+ const content = await parseResponseContent(response)173+ resolveReq({174+ routePath: replacedUrlParam,175+ mimeType,176+ content,177+ })178+ } catch (error) {179+ rejectReq(error)180+ }181+ })182+ }183+ })()184+ )185+ } catch (error) {186+ rejectGetInfo(error)187+ }188+ })189+ }190+}191+192+const isDynamicRoute = (path: string): boolean => {193+ return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194+}195+196+/**197+ * @experimental198+ * `saveContentToFile` is an experimental feature.199+ * The API might be changed.200+ */201+const createdDirs: Set<string> = new Set()202+export const saveContentToFile = async (203+ data: Promise<{ routePath: string; content: string | ArrayBuffer; mimeType: string } | undefined>,204+ fsModule: FileSystemModule,205+ outDir: string206+): Promise<string | undefined> => {207+ const awaitedData = await data208+ if (!awaitedData) {209+ return210+ }211+ const { routePath, content, mimeType } = awaitedData212+ const filePath = generateFilePath(routePath, outDir, mimeType)213+ const dirPath = dirname(filePath)214+215+ if (!createdDirs.has(dirPath)) {216+ await fsModule.mkdir(dirPath, { recursive: true })217+ createdDirs.add(dirPath)218+ }219+ if (typeof content === 'string') {220+ await fsModule.writeFile(filePath, content)221+ } else if (content instanceof ArrayBuffer) {222+ await fsModule.writeFile(filePath, new Uint8Array(content))223+ }224+ return filePath225+}226+227+/**228+ * @experimental229+ * `ToSSGInterface` is an experimental feature.230+ * The API might be changed.231+ */232+export interface ToSSGInterface {233+ (234+ // eslint-disable-next-line @typescript-eslint/no-explicit-any235+ app: Hono<any, any, any>,236+ fsModule: FileSystemModule,237+ options?: ToSSGOptions238+ ): Promise<ToSSGResult>239+}240+241+/**242+ * @experimental243+ * `ToSSGAdaptorInterface` is an experimental feature.244+ * The API might be changed.245+ */246+export interface ToSSGAdaptorInterface<247+ E extends Env = Env,248+ S extends Schema = {},249+ BasePath extends string = '/'250+> {251+ (app: Hono<E, S, BasePath>, options?: ToSSGOptions): Promise<ToSSGResult>252+}253+254+/**255+ * @experimental256+ * `toSSG` is an experimental feature.257+ * The API might be changed.258+ */259+export const toSSG: ToSSGInterface = async (app, fs, options) => {260+ let result: ToSSGResult | undefined = undefined261+ const getInfoPromises: Promise<unknown>[] = []262+ const savePromises: Promise<string | undefined>[] = []263+ try {264+ const outputDir = options?.dir ?? './static'265+ const concurrency = options?.concurrency ?? DEFAULT_CONCURRENCY266+267+ const getInfoGen = fetchRoutesContent(268+ app,269+ options?.beforeRequestHook,270+ options?.afterResponseHook,271+ concurrency272+ )273+ for (const getInfo of getInfoGen) {274+ getInfoPromises.push(275+ getInfo.then((getContentGen) => {276+ if (!getContentGen) {277+ return278+ }279+ for (const content of getContentGen) {280+ savePromises.push(saveContentToFile(content, fs, outputDir).catch((e) => e))281+ }282+ })283+ )284+ }285+ await Promise.all(getInfoPromises)286+ const files: string[] = []287+ for (const savePromise of savePromises) {288+ const fileOrError = await savePromise289+ if (typeof fileOrError === 'string') {290+ files.push(fileOrError)291+ } else if (fileOrError) {292+ throw fileOrError293+ }294+ }295+ result = { success: true, files }296+ } catch (error) {297+ const errorObj = error instanceof Error ? error : new Error(String(error))298+ result = { success: false, files: [], error: errorObj }299+ }300+ await options?.afterGenerateHook?.(result)301+ return result302+}