forked from jcubic/wayne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.umd.js
629 lines (617 loc) · 17.6 KB
/
index.umd.js
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
/*
* Wayne - Server Worker Routing library (v. 0.16.5)
*
* Copyright (c) 2022-2024 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under MIT license
*
* Thu, 06 Jun 2024 16:55:58 +0000
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.wayne = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FileSystem = FileSystem;
exports.HTTPResponse = void 0;
exports.RouteParser = RouteParser;
exports.Wayne = void 0;
exports.rpc = rpc;
exports.send = send;
/*
* Wayne - Server Worker Routing library (v. 0.16.5)
*
* Copyright (c) 2022-2024 Jakub T. Jankiewicz <https://jcubic.pl/me>
* Released under MIT license
*/
const root_url = get_root_path();
const root_url_re = new RegExp('^' + escape_re(root_url));
function same_origin(origin) {
return origin === self.location.origin;
}
function get_root_path() {
if (self.registration) {
const url = new URL(registration.scope);
return url.pathname.replace(/\/$/, '');
}
return location.pathname.replace(/\/[^\/]+$/, '');
}
function normalize_url(url) {
return url.replace(root_url_re, '');
}
function escape_re(str) {
if (typeof str == 'string') {
var special = /([\^\$\[\]\(\)\{\}\+\*\.\|\?])/g;
return str.replace(special, '\\$1');
}
}
function is_function(arg) {
return typeof arg === 'function';
}
function is_promise(arg) {
return arg && typeof arg === 'object' && is_function(arg.then);
}
// taken from Isomorphic-git MIT license
function isPromiseFs(fs) {
const test = targetFs => {
try {
// If readFile returns a promise then we can probably assume the other
// commands do as well
return targetFs.readFile().catch(e => e);
} catch (e) {
return e;
}
};
return is_promise(test(fs));
}
// List of commands all filesystems are expected to provide
const commands = ['stat', 'readdir', 'readFile'];
function bind_fs(fs) {
const result = {};
if (isPromiseFs(fs)) {
for (const command of commands) {
result[command] = fs[command].bind(fs);
}
} else {
for (const command of commands) {
result[command] = function (...args) {
return new Promise((resolve, reject) => {
fs[command](...args, function (err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
};
}
}
return result;
}
// -----------------------------------------------------------------------------
// :: Wayne Route Response Class
// -----------------------------------------------------------------------------
class HTTPResponse {
constructor(resolve, reject) {
this._resolve = resolve;
this._reject = reject;
}
html(data, init) {
this.send(data, {
type: 'text/html',
...init
});
}
text(data, init) {
this.send(data, init);
}
json(data, init) {
this.send(JSON.stringify(data), {
type: 'application/json',
...init
});
}
blob(blob, init = {}) {
this._resolve(new Response(blob, init));
}
send(data, {
type = 'text/plain',
...init
} = {}) {
if (![undefined, null].includes(data)) {
data = new Blob([data], {
type
});
}
this.blob(data, init);
}
async fetch(arg) {
if (typeof arg === 'string') {
const _res = await fetch(arg);
const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
this.send(await _res.arrayBuffer(), {
type
});
} else if (arg instanceof Request) {
return fetch(arg).then(this._resolve).catch(this._reject);
}
}
download(content, {
filename = 'download',
type = 'text/plain',
...init
} = {}) {
const headers = {
'Content-Disposition': `attachment; filename="${filename}"`
};
this.send(content, {
type,
headers,
...init
});
}
redirect(code, url) {
if (url === undefined) {
url = code;
code = 302;
}
if (!url.match(/https?:\/\//)) {
url = root_url + url;
}
this._resolve(Response.redirect(url, code));
}
sse({
onClose
} = {}) {
let send, close, stream, defunct;
stream = new ReadableStream({
cancel() {
defunct = true;
trigger(onClose);
},
start: controller => {
send = function (event) {
if (!defunct) {
const chunk = createChunk(event);
const payload = new TextEncoder().encode(chunk);
controller.enqueue(payload);
}
};
close = function close() {
controller.close();
stream = null;
trigger(onClose);
};
}
});
this._resolve(new Response(stream, {
headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive'
}
}));
return {
send,
close
};
}
}
// -----------------------------------------------------------------------------
// :: Route Parser
// :: code based on https://github.com/jcubic/route.js
// :: Copyright (C) 2014-2017 Jakub T. Jankiewicz <https://jcubic.pl/me>
// -----------------------------------------------------------------------------
exports.HTTPResponse = HTTPResponse;
function RouteParser() {
const name_re = '[a-zA-Z_][a-zA-Z_0-9]*';
const self = this;
const open_tag = '{';
const close_tag = '}';
const glob = '*';
const number = '\\d';
const optional = '?';
const open_group = '(';
const close_group = ')';
const plus = '+';
const dot = '.';
self.route_parser = function (open, close) {
const routes = {};
const tag_re = new RegExp('(' + escape_re(open) + name_re + escape_re(close) + ')', 'g');
const tokenizer_re = new RegExp(['(', escape_re(open), name_re, escape_re(close), '|', escape_re(glob), '|', escape_re(number), '|', escape_re(dot), '|', escape_re(optional), '|', escape_re(open_group), '|', escape_re(close_group), '|', escape_re(plus), ')'].join(''), 'g');
const clear_re = new RegExp(escape_re(open) + '(' + name_re + ')' + escape_re(close), 'g');
return function (str) {
const result = [];
let index = 0;
let parentheses = 0;
str = str.split(tokenizer_re).map(function (chunk, i, chunks) {
if (chunk === open_group) {
parentheses++;
} else if (chunk === close_group) {
parentheses--;
}
if ([open_group, plus, close_group, optional, dot, number].includes(chunk)) {
return chunk;
} else if (chunk === glob) {
result.push(index++);
return '(.*?)';
} else if (chunk.match(tag_re)) {
result.push(chunk.replace(clear_re, '$1'));
return '([^\\/]+)';
} else {
return chunk;
}
}).join('');
if (parentheses !== 0) {
throw new Error(`Wayne: Unbalanced parentheses in an expression: ${str}`);
}
return {
re: str,
names: result
};
};
};
const parse = self.route_parser(open_tag, close_tag);
self.parse = parse;
self.pick = function (routes, url, origin) {
let input;
let keys;
if (routes instanceof Array) {
input = {};
keys = routes;
routes.map(function (route) {
input[route] = route;
});
} else {
keys = Object.keys(routes);
input = routes;
}
const results = [];
for (let i = keys.length; i--;) {
const key = keys[i];
let pattern;
// check if origin match for full URL
if (key.match(/:\/\//)) {
const url = new URL(key);
if (url.origin !== origin) {
continue;
}
pattern = key.replace(url.origin, '');
} else if (!same_origin(origin)) {
// skip different origin
continue;
} else {
pattern = key;
}
const parts = parse(pattern);
const m = url.match(new RegExp('^' + parts.re + '$'));
if (m) {
const matched = m.slice(1);
const data = {};
if (matched.length) {
parts.names.forEach((name, i) => {
data[name] = matched[i];
});
}
results.push({
pattern: key,
data
});
}
}
return results;
};
}
function html(content) {
return ['<!DOCTYPE html>', '<html>', '<head>', '<meta charset="UTF-8">', '<title>Wayne Service Worker</title>', '</head>', '<body>', ...content, '</body>', '</html>'].join('\n');
}
function error500(error) {
var output = html(['<h1>Wayne: 500 Server Error</h1>', '<p>Service worker give 500 error</p>', `<p>${error.message || error}</p>`, `<pre>${error.stack || ''}</pre>`]);
return [output, {
status: 500,
statusText: '500 Server Error'
}];
}
function dir(prefix, path, list) {
var output = html(['<h1>Wayne</h1>', `<p>Content of ${path}</p>`, '<ul>', ...list.map(name => {
return `<li><a href="${root_url}${prefix}${path}${name}">${name}</a></li>`;
}), '</ul>']);
return [output, {
status: 404,
statusText: '404 Page Not Found'
}];
}
function error404(path) {
var output = html(['<h1>Wayne: 404 File Not Found</h1>', `<p>File ${path} not found`]);
return [output, {
status: 404,
statusText: '404 Page Not Found'
}];
}
function createChunk({
data,
event,
retry,
id
}) {
return Object.entries({
event,
id,
data,
retry
}).filter(([, value]) => value).map(([key, value]) => `${key}: ${value}`).join('\n') + '\n\n';
}
function trigger(maybeFn, ...args) {
if (typeof maybeFn === 'function') {
maybeFn(...args);
}
}
function chain_handlers(handlers, callback) {
if (handlers.length) {
return new Promise((resolve, reject) => {
let i = 0;
(async function recur() {
const handler = handlers[i];
if (!handler) {
return resolve();
}
try {
await callback(handler, function next() {
i++;
recur();
});
} catch (error) {
reject(error);
}
})();
});
}
}
async function list_dir({
fs,
path
}, path_name) {
const names = await fs.readdir(path_name);
return Promise.all(names.map(async name => {
const fullname = path.join(path_name, name);
const stat = await fs.stat(fullname);
if (stat.isDirectory()) {
return `${name}/`;
}
return name;
}));
}
// -----------------------------------------------------------------------------
// :: File System
// -----------------------------------------------------------------------------
function FileSystem(options) {
let {
path,
prefix = '',
test,
dir = () => '/',
fs,
mime,
default_file = 'index.html'
} = options;
fs = bind_fs(fs);
const parser = new RouteParser();
if (prefix && !prefix.startsWith('/')) {
prefix = `/${prefix}`;
}
if (!test) {
test = url => url.pathname.startsWith(prefix);
}
async function serve(res, path_name) {
const ext = path.extname(path_name);
const type = mime.getType(ext);
const data = await fs.readFile(path_name);
res.send(data, {
type
});
}
return async function (req, res, next) {
const method = req.method;
const url = new URL(req.url);
let path_name = normalize_url(decodeURIComponent(url.pathname));
url.pathname = path_name;
if (!(same_origin(url.origin) && (await test(url)))) {
return next();
}
if (req.method !== 'GET') {
return res.send('Method Not Allowed', {
status: 405
});
}
if (prefix) {
path_name = path_name.substring(prefix.length);
}
if (!path_name) {
path_name = '/';
}
path_name = path.join(await dir(), path_name);
try {
const stat = await fs.stat(path_name);
if (stat.isFile()) {
await serve(res, path_name);
} else if (stat.isDirectory()) {
const default_path = path.join(path_name, default_file);
const stat = await fs.stat(default_path);
if (stat.isFile()) {
await serve(res, default_path);
} else {
res.html(...dir(prefix, path_name, await list_dir({
fs,
path
}, path_name)));
}
}
} catch (e) {
console.log(e.stack);
if (typeof stat === 'undefined') {
res.html(...error404(path_name));
} else {
res.html(...error500(error));
}
}
};
}
// -----------------------------------------------------------------------------
// :: Main Wayne Constructor
// -----------------------------------------------------------------------------
class Wayne {
constructor({
filter = () => true
} = {}) {
this._er_handlers = [];
this._middlewares = [];
this._routes = {};
this._timeout = 5 * 60 * 1000; // 5 minutes
this._parser = new RouteParser();
self.addEventListener('fetch', event => {
if (filter(event.request) === false) {
return;
}
const promise = new Promise(async (resolve, reject) => {
const req = event.request;
try {
const res = new HTTPResponse(resolve, reject);
await chain_handlers(this._middlewares, function (fn, next) {
return fn(req, res, next);
});
const method = req.method;
const url = new URL(req.url);
const path = normalize_url(url.pathname);
const origin = url.origin;
const routes = this._routes[method];
if (routes) {
const match = this._parser.pick(routes, path, origin);
const have_wildcard = match.length > 1 && match.find(route => {
return !!route.pattern.match(/\*/);
});
if (match.length) {
let selected_route;
if (have_wildcard) {
selected_route = match.find(route => {
return !route.pattern.match(/\*/);
});
}
if (!(have_wildcard && selected_route)) {
selected_route = match[0];
}
const fns = [...this._middlewares, ...routes[selected_route.pattern]];
req.params = selected_route.data;
setTimeout(function () {
reject('Timeout Error');
}, this._timeout);
await chain_handlers(fns, (fn, next) => {
return fn(req, res, next);
});
return;
}
}
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
return;
}
fetch(event.request).then(resolve).catch(reject);
} catch (error) {
this._handle_error(resolve, req, error);
}
});
event.respondWith(promise.catch(() => {}));
});
['GET', 'POST', 'DELETE', 'PATCH', 'PUT'].forEach(method => {
this[method.toLowerCase()] = this.method(method);
});
}
_handle_error(resolve, req, error) {
const res = new HTTPResponse(resolve);
if (this._er_handlers.length) {
chain_handlers(this._er_handlers, function (handler, next) {
handler(error, req, res, next);
}, function (error) {
res.html(...error500(error));
});
} else {
res.html(...error500(error));
}
}
use(...fns) {
fns.forEach(fn => {
if (typeof fn === 'function') {
if (fn.length === 4) {
this._er_handlers.push(fn);
} else if (fn.length === 3) {
this._middlewares.push(fn);
}
}
});
}
method(method) {
return function (url, fn) {
if (!this._routes[method]) {
this._routes[method] = {};
}
const routes = this._routes[method];
if (!routes[url]) {
routes[url] = [];
}
routes[url].push(fn);
return this;
};
}
}
// -----------------------------------------------------------------------------
// :: RPC
// -----------------------------------------------------------------------------
exports.Wayne = Wayne;
function rpc(channel, methods) {
channel.addEventListener('message', async function handler(message) {
if (Object.keys(message.data).includes('method', 'id', 'args')) {
const {
method,
id,
args
} = message.data;
try {
const result = await methods[method](...args);
channel.postMessage({
id,
result
});
} catch (error) {
channel.postMessage({
id,
error
});
}
}
});
}
;
let rpc_id = 0;
function send(channel, method, args) {
return new Promise((resolve, reject) => {
const id = ++rpc_id;
const payload = {
id,
method,
args
};
channel.addEventListener('message', function handler(message) {
if (id == message.data.id) {
const data = message.data;
channel.removeEventListener('message', handler);
if (data.error) {
reject(data.error);
} else {
resolve(message.data);
}
}
});
channel.postMessage(payload);
});
}
;
},{}]},{},[1])(1)
});