@aomex/serve-static 1.4.0
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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/dist/index.d.ts +66 -0
- package/dist/index.js +93 -0
- package/dist/index.js.map +1 -0
- package/package.json +37 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Change Log
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
|
5
|
+
|
|
6
|
+
# [1.4.0](https://github.com/aomex/aomex/compare/v1.3.0...v1.4.0) (2024-06-29)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
* **serve-static:** 增加静态文件服务 ([4eb67c0](https://github.com/aomex/aomex/commit/4eb67c03657afc0ec4a11b15b0b2d16685481c43))
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-2024 geekact
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { WebContext, WebMiddleware } from '@aomex/web';
|
|
2
|
+
|
|
3
|
+
interface SendOptions {
|
|
4
|
+
/**
|
|
5
|
+
* 服务的根目录,请勿设置成根目录,否则源码可能被访问。
|
|
6
|
+
*/
|
|
7
|
+
root: string;
|
|
8
|
+
/**
|
|
9
|
+
* 没有指定文件名时,自动访问这个文件。默认值:`index.html`
|
|
10
|
+
*/
|
|
11
|
+
indexFile?: string | false;
|
|
12
|
+
/**
|
|
13
|
+
* 使用压缩过后的文件,如果未找到则继续使用源文件。支持后缀:
|
|
14
|
+
* - .gz
|
|
15
|
+
* - .br
|
|
16
|
+
*
|
|
17
|
+
* 默认值:`true`
|
|
18
|
+
*
|
|
19
|
+
*/
|
|
20
|
+
useCompressedFile?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* 设置 Cache-Control 报文
|
|
23
|
+
*
|
|
24
|
+
* @link https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cache-Control
|
|
25
|
+
*/
|
|
26
|
+
cacheControl?: {
|
|
27
|
+
/**
|
|
28
|
+
* 是否共享缓存。默认值:`public`
|
|
29
|
+
*
|
|
30
|
+
* - `public` 表明响应可以被任何对象(包括:发送请求的客户端,代理服务器,等等)缓存,即使是通常不可缓存的内容。(例如:1.该响应没有max-age指令或Expires消息头;2. 该响应对应的请求方法是 POST 。)
|
|
31
|
+
* - `private` 表明响应只能被单个用户缓存,不能作为共享缓存(即代理服务器不能缓存它)。私有缓存可以缓存响应内容,比如:对应用户的本地浏览器。
|
|
32
|
+
*
|
|
33
|
+
*/
|
|
34
|
+
publicOrPrivate?: 'public' | 'private';
|
|
35
|
+
/**
|
|
36
|
+
* 缓存的内容将在N毫秒后失效, 这个选项只在HTTP 1.1可用, 并如果和Last-Modified一起使用时, 优先级较高
|
|
37
|
+
*
|
|
38
|
+
* 默认值:`0`
|
|
39
|
+
*
|
|
40
|
+
*/
|
|
41
|
+
maxAge?: number;
|
|
42
|
+
/**
|
|
43
|
+
* 表示响应正文不会随时间而改变。资源(如果未过期)在服务器上不发生改变,因此客户端不应发送重新验证请求头(例如If-None-Match或 If-Modified-Since)来检查更新,即使用户显式地刷新页面。
|
|
44
|
+
*
|
|
45
|
+
* 默认值:`false`
|
|
46
|
+
*/
|
|
47
|
+
immutable?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* 在发布缓存副本之前,强制要求缓存把请求提交给原始服务器进行验证 (协商缓存验证)。
|
|
50
|
+
*
|
|
51
|
+
* 默认值:`false`
|
|
52
|
+
*/
|
|
53
|
+
noCache?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* 缓存不应存储有关客户端请求或服务器响应的任何内容,即不使用任何缓存。
|
|
56
|
+
*
|
|
57
|
+
* 默认值:`false`
|
|
58
|
+
*/
|
|
59
|
+
noStore?: boolean;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
declare const send: (ctx: WebContext, options: SendOptions) => Promise<boolean>;
|
|
63
|
+
|
|
64
|
+
declare const serveStatic: (options: SendOptions) => WebMiddleware;
|
|
65
|
+
|
|
66
|
+
export { type SendOptions, send, serveStatic };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// src/send.ts
|
|
2
|
+
import { stat } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createReadStream } from "node:fs";
|
|
5
|
+
var DOT_FILE_PATTERN = /(?:^\.|[\\/]\.)/;
|
|
6
|
+
var send = async (ctx, options) => {
|
|
7
|
+
const { request, response } = ctx;
|
|
8
|
+
const {
|
|
9
|
+
cacheControl: {
|
|
10
|
+
maxAge = 0,
|
|
11
|
+
immutable = false,
|
|
12
|
+
publicOrPrivate = "public",
|
|
13
|
+
noCache = false,
|
|
14
|
+
noStore = false
|
|
15
|
+
} = {},
|
|
16
|
+
indexFile = "index.html",
|
|
17
|
+
useCompressedFile = true
|
|
18
|
+
} = options;
|
|
19
|
+
const root = path.normalize(path.resolve(options.root ?? ""));
|
|
20
|
+
let { pathname: staticPath } = request;
|
|
21
|
+
try {
|
|
22
|
+
staticPath = decodeURIComponent(staticPath);
|
|
23
|
+
} catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
staticPath = path.normalize(staticPath.slice(path.parse(staticPath).root.length));
|
|
27
|
+
staticPath = path.join(root, staticPath);
|
|
28
|
+
if (DOT_FILE_PATTERN.test(staticPath.substring(root.length))) return false;
|
|
29
|
+
let stats;
|
|
30
|
+
try {
|
|
31
|
+
stats = await stat(staticPath);
|
|
32
|
+
if (stats.isDirectory()) {
|
|
33
|
+
if (!indexFile) return false;
|
|
34
|
+
staticPath = path.join(staticPath, indexFile);
|
|
35
|
+
stats = await stat(staticPath);
|
|
36
|
+
}
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
if (stats.isDirectory()) return false;
|
|
41
|
+
let compressExt = "";
|
|
42
|
+
if (useCompressedFile) {
|
|
43
|
+
if (request.accept.encodings("br", "identity") === "br" && await isFileExists(staticPath + ".br")) {
|
|
44
|
+
compressExt = ".br";
|
|
45
|
+
response.setHeader("Content-Encoding", "br");
|
|
46
|
+
} else if (request.accept.encodings("gzip", "identity") === "gzip" && await isFileExists(staticPath + ".gz")) {
|
|
47
|
+
compressExt = ".gz";
|
|
48
|
+
response.setHeader("Content-Encoding", "gz");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
response.setHeader("Content-Length", stats.size);
|
|
52
|
+
if (!response.hasHeader("Last-Modified")) {
|
|
53
|
+
response.setHeader("Last-Modified", stats.mtime.toUTCString());
|
|
54
|
+
}
|
|
55
|
+
if (!response.hasHeader("Cache-Control")) {
|
|
56
|
+
const directives = [];
|
|
57
|
+
directives.push(publicOrPrivate);
|
|
58
|
+
noCache && directives.push("no-cache");
|
|
59
|
+
noStore && directives.push("no-store");
|
|
60
|
+
directives.push(`max-age=${maxAge / 1e3 | 0}`);
|
|
61
|
+
immutable && directives.push("immutable");
|
|
62
|
+
response.setHeader("Cache-Control", directives.join(", "));
|
|
63
|
+
}
|
|
64
|
+
response.contentType = path.extname(staticPath) || "text";
|
|
65
|
+
ctx.send(createReadStream(staticPath + compressExt));
|
|
66
|
+
return true;
|
|
67
|
+
};
|
|
68
|
+
var isFileExists = async (file) => {
|
|
69
|
+
try {
|
|
70
|
+
const stats = await stat(file);
|
|
71
|
+
if (stats.isFile()) return true;
|
|
72
|
+
return false;
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// src/serve-static.ts
|
|
79
|
+
import { middleware } from "@aomex/core";
|
|
80
|
+
var serveStatic = (options) => {
|
|
81
|
+
return middleware.web(async (ctx, next) => {
|
|
82
|
+
const method = ctx.request.method;
|
|
83
|
+
if (method === "GET" || method === "HEAD") {
|
|
84
|
+
if (await send(ctx, options)) return;
|
|
85
|
+
}
|
|
86
|
+
return next();
|
|
87
|
+
});
|
|
88
|
+
};
|
|
89
|
+
export {
|
|
90
|
+
send,
|
|
91
|
+
serveStatic
|
|
92
|
+
};
|
|
93
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/send.ts","../src/serve-static.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { WebContext } from '@aomex/web';\nimport { createReadStream, type Stats } from 'node:fs';\n\nexport interface SendOptions {\n /**\n * 服务的根目录,请勿设置成根目录,否则源码可能被访问。\n */\n root: string;\n /**\n * 没有指定文件名时,自动访问这个文件。默认值:`index.html`\n */\n indexFile?: string | false;\n /**\n * 使用压缩过后的文件,如果未找到则继续使用源文件。支持后缀:\n * - .gz\n * - .br\n *\n * 默认值:`true`\n *\n */\n useCompressedFile?: boolean;\n /**\n * 设置 Cache-Control 报文\n *\n * @link https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Cache-Control\n */\n cacheControl?: {\n /**\n * 是否共享缓存。默认值:`public`\n *\n * - `public` 表明响应可以被任何对象(包括:发送请求的客户端,代理服务器,等等)缓存,即使是通常不可缓存的内容。(例如:1.该响应没有max-age指令或Expires消息头;2. 该响应对应的请求方法是 POST 。)\n * - `private` 表明响应只能被单个用户缓存,不能作为共享缓存(即代理服务器不能缓存它)。私有缓存可以缓存响应内容,比如:对应用户的本地浏览器。\n *\n */\n publicOrPrivate?: 'public' | 'private';\n /**\n * 缓存的内容将在N毫秒后失效, 这个选项只在HTTP 1.1可用, 并如果和Last-Modified一起使用时, 优先级较高\n *\n * 默认值:`0`\n *\n */\n maxAge?: number;\n /**\n * 表示响应正文不会随时间而改变。资源(如果未过期)在服务器上不发生改变,因此客户端不应发送重新验证请求头(例如If-None-Match或 If-Modified-Since)来检查更新,即使用户显式地刷新页面。\n *\n * 默认值:`false`\n */\n immutable?: boolean;\n /**\n * 在发布缓存副本之前,强制要求缓存把请求提交给原始服务器进行验证 (协商缓存验证)。\n *\n * 默认值:`false`\n */\n noCache?: boolean;\n /**\n * 缓存不应存储有关客户端请求或服务器响应的任何内容,即不使用任何缓存。\n *\n * 默认值:`false`\n */\n noStore?: boolean;\n };\n}\n\nconst DOT_FILE_PATTERN = /(?:^\\.|[\\\\/]\\.)/;\n\nexport const send = async (ctx: WebContext, options: SendOptions): Promise<boolean> => {\n const { request, response } = ctx;\n const {\n cacheControl: {\n maxAge = 0,\n immutable = false,\n publicOrPrivate = 'public',\n noCache = false,\n noStore = false,\n } = {},\n indexFile = 'index.html',\n useCompressedFile = true,\n } = options;\n const root = path.normalize(path.resolve(options.root ?? ''));\n\n let { pathname: staticPath } = request;\n try {\n staticPath = decodeURIComponent(staticPath);\n } catch {\n return false;\n }\n // 去掉 .. 路径再和根目录合并,防止非法访问\n staticPath = path.normalize(staticPath.slice(path.parse(staticPath).root.length));\n staticPath = path.join(root, staticPath);\n\n if (DOT_FILE_PATTERN.test(staticPath.substring(root.length))) return false;\n\n let stats: Stats;\n try {\n stats = await stat(staticPath);\n if (stats.isDirectory()) {\n if (!indexFile) return false;\n staticPath = path.join(staticPath, indexFile);\n stats = await stat(staticPath);\n }\n } catch {\n return false;\n }\n\n if (stats.isDirectory()) return false;\n\n let compressExt: string = '';\n if (useCompressedFile) {\n if (\n request.accept.encodings('br', 'identity') === 'br' &&\n (await isFileExists(staticPath + '.br'))\n ) {\n compressExt = '.br';\n response.setHeader('Content-Encoding', 'br');\n } else if (\n request.accept.encodings('gzip', 'identity') === 'gzip' &&\n (await isFileExists(staticPath + '.gz'))\n ) {\n compressExt = '.gz';\n response.setHeader('Content-Encoding', 'gz');\n }\n }\n\n response.setHeader('Content-Length', stats.size);\n if (!response.hasHeader('Last-Modified')) {\n response.setHeader('Last-Modified', stats.mtime.toUTCString());\n }\n\n if (!response.hasHeader('Cache-Control')) {\n const directives: string[] = [];\n directives.push(publicOrPrivate);\n noCache && directives.push('no-cache');\n noStore && directives.push('no-store');\n directives.push(`max-age=${(maxAge / 1000) | 0}`);\n immutable && directives.push('immutable');\n response.setHeader('Cache-Control', directives.join(', '));\n }\n\n response.contentType = path.extname(staticPath) || 'text';\n ctx.send(createReadStream(staticPath + compressExt));\n return true;\n};\n\nconst isFileExists = async (file: string) => {\n try {\n const stats = await stat(file);\n if (stats.isFile()) return true;\n return false;\n } catch {\n return false;\n }\n};\n","import { middleware } from '@aomex/core';\nimport type { WebMiddleware } from '@aomex/web';\nimport { send, type SendOptions } from './send';\n\nexport const serveStatic = (options: SendOptions): WebMiddleware => {\n return middleware.web(async (ctx, next) => {\n const method = ctx.request.method;\n if (method === 'GET' || method === 'HEAD') {\n if (await send(ctx, options)) return;\n }\n\n return next();\n });\n};\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,OAAO,UAAU;AAEjB,SAAS,wBAAoC;AA8D7C,IAAM,mBAAmB;AAElB,IAAM,OAAO,OAAO,KAAiB,YAA2C;AACrF,QAAM,EAAE,SAAS,SAAS,IAAI;AAC9B,QAAM;AAAA,IACJ,cAAc;AAAA,MACZ,SAAS;AAAA,MACT,YAAY;AAAA,MACZ,kBAAkB;AAAA,MAClB,UAAU;AAAA,MACV,UAAU;AAAA,IACZ,IAAI,CAAC;AAAA,IACL,YAAY;AAAA,IACZ,oBAAoB;AAAA,EACtB,IAAI;AACJ,QAAM,OAAO,KAAK,UAAU,KAAK,QAAQ,QAAQ,QAAQ,EAAE,CAAC;AAE5D,MAAI,EAAE,UAAU,WAAW,IAAI;AAC/B,MAAI;AACF,iBAAa,mBAAmB,UAAU;AAAA,EAC5C,QAAQ;AACN,WAAO;AAAA,EACT;AAEA,eAAa,KAAK,UAAU,WAAW,MAAM,KAAK,MAAM,UAAU,EAAE,KAAK,MAAM,CAAC;AAChF,eAAa,KAAK,KAAK,MAAM,UAAU;AAEvC,MAAI,iBAAiB,KAAK,WAAW,UAAU,KAAK,MAAM,CAAC,EAAG,QAAO;AAErE,MAAI;AACJ,MAAI;AACF,YAAQ,MAAM,KAAK,UAAU;AAC7B,QAAI,MAAM,YAAY,GAAG;AACvB,UAAI,CAAC,UAAW,QAAO;AACvB,mBAAa,KAAK,KAAK,YAAY,SAAS;AAC5C,cAAQ,MAAM,KAAK,UAAU;AAAA,IAC/B;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,YAAY,EAAG,QAAO;AAEhC,MAAI,cAAsB;AAC1B,MAAI,mBAAmB;AACrB,QACE,QAAQ,OAAO,UAAU,MAAM,UAAU,MAAM,QAC9C,MAAM,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ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@aomex/serve-static",
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "静态文件服务",
|
|
5
|
+
"repository": "git@github.com:aomex/aomex.git",
|
|
6
|
+
"homepage": "https://aomex.js.org",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"sideEffects": false,
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"import": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"package.json",
|
|
22
|
+
"README.md",
|
|
23
|
+
"CHANGELOG.md"
|
|
24
|
+
],
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"@aomex/core": "^1.0.0",
|
|
30
|
+
"@aomex/web": "^1.0.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@aomex/core": "^1.4.0",
|
|
34
|
+
"@aomex/web": "^1.4.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {}
|
|
37
|
+
}
|