-
Notifications
You must be signed in to change notification settings - Fork 44
/
server.ts
201 lines (172 loc) · 5.74 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Hono } from 'hono'
import type { Env, NotFoundHandler, ErrorHandler, MiddlewareHandler } from 'hono'
import { createMiddleware } from 'hono/factory'
import type { H } from 'hono/types'
import { IMPORTING_ISLANDS_ID } from '../constants.js'
import {
filePathToPath,
groupByDirectory,
listByDirectory,
sortDirectoriesByDepth,
} from '../utils/file.js'
const NOTFOUND_FILENAME = '_404.tsx'
const ERROR_FILENAME = '_error.tsx'
const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'] as const
type AppFile = { default: Hono }
type InnerMeta = {
[key in typeof IMPORTING_ISLANDS_ID]?: boolean
}
type RouteFile = {
default?: Function
} & { [M in (typeof METHODS)[number]]?: H[] } & InnerMeta
type RendererFile = { default: MiddlewareHandler }
type NotFoundFile = { default: NotFoundHandler }
type ErrorFile = { default: ErrorHandler }
type InitFunction<E extends Env = Env> = (app: Hono<E>) => void
export type ServerOptions<E extends Env = Env> = {
ROUTES?: Record<string, RouteFile>
RENDERER?: Record<string, RendererFile>
NOT_FOUND?: Record<string, NotFoundFile>
ERROR?: Record<string, ErrorFile>
root?: string
app?: Hono<E>
init?: InitFunction<E>
}
export const createApp = <E extends Env>(options?: ServerOptions<E>): Hono<E> => {
const root = options?.root ?? '/app/routes'
const rootRegExp = new RegExp(`^${root}`)
const app = options?.app ?? new Hono()
if (options?.init) {
options.init(app)
}
// Not Found
const NOT_FOUND_FILE =
options?.NOT_FOUND ??
import.meta.glob<NotFoundFile>('/app/routes/**/_404.(ts|tsx)', {
eager: true,
})
const notFoundMap = groupByDirectory(NOT_FOUND_FILE)
// Error
const ERROR_FILE =
options?.ERROR ??
import.meta.glob<ErrorFile>('/app/routes/**/_error.(ts|tsx)', {
eager: true,
})
const errorMap = groupByDirectory(ERROR_FILE)
// Renderer
const RENDERER_FILE =
options?.RENDERER ??
import.meta.glob<RendererFile>('/app/routes/**/_renderer.tsx', {
eager: true,
})
const rendererList = listByDirectory(RENDERER_FILE)
const applyRenderer = (app: Hono, rendererFile: string) => {
const renderer = RENDERER_FILE[rendererFile]
const rendererDefault = renderer['default']
if (rendererDefault) {
app.all('*', rendererDefault)
}
}
// Routes
const ROUTES_FILE =
options?.ROUTES ??
import.meta.glob<RouteFile | AppFile>('/app/routes/**/[!_]*.(ts|tsx|mdx)', {
eager: true,
})
const routesMap = sortDirectoriesByDepth(groupByDirectory(ROUTES_FILE))
for (const map of routesMap) {
for (const [dir, content] of Object.entries(map)) {
const subApp = new Hono()
// Renderer
let rendererPaths = rendererList[dir] ?? []
const getRendererPaths = (paths: string[]) => {
rendererPaths = rendererList[paths.join('/')]
if (!rendererPaths) {
paths.pop()
if (paths.length) {
getRendererPaths(paths)
}
}
return rendererPaths ?? []
}
const dirPaths = dir.split('/')
rendererPaths = getRendererPaths(dirPaths)
rendererPaths.sort((a, b) => a.split('/').length - b.split('/').length)
rendererPaths.map((path) => {
applyRenderer(subApp, path)
})
// Root path
let rootPath = dir.replace(rootRegExp, '')
rootPath = filePathToPath(rootPath)
for (const [filename, route] of Object.entries(content)) {
// @ts-expect-error route[IMPORTING_ISLANDS_ID] is not typed
const importingIslands = route[IMPORTING_ISLANDS_ID] as boolean
const setInnerMeta = createMiddleware(async function innerMeta(c, next) {
c.set(IMPORTING_ISLANDS_ID as any, importingIslands)
await next()
})
const routeDefault = route.default
const path = filePathToPath(filename)
// Instance of Hono
if (routeDefault && 'fetch' in routeDefault) {
subApp.route(path, routeDefault)
}
// export const POST = factory.createHandlers(...)
for (const m of METHODS) {
const handlers = (route as Record<string, H[]>)[m]
if (handlers) {
subApp.on(m, path, setInnerMeta)
subApp.on(m, path, ...handlers)
}
}
// export default factory.createHandlers(...)
if (routeDefault && Array.isArray(routeDefault)) {
subApp.get(path, setInnerMeta)
subApp.get(path, ...(routeDefault as H[]))
}
// export default function Helle() {}
if (typeof routeDefault === 'function') {
subApp.get(path, setInnerMeta)
subApp.get(path, (c) => {
return c.render(routeDefault(c), route as any)
})
}
}
// Not Found
applyNotFound(subApp, dir, notFoundMap)
// Error
applyError(subApp, dir, errorMap)
app.route(rootPath, subApp)
}
}
return app
}
function applyNotFound(app: Hono, dir: string, map: Record<string, Record<string, NotFoundFile>>) {
for (const [mapDir, content] of Object.entries(map)) {
if (dir === mapDir) {
const notFound = content[NOTFOUND_FILENAME]
if (notFound) {
const notFoundHandler = notFound.default
app.get('*', (c) => {
c.status(404)
return notFoundHandler(c)
})
}
}
}
}
function applyError(app: Hono, dir: string, map: Record<string, Record<string, ErrorFile>>) {
for (const [mapDir, content] of Object.entries(map)) {
if (dir === mapDir) {
const error = content[ERROR_FILENAME]
if (error) {
const errorHandler = error.default
app.onError((error, c) => {
c.status(500)
return errorHandler(error, c)
})
}
}
}
}