generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
151 lines (131 loc) · 3.55 KB
/
utils.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
import { stat } from 'node:fs/promises';
import { join } from 'node:path';
import { existsSync } from 'node:fs';
export function resolveModulePath(path) {
if (path instanceof URL || path instanceof Function) {
return path;
} else if (path[0] === '.' || path[0] === '/') {
return `file://${process.cwd()}/${path.replaceAll(/(\.+\/)/g, '')}`;
} else {
return import.meta.resolve(path);
}
}
export function getContentType(path) {
switch(path.toLowerCase().split('.').at(-1)) {
case 'html':
return 'text/html';
case 'js':
return 'application/javascript';
case 'css':
return 'text/css';
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'svg':
return 'image/svg+xml';
case 'txt':
return 'text/plain';
default:
return 'application/octet-stream';
}
}
/**
*
* @param {string} path
* @param {string} base
* @returns {ReadableStream}
*/
export const getFileStream = (path, base = `file://${process.cwd()}/`) => new ReadableStream({
async start(controller) {
try {
const url = URL.parse(path, base);
if (! (url instanceof URL) || url.protocol !== 'file:') {
throw new Error('Invalid file path.');
} else {
const { createReadStream } = await import('node:fs');
const fileStream = createReadStream(url.pathname);
for await (const chunk of fileStream) {
controller.enqueue(chunk);
}
}
} catch(err) {
controller.error(err);
} finally {
controller.close();
}
}
});
/**
*
* @param {string} path
* @param {object} [options]
* @param {string} [options.base]
* @param {string|null} [options.compression=null]
* @returns {Promise<Response>}
*/
export async function respondWithFile(path, {
base = `file://${process.cwd()}/`,
compression = null,
...headers
} = {}) {
const stream = getFileStream(path, base);
if (typeof compression === 'string') {
return new Response(stream.pipeThrough(new CompressionStream(compression), {
headers: {
'Content-Type': getContentType(path),
'Content-Encoding': compression,
...headers,
}
}));
} else {
return new Response(stream, {
headers: {
'Content-Type': getContentType(path),
...headers,
},
});
}
}
/**
* Creates a `file:` URL relative from the `pathname` of a URL, relative to project root.
*
* @param {string|URL} url The URL to resolve using `pathname`.
* @param {string} [root="/"] The root directory, relative to the project root/working directory.
* @returns {URL} The resolved file URL (`file:///path/to/project/:root/:pathname`).
* @throws {TypeError} If `url` is not a string or URL.
*/
export function getFileURL(url, root = '/') {
if (typeof url === 'string') {
return getFileURL(URL.parse(url), root);
} else if (! (url instanceof URL)) {
throw new TypeError('`url` must be a string or `URL`.');
} else {
const base = `file:${process.cwd()}/`;
const path = './' + [
...root.split('/').filter(seg => seg.length !== 0),
...url.pathname.split('/').filter(seg => seg.length !== 0),
].join('/');
return new URL(path, base);
}
}
/**
*
* @param {string} path
* @param {object} options
* @param {string[]} [options.indexFiles=["index.html","index.html"]]
* @returns {Promise<string|null>}
*/
export async function resolveStaticPath(path, { indexFiles = ['index.html', 'index.htm'] } = {}) {
if (existsSync(path)) {
const stats = await stat(path);
if (stats.isFile()) {
return path;
} else if (stats.isDirectory()) {
// Try each potential index file
return indexFiles.map(index => join(path, index)).find(existsSync) ?? null;
}
} else {
return null;
}
}