-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathcreateServer.ts
More file actions
214 lines (195 loc) · 6.22 KB
/
createServer.ts
File metadata and controls
214 lines (195 loc) · 6.22 KB
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
import { Writable } from 'node:stream';
import util from 'node:util';
import middie from '@fastify/middie';
import fastifySensible from '@fastify/sensible';
import Fastify from 'fastify';
import { createProxyMiddleware } from 'http-proxy-middleware';
import apiPlugin from './plugins/api/apiPlugin.js';
import compilerPlugin from './plugins/compiler/compilerPlugin.js';
import devtoolsPlugin from './plugins/devtools/devtoolsPlugin.js';
import faviconPlugin from './plugins/favicon/faviconPlugin.js';
import multipartPlugin from './plugins/multipart/multipartPlugin.js';
import symbolicatePlugin from './plugins/symbolicate/sybmolicatePlugin.js';
import wssPlugin from './plugins/wss/wssPlugin.js';
import { Internal, type Middleware, type Server } from './types.js';
import { handleCustomNetworkLoadResource } from './utils/networkLoadResourceHandler.js';
import { normalizeOptions } from './utils/normalizeOptions.js';
/**
* Create instance of development server, powered by Fastify.
*
* @param config Server configuration.
* @returns `start` and `stop` functions as well as an underlying Fastify `instance`.
*/
export async function createServer(config: Server.Config) {
// biome-ignore lint/style/useConst: needed in fastify constructor
let delegate: Server.Delegate;
const options = normalizeOptions(config.options);
/** Fastify instance powering the development server. */
const instance = Fastify({
disableRequestLogging: options.disableRequestLogging,
logger: {
level: 'trace',
stream: new Writable({
write: (chunk, _encoding, callback) => {
const log = JSON.parse(chunk.toString());
delegate?.logger.onMessage(log);
instance.wss?.apiServer.send(log);
callback();
},
}),
},
...(options.https ? { https: options.https } : {}),
});
delegate = config.delegate({
options,
log: instance.log,
notifyBuildStart: (platform) => {
instance.wss.apiServer.send({
event: Internal.EventTypes.BuildStart,
platform,
});
},
notifyBuildEnd: (platform) => {
instance.wss.apiServer.send({
event: Internal.EventTypes.BuildEnd,
platform,
});
},
broadcastToHmrClients: (event) => {
instance.wss.hmrServer.send(event);
},
broadcastToMessageClients: ({ method, params }) => {
instance.wss.messageServer.broadcast(method, params);
},
});
let handledDevMiddlewareNotice = false;
const devMiddleware = options.devMiddleware.createDevMiddleware({
projectRoot: options.rootDir,
serverBaseUrl: options.url,
logger: {
error: (...msg) => {
const message = util.format(...msg);
instance.log.error(message);
},
warn: (...msg) => {
const message = util.format(...msg);
instance.log.warn(message);
},
info: (...msg) => {
const message = util.format(...msg);
try {
if (!handledDevMiddlewareNotice) {
if (message.includes('JavaScript logs have moved!')) {
handledDevMiddlewareNotice = true;
return;
}
} else {
instance.log.debug(message);
return;
}
} catch (e) {
console.log(e);
}
},
},
// Preserve RN default handling for same-origin resources while
// allowing remote-origin source maps/resources to be loaded here.
unstable_customInspectorMessageHandler: (connection) => {
return {
handleDeviceMessage: () => {},
handleDebuggerMessage: (msg) => {
if (handleCustomNetworkLoadResource(connection, msg, options.url)) {
return true;
}
},
};
},
unstable_experiments: {
// @ts-expect-error removed in 0.76, keep this for backkwards compatibility
enableNewDebugger: true,
},
});
const proxyMiddlewares = options.proxy?.map((proxyOptions) => {
return createProxyMiddleware(proxyOptions);
});
// Register plugins
await instance.register(fastifySensible);
await instance.register(middie);
await instance.register(wssPlugin, {
delegate,
endpoints: devMiddleware.websocketEndpoints,
});
await instance.register(multipartPlugin);
await instance.register(apiPlugin, {
delegate,
prefix: '/api',
});
await instance.register(compilerPlugin, {
delegate,
});
await instance.register(devtoolsPlugin, {
delegate,
});
await instance.register(symbolicatePlugin, {
delegate,
});
// below is to prevent showing `GET 400 /favicon.ico`
// errors in console when requesting the bundle via browser
await instance.register(faviconPlugin);
instance.addHook('onSend', async (request, reply, payload) => {
reply.header('X-Content-Type-Options', 'nosniff');
reply.header('X-React-Native-Project-Root', options.rootDir);
const [pathname] = request.url.split('?');
if (pathname.endsWith('.map')) {
reply.header('Access-Control-Allow-Origin', 'devtools://devtools');
}
return payload;
});
// Setup middlewares
// Expose built-in middlewares to setupMiddlewares
const builtInMiddlewares: Middleware[] = [
{
name: 'dev-middleware',
middleware: devMiddleware.middleware,
},
...(proxyMiddlewares?.map((proxyMiddleware, index) => ({
name: `proxy-middleware-${index}`,
middleware: proxyMiddleware,
})) ?? []),
];
const finalMiddlewares = options.setupMiddlewares(
builtInMiddlewares,
instance
);
// Register middlewares
finalMiddlewares.forEach((middleware) => {
if (typeof middleware === 'object') {
if (middleware.path !== undefined) {
instance.use(middleware.path, middleware.middleware);
} else {
instance.use(middleware.middleware);
}
} else {
instance.use(middleware);
}
});
// Register routes
instance.get('/', async () => delegate.messages.getHello());
instance.get('/status', async () => delegate.messages.getStatus());
/** Start the development server. */
async function start() {
await instance.listen({
port: options.port,
host: options.host,
});
}
/** Stop the development server. */
async function stop() {
await instance.close();
}
return {
start,
stop,
instance,
};
}