@jon49/sw 0.13.0 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/routes.ts +43 -56
- package/package.json +2 -2
package/lib/routes.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
let {
|
|
1
|
+
let { links, globalDb } =
|
|
2
2
|
// @ts-ignore
|
|
3
3
|
self.app as { links: { file: string, url: string }[], html: Function, db: any, globalDb: any }
|
|
4
4
|
|
|
@@ -7,21 +7,20 @@ if (!links) {
|
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
function redirect(req: Request) {
|
|
10
|
-
|
|
10
|
+
return Response.redirect(req.referrer, 303)
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
const searchParamsHandler = {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
get(obj: any, prop: string) {
|
|
15
|
+
if (prop === "_url") {
|
|
16
|
+
return obj
|
|
17
|
+
}
|
|
18
|
+
return obj.searchParams.get(prop)
|
|
17
19
|
}
|
|
18
|
-
return obj.searchParams.get(prop)
|
|
19
|
-
}
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
function searchParams<TReturn>(
|
|
23
|
-
|
|
24
|
-
return new Proxy(url, searchParamsHandler)
|
|
22
|
+
function searchParams<TReturn>(url: URL): TReturn & { _url: URL } {
|
|
23
|
+
return new Proxy(url, searchParamsHandler)
|
|
25
24
|
}
|
|
26
25
|
|
|
27
26
|
interface ResponseOptions {
|
|
@@ -36,15 +35,15 @@ let isHtml = (value: any) =>
|
|
|
36
35
|
&& value.throw instanceof Function
|
|
37
36
|
|
|
38
37
|
// @ts-ignore
|
|
39
|
-
export async function getResponse(event: FetchEvent): Promise<Response>
|
|
38
|
+
export async function getResponse(event: FetchEvent): Promise<Response> {
|
|
40
39
|
try {
|
|
41
|
-
const req
|
|
40
|
+
const req: Request = event.request
|
|
42
41
|
const url = normalizeUrl(req.url)
|
|
43
42
|
return (
|
|
44
43
|
!url.pathname.startsWith("/web/")
|
|
45
44
|
? fetch(req)
|
|
46
|
-
|
|
47
|
-
} catch(error) {
|
|
45
|
+
: executeHandler({ url, req, event }))
|
|
46
|
+
} catch (error) {
|
|
48
47
|
console.error("Get Response Error", error)
|
|
49
48
|
return new Response("Oops something happened which shouldn't have!")
|
|
50
49
|
}
|
|
@@ -53,7 +52,7 @@ export async function getResponse(event: FetchEvent): Promise<Response> {
|
|
|
53
52
|
function getErrors(errors: any): string[] {
|
|
54
53
|
return typeof errors === "string"
|
|
55
54
|
? [errors]
|
|
56
|
-
|
|
55
|
+
: call(options.handleErrors, errors) ?? []
|
|
57
56
|
}
|
|
58
57
|
|
|
59
58
|
function isHtmf(req: Request) {
|
|
@@ -66,12 +65,13 @@ function htmfHeader(req: Request, events: any = {}, messages: string[] = [])
|
|
|
66
65
|
let userMessages =
|
|
67
66
|
messages?.length > 0
|
|
68
67
|
? { "user-messages": messages }
|
|
69
|
-
|
|
68
|
+
: null
|
|
70
69
|
return {
|
|
71
70
|
"hf-events": JSON.stringify({
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
71
|
+
...userMessages,
|
|
72
|
+
...(events || {})
|
|
73
|
+
}) ?? "{}"
|
|
74
|
+
}
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
function call(fn: Function | undefined, args: any) {
|
|
@@ -90,7 +90,7 @@ function isMethod(method: unknown) {
|
|
|
90
90
|
|
|
91
91
|
let cache = new Map<string, any>()
|
|
92
92
|
export async function findRoute(url: URL, method: unknown) {
|
|
93
|
-
let validMethod
|
|
93
|
+
let validMethod: MethodTypes = isMethod(method)
|
|
94
94
|
if (validMethod) {
|
|
95
95
|
// @ts-ignore
|
|
96
96
|
if (!self.app?.routes) {
|
|
@@ -102,7 +102,7 @@ export async function findRoute(url: URL, method: unknown) {
|
|
|
102
102
|
// @ts-ignore
|
|
103
103
|
if (r.file
|
|
104
104
|
&& (r.route instanceof RegExp && r.route.test(url.pathname)
|
|
105
|
-
|
|
105
|
+
|| (r.route instanceof Function && r.route(url)))) {
|
|
106
106
|
let file = links?.find(x => x.url === r.file)?.file
|
|
107
107
|
// Load file
|
|
108
108
|
if (!file) {
|
|
@@ -142,7 +142,7 @@ interface ExectuteHandlerOptions {
|
|
|
142
142
|
// @ts-ignore
|
|
143
143
|
event: FetchEvent
|
|
144
144
|
}
|
|
145
|
-
async function executeHandler({ url, req, event }: ExectuteHandlerOptions)
|
|
145
|
+
async function executeHandler({ url, req, event }: ExectuteHandlerOptions): Promise<Response> {
|
|
146
146
|
let method = req.method.toLowerCase()
|
|
147
147
|
let isPost = method === "post"
|
|
148
148
|
if (!isPost) {
|
|
@@ -153,16 +153,6 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
153
153
|
if (url.searchParams.get("login") === "success") {
|
|
154
154
|
await globalDb.setLoggedIn(true)
|
|
155
155
|
}
|
|
156
|
-
|
|
157
|
-
let lastUrl: string | undefined
|
|
158
|
-
if (url.pathname === "/web/" && (lastUrl = (await db.get("last-url"))?.url)) {
|
|
159
|
-
url = new URL(lastUrl)
|
|
160
|
-
} else if (url.searchParams.has("pushUrl") || url.searchParams.has("hz")) {
|
|
161
|
-
let saveUrl = new URL(url.href)
|
|
162
|
-
saveUrl.searchParams.delete("pushUrl")
|
|
163
|
-
saveUrl.searchParams.delete("hz")
|
|
164
|
-
await db.set("last-url", { url: saveUrl.href }, { sync: false })
|
|
165
|
-
}
|
|
166
156
|
}
|
|
167
157
|
|
|
168
158
|
let handlers =
|
|
@@ -174,19 +164,19 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
174
164
|
try {
|
|
175
165
|
let messages: string[] = []
|
|
176
166
|
const data = await getData(req)
|
|
177
|
-
let query = searchParams<{ handler?: string }>(
|
|
167
|
+
let query = searchParams<{ handler?: string }>(url)
|
|
178
168
|
let args = { req, data, query }
|
|
179
169
|
let result = await (
|
|
180
170
|
handlers instanceof Function
|
|
181
171
|
? handlers(args)
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
172
|
+
: (call(handlers[query.handler ?? ""], args)
|
|
173
|
+
|| call(handlers[method], args)
|
|
174
|
+
|| Promise.reject("I'm sorry, I didn't understand where to route your request.")))
|
|
185
175
|
|
|
186
176
|
if (!result) {
|
|
187
177
|
return isPost
|
|
188
178
|
? redirect(req)
|
|
189
|
-
|
|
179
|
+
: new Response("Not Found!", { status: 404 })
|
|
190
180
|
}
|
|
191
181
|
|
|
192
182
|
if (isPost && result.message == null) {
|
|
@@ -194,10 +184,6 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
194
184
|
}
|
|
195
185
|
|
|
196
186
|
if (isHtml(result)) {
|
|
197
|
-
if (url.searchParams.has("hz")) {
|
|
198
|
-
result = html`<template>${result}</template>`
|
|
199
|
-
}
|
|
200
|
-
|
|
201
187
|
return streamResponse({
|
|
202
188
|
body: result,
|
|
203
189
|
headers: htmfHeader(req, null, messages)
|
|
@@ -226,9 +212,9 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
226
212
|
}
|
|
227
213
|
}
|
|
228
214
|
return new Response(result.body, {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
215
|
+
status: result.status ?? 200,
|
|
216
|
+
headers: result.headers
|
|
217
|
+
})
|
|
232
218
|
}
|
|
233
219
|
|
|
234
220
|
} catch (error) {
|
|
@@ -240,7 +226,7 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
240
226
|
return new Response("Not Found!", { status: 404 })
|
|
241
227
|
}
|
|
242
228
|
} else {
|
|
243
|
-
let errors
|
|
229
|
+
let errors: string[] = getErrors(error)
|
|
244
230
|
let headers = htmfHeader(req, {}, errors)
|
|
245
231
|
return new Response(null, {
|
|
246
232
|
status: isPost ? 400 : 500,
|
|
@@ -257,7 +243,7 @@ async function executeHandler({ url, req, event }: ExectuteHandlerOptions) : Pro
|
|
|
257
243
|
}
|
|
258
244
|
|
|
259
245
|
async function getData(req: Request) {
|
|
260
|
-
let o
|
|
246
|
+
let o: any = {}
|
|
261
247
|
if (req.headers.get("content-type")?.includes("application/x-www-form-urlencoded")) {
|
|
262
248
|
const formData = await req.formData()
|
|
263
249
|
for (let [key, val] of formData.entries()) {
|
|
@@ -278,7 +264,7 @@ async function getData(req: Request) {
|
|
|
278
264
|
return o
|
|
279
265
|
}
|
|
280
266
|
|
|
281
|
-
async function cacheResponse(url: string, event?: { request: string | Request } | undefined)
|
|
267
|
+
async function cacheResponse(url: string, event?: { request: string | Request } | undefined): Promise<Response> {
|
|
282
268
|
url = links?.find(x => x.url === url)?.file || url
|
|
283
269
|
const match = await caches.match(url)
|
|
284
270
|
if (match) return match
|
|
@@ -294,10 +280,10 @@ async function cacheResponse(url: string, event?: { request: string | Request }
|
|
|
294
280
|
}
|
|
295
281
|
|
|
296
282
|
const encoder = new TextEncoder()
|
|
297
|
-
function streamResponse(response: { body: Generator, headers?: any })
|
|
283
|
+
function streamResponse(response: { body: Generator, headers?: any }): Response {
|
|
298
284
|
let { body, headers } = response
|
|
299
285
|
const stream = new ReadableStream({
|
|
300
|
-
async start(controller
|
|
286
|
+
async start(controller: ReadableStreamDefaultController<any>) {
|
|
301
287
|
try {
|
|
302
288
|
for await (let x of body) {
|
|
303
289
|
if (typeof x === "string")
|
|
@@ -314,17 +300,18 @@ function streamResponse(response: { body: Generator, headers?: any }) : Response
|
|
|
314
300
|
headers: {
|
|
315
301
|
"content-type": "text/html; charset=utf-8",
|
|
316
302
|
...headers,
|
|
317
|
-
}
|
|
303
|
+
}
|
|
304
|
+
})
|
|
318
305
|
}
|
|
319
306
|
|
|
320
307
|
/**
|
|
321
308
|
* /my/url -> /my/url/
|
|
322
309
|
* /my/script.js -> /my/script.js
|
|
323
310
|
*/
|
|
324
|
-
function normalizeUrl(url: string)
|
|
311
|
+
function normalizeUrl(url: string): URL {
|
|
325
312
|
let uri = new URL(url)
|
|
326
313
|
let path = uri.pathname
|
|
327
|
-
!uri.pathname.endsWith("/") && (uri.pathname = isFile(path) ? path : path+"/")
|
|
314
|
+
!uri.pathname.endsWith("/") && (uri.pathname = isFile(path) ? path : path + "/")
|
|
328
315
|
return uri
|
|
329
316
|
}
|
|
330
317
|
|
|
@@ -340,10 +327,10 @@ export interface RouteGetArgs {
|
|
|
340
327
|
export interface RoutePostArgs {
|
|
341
328
|
query: any
|
|
342
329
|
data: any
|
|
343
|
-
req: Request
|
|
330
|
+
req: Request
|
|
344
331
|
}
|
|
345
332
|
|
|
346
|
-
export interface
|
|
333
|
+
export interface RouteObjectReturn {
|
|
347
334
|
body?: string | AsyncGenerator | null
|
|
348
335
|
status?: number
|
|
349
336
|
headers?: any
|
|
@@ -360,7 +347,7 @@ export interface RouteHandler<T> {
|
|
|
360
347
|
| RouteObjectReturn
|
|
361
348
|
| undefined
|
|
362
349
|
| null
|
|
363
|
-
| void
|
|
350
|
+
| void>
|
|
364
351
|
}
|
|
365
352
|
|
|
366
353
|
export interface RoutePostHandler {
|
|
@@ -379,7 +366,7 @@ interface Route_ {
|
|
|
379
366
|
}
|
|
380
367
|
|
|
381
368
|
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
|
|
382
|
-
Pick<T, Exclude<keyof T, Keys>>
|
|
369
|
+
Pick<T, Exclude<keyof T, Keys>>
|
|
383
370
|
& {
|
|
384
371
|
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>
|
|
385
372
|
}[Keys]
|
package/package.json
CHANGED