-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
commands.ts
313 lines (276 loc) · 8.81 KB
/
commands.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
import * as path from "path";
import os from "os";
import { execSync } from "child_process";
import * as fse from "fs-extra";
import exitHook from "exit-hook";
import ora from "ora";
import prettyMs from "pretty-ms";
import WebSocket from "ws";
import type { Server } from "http";
import type * as Express from "express";
import type { createApp as createAppType } from "@remix-run/serve";
import getPort, { makeRange } from "get-port";
import { BuildMode, isBuildMode } from "../build";
import * as colors from "../colors";
import * as compiler from "../compiler";
import type { RemixConfig } from "../config";
import { readConfig } from "../config";
import { formatRoutes, RoutesFormat, isRoutesFormat } from "../config/format";
import { createApp } from "./create";
import { loadEnv } from "../env";
import { log } from "../logging";
import { setupRemix, isSetupPlatform, SetupPlatform } from "./setup";
export * as migrate from "./migrate";
export async function create({
appTemplate,
projectDir,
remixVersion,
installDeps,
packageManager,
useTypeScript,
githubToken,
debug,
}: {
appTemplate: string;
projectDir: string;
remixVersion?: string;
installDeps: boolean;
packageManager: "npm" | "yarn" | "pnpm";
useTypeScript: boolean;
githubToken?: string;
debug?: boolean;
}) {
let spinner = ora("Creating your app…").start();
await createApp({
appTemplate,
projectDir,
remixVersion,
installDeps,
packageManager,
useTypeScript,
githubToken,
debug,
});
spinner.stop();
spinner.clear();
}
export async function init(
projectDir: string,
packageManager: "npm" | "yarn" | "pnpm"
) {
let initScriptDir = path.join(projectDir, "remix.init");
let initScript = path.resolve(initScriptDir, "index.js");
let initPackageJson = path.resolve(initScriptDir, "package.json");
let isTypeScript = fse.existsSync(path.join(projectDir, "tsconfig.json"));
if (await fse.pathExists(initScript)) {
if (await fse.pathExists(initPackageJson)) {
execSync(`${packageManager} install`, {
stdio: "ignore",
cwd: initScriptDir,
});
}
let initFn = require(initScript);
try {
await initFn({ isTypeScript, packageManager, rootDirectory: projectDir });
} catch (error) {
if (error instanceof Error) {
error.message = `${colors.error("🚨 Oops, remix.init failed")}\n\n${
error.message
}`;
}
throw error;
}
}
}
export async function setup(platformArg?: string) {
let platform: SetupPlatform;
if (
platformArg === "cloudflare-workers" ||
platformArg === "cloudflare-pages"
) {
console.warn(
`Using '${platformArg}' as a platform value is deprecated. Use ` +
"'cloudflare' instead."
);
console.log("HINT: check the `postinstall` script in `package.json`");
platform = SetupPlatform.Cloudflare;
} else {
platform = isSetupPlatform(platformArg) ? platformArg : SetupPlatform.Node;
}
await setupRemix(platform);
log(`Successfully setup Remix for ${platform}.`);
}
export async function routes(
remixRoot?: string,
formatArg?: string
): Promise<void> {
let config = await readConfig(remixRoot);
let format = isRoutesFormat(formatArg) ? formatArg : RoutesFormat.jsx;
console.log(formatRoutes(config.routes, format));
}
export async function build(
remixRoot: string,
modeArg?: string,
sourcemap: boolean = false
): Promise<void> {
let mode = isBuildMode(modeArg) ? modeArg : BuildMode.Production;
log(`Building Remix app in ${mode} mode...`);
if (modeArg === BuildMode.Production && sourcemap) {
console.warn(
"\n⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️"
);
console.warn(
"You have enabled source maps in production. This will make your " +
"server-side code visible to the public and is highly discouraged! If " +
"you insist, please ensure you are using environment variables for " +
"secrets and not hard-coding them into your source!"
);
console.warn(
"⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️\n"
);
}
let start = Date.now();
let config = await readConfig(remixRoot);
fse.emptyDirSync(config.assetsBuildDirectory);
await compiler.build(config, {
mode: mode,
sourcemap,
onBuildFailure: (failure: compiler.BuildError) => {
compiler.formatBuildFailure(failure);
throw Error();
},
});
log(`Built in ${prettyMs(Date.now() - start)}`);
}
type WatchCallbacks = {
onRebuildStart?(): void;
onInitialBuild?(): void;
};
export async function watch(
remixRootOrConfig: string | RemixConfig,
modeArg?: string,
callbacks?: WatchCallbacks
): Promise<void> {
let { onInitialBuild, onRebuildStart } = callbacks || {};
let mode = isBuildMode(modeArg) ? modeArg : BuildMode.Development;
console.log(`Watching Remix app in ${mode} mode...`);
let start = Date.now();
let config =
typeof remixRootOrConfig === "object"
? remixRootOrConfig
: await readConfig(remixRootOrConfig);
let wss = new WebSocket.Server({ port: config.devServerPort });
function broadcast(event: { type: string; [key: string]: any }) {
setTimeout(() => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(event));
}
});
}, config.devServerBroadcastDelay);
}
function log(_message: string) {
let message = `💿 ${_message}`;
console.log(message);
broadcast({ type: "LOG", message });
}
let closeWatcher = await compiler.watch(config, {
mode,
onInitialBuild,
onRebuildStart() {
start = Date.now();
onRebuildStart?.();
log("Rebuilding...");
},
onRebuildFinish() {
log(`Rebuilt in ${prettyMs(Date.now() - start)}`);
broadcast({ type: "RELOAD" });
},
onFileCreated(file) {
log(`File created: ${path.relative(process.cwd(), file)}`);
},
onFileChanged(file) {
log(`File changed: ${path.relative(process.cwd(), file)}`);
},
onFileDeleted(file) {
log(`File deleted: ${path.relative(process.cwd(), file)}`);
},
});
console.log(`💿 Built in ${prettyMs(Date.now() - start)}`);
let resolve: () => void;
exitHook(() => {
resolve();
});
return new Promise<void>((r) => {
resolve = r;
}).then(async () => {
wss.close();
await closeWatcher();
fse.emptyDirSync(config.assetsBuildDirectory);
fse.rmSync(config.serverBuildPath);
});
}
export async function dev(remixRoot: string, modeArg?: string) {
let createApp: typeof createAppType;
let express: typeof Express;
try {
// eslint-disable-next-line import/no-extraneous-dependencies
let serve = require("@remix-run/serve");
createApp = serve.createApp;
express = require("express");
} catch (err) {
throw new Error(
"Could not locate @remix-run/serve. Please verify you have it installed " +
"to use the dev command."
);
}
let config = await readConfig(remixRoot);
let mode = isBuildMode(modeArg) ? modeArg : BuildMode.Development;
await loadEnv(config.rootDirectory);
let port = await getPort({
port: process.env.PORT ? Number(process.env.PORT) : makeRange(3000, 3100),
});
if (config.serverEntryPoint) {
throw new Error("remix dev is not supported for custom servers.");
}
let app = express();
app.disable("x-powered-by");
app.use((_, __, next) => {
purgeAppRequireCache(config.serverBuildPath);
next();
});
app.use(createApp(config.serverBuildPath, mode));
let server: Server | null = null;
try {
await watch(config, mode, {
onInitialBuild: () => {
let onListen = () => {
let address =
process.env.HOST ||
Object.values(os.networkInterfaces())
.flat()
.find((ip) => ip?.family === "IPv4" && !ip.internal)?.address;
if (!address) {
console.log(`Remix App Server started at http://localhost:${port}`);
} else {
console.log(
`Remix App Server started at http://localhost:${port} (http://${address}:${port})`
);
}
};
server = process.env.HOST
? app.listen(port, process.env.HOST, onListen)
: app.listen(port, onListen);
},
});
} finally {
server!?.close();
}
}
function purgeAppRequireCache(buildPath: string) {
for (let key in require.cache) {
if (key.startsWith(buildPath)) {
delete require.cache[key];
}
}
}