Browse Source

Update

master
186526 3 months ago
parent
commit
efa5c2f2f2
Signed by: 186526 GPG Key ID: C7EB1E6B8CC5E51D
15 changed files with 1208 additions and 14 deletions
  1. 21
      .drone.yml
  2. 1
      .gitignore
  3. 402
      build/index.js
  4. 1
      build/index.min.js
  5. 494
      build/index.sw.js
  6. 1
      build/index.sw.min.js
  7. 5
      index.d.ts
  8. 15
      package.json
  9. 2
      src/sw/sw.js
  10. 12
      sw.js
  11. 8
      test/index.js
  12. 27
      test/sw/index.html
  13. 22
      test/sw/sw.js
  14. 1
      test/sw/sw2express.min.js
  15. 210
      yarn.lock

21
.drone.yml

@ -0,0 +1,21 @@
kind: pipeline
type: docker
name: build-dist
steps:
- name: build
image: node:alpine
commands:
- yarn add
- yarn dist
- name: git-push
image: appleboy/drone-git-push
settings:
key:
from_secret: ssh_key
remote: ssh://[email protected]:10022/186526/Sw2Express.git
remote_name: origin
branch: master
commit: true
commit_message: "[Drone] Auto Build Dist"

1
.gitignore

@ -1,4 +1,3 @@
build
node_modules
package
.vscode

402
build/index.js

