-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
365 lines (335 loc) · 9.7 KB
/
server.ts
File metadata and controls
365 lines (335 loc) · 9.7 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import { IClient, IServer, renderLayout, SearchParams } from './lib.ts'
import { fs, jsonc, path, serveFile, tsBlankSpace } from './mod.ts'
import { h } from 'preact'
import { renderToString } from 'preact-render-to-string'
import * as v from 'valibot'
const _dirname = import.meta.dirname
if (!_dirname) throw new Error(`Expected "import.meta.dirname" to be truthy`)
const apiModule = fs.existsSync(path.join(Deno.cwd(), './api.ts'))
? await import(path.join(Deno.cwd(), './api.ts'))
: {}
const serverModule = fs.existsSync(path.join(Deno.cwd(), './server.ts'))
? await import(path.join(Deno.cwd(), './server.ts'))
: {}
export async function requestHandler(req: Request) {
if (!_dirname) throw new Error(`Expected "import.meta.dirname" to be truthy`)
const url = new URL(req.url)
// Route matching.
if (serverModule.router?.routes) {
const result = await matchRoute(serverModule.router.routes, url, req)
if (result) {
if (req.headers.get('upgrade') === 'websocket') {
const { socket, response } = Deno.upgradeWebSocket(req)
const pagePath = result
const pagePathAbs = path.join(Deno.cwd(), pagePath)
const serverPathAbs = pagePathAbs.replace(/\.(t|j)s$/u, '.server.ts')
if (await fs.exists(serverPathAbs)) {
const ServerWebSocket = (await import(serverPathAbs)).ServerWebSocket
socket.addEventListener('open', () => {
ServerWebSocket(socket)
})
}
return response
} else if (req.method === 'GET') {
return await renderPage(url, result)
} else if (req.method === 'POST') {
return await getPageData(url, result)
}
}
}
// Serve JavaScript files.
for (const slug of ['components', 'layouts', 'pages', 'utilities']) {
if (url.pathname.startsWith(`/${slug}`)) {
const tsFile = path.join(Deno.cwd(), url.pathname)
const text = await Deno.readTextFile(tsFile)
const output = tsBlankSpace(text)
return new Response(output, {
headers: {
'Content-Type': 'application/javascript',
},
})
}
}
for (const slug of ['dependencies']) {
if (url.pathname.startsWith(`/${slug}`)) {
const filepath = path.join(Deno.cwd(), url.pathname)
if (!filepath.startsWith(filepath)) {
throw new Error('Bad path')
}
const stat = await Deno.stat(filepath).catch((err) => {
if (err instanceof Deno.errors.NotFound) return null
throw err
})
if (stat) {
return serveFile(req, filepath, {
fileInfo: stat,
})
}
}
}
if (
req.method === 'GET' &&
(url.pathname === '/lib.ts')
) {
const tsFile = path.join(_dirname, url.pathname)
const text = await Deno.readTextFile(tsFile)
const output = tsBlankSpace(text)
return new Response(output, {
headers: {
'Content-Type': 'application/javascript',
},
})
}
if (
req.method === 'GET' &&
(url.pathname === '/api.ts')
) {
const tsFile = path.join(Deno.cwd(), url.pathname)
const text = await Deno.readTextFile(tsFile)
const output = tsBlankSpace(text)
return new Response(output, {
headers: {
'Content-Type': 'application/javascript',
},
})
}
// Serve static files.
{
const staticDir = path.join(Deno.cwd(), 'static')
const filepath = path.join(staticDir, url.pathname)
if (!filepath.startsWith(staticDir)) {
throw new Error('Bad path')
}
const stat = await Deno.stat(filepath).catch((err) => {
if (err instanceof Deno.errors.NotFound) return null
throw err
})
if (stat) {
return serveFile(req, filepath, {
fileInfo: stat,
})
}
}
// RPC.
if (req.method === 'POST' && url.pathname === '/rpc') {
const json = await req.json()
const result = await apiModule?.api?.[json.fn]?.resolve?.(json.data ?? {})
return new Response(JSON.stringify(result, null, '\t'), {
headers: {
'Content-Type': 'application/json',
},
})
}
// Serve 404 page.
return new Response('404: Not Found', {
status: 404,
})
}
async function renderPage(url: URL, clientPath: string) {
const serverPath = clientPath.replace(/\.(t|j)s$/u, '.server.$1s')
const clientPathAbs = path.join(Deno.cwd(), clientPath)
const serverPathAbs = path.join(Deno.cwd(), serverPath)
const [ClientResult, ServerResult] = await Promise.allSettled([
import(clientPathAbs),
import(serverPathAbs),
])
if (ClientResult.status === 'rejected') {
return new Response(
`Failed to find page: "${clientPath}"\n${ClientResult.reason}\n`,
{
status: 404,
headers: {
'Content-Type': 'text/plain',
},
},
)
}
const Client: IClient = ClientResult.value
if (Client.URLParamSchema !== undefined && typeof Client.URLParamSchema !== 'function') {
return error(`"URLParamSchema" must be a function in file: "${clientPath}"`)
}
if (typeof Client.Page !== 'function') {
return error(`"Page" must be a function in file: "${clientPath}"`)
}
const Server: IServer = ServerResult.status === 'fulfilled' ? ServerResult.value : {}
if (Server.Head !== undefined && typeof Server.Head !== 'function') {
return error(`"Head" must be a function in file: "${serverPath}"`)
}
if (Server.DataSchema !== undefined && typeof Server.DataSchema !== 'function') {
return error(`"DataSchema" must be a function in file: "${serverPath}"`)
}
if (Server.Data !== undefined && typeof Server.Data !== 'function') {
return error(`"Data" must be a function in file: "${serverPath}"`)
}
const imports =
jsonc.parse(await Deno.readTextFile(path.join(Deno.cwd(), './deno.jsonc'))).imports
if (imports['~/lib']) {
imports['~/lib'] = '/lib.ts'
}
if (imports['~/api']) {
imports['~/api'] = '/api.ts'
}
for (const id in imports) {
if (imports[id].startsWith('./')) {
imports[id] = imports[id].slice(1)
}
if (!imports[id].startsWith('/')) {
delete imports[id]
}
}
const [serverHeadResult, serverDataSchemaResult, serverDataResult] = await Promise.allSettled([
Server?.Head?.(),
Server?.DataSchema?.(),
Server?.Data?.(),
])
if (serverHeadResult.status === 'rejected') {
return error(serverHeadResult.reason)
}
if (serverDataSchemaResult.status === 'rejected') {
return error(serverDataSchemaResult.reason)
}
if (serverDataResult.status === 'rejected') {
return error(serverDataResult.reason)
}
const serverHead = serverHeadResult.value
const serverDataSchema = serverDataSchemaResult.value
const serverData = serverDataResult.value
if (
serverHead !== undefined && typeof serverHead !== 'string'
) {
return error(`"Head()" must return a string in file: "${serverPath}"`)
}
if (serverData === undefined) {
if (serverDataSchema !== undefined) {
return error(`"DataSchema()" must not exist without Data() in file: "${serverPath}"`)
}
} else {
if (serverDataSchema === undefined) {
return error(`"DataSchema()" must exist if Data() exists in file: "${serverPath}"`)
}
const result = v.safeParse(serverDataSchema, serverData)
if (!result.success) {
return error(JSON.stringify(result.issues, null, '\t'))
}
}
const text = renderHtml(
url,
clientPath,
Client,
imports,
serverData,
serverHead,
)
return new Response(text, {
headers: {
'Content-Type': 'text/html',
},
})
function error(message: string) {
return new Response(message, {
status: 500,
headers: {
'Content-Type': 'text/plain',
},
})
}
}
async function matchRoute(routes, url: URL, req) {
for (const routePattern in routes) {
const match = new URLPattern({ pathname: routePattern }).exec(url.href)
if (match) {
const socket = ''
const result = await routes[routePattern](req, match, socket)
return result
}
}
return null
}
async function getPageData(url: URL, pagePath: string) {
const pagePathAbs = path.join(Deno.cwd(), pagePath)
const serverPathAbs = pagePathAbs.replace(/\.(t|j)s$/u, '.server.ts')
if (await fs.exists(serverPathAbs)) {
const fn = (await import(serverPathAbs)).Data
if (fn) {
const data = await fn(url)
return new Response(JSON.stringify({ data }), {
headers: {
'Content-Type': 'application/json',
},
})
}
}
return new Response('{}', {
headers: {
'Content-Type': 'application/json',
},
})
}
export function renderHtml(
url: URL,
clientPath: string,
Client: IClient,
imports: Record<string, string>,
serverData: Record<PropertyKey, unknown>,
serverHead: string,
) {
const searchParams = new SearchParams(url)
const layoutHtml = renderToString(
h(() => renderLayout(Client.Page, Client.Layout, serverData, searchParams), {}),
)
const html = String.raw
let headContent = html`
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<script type="importmap">
{
"imports": ${JSON.stringify(imports, null, '\t').replaceAll('\n', '\n\t\t\t')}
}
</script>
<script type="module">
import { h, hydrate, render } from "preact";
import { SearchParams, renderLayout } from '~/lib'
import * as module from "${clientPath.replace(/^\./, '~')}"
const searchParams = new SearchParams()
fetch(new URL(window.location).pathname, { method: "POST" })
.then((res) => res.json())
.then((json) => {
const Page = module.Page
const Layout = module.Layout
const ClientWebSocket = module.ClientWebSocket
if (ClientWebSocket) {
const ws = new WebSocket('ws://localhost:8000')
ClientWebSocket(ws)
}
hydrate(
h(() => renderLayout(Page, Layout, json.data, searchParams), {}),
document.querySelector("body"),
);
});
</script>
<!-- Head() start -->
${serverHead ? serverHead : ''}
<!-- Head() end -->
<title>Site</title>
`
headContent = headContent.trim()
if (Client.Layout) {
headContent = headContent.replaceAll(/\n/g, '\n\t\t')
} else {
headContent = headContent.replaceAll(/\n/g, '\n\t\t\t')
}
return html`
<!DOCTYPE html>
<html>
<head>
${headContent}
</head>
<body>
${layoutHtml}
</body>
</html>
`.replace(/^\n\t{3}/, '').replaceAll(/\n\t{3}/g, '\n')
}