forked from broccolijs/broccoli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
174 lines (155 loc) · 5.08 KB
/
middleware.ts
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
import fs from 'fs';
import url from 'url';
import path from 'path';
import mime from 'mime-types';
import handlebars from 'handlebars';
import Watcher from './watcher';
import BuildError from './errors/build';
import resolvePath from 'resolve-path';
// @ts-ignore
import ansiHTML from 'ansi-html';
// Resets foreground and background colors to black
// and white respectively
ansiHTML.setColors({
reset: ['#000', '#fff'],
});
const errorTemplate = handlebars.compile(
fs.readFileSync(path.resolve(__dirname, 'templates/error.html')).toString()
);
const dirTemplate = handlebars.compile(
fs.readFileSync(path.resolve(__dirname, 'templates/dir.html')).toString()
);
interface MiddlewareOptions {
autoIndex?: boolean;
liveReloadPath?: string;
}
// You must call watcher.start() before you call `getMiddleware`
//
// This middleware is for development use only. It hasn't been reviewed
// carefully enough to run on a production server.
//
// Supported options:
// autoIndex (default: true) - set to false to disable directory listings
// liveReloadPath - LiveReload script URL for error pages
function handleRequest(
outputPath: string,
request: any,
response: any,
next: any,
options: MiddlewareOptions
) {
// eslint-disable-next-line node/no-deprecated-api
const urlObj = url.parse(request.url);
const pathname = urlObj.pathname || '';
let filename: string, stat;
try {
filename = decodeURIComponent(pathname);
if (!filename) {
response.writeHead(400);
response.end();
return;
}
filename = resolvePath(outputPath, filename.substr(1));
} catch (err) {
response.writeHead(err.status || 500);
response.end();
return;
}
try {
stat = fs.statSync(filename);
} catch (e) {
// not found
next();
return;
}
if (stat.isDirectory()) {
const indexFilename = path.join(filename, 'index.html');
const hasIndex = fs.existsSync(indexFilename);
if (!hasIndex && !options.autoIndex) {
next();
return;
}
if (pathname[pathname.length - 1] !== '/') {
urlObj.pathname += '/';
urlObj.host = request.headers['host'];
urlObj.protocol = request.socket.encrypted ? 'https' : 'http';
response.setHeader('Location', url.format(urlObj));
response.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
response.writeHead(301);
response.end();
return;
}
if (!hasIndex) {
// implied: options.autoIndex is true
const context = {
url: request.url,
files: fs
.readdirSync(filename)
.sort()
.map(child => {
const stat = fs.statSync(path.join(filename, child)),
isDir = stat.isDirectory();
return {
href: child + (isDir ? '/' : ''),
type: isDir
? 'dir'
: path
.extname(child)
.replace('.', '')
.toLowerCase(),
};
}),
liveReloadPath: options.liveReloadPath,
};
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
response.writeHead(200);
response.end(dirTemplate(context));
return;
}
// otherwise serve index.html
filename = indexFilename;
stat = fs.statSync(filename);
}
const lastModified = stat.mtime.toUTCString();
response.setHeader('Last-Modified', lastModified);
// nginx style treat last-modified as a tag since browsers echo it back
if (request.headers['if-modified-since'] === lastModified) {
response.writeHead(304);
response.end();
return;
}
response.setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
response.setHeader('Content-Length', stat.size);
response.setHeader('Content-Type', mime.contentType(path.extname(filename)));
// read file sync so we don't hold open the file creating a race with
// the builder (Windows does not allow us to delete while the file is open).
const buffer = fs.readFileSync(filename);
response.writeHead(200);
response.end(buffer);
}
export = function getMiddleware(watcher: Watcher, options: MiddlewareOptions = {}) {
if (options.autoIndex == null) options.autoIndex = true;
const outputPath = path.resolve(watcher.builder.outputPath);
return async function broccoliMiddleware(request: any, response: any, next: any) {
if (watcher.currentBuild == null) {
throw new Error('Waiting for initial build to start');
}
try {
await watcher.currentBuild;
handleRequest(outputPath, request, response, next, options);
} catch (error) {
// All errors thrown from builder.build() are guaranteed to be
// Builder.BuildError instances.
const context = {
stack: ansiHTML(error.stack || ''),
liveReloadPath: options.liveReloadPath,
payload: error.broccoliPayload,
};
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.writeHead(500);
response.end(errorTemplate(context));
return error.stack;
}
};
};