@ -0,0 +1,402 @@
class nodeRequest {
constructor(req, body) {
this.req = req;
this.headers = req.headers;
this.method = req.method;
this.host = this.headers["x-forward-for"] || req.host;
this.protocol = this.headers["x-forward-proto"] || req.protocol;
this.path = req.url;
if (this.method === "POST") {
this.body = body;
}
}
}
class swRequest {
constructor(req, body) {
this.req = req;
this.headers = Object.fromEntries(req.headers.entries());
this.method = req.method;
this.url = new URL(req.url);
this.host = this.headers["x-forward-for"] || this.url.host;
this.path = this.url.pathname;
this.protocol = this.headers["x-forward-proto"] || this.url.protocol;
if (this.method === "POST") {
this.body = body;
}
}
}
const Headers = {
"Content-Type": "text/plain",
server: "Sw=>Express",
"X-Powered-By": (() => {
switch (checkPlatform()) {
case "NODE":
return `Node.js ${process.version}`;
case "SW":
return `Service Worker`;
default:
return "JavaScript";
}
})(),
"X-Served-By": "Sw=>Express",
};
class nodeReply {
constructor(response,request,options) {
this.request = request;
this.response = response;
this.statusCode = 200;
this.headers = Headers;
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
Nativesend(text) {
this.response.statusCode = this.statusCode;
for (let i in this.headers) {
this.response.setHeader(i, this.headers[i]);
}
this.isSendHeader = true;
this.response.write(text);
return this;
}
send(text){
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
}
async end(text){
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
if(this.options.ETag){
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.setHeader('ETag',ETag);
if(ETag === this.request.headers["if-none-match"]){
this.statusCode = 304;
this.response.statusCode = this.statusCode;
this.response.end('');
return true;
}else {
this.Nativeend(this.MSG);
}
return true;
}
this.Nativeend(this.MSG);
return true;
}
json(text) {
this.response.statusCode = this.statusCode;
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
}
for (let i in this.headers) {
if (i !== "Content-Type") {
this.response.setHeader(i, this.headers[i]);
}
}
this.isSendHeader = true;
this.response.write(text);
return this;
}
Nativeend(text) {
if (!this.isSendHeader && text) this.Nativesend(text).Nativeend();
else this.response.end(text);
this.isEnd = true;
return true;
}
}
class swReply {
constructor(request,options) {
//this.response = response;
this.request = request;
this.statusCode = 200;
this.headers = Headers;
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
async GenResponse() {
if(this.options.ETag){
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.headers.ETag = ETag;
this.requestHeaders = Object.fromEntries(this.request.headers.entries());
if(ETag === this.requestHeaders["if-none-match"]){
return new Response(null,{
headers: this.headers,
status: 304
});
}
}
this.isSendHeader = true;
return new Response(this.MSG, {
headers: this.headers,
status: this.statusCode,
});
}
send(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
return this;
}
json(text) {
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
}
this.send(text);
return this;
}
end(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
this.isEnd = true;
return this;
}
}
function Code(statusCode) {
return {
GenAsync: async function (res, rep) {
rep.statusCode = statusCode;
rep.setHeader("Content-Type", "text/plain");
rep.send(`Error: ${statusCode}`);
},
};
}
//import http from "http";
async function startHTTPServer(PORT) {
const http = await import('http').then((e) => e.default);
const app = http.createServer();
if (PORT) {
app.listen(PORT);
}
return app;
}
async function doRequest$1(func, NodeRequest, NodeReply) {
const rep = await func(NodeRequest, NodeReply).catch(async (e) => {
await doRequest$1(Code(500).GenAsync, NodeRequest, NodeReply);
console.log(e.stack);
});
if (!NodeReply.isEnd) NodeReply.end(rep);
}
const newHTTPServer = async (port) => {
return async (that) => {
const server = await startHTTPServer(port);
server.on("request", await HTTPHandler(that));
return server;
};
};
const HTTPHandler = async (that) => {
return async (request, response) => {
let body = await new Promise((resolve) => {
if (request.method === "POST" && !request.body) {
let body = [];
request.on("data", (chunk) => body.push(chunk));
request.on("end", () => {
body = Buffer.concat(body).toString();
resolve(body);
});
} else if (request.body) {
resolve(request.body);
} else {
resolve();
}
});
let NodeRequest = new nodeRequest(request, body),
NodeReply = new nodeReply(response,request,that.options),
path = request.url;
new Promise((resolve) => {
if (that.options.logger) {
console.log(
`[${new Date().toLocaleString()}] ${request.socket.remoteAddress} - ${
request.method
} ${path}`
);
resolve();
}
});
await Promise.all(
that._middleWare.map((middleware) => middleware(NodeRequest, NodeReply))
);
if (that._route[path]) {
if (that._route[path][request.method]) {
await doRequest$1(
that._route[path][request.method],
NodeRequest,
NodeReply
);
} else if (that._route[path].all) {
await doRequest$1(that._route[path].all, NodeRequest, NodeReply);
} else {
await doRequest$1(Code(500).GenAsync, NodeRequest, NodeReply);
}
} else {
await doRequest$1(Code(404).GenAsync, NodeRequest, NodeReply);
}
};
};
const makeHandler = (that) => {
return async (request) => {
let body = "";
if (request.method === "POST") {
body = await request.text();
}
let req = new swRequest(request, body),
rep = new swReply(request,that.options),
answer;
const path = req.path;
await Promise.all(
that._middleWare.map((middleware) => middleware(req, rep))
);
if (that._route[path]) {
if (that._route[path][request.method]) {
answer = await doRequest(that._route[path][request.method], req, rep);
} else if (that._route[path].all) {
answer = await doRequest(that._route[path].all, req, rep);
} else {
answer = await doRequest(Code(500).GenAsync, req, rep);
}
} else {
answer = await doRequest(Code(404).GenAsync, req, rep);
}
return answer;
};
};
async function doRequest(func, req, rep) {
const funcAnswer = await func(req, rep).catch(async (e) => {
await doRequest(Code(500).GenAsync, req, rep);
console.log(e.stack);
});
if (!rep.isEnd) rep.end(funcAnswer);
return await rep.GenResponse();
}
var toMD5 = ()=>{
if(globalThis.platform==="NODE"){
const crypto = import('crypto').then(e=>e.default);
return async(text)=>{
const md5 = (await crypto).createHash("md5");
const answer = md5.update(text).digest('hex');
return answer;
}
}else if(globalThis.platform==="SW"){
return async(text)=>{
const textUint8 = new TextEncoder().encode(text);
const hashBuffer = await crypto.subtle.digest('MD5',textUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
}else {
return async(text)=>{
throw new Error("Can't Found Platform!");
}
}};
function checkPlatform() {
if (!(typeof process === "undefined")) {
return "NODE";
} else if (!(typeof self === "undefined")) {
return "SW";
} else {
return "UNKNOWN";
}
}
class sw2express {
constructor({ logger = false,ETag = true }) {
this.options = {
logger: logger,
ETag: ETag,
};
this._route = {};
this._middleWare = [];
globalThis.platform = checkPlatform();
globalThis.md5 = toMD5();
}
use(MiddleWare) {
this._middleWare.push(MiddleWare);
return this;
}
route(url) {
this._route[url] = {};
const that = {
POST: (func) => {
this._route[url].POST = func;
return that;
},
GET: (func) => {
this._route[url].GET = func;
return that;
},
all: (func) => {
this._route[url].all = func;
return that;
},
};
return that;
}
makeNewHandler(platform) {
switch (platform) {
case "NODE": {
return {
listen: (port) => newHTTPServer(port).then((e) => e(this)),
Handler: newHTTPServer()
.then((e) => e(this))
.then((e) => e),
};
}
case "SW": {
return makeHandler(this);
}
default:
return new Error("Invalid Platform");
}
}
listen(port) {
switch (checkPlatform()) {
case "NODE": {
let answer = "NODE",
Handler = this.makeNewHandler(answer);
Handler.listen(port);
return Handler;
}
case "SW": {
let answer = "SW",
Handler = this.makeNewHandler(answer);
self.addEventListener("fetch", (event) =>
event.respondWith(Handler(event.request))
);
return Handler;
}
}
}
async extend({ name, func, bootstrap }) {
this[name] = func;
return await bootstrap(this);
}
}
export default sw2express;
export { checkPlatform };

1
build/index.min.js
File diff suppressed because it is too large
View File

494
build/index.sw.js

@ -0,0 +1,494 @@
(async function(){
const sw2express = await Promise.resolve().then(function () { return index; });
const packageJson = await Promise.resolve().then(function () { return _package$1; });
if(!(self["sw2express-Version"] = packageJson.version)){
self["sw2express-Version"] = packageJson.version;
self.sw2express = sw2express.default;
self.checkPlatform = sw2express.checkPlatform;
}else {
console.warn("sw2express is loaded");
}
})();
class nodeRequest {
constructor(req, body) {
this.req = req;
this.headers = req.headers;
this.method = req.method;
this.host = this.headers["x-forward-for"] || req.host;
this.protocol = this.headers["x-forward-proto"] || req.protocol;
this.path = req.url;
if (this.method === "POST") {
this.body = body;
}
}
}
class swRequest {
constructor(req, body) {
this.req = req;
this.headers = Object.fromEntries(req.headers.entries());
this.method = req.method;
this.url = new URL(req.url);
this.host = this.headers["x-forward-for"] || this.url.host;
this.path = this.url.pathname;
this.protocol = this.headers["x-forward-proto"] || this.url.protocol;
if (this.method === "POST") {
this.body = body;
}
}
}
const Headers = {
"Content-Type": "text/plain",
server: "Sw=>Express",
"X-Powered-By": (() => {
switch (checkPlatform()) {
case "NODE":
return `Node.js ${process.version}`;
case "SW":
return `Service Worker`;
default:
return "JavaScript";
}
})(),
"X-Served-By": "Sw=>Express",
};
class nodeReply {
constructor(response,request,options) {
this.request = request;
this.response = response;
this.statusCode = 200;
this.headers = Headers;
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
Nativesend(text) {
this.response.statusCode = this.statusCode;
for (let i in this.headers) {
this.response.setHeader(i, this.headers[i]);
}
this.isSendHeader = true;
this.response.write(text);
return this;
}
send(text){
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
}
async end(text){
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
if(this.options.ETag){
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.setHeader('ETag',ETag);
if(ETag === this.request.headers["if-none-match"]){
this.statusCode = 304;
this.response.statusCode = this.statusCode;
this.response.end('');
return true;
}else {
this.Nativeend(this.MSG);
}
return true;
}
this.Nativeend(this.MSG);
return true;
}
json(text) {
this.response.statusCode = this.statusCode;
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
}
for (let i in this.headers) {
if (i !== "Content-Type") {
this.response.setHeader(i, this.headers[i]);
}
}
this.isSendHeader = true;
this.response.write(text);
return this;
}
Nativeend(text) {
if (!this.isSendHeader && text) this.Nativesend(text).Nativeend();
else this.response.end(text);
this.isEnd = true;
return true;
}
}
class swReply {
constructor(request,options) {
//this.response = response;
this.request = request;
this.statusCode = 200;
this.headers = Headers;
this.isSendHeader = false;
this.isEnd = false;
this.sendMsg = [];
this.options = options;
}
setHeader(name, value) {
this.headers[name] = value;
return this;
}
getHeader(name) {
return this.headers[name];
}
async GenResponse() {
if(this.options.ETag){
const ETag = `W/"${await globalThis.md5(this.MSG)}"`;
this.headers.ETag = ETag;
this.requestHeaders = Object.fromEntries(this.request.headers.entries());
if(ETag === this.requestHeaders["if-none-match"]){
return new Response(null,{
headers: this.headers,
status: 304
});
}
}
this.isSendHeader = true;
return new Response(this.MSG, {
headers: this.headers,
status: this.statusCode,
});
}
send(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
return this;
}
json(text) {
if (this.headers["Content-Type"] === "text/plain") {
this.response.setHeader(i, this.headers[i]);
}
this.send(text);
return this;
}
end(text) {
this.sendMsg.push(text);
this.MSG = this.sendMsg.join("");
this.isEnd = true;
return this;
}
}
function Code(statusCode) {
return {
GenAsync: async function (res, rep) {
rep.statusCode = statusCode;
rep.setHeader("Content-Type", "text/plain");
rep.send(`Error: ${statusCode}`);
},
};
}
//import http from "http";
async function startHTTPServer(PORT) {
const http = await import('http').then((e) => e.default);
const app = http.createServer();
if (PORT) {
app.listen(PORT);
}
return app;
}
async function doRequest$1(func, NodeRequest, NodeReply) {
const rep = await func(NodeRequest, NodeReply).catch(async (e) => {
await doRequest$1(Code(500).GenAsync, NodeRequest, NodeReply);
console.log(e.stack);
});
if (!NodeReply.isEnd) NodeReply.end(rep);
}
const newHTTPServer = async (port) => {
return async (that) => {
const server = await startHTTPServer(port);
server.on("request", await HTTPHandler(that));
return server;
};
};
const HTTPHandler = async (that) => {
return async (request, response) => {
let body = await new Promise((resolve) => {
if (request.method === "POST" && !request.body) {
let body = [];
request.on("data", (chunk) => body.push(chunk));
request.on("end", () => {
body = Buffer.concat(body).toString();
resolve(body);
});
} else if (request.body) {
resolve(request.body);
} else {
resolve();
}
});
let NodeRequest = new nodeRequest(request, body),
NodeReply = new nodeReply(response,request,that.options),
path = request.url;
new Promise((resolve) => {
if (that.options.logger) {
console.log(
`[${new Date().toLocaleString()}] ${request.socket.remoteAddress} - ${
request.method
} ${path}`
);
resolve();
}
});
await Promise.all(
that._middleWare.map((middleware) => middleware(NodeRequest, NodeReply))
);
if (that._route[path]) {
if (that._route[path][request.method]) {
await doRequest$1(
that._route[path][request.method],
NodeRequest,
NodeReply
);
} else if (that._route[path].all) {
await doRequest$1(that._route[path].all, NodeRequest, NodeReply);
} else {
await doRequest$1(Code(500).GenAsync, NodeRequest, NodeReply);
}
} else {
await doRequest$1(Code(404).GenAsync, NodeRequest, NodeReply);
}
};
};
const makeHandler = (that) => {
return async (request) => {
let body = "";
if (request.method === "POST") {
body = await request.text();
}
let req = new swRequest(request, body),
rep = new swReply(request,that.options),
answer;
const path = req.path;
await Promise.all(
that._middleWare.map((middleware) => middleware(req, rep))
);
if (that._route[path]) {
if (that._route[path][request.method]) {
answer = await doRequest(that._route[path][request.method], req, rep);
} else if (that._route[path].all) {
answer = await doRequest(that._route[path].all, req, rep);
} else {
answer = await doRequest(Code(500).GenAsync, req, rep);
}
} else {
answer = await doRequest(Code(404).GenAsync, req, rep);
}
return answer;
};
};
async function doRequest(func, req, rep) {
const funcAnswer = await func(req, rep).catch(async (e) => {
await doRequest(Code(500).GenAsync, req, rep);
console.log(e.stack);
});
if (!rep.isEnd) rep.end(funcAnswer);
return await rep.GenResponse();
}
var toMD5 = ()=>{
if(globalThis.platform==="NODE"){
const crypto = import('crypto').then(e=>e.default);
return async(text)=>{
const md5 = (await crypto).createHash("md5");
const answer = md5.update(text).digest('hex');
return answer;
}
}else if(globalThis.platform==="SW"){
return async(text)=>{
const textUint8 = new TextEncoder().encode(text);
const hashBuffer = await crypto.subtle.digest('MD5',textUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
}else {
return async(text)=>{
throw new Error("Can't Found Platform!");
}
}};
function checkPlatform() {
if (!(typeof process === "undefined")) {
return "NODE";
} else if (!(typeof self === "undefined")) {
return "SW";
} else {
return "UNKNOWN";
}
}
class sw2express {
constructor({ logger = false,ETag = true }) {
this.options = {
logger: logger,
ETag: ETag,
};
this._route = {};
this._middleWare = [];
globalThis.platform = checkPlatform();
globalThis.md5 = toMD5();
}
use(MiddleWare) {
this._middleWare.push(MiddleWare);
return this;
}
route(url) {
this._route[url] = {};
const that = {
POST: (func) => {
this._route[url].POST = func;
return that;
},
GET: (func) => {
this._route[url].GET = func;
return that;
},
all: (func) => {
this._route[url].all = func;
return that;
},
};
return that;
}
makeNewHandler(platform) {
switch (platform) {
case "NODE": {
return {
listen: (port) => newHTTPServer(port).then((e) => e(this)),
Handler: newHTTPServer()
.then((e) => e(this))
.then((e) => e),
};
}
case "SW": {
return makeHandler(this);
}
default:
return new Error("Invalid Platform");
}
}
listen(port) {
switch (checkPlatform()) {
case "NODE": {
let answer = "NODE",
Handler = this.makeNewHandler(answer);
Handler.listen(port);
return Handler;
}
case "SW": {
let answer = "SW",
Handler = this.makeNewHandler(answer);
self.addEventListener("fetch", (event) =>
event.respondWith(Handler(event.request))
);
return Handler;
}
}
}
async extend({ name, func, bootstrap }) {
this[name] = func;
return await bootstrap(this);
}
}
var index = /*#__PURE__*/Object.freeze({
__proto__: null,
checkPlatform: checkPlatform,
'default': sw2express
});
var type = "module";
var main = "index.js";
var name = "sw2express";
var version = "0.0.2";
var description = "A lite & simple cross-platform Express-like web application framework";
var directories = {
test: "test"
};
var scripts = {
"build:normal": "rollup index.js -p @rollup/plugin-json -o build/index.js && minify build/index.js > build/index.min.js",
"build:sw": "rollup sw.js -p @rollup/plugin-json --inlineDynamicImports -o build/index.sw.js && minify build/index.sw.js > build/index.sw.min.js",
prettier: "prettier -w \\*\\*.js \\*\\*.ts",
dist: "yarn build:normal&yarn build:sw",
clean: "rm -rf ./build"
};
var repository = {
type: "git",
url: "https://git.186526.xyz/186526/Sw2Express.git"
};
var keywords = [
"Express-like",
"Web",
"Framework",
"API",
"express"
];
var author = "real186 <[email protected]>";
var license = "WTFPL";
var mode = "module";
var devDependencies = {
"@rollup/plugin-json": "^4.1.0",
minify: "^7.0.1",
prettier: "^2.2.1",
rollup: "^2.44.0",
yarn: "^1.22.10"
};
var types = "index.d.ts";
var dependencies = {
};
var _package = {
type: type,
main: main,
name: name,
version: version,
description: description,
directories: directories,
scripts: scripts,
repository: repository,
keywords: keywords,
author: author,
license: license,
mode: mode,
devDependencies: devDependencies,
types: types,
dependencies: dependencies
};
var _package$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
type: type,
main: main,
name: name,
version: version,
description: description,
directories: directories,
scripts: scripts,
repository: repository,
keywords: keywords,
author: author,
license: license,
mode: mode,
devDependencies: devDependencies,
types: types,
dependencies: dependencies,
'default': _package
});

1
build/index.sw.min.js
File diff suppressed because it is too large
View File

5
index.d.ts

@ -183,3 +183,8 @@ declare class sw2express {
listen(port: number): any;
}
export default sw2express;
/**
* Check the platform that sw2express is running on
* @returns Name of Platform
*/
export const checkPlatform = () => string;

15
package.json

@ -8,8 +8,11 @@
"test": "test"
},
"scripts": {
"build": "rollup index.js -o build/index.js",
"prettier": "prettier -w \\*\\*.js \\*\\*.ts"
"build:normal": "rollup index.js -p @rollup/plugin-json -o build/index.js && minify build/index.js > build/index.min.js",
"build:sw": "rollup sw.js -p @rollup/plugin-json --inlineDynamicImports -o build/index.sw.js && minify build/index.sw.js > build/index.sw.min.js",
"prettier": "prettier -w \\*\\*.js \\*\\*.ts",
"dist": "yarn build:normal&yarn build:sw",
"clean": "rm -rf ./build"
},
"repository": {
"type": "git",
@ -26,8 +29,12 @@
"license": "WTFPL",
"mode": "module",
"devDependencies": {
"@rollup/plugin-json": "^4.1.0",
"minify": "^7.0.1",
"prettier": "^2.2.1",
"rollup": "^2.44.0"
"rollup": "^2.44.0",
"yarn": "^1.22.10"
},
"types":"index.d.ts"
"types": "index.d.ts",
"dependencies": {}
}

2
src/sw/sw.js

@ -31,7 +31,7 @@ export const makeHandler = (that) => {
};
export async function doRequest(func, req, rep) {
const funcAnswer = await func(req, rep).catch(async (e) => {
await doRequest(page.Code(500).GenAsync, NodeRequest, NodeReply);
await doRequest(page.Code(500).GenAsync, req, rep);
console.log(e.stack);
});
if (!rep.isEnd) rep.end(funcAnswer);

12
sw.js

@ -0,0 +1,12 @@
(async function(){
"use strict";
const sw2express = await import("./index.js");
const packageJson = await import("./package.json");
if(!(self["sw2express-Version"] = packageJson.version)){
self["sw2express-Version"] = packageJson.version;
self.sw2express = sw2express.default;
self.checkPlatform = sw2express.checkPlatform;
}else{
console.warn("sw2express is loaded")
}
})()

8
test/index.js

@ -30,11 +30,3 @@ app
.GET(async (req, rep) => "Hello World");
app.listen(8080);
const appEchoHelloWorld = new sw2express({
logger: false,
ETag: false
});
appEchoHelloWorld.route('/').GET(async (req, rep) => "Hello World");
appEchoHelloWorld.listen(8000);

27
test/sw/index.html

@ -0,0 +1,27 @@
<script>
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js", {
scope: "/",
})
.then((registration) =>{
console.info(
`Service Worker registration successful with scope: ${registration.scope}`
)
window.location.href = "/";
}
)
.catch((error) =>
console.warn(`Service Worker registration failed: ${error}`)
);
}
});
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("controllerchange", () => {
window.location.reload();
});
}
});
</script>

