Skip to content
Myr

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

8 files+1232 added−1228 removed

modified:deno_dist/helper/ssg/index.ts+2 added-360 removed
added:deno_dist/helper/ssg/middleware.ts+62 added
1import type { Context } from '../../context.ts'2import type { Env, MiddlewareHandler } from '../../types.ts'34export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })67interface SSGParam {8 [key: string]: string9}10export type SSGParams = SSGParam[]1112interface 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}1819export type AddedSSGDataRequest = Request & {20 ssgParams?: SSGParams21}2223/**24 * Define SSG Route25 */26export 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}3031/**32 * @experimental33 * `isSSGContext` is an experimental feature.34 * The API might be changed.35 */36export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]3738/**39 * @experimental40 * `disableSSG` is an experimental feature.41 * The API might be changed.42 */43export const disableSSG = (): MiddlewareHandler =>44 async function disableSSG(c, next) {45 if (isSSGContext(c)) {46 return SSG_DISABLED_RESPONSE47 }48 await next()49 }5051/**52 * @experimental53 * `onlySSG` is an experimental feature.54 * The API might be changed.55 */56export 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
1import { replaceUrlParam } from '../../client/utils.ts'2import type { Hono } from '../../hono.ts'3import type { Env, Schema } from '../../types.ts'4import { createPool } from '../../utils/concurrent.ts'5import { getExtension } from '../../utils/mime.ts'6import type { AddedSSGDataRequest, SSGParams } from './middleware.ts'7import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware.ts'8import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils.ts'910const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.15 * The API might be changed.16 */17export interface FileSystemModule {18 writeFile(path: string, data: string | Uint8Array): Promise<void>19 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20}2122/**23 * @experimental24 * `ToSSGResult` is an experimental feature.25 * The API might be changed.26 */27export interface ToSSGResult {28 success: boolean29 files: string[]30 error?: Error31}3233const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34 const extension = determineExtension(mimeType)3536 if (routePath.endsWith(`.${extension}`)) {37 return joinPaths(outDir, routePath)38 }3940 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}4849const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50 const contentType = response.headers.get('Content-Type')5152 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}6465const 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}7778export type BeforeRequestHook = (req: Request) => Request | false79export type AfterResponseHook = (res: Response) => Response | false80export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>8182export interface ToSSGOptions {83 dir?: string84 beforeRequestHook?: BeforeRequestHook85 afterResponseHook?: AfterResponseHook86 afterGenerateHook?: AfterGenerateHook87 concurrency?: number88}8990/**91 * @experimental92 * `fetchRoutesContent` is an experimental feature.93 * The API might be changed.94 */95export 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 })114115 for (const route of filterStaticGenerateRoutes(app)) {116 // GET Route Info117 const thisRouteBaseURL = new URL(route.path, baseURL).toString()118119 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 }127128 // eslint-disable-next-line no-async-promise-executor129 yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130 try {131 await pool.run(() => app.fetch(forGetInfoURLRequest))132133 if (!forGetInfoURLRequest.ssgParams) {134 if (isDynamicRoute(route.path)) {135 resolveGetInfo(undefined)136 return137 }138 forGetInfoURLRequest.ssgParams = [{}]139 }140141 const requestInit = {142 method: forGetInfoURLRequest.method,143 headers: forGetInfoURLRequest.headers,144 }145146 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}191192const isDynamicRoute = (path: string): boolean => {193 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194}195196/**197 * @experimental198 * `saveContentToFile` is an experimental feature.199 * The API might be changed.200 */201const createdDirs: Set<string> = new Set()202export 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)214215 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}226227/**228 * @experimental229 * `ToSSGInterface` is an experimental feature.230 * The API might be changed.231 */232export 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}240241/**242 * @experimental243 * `ToSSGAdaptorInterface` is an experimental feature.244 * The API might be changed.245 */246export 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}253254/**255 * @experimental256 * `toSSG` is an experimental feature.257 * The API might be changed.258 */259export 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_CONCURRENCY266267 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
1import { beforeEach, describe, expect, it } from 'vitest'2import { Hono } from '../../hono'3// eslint-disable-next-line @typescript-eslint/no-unused-vars4import { jsx } from '../../jsx'5import { poweredBy } from '../../middleware/powered-by'6import {7 SSG_DISABLED_RESPONSE,8 fetchRoutesContent,9 saveContentToFile,10 ssgParams,11 toSSG,12 isSSGContext,13 disableSSG,14 onlySSG,15} from './index'16import type {17 BeforeRequestHook,18 AfterResponseHook,19 AfterGenerateHook,20 FileSystemModule,21} from './index'2223const 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}4344describe('toSSG function', () => {45 let app: Hono46 let fsMock: FileSystemModule4748 const postParams = [{ post: '1' }, { post: '2' }]4950 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 })7576 // Included params77 app.get(78 '/post/:post',79 ssgParams(() => postParams),80 (c) => c.html(<h1>{c.req.param('post')}</h1>)81 )8283 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 )8889 type Env = {90 Bindings: {91 FOO_DB: string92 }93 Variables: {94 FOO_VAR: string95 }96 }9798 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 )106107 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 }121122 const result = await toSSG(app, fsMock, { dir: './static' })123124 for (const postParam of postParams) {125 const html = writtenFiles[`static/post/${postParam.post}.html`]126 expect(html).toBe(`<h1>${postParam.post}</h1>`)127 }128129 for (let i = 1; i <= 3; i++) {130 const html = writtenFiles[`static/user/${i}.html`]131 expect(html).toBe(`<h1>${i}</h1>`)132 }133134 expect(result.files.length).toBe(10)135 expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {136 recursive: true,137 })138 })139140 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 }145146 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 })151152 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 }157158 const result = await toSSG(app, fsMock, { dir: './static' })159160 expect(result.success).toBe(false)161 expect(result.error).toBeDefined()162 expect(result.files).toStrictEqual([])163 })164165 it('Should correctly generate files with the expected paths', async () => {166 await toSSG(app, fsMock, { dir: './static' })167168 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 })179180 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 })190191 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 })197198 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 })208209 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 })215216 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 })226227 await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })228229 expect(afterGenerateHookMock).toHaveBeenCalled()230 expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())231 })232233 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 }238239 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 })250251 expect(signalAddEventListener).not.toHaveBeenCalled()252 })253})254255describe('fetchRoutesContent function', () => {256 let app: Hono257258 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 })265266 it('should fetch the correct content and MIME type for each route', async () => {267 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))268269 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 })282283 it('should skip middleware routes', async () => {284 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))285 expect(htmlMap.has('*')).toBeFalsy()286 })287288 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})294295describe('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 )314315 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 ]342343 let fsMock: FileSystemModule344345 beforeEach(() => {346 fsMock = {347 writeFile: vi.fn(() => Promise.resolve()),348 mkdir: vi.fn(() => Promise.resolve()),349 }350 })351352 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 }356357 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 })390391 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 })403404 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 }409410 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})429430describe('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 })439440 it('should skip /shops/:id dynamic route', async () => {441 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))442 expect(htmlMap.has('/shops/:id')).toBeFalsy()443 })444445 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 })449450 it('should skip /foo/* dynamic route', async () => {451 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))452 expect(htmlMap.has('/foo/*')).toBeFalsy()453 })454455 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})460461describe('isSSGContext()', () => {462 const app = new Hono()463 app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))464465 const fsMock: FileSystemModule = {466 writeFile: vi.fn(() => Promise.resolve()),467 mkdir: vi.fn(() => Promise.resolve()),468 }469470 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 })474475 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})480481describe('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>))487488 const fsMock: FileSystemModule = {489 writeFile: vi.fn(() => Promise.resolve()),490 mkdir: vi.fn(() => Promise.resolve()),491 }492493 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 })503504 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
1import { replaceUrlParam } from '../../client/utils'2import type { Context } from '../../context'3import type { Hono } from '../../hono'4import type { Env, MiddlewareHandler, Schema } from '../../types'5import { createPool } from '../../utils/concurrent'6import { getExtension } from '../../utils/mime'7import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'89const SSG_CONTEXT = 'HONO_SSG_CONTEXT'10export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })1112const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg1314/**15 * @experimental16 * `FileSystemModule` is an experimental feature.17 * The API might be changed.18 */19export interface FileSystemModule {20 writeFile(path: string, data: string | Uint8Array): Promise<void>21 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>22}2324/**25 * @experimental26 * `ToSSGResult` is an experimental feature.27 * The API might be changed.28 */29export interface ToSSGResult {30 success: boolean31 files: string[]32 error?: Error33}3435const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {36 const extension = determineExtension(mimeType)3738 if (routePath.endsWith(`.${extension}`)) {39 return joinPaths(outDir, routePath)40 }4142 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}5051const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {52 const contentType = response.headers.get('Content-Type')5354 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}6667const 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}7980interface SSGParam {81 [key: string]: string82}83type SSGParams = SSGParam[]8485interface 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}9192type AddedSSGDataRequest = Request & {93 ssgParams?: SSGParams94}95/**96 * Define SSG Route97 */98export 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}102103export type BeforeRequestHook = (req: Request) => Request | false104export type AfterResponseHook = (res: Response) => Response | false105export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>106107export interface ToSSGOptions {108 dir?: string109 beforeRequestHook?: BeforeRequestHook110 afterResponseHook?: AfterResponseHook111 afterGenerateHook?: AfterGenerateHook112 concurrency?: number113}114115/**116 * @experimental117 * `fetchRoutesContent` is an experimental feature.118 * The API might be changed.119 */120export 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 })139140 for (const route of filterStaticGenerateRoutes(app)) {141 // GET Route Info142 const thisRouteBaseURL = new URL(route.path, baseURL).toString()143144 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 }152153 // eslint-disable-next-line no-async-promise-executor154 yield new Promise(async (resolveGetInfo, rejectGetInfo) => {155 try {156 await pool.run(() => app.fetch(forGetInfoURLRequest))157158 if (!forGetInfoURLRequest.ssgParams) {159 if (isDynamicRoute(route.path)) {160 resolveGetInfo(undefined)161 return162 }163 forGetInfoURLRequest.ssgParams = [{}]164 }165166 const requestInit = {167 method: forGetInfoURLRequest.method,168 headers: forGetInfoURLRequest.headers,169 }170171 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}216217const isDynamicRoute = (path: string): boolean => {218 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))219}220221/**222 * @experimental223 * `saveContentToFile` is an experimental feature.224 * The API might be changed.225 */226const createdDirs: Set<string> = new Set()227export 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)239240 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}251252/**253 * @experimental254 * `ToSSGInterface` is an experimental feature.255 * The API might be changed.256 */257export 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}265266/**267 * @experimental268 * `ToSSGAdaptorInterface` is an experimental feature.269 * The API might be changed.270 */271export 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}278279/**280 * @experimental281 * `toSSG` is an experimental feature.282 * The API might be changed.283 */284export 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_CONCURRENCY291292 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}328329/**330 * @experimental331 * `isSSGContext` is an experimental feature.332 * The API might be changed.333 */334export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]335336/**337 * @experimental338 * `disableSSG` is an experimental feature.339 * The API might be changed.340 */341export const disableSSG = (): MiddlewareHandler =>342 async function disableSSG(c, next) {343 if (isSSGContext(c)) {344 return SSG_DISABLED_RESPONSE345 }346 await next()347 }348349/**350 * @experimental351 * `onlySSG` is an experimental feature.352 * The API might be changed.353 */354export const onlySSG = (): MiddlewareHandler =>355 async function onlySSG(c, next) {356 if (!isSSGContext(c)) {357 return c.notFound()358 }359 await next()360 }1export * from './ssg'2export { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'
added:src/helper/ssg/middleware.ts+62 added
1import type { Context } from '../../context'2import type { Env, MiddlewareHandler } from '../../types'34export const SSG_CONTEXT = 'HONO_SSG_CONTEXT'5export const SSG_DISABLED_RESPONSE = new Response('SSG is disabled', { status: 404 })67interface SSGParam {8 [key: string]: string9}10export type SSGParams = SSGParam[]1112interface 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}1819export type AddedSSGDataRequest = Request & {20 ssgParams?: SSGParams21}2223/**24 * Define SSG Route25 */26export 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}3031/**32 * @experimental33 * `isSSGContext` is an experimental feature.34 * The API might be changed.35 */36export const isSSGContext = (c: Context): boolean => !!c.env?.[SSG_CONTEXT]3738/**39 * @experimental40 * `disableSSG` is an experimental feature.41 * The API might be changed.42 */43export const disableSSG = (): MiddlewareHandler =>44 async function disableSSG(c, next) {45 if (isSSGContext(c)) {46 return SSG_DISABLED_RESPONSE47 }48 await next()49 }5051/**52 * @experimental53 * `onlySSG` is an experimental feature.54 * The API might be changed.55 */56export 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
1import { beforeEach, describe, expect, it } from 'vitest'2import { Hono } from '../../hono'3// eslint-disable-next-line @typescript-eslint/no-unused-vars4import { jsx } from '../../jsx'5import { poweredBy } from '../../middleware/powered-by'6import { SSG_DISABLED_RESPONSE, ssgParams, isSSGContext, disableSSG, onlySSG } from './middleware'7import { fetchRoutesContent, saveContentToFile, toSSG } from './ssg'8import type {9 BeforeRequestHook,10 AfterResponseHook,11 AfterGenerateHook,12 FileSystemModule,13} from './ssg'1415const 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}3536describe('toSSG function', () => {37 let app: Hono38 let fsMock: FileSystemModule3940 const postParams = [{ post: '1' }, { post: '2' }]4142 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 })6768 // Included params69 app.get(70 '/post/:post',71 ssgParams(() => postParams),72 (c) => c.html(<h1>{c.req.param('post')}</h1>)73 )7475 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 )8081 type Env = {82 Bindings: {83 FOO_DB: string84 }85 Variables: {86 FOO_VAR: string87 }88 }8990 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 )9899 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 }113114 const result = await toSSG(app, fsMock, { dir: './static' })115116 for (const postParam of postParams) {117 const html = writtenFiles[`static/post/${postParam.post}.html`]118 expect(html).toBe(`<h1>${postParam.post}</h1>`)119 }120121 for (let i = 1; i <= 3; i++) {122 const html = writtenFiles[`static/user/${i}.html`]123 expect(html).toBe(`<h1>${i}</h1>`)124 }125126 expect(result.files.length).toBe(10)127 expect(fsMock.mkdir).toHaveBeenCalledWith(expect.any(String), {128 recursive: true,129 })130 })131132 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 }137138 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 })143144 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 }149150 const result = await toSSG(app, fsMock, { dir: './static' })151152 expect(result.success).toBe(false)153 expect(result.error).toBeDefined()154 expect(result.files).toStrictEqual([])155 })156157 it('Should correctly generate files with the expected paths', async () => {158 await toSSG(app, fsMock, { dir: './static' })159160 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 })171172 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 })182183 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 })189190 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 })200201 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 })207208 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 })218219 await toSSG(app, fsMock, { dir: './static', afterGenerateHook: afterGenerateHookMock })220221 expect(afterGenerateHookMock).toHaveBeenCalled()222 expect(afterGenerateHookMock).toHaveBeenCalledWith(expect.anything())223 })224225 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 }230231 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 })242243 expect(signalAddEventListener).not.toHaveBeenCalled()244 })245})246247describe('fetchRoutesContent function', () => {248 let app: Hono249250 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 })257258 it('should fetch the correct content and MIME type for each route', async () => {259 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))260261 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 })274275 it('should skip middleware routes', async () => {276 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))277 expect(htmlMap.has('*')).toBeFalsy()278 })279280 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})286287describe('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 )306307 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 ]334335 let fsMock: FileSystemModule336337 beforeEach(() => {338 fsMock = {339 writeFile: vi.fn(() => Promise.resolve()),340 mkdir: vi.fn(() => Promise.resolve()),341 }342 })343344 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 }348349 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 })382383 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 })395396 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 }401402 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})421422describe('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 })431432 it('should skip /shops/:id dynamic route', async () => {433 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))434 expect(htmlMap.has('/shops/:id')).toBeFalsy()435 })436437 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 })441442 it('should skip /foo/* dynamic route', async () => {443 const htmlMap = await resolveRoutesContent(fetchRoutesContent(app))444 expect(htmlMap.has('/foo/*')).toBeFalsy()445 })446447 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})452453describe('isSSGContext()', () => {454 const app = new Hono()455 app.get('/', (c) => c.html(<h1>{isSSGContext(c) ? 'SSG' : 'noSSG'}</h1>))456457 const fsMock: FileSystemModule = {458 writeFile: vi.fn(() => Promise.resolve()),459 mkdir: vi.fn(() => Promise.resolve()),460 }461462 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 })466467 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})472473describe('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>))479480 const fsMock: FileSystemModule = {481 writeFile: vi.fn(() => Promise.resolve()),482 mkdir: vi.fn(() => Promise.resolve()),483 }484485 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 })495496 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
1import { replaceUrlParam } from '../../client/utils'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { createPool } from '../../utils/concurrent'5import { getExtension } from '../../utils/mime'6import type { AddedSSGDataRequest, SSGParams } from './middleware'7import { SSG_DISABLED_RESPONSE, SSG_CONTEXT } from './middleware'8import { joinPaths, dirname, filterStaticGenerateRoutes } from './utils'910const DEFAULT_CONCURRENCY = 2 // default concurrency for ssg1112/**13 * @experimental14 * `FileSystemModule` is an experimental feature.15 * The API might be changed.16 */17export interface FileSystemModule {18 writeFile(path: string, data: string | Uint8Array): Promise<void>19 mkdir(path: string, options: { recursive: boolean }): Promise<void | string>20}2122/**23 * @experimental24 * `ToSSGResult` is an experimental feature.25 * The API might be changed.26 */27export interface ToSSGResult {28 success: boolean29 files: string[]30 error?: Error31}3233const generateFilePath = (routePath: string, outDir: string, mimeType: string) => {34 const extension = determineExtension(mimeType)3536 if (routePath.endsWith(`.${extension}`)) {37 return joinPaths(outDir, routePath)38 }3940 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}4849const parseResponseContent = async (response: Response): Promise<string | ArrayBuffer> => {50 const contentType = response.headers.get('Content-Type')5152 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}6465const 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}7778export type BeforeRequestHook = (req: Request) => Request | false79export type AfterResponseHook = (res: Response) => Response | false80export type AfterGenerateHook = (result: ToSSGResult) => void | Promise<void>8182export interface ToSSGOptions {83 dir?: string84 beforeRequestHook?: BeforeRequestHook85 afterResponseHook?: AfterResponseHook86 afterGenerateHook?: AfterGenerateHook87 concurrency?: number88}8990/**91 * @experimental92 * `fetchRoutesContent` is an experimental feature.93 * The API might be changed.94 */95export 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 })114115 for (const route of filterStaticGenerateRoutes(app)) {116 // GET Route Info117 const thisRouteBaseURL = new URL(route.path, baseURL).toString()118119 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 }127128 // eslint-disable-next-line no-async-promise-executor129 yield new Promise(async (resolveGetInfo, rejectGetInfo) => {130 try {131 await pool.run(() => app.fetch(forGetInfoURLRequest))132133 if (!forGetInfoURLRequest.ssgParams) {134 if (isDynamicRoute(route.path)) {135 resolveGetInfo(undefined)136 return137 }138 forGetInfoURLRequest.ssgParams = [{}]139 }140141 const requestInit = {142 method: forGetInfoURLRequest.method,143 headers: forGetInfoURLRequest.headers,144 }145146 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}191192const isDynamicRoute = (path: string): boolean => {193 return path.split('/').some((segment) => segment.startsWith(':') || segment.includes('*'))194}195196/**197 * @experimental198 * `saveContentToFile` is an experimental feature.199 * The API might be changed.200 */201const createdDirs: Set<string> = new Set()202export 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)214215 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}226227/**228 * @experimental229 * `ToSSGInterface` is an experimental feature.230 * The API might be changed.231 */232export 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}240241/**242 * @experimental243 * `ToSSGAdaptorInterface` is an experimental feature.244 * The API might be changed.245 */246export 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}253254/**255 * @experimental256 * `toSSG` is an experimental feature.257 * The API might be changed.258 */259export 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_CONCURRENCY266267 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}