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