22
test/sw/sw.js

@ -0,0 +1,22 @@
importScripts('./sw2express.min.js');
const app = new sw2express({
logger:true,
ETag:false,
});
app.route('/').all(async(req,rep)=>{
rep.send(`Send From ${checkPlatform()}\n`);
rep.send("Hello World, Sw2Express!");
});
app.route('/sw.js').all(async(req,rep)=>{
const answer = await fetch('./sw.js');
const text = await answer.text();
rep.setHeader('Content-Type', 'application/javascript; charset=utf-8');
rep.send(text);
})
app.route('/update.html').all(async(req,rep)=>{
const answer = await fetch('./index.html');
const text = await answer.text();
rep.setHeader('Content-Type', 'text/html; charset=utf-8');
rep.end(text);
})
app.listen(8080);

1
test/sw/sw2express.min.js

@ -0,0 +1 @@
../../build/index.sw.min.js

210
yarn.lock

@ -2,19 +2,229 @@
# yarn lockfile v1
"@rollup/[email protected]^4.1.0":
version "4.1.0"
resolved "https://registry.npmjs.org/@rollup/plugin-json/-/plugin-json-4.1.0.tgz#54e09867ae6963c593844d8bd7a9c718294496f3"
integrity sha512-yfLbTdNS6amI/2OpmbiBoW12vngr5NW2jCJVZSBEz+H5KfUJZ2M7sDjk0U6GOOdCWFVScShte29o9NezJ53TPw==
dependencies:
"@rollup/pluginutils" "^3.0.8"
"@rollup/[email protected]^3.0.8":
version "3.1.0"
resolved "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz#706b4524ee6dc8b103b3c995533e5ad680c02b9b"
integrity sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==
dependencies:
"@types/estree" "0.0.39"
estree-walker "^1.0.1"
picomatch "^2.2.2"
"@types/[email protected]":
version "0.0.39"
resolved "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f"
integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==
[email protected]^1.0.0:
version "1.1.1"
resolved "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef"
integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==
[email protected]^4.1.1:
version "4.1.2"
resolved "https://registry.npmjs.org/camel-case/-/camel-case-4.1.2.tgz#9728072a954f805228225a6deea6b38461e1bd5a"
integrity sha512-gxGWBrTT1JuMx6R+o5PTXMmUnhnVzLQ9SNutD4YqKtI6ap897t3tKECYla6gCWEkplXnlNybEkZg9GEGxKFCgw==
dependencies:
pascal-case "^3.1.2"
tslib "^2.0.3"
[email protected]^4.2.3:
version "4.2.3"
resolved "https://registry.npmjs.org/clean-css/-/clean-css-4.2.3.tgz#507b5de7d97b48ee53d84adb0160ff6216380f78"
integrity sha512-VcMWDN54ZN/DS+g58HYL5/n4Zrqe8vHJpGA8KdgUXFU4fuP/aHNw8eld9SyEIyabIMJX/0RaY/fplOo5hYLSFA==
dependencies:
source-map "~0.6.0"
cle[email protected]^5.0.1:
version "5.1.2"
resolved "https://registry.npmjs.org/clean-css/-/clean-css-5.1.2.tgz#6ea0da7286b4ddc2469a1b776e2461a5007eed54"
integrity sha512-QcaGg9OuMo+0Ds933yLOY+gHPWbxhxqF0HDexmToPf8pczvmvZGYzd+QqWp9/mkucAOKViI+dSFOqoZIvXbeBw==
dependencies:
source-map "~0.6.0"
[email protected]^2.20.0:
version "2.20.3"
resolved "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==
[email protected]^4.1.1:
version "4.1.1"
resolved "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068"
integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==
[email protected]~0.2.5:
version "0.2.5"
resolved "https://registry.npmjs.org/css-b64-images/-/css-b64-images-0.2.5.tgz#42005d83204b2b4a5d93b6b1a5644133b5927a02"
integrity sha1-QgBdgyBLK0pdk7axpWRBM7WSegI=
[email protected]^4.1.0:
version "4.3.1"
resolved "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz#f0d229c505e0c6d8c49ac553d1b13dc183f6b2ee"
integrity sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==
dependencies:
ms "2.1.2"
[email protected]^3.0.4:
version "3.0.4"
resolved "https://registry.npmjs.org/dot-case/-/dot-case-3.0.4.tgz#9b2b670d00a431667a8a75ba29cd1b98809ce751"
integrity sha512-Kv5nKlh6yRrdrGvxeJ2e5y2eRUpkUosIW4A2AS38zwSz27zu7ufDwQPi5Jhs3XAlGNetl3bmnGhQsMtkKJnj3w==
dependencies:
no-case "^3.0.4"
tslib "^2.0.3"
[email protected]^1.0.1:
version "1.0.1"
resolved "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz#31bc5d612c96b704106b477e6dd5d8aa138cb700"
integrity sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==
[email protected]~2.3.1:
version "2.3.2"
resolved "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a"
integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==
[email protected]^1.2.0:
version "1.2.0"
resolved "https://registry.npmjs.org/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"
integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==
[email protected]^5.1.1:
version "5.1.1"
resolved "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-5.1.1.tgz#922e96f1f3bb60832c2634b79884096389b1f054"
integrity sha512-ZPr5MNObqnV/T9akshPKbVgyOqLmy+Bxo7juKCfTfnjNniTAMdy4hz21YQqoofMBJD2kdREaqPPdThoR78Tgxg==
dependencies:
camel-case "^4.1.1"
clean-css "^4.2.3"
commander "^4.1.1"
he "^1.2.0"
param-case "^3.0.3"
relateurl "^0.2.7"
terser "^4.6.3"
[email protected]^2.0.2:
version "2.0.2"
resolved "https://registry.npmjs.org/lower-case/-/lower-case-2.0.2.tgz#6fa237c63dbdc4a82ca0fd882e4722dc5e634e28"
integrity sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==
dependencies:
tslib "^2.0.3"
[email protected]^7.0.1:
version "7.0.1"
resolved "https://registry.npmjs.org/minify/-/minify-7.0.1.tgz#f368afeadcf1cd2525d18c32446112f595e951d0"
integrity sha512-U3CjnPKRjPu3DxZX7NsB833r2ijbw9af3fHsaChn6o7BHKvaT/zxYDQ8Q/3W7VFXGDrnkAx6XBx3ggEf5KJm7A==
dependencies:
clean-css "^5.0.1"
css-b64-images "~0.2.5"
debug "^4.1.0"
html-minifier-terser "^5.1.1"
terser "^5.3.2"
try-to-catch "^3.0.0"
[email protected]:
version "2.1.2"
resolved "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009"
integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==
[email protected]^3.0.4:
version "3.0.4"
resolved "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz#d361fd5c9800f558551a8369fc0dcd4662b6124d"
integrity sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==
dependencies:
lower-case "^2.0.2"
tslib "^2.0.3"
[email protected]^3.0.3:
version "3.0.4"
resolved "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz#7d17fe4aa12bde34d4a77d91acfb6219caad01c5"
integrity sha512-RXlj7zCYokReqWpOPH9oYivUzLYZ5vAPIfEmCTNViosC78F8F0H9y7T7gG2M39ymgutxF5gcFEsyZQSph9Bp3A==
dependencies:
dot-case "^3.0.4"
tslib "^2.0.3"
[email protected]^3.1.2:
version "3.1.2"
resolved "https://registry.npmjs.org/pascal-case/-/pascal-case-3.1.2.tgz#b48e0ef2b98e205e7c1dae747d0b1508237660eb"
integrity sha512-uWlGT3YSnK9x3BQJaOdcZwrnV6hPpd8jFH1/ucpiLRPh/2zCVJKS19E4GvYHvaCcACn3foXZ0cLB9Wrx1KGe5g==
dependencies:
no-case "^3.0.4"
tslib "^2.0.3"
[email protected]^2.2.2:
version "2.2.3"
resolved "https://registry.npmjs.org/picomatch/-/picomatch-2.2.3.tgz#465547f359ccc206d3c48e46a1bcb89bf7ee619d"
integrity sha512-KpELjfwcCDUb9PeigTs2mBJzXUPzAuP2oPcA989He8Rte0+YUAjw1JVedDhuTKPkHjSYzMN3npC9luThGYEKdg==
[email protected]^2.2.1:
version "2.2.1"
resolved "https://registry.npmjs.org/prettier/-/prettier-2.2.1.tgz#795a1a78dd52f073da0cd42b21f9c91381923ff5"
integrity sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q==
[email protected]^0.2.7:
version "0.2.7"
resolved "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz#54dbf377e51440aca90a4cd274600d3ff2d888a9"
integrity sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=
[email protected]^2.44.0:
version "2.44.0"
resolved "https://registry.npmjs.org/rollup/-/rollup-2.44.0.tgz#8da324d1c4fd12beef9ae6e12f4068265b6d95eb"
integrity sha512-rGSF4pLwvuaH/x4nAS+zP6UNn5YUDWf/TeEU5IoXSZKBbKRNTCI3qMnYXKZgrC0D2KzS2baiOZt1OlqhMu5rnQ==
optionalDependencies:
fsevents "~2.3.1"
[email protected]~0.5.12, [email protected]~0.5.19:
version "0.5.19"
resolved "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61"
integrity sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==
dependencies:
buffer-from "^1.0.0"
source-map "^0.6.0"
[email protected]^0.6.0, [email protected]~0.6.0, [email protected]~0.6.1:
version "0.6.1"
resolved "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==
[email protected]~0.7.2:
version "0.7.3"
resolved "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz#5302f8169031735226544092e64981f751750383"
integrity sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==
[email protected]^4.6.3:
version "4.8.0"
resolved "https://registry.npmjs.org/terser/-/terser-4.8.0.tgz#63056343d7c70bb29f3af665865a46fe03a0df17"
integrity sha512-EAPipTNeWsb/3wLPeup1tVPaXfIaU68xMnVdPafIL1TV05OhASArYyIfFvnvJCNrR2NIOvDVNNTFRa+Re2MWyw==
dependencies:
commander "^2.20.0"
source-map "~0.6.1"
source-map-support "~0.5.12"
[email protected]^5.3.2:
version "5.6.1"
resolved "https://registry.npmjs.org/terser/-/terser-5.6.1.tgz#a48eeac5300c0a09b36854bf90d9c26fb201973c"
integrity sha512-yv9YLFQQ+3ZqgWCUk+pvNJwgUTdlIxUk1WTN+RnaFJe2L7ipG2csPT0ra2XRm7Cs8cxN7QXmK1rFzEwYEQkzXw==
dependencies:
commander "^2.20.0"
source-map "~0.7.2"
source-map-support "~0.5.19"
[email protected]^3.0.0:
version "3.0.0"
resolved "https://registry.npmjs.org/try-to-catch/-/try-to-catch-3.0.0.tgz#a1903b44d13d5124c54d14a461d22ec1f52ea14b"
integrity sha512-eIm6ZXwR35jVF8By/HdbbkcaCDTBI5PpCPkejRKrYp0jyf/DbCCcRhHD7/O9jtFI3ewsqo9WctFEiJTS6i+CQA==
[email protected]^2.0.3:
version "2.2.0"
resolved "https://registry.npmjs.org/tslib/-/tslib-2.2.0.tgz#fb2c475977e35e241311ede2693cee1ec6698f5c"
integrity sha512-gS9GVHRU+RGn5KQM2rllAlR3dU6m7AcpJKdtH8gFvQiC4Otgk98XnmMU+nZenHt/+VhnBPWwgrJsyrdcw6i23w==
[email protected]^1.22.10:
version "1.22.10"
resolved "https://registry.npmjs.org/yarn/-/yarn-1.22.10.tgz#c99daa06257c80f8fa2c3f1490724e394c26b18c"
integrity sha512-IanQGI9RRPAN87VGTF7zs2uxkSyQSrSPsju0COgbsKQOOXr5LtcVPeyXWgwVa0ywG3d8dg6kSYKGBuYK021qeA==
Loading…
Cancel
Save