-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.tsx
401 lines (378 loc) · 10.3 KB
/
app.tsx
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import { o } from './jsx/jsx.js'
import { scanTemplateDir } from '../template-file.js'
import { NextFunction, Request, Response, Router } from 'express'
import type { Context, ExpressContext, WsContext } from './context'
import type { Element } from './jsx/types'
import {
escapeHTMLAttributeValue,
escapeHTMLTextContent,
unquote,
writeNode,
} from './jsx/html.js'
import { sendHTMLHeader } from './express.js'
import { OnWsMessage } from '../ws/wss.js'
import { dispatchUpdate } from './jsx/dispatch.js'
import { EarlyTerminate, MessageException } from '../exception.js'
import { getWSSession } from './session.js'
import DemoCookieSession from './pages/demo-cookie-session.js'
import { Flush } from './components/flush.js'
import { LayoutType, config } from '../config.js'
import Stats from './components/stats.js'
import { MuteConsole, Script } from './components/script.js'
import {
matchRoute,
menuRoutes,
PageRouteMatch,
redirectDict,
} from './routes.js'
import Chatroom from './pages/chatroom.js'
import type { ClientMountMessage, ClientRouteMessage } from '../../client/types'
import { then } from '@beenotung/tslib/result.js'
import { webAppStyle, ionicAppStyle } from './app-style.js'
import { preIonicAppScript, postIonicAppScript } from './styles/mobile-style.js'
import { renderWebTemplate } from '../../template/web.js'
import { renderIonicTemplate } from '../../template/ionic.js'
import { HTMLStream } from './jsx/stream.js'
import DemoUpload from './pages/demo-upload.js'
import { getWsCookies } from './cookie.js'
import Navbar from './components/navbar.js'
import Sidebar from './components/sidebar.js'
import { logRequest } from './log.js'
import { WindowStub } from '../../client/internal.js'
import { updateRequestSession } from '../../db/request-log.js'
import { Link } from './components/router.js'
if (config.development) {
scanTemplateDir('template')
}
function renderTemplate(
stream: HTMLStream,
context: Context,
route: PageRouteMatch,
) {
let layout_type = route.layout_type || config.layout_type
let App = layouts[layout_type]
let app = App(route)
let render =
route.renderTemplate ||
(App == IonicApp ? renderIonicTemplate : renderWebTemplate)
render(stream, {
title: escapeHTMLTextContent(route.title),
description: unquote(escapeHTMLAttributeValue(route.description)),
app:
typeof app == 'string' ? app : stream => writeNode(stream, app, context),
})
}
function CurrentNavigationMetaData(attrs: {}, context: Context) {
let js = `_navigation_type_="${context.type}";`
if (context.type == 'express') {
js += `_navigation_method_="${context.req.method}";`
}
return Script(js)
}
let scripts = config.development ? (
<>
<CurrentNavigationMetaData />
<script src="/js/index.js" type="module" defer></script>
</>
) : (
<>
{MuteConsole}
<CurrentNavigationMetaData />
<script src="/js/bundle.min.js" type="module" defer></script>
</>
)
let brand = (
<div style="color: darkblue; font-weight: bold">
<Link
style="font-size: 1.7rem; text-decoration: none"
class="text-no-wrap"
href="/"
>
{config.site_name}
</Link>{' '}
<div class="text-no-wrap">
<a target="_blank" href="https://hn.algolia.com/?query=ts-liveview">
HN
</a>{' '}
<a target="_blank" href="https://github.com/beenotung/ts-liveview">
git
</a>
</div>
</div>
)
type Layout = (route: PageRouteMatch) => Element
let layouts: Record<LayoutType, Layout> = {
[LayoutType.navbar]: NavbarApp,
[LayoutType.sidebar]: SidebarApp,
[LayoutType.ionic]: IonicApp,
}
function NavbarApp(route: PageRouteMatch): Element {
// you can write the AST direct for more compact wire-format
return [
'div.app',
{},
[
// or you can write in JSX for better developer-experience (if you're coming from React)
<>
{webAppStyle}
<Flush />
<Navbar brand={brand} menuRoutes={menuRoutes} />
<hr />
{scripts}
{route.node}
<Flush />
<Footer />
</>,
],
]
}
function SidebarApp(route: PageRouteMatch): Element {
// you can write the AST direct for more compact wire-format
return [
'div.app',
{},
[
// or you can write in JSX for better developer-experience (if you're coming from React)
<>
{webAppStyle}
{scripts}
{Sidebar.style}
<Flush />
<div class={Sidebar.containerClass}>
<Sidebar brand={brand} menuRoutes={menuRoutes} />
<div
class={Sidebar.mainContainerClass}
style="display: flex; flex-direction: column"
>
<div style="flex-grow: 1; padding: 0 1rem">{route.node}</div>
<Footer style="padding: 0.5rem;" />
</div>
</div>
<Flush />
</>,
],
]
}
function IonicApp(route: PageRouteMatch): Element {
// you can write the AST direct for more compact wire-format
return [
'div.app',
{},
[
// or you can write in JSX for better developer-experience (if you're coming from React)
<>
{ionicAppStyle}
{scripts}
{preIonicAppScript}
<Flush />
<ion-app>{route.node}</ion-app>
{postIonicAppScript}
<Flush />
</>,
],
]
}
function Footer(attrs: { style?: string }) {
return (
<footer
style={
'border-top: 1px solid #aaa; padding-top: 0.5rem; margin-top: 0.5rem;' +
(attrs.style || '')
}
>
<div style="margin-bottom: 0.75rem">
Made with 💝 by{' '}
<a target="_blank" href="https://github.com/beenotung">
Beeno
</a>
</div>
<Stats />
</footer>
)
}
// prefer flat router over nested router for less overhead
export function attachRoutes(app: Router) {
// ajax/upload/middleware routes
DemoCookieSession.attachRoutes(app)
Chatroom.attachRoutes(app)
DemoUpload.attachRoutes(app)
// redirect routes
Object.entries(redirectDict).forEach(([from, to]) =>
app.use(from, (_req, res) => res.redirect(to)),
)
// liveview routes
app.use(handleLiveView)
}
async function handleLiveView(req: Request, res: Response, next: NextFunction) {
sendHTMLHeader(res)
let context: ExpressContext = {
type: 'express',
req,
res,
next,
url: req.url,
}
try {
await then(
matchRoute(context),
route => {
if (route.status) {
res.status(route.status)
}
route.description = route.description.replace(/"/g, "'")
if (route.streaming === false) {
responseHTML(res, context, route)
} else {
streamHTML(res, context, route)
}
},
onError,
)
} catch (error) {
onError(error)
}
function onError(error: unknown) {
if (error == EarlyTerminate) {
return
}
if (error instanceof MessageException) {
res.json({ message: error.message })
return
}
res.status(500)
res.json({ error: String(error) })
console.error(error)
}
}
function responseHTML(
res: Response,
context: ExpressContext,
route: PageRouteMatch,
) {
let html = ''
let stream = {
write(chunk: string) {
html += chunk
},
flush() {},
}
try {
renderTemplate(stream, context, route)
} catch (error) {
if (error === EarlyTerminate) {
return
}
console.error('Failed to render App:', error)
if (!res.headersSent) {
res.status(500)
}
html +=
error instanceof Error
? 'Internal Error: ' + escapeHTMLTextContent(error.message)
: 'Unknown Error: ' + escapeHTMLTextContent(String(error))
}
// deepcode ignore XSS: the dynamic content is html-escaped
res.end(html)
}
function streamHTML(
res: Response,
context: ExpressContext,
route: PageRouteMatch,
) {
try {
renderTemplate(res, context, route)
res.end()
} catch (error) {
if (error === EarlyTerminate) {
return
}
console.error('Failed to render App:', error)
if (!res.headersSent) {
res.status(500)
}
// deepcode ignore XSS: the dynamic content is html-escaped
res.end(
error instanceof Error
? 'Internal Error: ' + escapeHTMLTextContent(error.message)
: 'Unknown Error: ' + escapeHTMLTextContent(String(error)),
)
}
}
export let onWsMessage: OnWsMessage = async (event, ws, _wss) => {
console.log('ws message:', event)
// TODO handle case where event[0] is not url
let eventType: string | undefined
let url: string
let args: unknown[] | undefined
let session = getWSSession(ws)
let navigation_type: WindowStub['_navigation_type_']
let navigation_method: WindowStub['_navigation_method_']
if (event[0] === 'mount') {
event = event as ClientMountMessage
eventType = 'mount'
url = event[1]
session.language = event[2]
let timeZone = event[3]
if (timeZone && timeZone !== 'null') {
session.timeZone = timeZone
}
session.timezoneOffset = event[4]
updateRequestSession(ws.session_id, session)
let cookie = event[5]
if (cookie) {
getWsCookies(ws.ws).unsignedCookies = Object.fromEntries(
new URLSearchParams(
cookie
.split(';')
.map(s => s.trim())
.join('&'),
),
)
}
navigation_type = event[6]
navigation_method = event[7]
logRequest(ws.request, 'ws', url, ws.session_id)
} else if (event[0][0] === '/') {
event = event as ClientRouteMessage
eventType = 'route'
url = event[0]
args = event.slice(1)
logRequest(ws.request, 'ws', url, ws.session_id)
} else {
console.log('unknown type of ws message:', event)
return
}
session.url = url
let context: WsContext = {
type: 'ws',
ws,
url,
args,
event: eventType,
session,
}
try {
await then(
matchRoute(context),
route => {
let App = layouts[route.layout_type || config.layout_type]
let node = App(route)
if (navigation_type === 'express' && navigation_method !== 'GET') return
dispatchUpdate(context, node, route.title)
},
onError,
)
} catch (error) {
onError(error)
}
function onError(error: unknown) {
if (error == EarlyTerminate) {
return
}
if (error instanceof MessageException) {
ws.send(error.message)
return
}
console.error(error)
}
}