-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcreate-middlewares.ts
231 lines (202 loc) · 6.74 KB
/
create-middlewares.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
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
import chokidar from 'chokidar';
import { Middleware } from 'koa';
import koaCompress from 'koa-compress';
import koaEtag from 'koa-etag';
import koaStatic from 'koa-static';
import koaCors from '@koa/cors';
import Koa from 'koa';
import { Server } from 'net';
import { ParsedConfig } from './config';
import { compatibilityModes } from './constants';
import { createBasePathMiddleware } from './middleware/base-path';
import { createEtagCacheMiddleware } from './middleware/etag-cache';
import { createHistoryAPIFallbackMiddleware } from './middleware/history-api-fallback';
import { createMessageChannelMiddleware } from './middleware/message-channel';
import { createPluginMimeTypeMiddleware } from './middleware/plugin-mime-type';
import { createPluginServeMiddlware } from './middleware/plugin-serve';
import { createPluginTransformMiddlware } from './middleware/plugin-transform';
import { createResponseTransformMiddleware } from './middleware/response-transform';
import { createWatchServedFilesMiddleware } from './middleware/watch-served-files';
import { Plugin } from './Plugin';
import { babelTransformPlugin } from './plugins/babelTransformPlugin';
import { fileExtensionsPlugin } from './plugins/fileExtensionsPlugin';
import { nodeResolvePlugin } from './plugins/nodeResolvePlugin';
import { polyfillsLoaderPlugin } from './plugins/polyfillsLoaderPlugin';
import { resolveModuleImportsPlugin } from './plugins/resolveModuleImportsPlugin';
import { logDebug } from './utils/utils';
import { MessageChannel } from './utils/MessageChannel';
import { browserReloadPlugin } from './plugins/browserReloadPlugin';
const defaultCompressOptions = {
filter(contentType: string) {
// event stream doesn't like compression
return contentType !== 'text/event-stream';
},
};
function hasHook(plugins: Plugin[], hook: string) {
return plugins.some(plugin => hook in plugin);
}
/**
* Creates middlewares based on the given configuration. The middlewares can be
* used by a koa server using `app.use()`:
*/
export function createMiddlewares(config: ParsedConfig, fileWatcher = chokidar.watch([])) {
const {
appIndex,
appIndexDir,
basePath,
compatibilityMode,
compress,
customBabelConfig,
customMiddlewares,
responseTransformers,
fileExtensions,
nodeResolve,
eventStream,
polyfillsLoader,
polyfillsLoaderConfig,
readUserBabelConfig,
plugins,
rootDir,
watch,
logErrorsToBrowser,
watchDebounce,
babelExclude,
babelModernExclude,
babelModuleExclude,
customBabelInclude,
customBabelExclude,
cors,
} = config;
const middlewares: Middleware[] = [];
middlewares.push((ctx, next) => {
logDebug(`Receiving request: ${ctx.url}`);
return next();
});
if (compress) {
const options = typeof compress === 'object' ? compress : defaultCompressOptions;
middlewares.push(koaCompress(options));
}
if (!Object.values(compatibilityModes).includes(compatibilityMode)) {
throw new Error(
`Unknown compatibility mode: ${compatibilityMode}. Must be one of: ${Object.values(
compatibilityModes,
)}`,
);
}
const setupCompatibility = compatibilityMode !== compatibilityModes.NONE;
const setupBabel = customBabelConfig || readUserBabelConfig;
const setupHistoryFallback = appIndex;
const setupMessageChannel =
eventStream && (watch || (logErrorsToBrowser && (setupCompatibility || nodeResolve)));
const messageChannel = setupMessageChannel ? new MessageChannel() : undefined;
if (fileExtensions.length > 0) {
plugins.unshift(fileExtensionsPlugin({ fileExtensions }));
}
if (nodeResolve || hasHook(plugins, 'resolveImport')) {
if (nodeResolve) {
plugins.push(nodeResolvePlugin({ rootDir, fileExtensions, nodeResolve }));
}
plugins.push(resolveModuleImportsPlugin({ rootDir, plugins }));
}
if (setupCompatibility || setupBabel) {
plugins.push(
babelTransformPlugin({
rootDir,
readUserBabelConfig,
nodeResolve,
compatibilityMode,
customBabelConfig,
fileExtensions,
babelExclude,
babelModernExclude,
babelModuleExclude,
customBabelInclude,
customBabelExclude,
}),
);
}
if (polyfillsLoader && setupCompatibility) {
plugins.push(
polyfillsLoaderPlugin({
rootDir,
compatibilityMode,
polyfillsLoaderConfig,
}),
);
}
if (watch) {
plugins.push(browserReloadPlugin({ watchDebounce }));
}
// strips a base path from requests
if (basePath) {
middlewares.push(createBasePathMiddleware({ basePath }));
}
// adds custom user's middlewares
if (customMiddlewares && customMiddlewares.length > 0) {
customMiddlewares.forEach(customMiddleware => {
middlewares.push(customMiddleware);
});
}
middlewares.push(async (ctx, next) => {
await next();
logDebug(`Serving request: ${ctx.url} with status: ${ctx.status}`);
});
// serves 304 responses if resource hasn't changed
middlewares.push(createEtagCacheMiddleware());
// adds etag headers for caching
middlewares.push(koaEtag());
// communicates with browser for reload or logging
if (setupMessageChannel && messageChannel) {
middlewares.push(createMessageChannelMiddleware({ messageChannel }));
}
// watches served files
middlewares.push(
createWatchServedFilesMiddleware({
rootDir,
fileWatcher,
}),
);
// serves index.html for non-file requests for SPA routing
if (setupHistoryFallback && typeof appIndex === 'string' && typeof appIndexDir === 'string') {
middlewares.push(createHistoryAPIFallbackMiddleware({ appIndex, appIndexDir }));
}
middlewares.push(
createPluginTransformMiddlware({
plugins,
fileWatcher,
rootDir,
fileExtensions,
messageChannel,
logErrorsToBrowser,
}),
);
// DEPRECATED: Response transformers (now split up in serve and transform in plugins)
if (responseTransformers) {
middlewares.push(createResponseTransformMiddleware({ responseTransformers }));
}
middlewares.push(createPluginMimeTypeMiddleware({ plugins }));
if (cors) {
middlewares.push(koaCors());
}
middlewares.push(createPluginServeMiddlware({ plugins }));
// serve static files
middlewares.push(
koaStatic(rootDir, {
hidden: true,
setHeaders(res) {
res.setHeader('cache-control', 'no-cache');
},
}),
);
return {
middlewares,
// callback called by start-server
async onServerStarted(app: Koa, server: Server) {
// call server start plugin hooks in parallel
const startHooks = plugins
.filter(pl => !!pl.serverStart)
.map(pl => pl.serverStart?.({ config, app, server, fileWatcher, messageChannel }));
await Promise.all(startHooks);
},
};
}