-
Notifications
You must be signed in to change notification settings - Fork 1
/
www.ts
1863 lines (1673 loc) · 46.1 KB
/
www.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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// helper functions for the world wide web with Bun
if (typeof Bun === "undefined") {
throw new Error("Requires Bun")
}
import * as fs from "node:fs"
import * as path from "node:path"
import type {
ServeOptions,
WebSocketServeOptions,
SocketAddress,
ServerWebSocket,
ServerWebSocketSendStatus,
WebSocketHandler,
} from "bun"
import * as sqlite from "bun:sqlite"
export const isDev = Boolean(Bun.env["DEV"])
export type Req = {
method: string,
headers: Headers,
url: URL,
params: Record<string, string>,
text: () => Promise<string>,
arrayBuffer: () => Promise<ArrayBuffer>,
json<T = any>(): Promise<T>,
formData: () => Promise<FormData>,
blob: () => Promise<Blob>,
getIP: () => string | null,
getCookies: () => Record<string, string>,
}
export type Res = {
headers: Headers,
status: number,
body: null | BodyInit,
send: (data?: BodyInit | null, opt?: ResOpt) => void,
sendText: (content: string, opt?: ResOpt) => void,
sendHTML: (content: string, opt?: ResOpt) => void,
sendJSON: <T = any>(content: T, opt?: ResOpt) => void,
sendFile: (path: string, opt?: ResOpt) => void,
redirect: (url: string, status?: number) => void,
}
export type ResOpt = {
headers?: Record<string, string>,
status?: number,
}
export type SendFileOpt = ResOpt & {
mimes?: Record<string, string>,
}
export type Ctx = {
req: Req,
res: Res,
next: () => void,
upgrade: (opts?: ServerUpgradeOpts) => boolean,
onFinish: (action: () => void) => void,
onError: (action: (e: Error) => void) => void,
}
export type Handler = (ctx: Ctx) => void
export type ErrorHandler = (ctx: Ctx, err: Error) => void
export type NotFoundHandler = (ctx: Ctx) => void
export class Registry<T> extends Map<number, T> {
private lastID: number = 0
push(v: T): number {
const id = this.lastID
this.set(id, v)
this.lastID++
return id
}
pushd(v: T): () => void {
const id = this.push(v)
return () => this.delete(id)
}
}
export type Server = {
use: (handler: Handler) => void,
error: (handler: ErrorHandler) => void,
notFound: (action: NotFoundHandler) => void,
stop: (closeActiveConnections?: boolean) => void,
hostname: string,
url: URL,
port: number,
ws: {
clients: Map<string, WebSocket>,
onMessage: (action: (ws: WebSocket, msg: string | Buffer) => void) => EventController,
onOpen: (action: (ws: WebSocket) => void) => EventController,
onClose: (action: (ws: WebSocket) => void) => EventController,
broadcast: (data: string | Bun.BufferSource, compress?: boolean) => void,
publish: (
topic: string,
data: string | DataView | ArrayBuffer | SharedArrayBuffer,
compress?: boolean,
) => ServerWebSocketSendStatus,
},
}
export type ServerOpts = Omit<ServeOptions, "fetch"> | Omit<WebSocketServeOptions, "fetch">
export type ServerUpgradeOpts<T = undefined> = {
headers?: HeadersInit,
data?: T,
}
export type EventController = {
paused: boolean,
cancel: () => void
}
export function createEvent<Args extends any[] = any[]>() {
const actions = new Registry<(...args: Args) => void>()
function add(action: (...args: Args) => void): EventController {
let paused = false
const cancel = actions.pushd((...args: Args) => {
if (paused) return
action(...args)
})
return {
get paused() {
return paused
},
set paused(p: boolean) {
paused = p
},
cancel: cancel,
}
}
function addOnce(action: (...args: Args) => void): EventController {
const ev = add((...args) => {
ev.cancel()
action(...args)
})
return ev
}
const next = () => new Promise((res) => addOnce((...args) => res(args)))
const trigger = (...args: Args) => actions.forEach((action) => action(...args))
const numListeners = () => actions.size
const clear = () => actions.clear()
return {
add,
addOnce,
next,
trigger,
numListeners,
clear,
}
}
export type WebSocketData = {
id: string,
}
// TODO: support arbituary data
export type WebSocket = ServerWebSocket<WebSocketData>
const isPromise = (input: any): input is Promise<any> => {
return input
&& typeof input.then === "function"
&& typeof input.catch === "function"
}
export function createServer(opts: ServerOpts = {}): Server {
const wsClients = new Map<string, WebSocket>()
const wsEvents = {
message: createEvent<[WebSocket, string | Buffer]>(),
open: createEvent<[WebSocket]>(),
close: createEvent<[WebSocket]>(),
}
const websocket: WebSocketHandler<WebSocketData> = {
message: (ws, msg) => {
wsEvents.message.trigger(ws, msg)
},
open: (ws) => {
const id = crypto.randomUUID()
wsClients.set(id, ws)
ws.data = {
id: id,
}
wsEvents.open.trigger(ws)
},
close: (ws) => {
wsClients.delete(ws.data.id)
wsEvents.close.trigger(ws)
},
}
async function fetch(bunReq: Request): Promise<Response> {
return new Promise((resolve) => {
let done = false
const req: Req = {
method: bunReq.method,
url: new URL(bunReq.url),
headers: bunReq.headers,
params: {},
text: bunReq.text.bind(bunReq),
json: bunReq.json.bind(bunReq),
arrayBuffer: bunReq.arrayBuffer.bind(bunReq),
formData: bunReq.formData.bind(bunReq),
blob: bunReq.blob.bind(bunReq),
getIP: () => {
let ip = bunReq.headers.get("X-Forwarded-For")?.split(",")[0].trim()
?? bunServer.requestIP(bunReq)?.address
if (!ip) return null
const ipv6Prefix = "::ffff:"
// ipv4 in ipv6
if (ip?.startsWith(ipv6Prefix)) {
ip = ip.substring(ipv6Prefix.length)
}
const localhostIPs = new Set([
"127.0.0.1",
"::1",
])
if (localhostIPs.has(ip)) return null
return ip
},
getCookies: () => {
const str = bunReq.headers.get("Cookie")
if (!str) return {}
const cookies: Record<string, string> = {}
for (const c of str.split(";")) {
const [k, v] = c.split("=")
cookies[k.trim()] = v.trim()
}
return cookies
},
}
const onFinishEvents: Array<() => void> = []
const onErrorEvents: Array<(e: Error) => void> = []
let headers = new Headers()
let status = 200
let body: null | BodyInit = null
function send(b?: BodyInit | null, opt: ResOpt = {}) {
if (done) return
body = b ?? body
status = opt.status ?? status
if (opt.headers) {
for (const k in opt.headers) {
headers.set(k, opt.headers[k])
}
}
const bunRes = new Response(body, {
headers: headers,
status: status,
})
if (bunReq.method.toLowerCase() === "head") {
// TODO
}
resolve(bunRes)
done = true
onFinishEvents.forEach((f) => f())
}
function sendText(content: string, opt: ResOpt = {}) {
headers.set("Content-Type", "text/plain; charset=utf-8")
send(content, opt)
}
function sendHTML(content: string, opt: ResOpt = {}) {
headers.set("Content-Type", "text/html; charset=utf-8")
send(content, opt)
}
function sendJSON(content: unknown, opt: ResOpt = {}) {
headers.set("Content-Type", "application/json; charset=utf-8")
send(JSON.stringify(content), opt)
}
function sendFile(p: string, opt: SendFileOpt = {}) {
if (!isFileSync(p)) return
const file = Bun.file(p)
if (file.size === 0) return
const mtimeServer = req.headers.get("If-Modified-Since")
const mtimeClient = toHTTPDate(new Date(file.lastModified))
if (mtimeServer === mtimeClient) {
return send(null, { status: 304 })
}
// TODO: stream not working
// https://github.com/oven-sh/bun/blob/main/examples/http-file-extended.ts
// const range = bunReq.headers.get("Range")
// if (range) {
// let [start, end] = range
// .replace("bytes=", "")
// .split("-")
// .map(parseInt)
// start = start || 0
// end = end || file.size - 1
// if (start >= file.size || end >= file.size) {
// headers.set("Content-Range", `bytes */${file.size}`)
// return send(null, { status: 416 })
// }
// headers.set("Content-Range", `bytes ${start}-${end}/${file.size}`)
// headers.set("Content-Length", "" + (end - start + 1))
// headers.set("Accept-Ranges", "bytes")
// return send(file.slice(start, end), {
// ...opt,
// status: 206,
// })
// }
headers.set("Last-Modified", mtimeClient)
headers.set("Cache-Control", "no-cache")
return send(file, opt)
}
function redirect(url: string, s: number = 302) {
headers.set("Location", url)
status = s
send(null)
}
const res: Res = {
get status() { return status },
set status(s) { status = s },
get body() { return body },
set body(b) { body = b },
headers,
send,
sendText,
sendHTML,
sendJSON,
sendFile,
redirect,
}
const curHandlers = [...handlers]
function next() {
if (done) return
const h = curHandlers.shift()
const ctx: Ctx = {
req,
res,
next,
upgrade: (opts) => {
const success = bunServer.upgrade(bunReq, opts)
// @ts-ignore
if (success) resolve(undefined)
return success
},
onFinish(action) {
onFinishEvents.push(action)
},
onError(action) {
onErrorEvents.push(action)
},
}
if (h) {
try {
const res = h(ctx)
if (isPromise(res)) {
res.catch((e) => {
errHandler(ctx, e)
onErrorEvents.forEach((f) => f(e))
})
}
} catch (e) {
errHandler(ctx, e as Error)
onErrorEvents.forEach((f) => f(e as Error))
}
} else {
notFoundHandler(ctx)
}
}
next()
})
}
const bunServer = Bun.serve({
...opts,
websocket,
fetch,
development: isDev,
})
const handlers: Handler[] = []
const use = (handler: Handler) => handlers.push(handler)
let errHandler: ErrorHandler = ({ req, res, next }, err) => {
console.error(err)
res.status = 500
res.sendText("500 internal server error")
}
let notFoundHandler: NotFoundHandler = ({ res }) => {
res.status = 404
res.sendText("404 not found")
}
return {
use: use,
error: (action: ErrorHandler) => errHandler = action,
notFound: (action: NotFoundHandler) => notFoundHandler = action,
stop: bunServer.stop.bind(bunServer),
hostname: bunServer.hostname,
url: bunServer.url,
port: bunServer.port,
ws: {
clients: wsClients,
onMessage: (action) => wsEvents.message.add(action),
onOpen: (action) => wsEvents.open.add(action),
onClose: (action) => wsEvents.close.add(action),
publish: bunServer.publish.bind(bunServer),
// TODO: option to exclude self
broadcast: (data: string | Bun.BufferSource, compress?: boolean) => {
wsClients.forEach((client) => {
client.send(data, compress)
})
},
},
}
}
type Func = (...args: any[]) => any
export function overload2<A extends Func, B extends Func>(fn1: A, fn2: B): A & B {
return ((...args) => {
const al = args.length
if (al === fn1.length) return fn1(...args)
if (al === fn2.length) return fn2(...args)
}) as A & B
}
export function overload3<
A extends Func,
B extends Func,
C extends Func,
>(fn1: A, fn2: B, fn3: C): A & B & C {
return ((...args) => {
const al = args.length
if (al === fn1.length) return fn1(...args)
if (al === fn2.length) return fn2(...args)
if (al === fn3.length) return fn3(...args)
}) as A & B & C
}
export function overload4<
A extends Func,
B extends Func,
C extends Func,
D extends Func,
>(fn1: A, fn2: B, fn3: C, fn4: D): A & B & C & D {
return ((...args) => {
const al = args.length
if (al === fn1.length) return fn1(...args)
if (al === fn2.length) return fn2(...args)
if (al === fn3.length) return fn3(...args)
if (al === fn4.length) return fn4(...args)
}) as A & B & C & D
}
export const route = overload2((pat: string, handler: Handler): Handler => {
return (ctx) => {
const match = matchPath(pat, decodeURI(ctx.req.url.pathname))
if (match) {
ctx.req.params = match
return handler(ctx)
} else {
ctx.next()
}
}
}, (method: string, pat: string, handler: Handler): Handler => {
return (ctx) => {
let rm = ctx.req.method.toLowerCase()
rm = rm === "head" ? "get" : rm
const m = method.toLowerCase()
if (rm === m) {
return route(pat, handler)(ctx)
} else {
ctx.next()
}
}
})
export function files(route = "", root = ""): Handler {
return ({ req, res, next }) => {
route = trimSlashes(route)
const pathname = trimSlashes(decodeURI(req.url.pathname))
if (!pathname.startsWith(route)) return next()
const baseDir = "./" + trimSlashes(root)
const relativeURLPath = pathname.replace(new RegExp(`^${route}/?`), "")
const p = path.join(baseDir, relativeURLPath)
return res.sendFile(p)
}
}
export function dir(route = "", root = ""): Handler {
return ({ req, res, next }) => {
route = trimSlashes(route)
const pathname = trimSlashes(decodeURI(req.url.pathname))
if (!pathname.startsWith(route)) return next()
const baseDir = "./" + trimSlashes(root)
const relativeURLPath = pathname.replace(new RegExp(`^${route}/?`), "")
const p = path.join(baseDir, relativeURLPath)
if (isFileSync(p)) {
return res.sendFile(p)
} else if (isDirSync(p)) {
const entries = fs.readdirSync(p)
.filter((entry) => !entry.startsWith("."))
.sort((a, b) => a > b ? -1 : 1)
.sort((a, b) => path.extname(a) > path.extname(b) ? 1 : -1)
const files = []
const dirs = []
for (const entry of entries) {
const pp = path.join(p, entry)
if (isDirSync(pp)) {
dirs.push(entry)
} else if (isFileSync(pp)) {
files.push(entry)
}
}
const isRoot = relativeURLPath === ""
return res.sendHTML("<!DOCTYPE html>" + h("html", { lang: "en" }, [
h("head", {}, [
h("title", {}, decodeURI(req.url.pathname)),
h("style", {}, css({
"*": {
"margin": "0",
"padding": "0",
"box-sizing": "border-box",
},
"body": {
"padding": "16px",
"font-size": "24px",
"font-family": "Monospace",
},
"li": {
"list-style": "none",
},
"a": {
"color": "blue",
"text-decoration": "none",
":hover": {
"background": "blue",
"color": "white",
},
},
})),
]),
h("body", {}, [
h("ul", {}, [
...(isRoot ? [] : [
h("a", { href: `/${parentPath(pathname)}`, }, ".."),
]),
...dirs.map((dir) => h("li", {}, [
h("a", { href: `/${pathname}/${dir}`, }, dir + "/"),
])),
...files.map((file) => h("li", {}, [
h("a", { href: `/${pathname}/${file}`, }, file),
])),
]),
]),
]))
}
}
}
export type RateLimiterOpts = {
time: number,
limit: number,
handler: Handler,
}
export function rateLimiter(opts: RateLimiterOpts): Handler {
const reqCounter: Record<string, number> = {}
return (ctx) => {
const ip = ctx.req.getIP()
if (!ip) return ctx.next()
if (!(ip in reqCounter)) {
reqCounter[ip] = 0
}
reqCounter[ip] += 1
setTimeout(() => {
reqCounter[ip] -= 1
if (reqCounter[ip] === 0) {
delete reqCounter[ip]
}
}, opts.time * 1000)
if (reqCounter[ip] > opts.limit) {
ctx.res.status = 429
return opts.handler(ctx)
}
return ctx.next()
}
}
export function toHTTPDate(d: Date) {
return d.toUTCString()
}
export type LoggerOpts = {
filter?: (req: Req, res: Res) => boolean,
db?: string,
file?: string,
stdout?: boolean,
stderr?: boolean,
}
export function toReadableSize(byteSize: number) {
const toFixed = (n: number) => Number(n.toFixed(2))
if (byteSize >= Math.pow(1024, 4)) {
return `${toFixed(byteSize / 1024 / 1024 / 1024 / 1024)}tb`
} else if (byteSize >= Math.pow(1024, 3)) {
return `${toFixed(byteSize / 1024 / 1024 / 1024)}gb`
} else if (byteSize >= Math.pow(1024, 2)) {
return `${toFixed(byteSize / 1024 / 1024)}mb`
} else if (byteSize >= Math.pow(1024, 1)) {
return `${toFixed(byteSize / 1024)}kb`
} else {
return `${byteSize}b`
}
}
// TODO: is there a way to get bun calculated Content-Length result?
// TODO: ReadableStream?
export function getBodySize(body: BodyInit) {
if (typeof body === "string") {
return Buffer.byteLength(body)
} else if (body instanceof Blob) {
return body.size
} else if (body instanceof ArrayBuffer || "byteLength" in body) {
return body.byteLength
} else if (body instanceof URLSearchParams) {
return Buffer.byteLength(body.toString())
} else if (body instanceof FormData) {
let size = 0
body.forEach((v, k) => {
if (typeof v === "string") {
size += Buffer.byteLength(v)
} else {
size += v.size
}
})
return size
}
return 0
}
// TODO: can there be a onStart() to record time
export function logger(opts: LoggerOpts = {}): Handler {
let reqTable: Table | null = null
if (opts.db) {
const db = createDatabase(opts.db)
reqTable = db.table("request", {
"id": { type: "INTEGER", primaryKey: true, autoIncrement: true },
"method": { type: "TEXT" },
"path": { type: "TEXT" },
"params": { type: "TEXT" },
"ip": { type: "TEXT", allowNull: true },
"err": { type: "TEXT", allowNull: true },
}, {
timeCreated: true,
})
}
return ({ req, res, next, onFinish, onError }) => {
if (opts.filter) {
if (!opts.filter(req, res)) {
return next()
}
}
const genMsg = (msgOpts: {
color?: boolean,
} = {}) => {
const a = mapValues(ansi, (v) => {
if (msgOpts.color) {
return v
} else {
if (typeof v === "string") {
return ""
} else if (typeof v === "function") {
return () => ""
}
return v
}
})
const endTime = new Date()
const msg = []
const year = endTime.getUTCFullYear().toString().padStart(4, "0")
const month = (endTime.getUTCMonth() + 1).toString().padStart(2, "0")
const date = endTime.getUTCDate().toString().padStart(2, "0")
const hour = endTime.getUTCHours().toString().padStart(2, "0")
const minute = endTime.getUTCMinutes().toString().padStart(2, "0")
const seconds = endTime.getUTCSeconds().toString().padStart(2, "0")
// TODO: why this turns dim red for 4xx and 5xx responses?
msg.push(`${a.dim}[${year}-${month}-${date} ${hour}:${minute}:${seconds}]${a.reset}`)
const statusClor = {
"1": a.yellow,
"2": a.green,
"3": a.blue,
"4": a.red,
"5": a.red,
}[res.status.toString()[0]] ?? a.yellow
msg.push(`${a.bold}${statusClor}${res.status}${a.reset}`)
msg.push(req.method)
msg.push(req.url.pathname)
msg.push(`${a.dim}${endTime.getTime() - startTime.getTime()}ms${a.reset}`)
const size = res.body ? getBodySize(res.body) : 0
if (size) {
msg.push(`${a.dim}${toReadableSize(size)}${a.reset}`)
}
return msg.join(" ")
}
const startTime = new Date()
onFinish(() => {
if (opts.stdout !== false) {
console.log(genMsg({ color: true }))
}
if (opts.file) {
fs.appendFileSync(opts.file, genMsg({ color: false }) + "\n", "utf8")
}
if (reqTable) {
reqTable.insert({
"method": req.method,
"path": req.url.pathname,
"params": req.url.search,
"ip": req.getIP(),
})
}
})
onError((e) => {
if (reqTable) {
// TODO
}
})
return next()
}
}
const trimSlashes = (str: string) => str.replace(/\/*$/, "").replace(/^\/*/, "")
const parentPath = (p: string, sep = "/") => p.split(sep).slice(0, -1).join(sep)
export function matchPath(pat: string, url: string): Record<string, string> | null {
pat = pat.replace(/\/$/, "")
url = url.replace(/\/$/, "")
if (pat === url) return {}
const vars = pat.match(/:[^\/]+/g) || []
let regStr = pat
for (const v of vars) {
const name = v.substring(1)
regStr = regStr.replace(v, `(?<${name}>[^\/]+)`)
}
regStr = "^" + regStr + "$"
const reg = new RegExp(regStr)
const matches = reg.exec(url)
if (matches) {
return { ...matches.groups }
} else {
return null
}
}
export type ColumnType =
| "INTEGER"
| "TEXT"
| "BOOLEAN"
| "REAL"
| "BLOB"
export type ColumnDef = {
type: ColumnType,
primaryKey?: boolean,
autoIncrement?: boolean,
allowNull?: boolean,
unique?: boolean,
default?: string | number,
index?: boolean,
fts?: boolean,
reference?: {
table: string,
column: string,
},
}
export type CreateDatabaseOpts = {
wal?: boolean,
}
export type WhereOp =
| "="
| ">"
| "<"
| ">="
| "<="
| "!="
| "BETWEEN"
| "LIKE"
| "IN"
| "NOT BETWEEN"
| "NOT LIKE"
| "NOT IN"
export type WhereOpSingle =
| "IS NULL"
| "IS NOT NULL"
export type WhereValue =
| string
| { value: string, op: WhereOp }
| { op: WhereOpSingle }
export type DBVal = string | number | boolean | Uint8Array | null
export type DBVars = Record<string, DBVal>
export type DBData = Record<string, DBVal>
export type WhereCondition = Record<string, WhereValue>
export type OrderCondition = {
columns: string[],
desc?: boolean,
}
export type LimitCondition = number
export type SelectOpts = {
columns?: "*" | ColumnName[],
distinct?: boolean,
where?: WhereCondition,
order?: OrderCondition,
limit?: LimitCondition,
join?: JoinTable<any>[],
}
export type ColumnName = string | {
name: string,
as: string,
}
export type JoinType =
| "INNER"
| "LEFT"
| "RIGHT"
| "FULL"
export type JoinTable<D> = {
table: Table<D>,
columns?: "*" | ColumnName[],
on: {
column: string,
matchTable: Table<any>,
matchColumn: string,
},
where?: WhereCondition,
order?: OrderCondition,
join?: JoinType,
}
export type TableSchema = Record<string, ColumnDef>
export type Table<D = DBData> = {
name: string,
select: <D2 = D>(opts?: SelectOpts) => D2[],
insert: (data: D) => void,
update: (data: Partial<D>, where: WhereCondition) => void,
delete: (where: WhereCondition) => void,
find: <D2 = D>(where: WhereCondition) => D2,
findAll: <D2 = D>(where: WhereCondition) => D2[],
count: (where?: WhereCondition) => number,
search: (text: string) => D[],
schema: TableSchema,
}
export type TableOpts<D> = {
timeCreated?: boolean,
timeUpdated?: boolean,
paranoid?: boolean,
initData?: D[],
}
type TableData<D extends DBData, O extends TableOpts<D>> =
(O extends { timeCreated: true } ? D & { time_created?: string } : D)
& (O extends { timeUpdated: true } ? D & { time_updated?: string } : D)
& (O extends { paranoid: true } ? D & { time_deleted?: string } : D)
// https://discord.com/channels/508357248330760243/1203901900844572723
// typescript has no partial type inference...
export type Database = {
table: <D extends DBData, O extends TableOpts<D> = TableOpts<D>>(
name: string,
schema: TableSchema,
opts?: O,
) => Table<TableData<D, O>>,
getTable: <D extends DBData = any>(name: string) => Table<D> | void,
transaction: (action: () => void) => void,
close: () => void,
serialize: (name?: string) => Buffer,
}
// TODO: support views
// TODO: builtin cache system
export function createDatabase(dbname: string, opts: CreateDatabaseOpts = {}): Database {
const bdb = new sqlite.Database(dbname)
const queries: Record<string, sqlite.Statement> = {}
if (opts.wal) {
bdb.run("PRAGMA journal_mode = WAL;")
}
function compile(sql: string) {
sql = sql.trim()
if (!queries[sql]) {
queries[sql] = bdb.query(sql)
}
return queries[sql]
}
function genColumnNameSQL(columns: "*" | ColumnName[] = "*") {
if (!columns || columns === "*") return "*"
return columns.map((c) => {
if (typeof c === "string") return c
if (c.as) return `${c.name} AS ${c.as}`
}).join(",")
}
// TODO: support OR
function genWhereSQL(where: WhereCondition, vars: DBVars) {
return `WHERE ${Object.entries(where).map(([k, v]) => {
if (typeof v === "object") {
if ("value" in v) {
vars[`$where_${k}`] = v.value
return `${k} ${v.op} $where_${k}`
} else {
return `${k} ${v.op}`
}
} else {
vars[`$where_${k}`] = v
return `${k} = $where_${k}`
}
}).join(" AND ")}`
}
function genOrderSQL(order: OrderCondition) {
return `ORDER BY ${order.columns.join(", ")}${order.desc ? " DESC" : ""}`
}
function genLimitSQL(limit: LimitCondition, vars: DBVars) {
vars["$limit"] = limit
return `LIMIT $limit`
}
// TODO: support multiple values
function genValuesSQL(data: DBData, vars: DBVars) {
return `VALUES (${Object.entries(data).map(([k, v]) => {
vars[`$value_${k}`] = v
return `$value_${k}`
}).join(", ")})`
}
const specialVars = new Set([
"CURRENT_TIMESTAMP",
])
function genSetSQL(data: DBData, vars: DBVars) {
return `SET ${Object.entries(data).map(([k, v]) => {
if (typeof v === "string" && specialVars.has(v)) {
return `${k} = ${v}`
} else {
vars[`$set_${k}`] = v
return `${k} = $set_${k}`
}
}).join(", ")}`
}
function genColumnSQL(name: string, opts: ColumnDef) {
let code = name + " " + opts.type
if (opts.primaryKey) code += " PRIMARY KEY"
if (opts.autoIncrement) code += " AUTOINCREMENT"
if (!opts.allowNull) code += " NOT NULL"
if (opts.unique) code += " UNIQUE"
if (opts.default !== undefined) code += ` DEFAULT ${opts.default}`
if (opts.reference) code += ` REFERENCES ${opts.reference.table}(${opts.reference.column})`
return code
}
function genColumnsSQL(input: Record<string, ColumnDef>) {
return Object.entries(input)
.map(([name, opts]) => " " + genColumnSQL(name, opts))
.join(",\n")
}
function transaction(action: () => void) {
return bdb.transaction(action)()
}
function run(sql: string) {