-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathconfig.ts
566 lines (480 loc) · 15.5 KB
/
config.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import * as path from "path";
import { pathToFileURL } from "url";
import * as fse from "fs-extra";
import getPort from "get-port";
import type { RouteManifest, DefineRoutesFunction } from "./config/routes";
import { defineRoutes } from "./config/routes";
import { defineConventionalRoutes } from "./config/routesConvention";
import { ServerMode, isValidServerMode } from "./config/serverModes";
import { serverBuildVirtualModule } from "./compiler/virtualModules";
import { writeConfigDefaults } from "./compiler/utils/tsconfig/write-config-defaults";
import { flatRoutes } from "./config/flat-routes";
export interface RemixMdxConfig {
rehypePlugins?: any[];
remarkPlugins?: any[];
}
export type RemixMdxConfigFunction = (
filename: string
) => Promise<RemixMdxConfig | undefined> | RemixMdxConfig | undefined;
export type ServerBuildTarget =
| "node-cjs"
| "arc"
| "netlify"
| "vercel"
| "cloudflare-pages"
| "cloudflare-workers"
| "deno";
export type ServerModuleFormat = "esm" | "cjs";
export type ServerPlatform = "node" | "neutral";
type Dev = {
port?: number;
appServerPort?: number;
remixRequestHandlerPath?: string;
rebuildPollIntervalMs?: number;
};
interface FutureConfig {
unstable_cssModules: boolean;
unstable_cssSideEffectImports: boolean;
unstable_dev: boolean | Dev;
unstable_postcss: boolean;
unstable_tailwind: boolean;
unstable_vanillaExtract: boolean;
v2_errorBoundary: boolean;
v2_meta: boolean;
v2_routeConvention: boolean;
}
/**
* The user-provided config in `remix.config.js`.
*/
export interface AppConfig {
/**
* The path to the `app` directory, relative to `remix.config.js`. Defaults
* to `"app"`.
*/
appDirectory?: string;
/**
* The path to a directory Remix can use for caching things in development,
* relative to `remix.config.js`. Defaults to `".cache"`.
*/
cacheDirectory?: string;
/**
* A function for defining custom routes, in addition to those already defined
* using the filesystem convention in `app/routes`. Both sets of routes will
* be merged.
*/
routes?: (
defineRoutes: DefineRoutesFunction
) => Promise<ReturnType<DefineRoutesFunction>>;
/**
* The path to the server build, relative to `remix.config.js`. Defaults to
* "build".
*
* @deprecated Use {@link ServerConfig.serverBuildPath} instead.
*/
serverBuildDirectory?: string;
/**
* The path to the server build file, relative to `remix.config.js`. This file
* should end in a `.js` extension and should be deployed to your server.
*
* If omitted, the default build path will be based on your
* {@link ServerConfig.serverBuildTarget}.
*/
serverBuildPath?: string;
/**
* The path to the browser build, relative to `remix.config.js`. Defaults to
* "public/build".
*/
assetsBuildDirectory?: string;
/**
* The path to the browser build, relative to remix.config.js. Defaults to
* "public/build".
*
* @deprecated Use `{@link ServerConfig.assetsBuildDirectory}` instead
*/
browserBuildDirectory?: string;
/**
* The URL prefix of the browser build with a trailing slash. Defaults to
* `"/build/"`. This is the path the browser will use to find assets.
*/
publicPath?: string;
/**
* The port number to use for the dev server. Defaults to 8002.
*/
devServerPort?: number;
/**
* The delay, in milliseconds, before the dev server broadcasts a reload
* event. There is no delay by default.
*/
devServerBroadcastDelay?: number;
/**
* Additional MDX remark / rehype plugins.
*/
mdx?: RemixMdxConfig | RemixMdxConfigFunction;
/**
* The output format of the server build. Defaults to "cjs".
*
* @deprecated Use {@link ServerConfig.serverBuildTarget} instead.
*/
serverModuleFormat?: ServerModuleFormat;
/**
* The platform the server build is targeting. Defaults to "node".
*
* @deprecated Use {@link ServerConfig.serverBuildTarget} instead.
*/
serverPlatform?: ServerPlatform;
/**
* The target of the server build. Defaults to "node-cjs".
*/
serverBuildTarget?: ServerBuildTarget;
/**
* A server entrypoint, relative to the root directory that becomes your
* server's main module. If specified, Remix will compile this file along with
* your application into a single file to be deployed to your server. This
* file can use either a `.js` or `.ts` file extension.
*/
server?: string;
/**
* A list of filenames or a glob patterns to match files in the `app/routes`
* directory that Remix will ignore. Matching files will not be recognized as
* routes.
*/
ignoredRouteFiles?: string[];
/**
* A list of patterns that determined if a module is transpiled and included
* in the server bundle. This can be useful when consuming ESM only packages
* in a CJS build.
*/
serverDependenciesToBundle?: Array<string | RegExp>;
/**
* A function for defining custom directories to watch while running `remix dev`, in addition to `appDirectory`.
*/
watchPaths?:
| string
| string[]
| (() => Promise<string | string[]> | string | string[]);
future?: Partial<FutureConfig>;
}
/**
* Fully resolved configuration object we use throughout Remix.
*/
export interface RemixConfig {
/**
* The absolute path to the root of the Remix project.
*/
rootDirectory: string;
/**
* The absolute path to the application source directory.
*/
appDirectory: string;
/**
* The absolute path to the cache directory.
*/
cacheDirectory: string;
/**
* The path to the entry.client file, relative to `config.appDirectory`.
*/
entryClientFile: string;
/**
* The path to the entry.server file, relative to `config.appDirectory`.
*/
entryServerFile: string;
/**
* An object of all available routes, keyed by route id.
*/
routes: RouteManifest;
/**
* The path to the server build file. This file should end in a `.js`. Defaults
* are based on {@link ServerConfig.serverBuildTarget}.
*/
serverBuildPath: string;
/**
* The absolute path to the assets build directory.
*/
assetsBuildDirectory: string;
/**
* the original relative path to the assets build directory
*/
relativeAssetsBuildDirectory: string;
/**
* The URL prefix of the public build with a trailing slash.
*/
publicPath: string;
/**
* The mode to use to run the server.
*/
serverMode: ServerMode;
/**
* The port number to use for the dev (asset) server.
*/
devServerPort: number;
/**
* The delay before the dev (asset) server broadcasts a reload event.
*/
devServerBroadcastDelay: number;
/**
* Additional MDX remark / rehype plugins.
*/
mdx?: RemixMdxConfig | RemixMdxConfigFunction;
/**
* The output format of the server build. Defaults to "cjs".
*/
serverModuleFormat: ServerModuleFormat;
/**
* The platform the server build is targeting. Defaults to "node".
*/
serverPlatform: ServerPlatform;
/**
* The target of the server build.
*/
serverBuildTarget?: ServerBuildTarget;
/**
* The default entry module for the server build if a {@see RemixConfig.customServer} is not provided.
*/
serverBuildTargetEntryModule: string;
/**
* A server entrypoint relative to the root directory that becomes your server's main module.
*/
serverEntryPoint?: string;
/**
* A list of patterns that determined if a module is transpiled and included
* in the server bundle. This can be useful when consuming ESM only packages
* in a CJS build.
*/
serverDependenciesToBundle: Array<string | RegExp>;
/**
* A list of directories to watch.
*/
watchPaths: string[];
/**
* The path for the tsconfig file, if present on the root directory.
*/
tsconfigPath: string | undefined;
future: FutureConfig;
}
/**
* Returns a fully resolved config object from the remix.config.js in the given
* root directory.
*/
export async function readConfig(
remixRoot?: string,
serverMode = ServerMode.Production
): Promise<RemixConfig> {
if (!isValidServerMode(serverMode)) {
throw new Error(`Invalid server mode "${serverMode}"`);
}
if (!remixRoot) {
remixRoot = process.env.REMIX_ROOT || process.cwd();
}
let rootDirectory = path.resolve(remixRoot);
let configFile = findConfig(rootDirectory, "remix.config");
let appConfig: AppConfig = {};
if (configFile) {
let appConfigModule: any;
try {
// shout out to next
// https://github.com/vercel/next.js/blob/b15a976e11bf1dc867c241a4c1734757427d609c/packages/next/server/config.ts#L748-L765
if (process.env.NODE_ENV === "test") {
// dynamic import does not currently work inside of vm which
// jest relies on so we fall back to require for this case
// https://github.com/nodejs/node/issues/35889
appConfigModule = require(configFile);
} else {
appConfigModule = await import(pathToFileURL(configFile).href);
}
appConfig = appConfigModule?.default || appConfigModule;
} catch (error: unknown) {
throw new Error(
`Error loading Remix config at ${configFile}\n${String(error)}`
);
}
}
let customServerEntryPoint = appConfig.server;
let serverBuildTarget: ServerBuildTarget | undefined =
appConfig.serverBuildTarget;
let serverModuleFormat: ServerModuleFormat =
appConfig.serverModuleFormat || "cjs";
let serverPlatform: ServerPlatform = appConfig.serverPlatform || "node";
switch (appConfig.serverBuildTarget) {
case "cloudflare-pages":
case "cloudflare-workers":
case "deno":
serverModuleFormat = "esm";
serverPlatform = "neutral";
break;
}
let mdx = appConfig.mdx;
let appDirectory = path.resolve(
rootDirectory,
appConfig.appDirectory || "app"
);
let cacheDirectory = path.resolve(
rootDirectory,
appConfig.cacheDirectory || ".cache"
);
let entryClientFile = findEntry(appDirectory, "entry.client");
if (!entryClientFile) {
throw new Error(`Missing "entry.client" file in ${appDirectory}`);
}
let entryServerFile = findEntry(appDirectory, "entry.server");
if (!entryServerFile) {
throw new Error(`Missing "entry.server" file in ${appDirectory}`);
}
let serverBuildPath = "build/index.js";
switch (serverBuildTarget) {
case "arc":
serverBuildPath = "server/index.js";
break;
case "cloudflare-pages":
serverBuildPath = "functions/[[path]].js";
break;
case "netlify":
serverBuildPath = ".netlify/functions-internal/server.js";
break;
case "vercel":
serverBuildPath = "api/index.js";
break;
}
serverBuildPath = path.resolve(rootDirectory, serverBuildPath);
// retain deprecated behavior for now
if (appConfig.serverBuildDirectory) {
serverBuildPath = path.resolve(
rootDirectory,
path.join(appConfig.serverBuildDirectory, "index.js")
);
}
if (appConfig.serverBuildPath) {
serverBuildPath = path.resolve(rootDirectory, appConfig.serverBuildPath);
}
let assetsBuildDirectory =
appConfig.assetsBuildDirectory ||
appConfig.browserBuildDirectory ||
path.join("public", "build");
let absoluteAssetsBuildDirectory = path.resolve(
rootDirectory,
assetsBuildDirectory
);
let devServerPort =
Number(process.env.REMIX_DEV_SERVER_WS_PORT) ||
(await getPort({ port: Number(appConfig.devServerPort) || 8002 }));
// set env variable so un-bundled servers can use it
process.env.REMIX_DEV_SERVER_WS_PORT = `${devServerPort}`;
let devServerBroadcastDelay = appConfig.devServerBroadcastDelay || 0;
let defaultPublicPath = "/build/";
switch (serverBuildTarget) {
case "arc":
defaultPublicPath = "/_static/build/";
break;
}
let publicPath = addTrailingSlash(appConfig.publicPath || defaultPublicPath);
let rootRouteFile = findEntry(appDirectory, "root");
if (!rootRouteFile) {
throw new Error(`Missing "root" route file in ${appDirectory}`);
}
let routes: RouteManifest = {
root: { path: "", id: "root", file: rootRouteFile },
};
let routesConvention = appConfig.future?.v2_routeConvention
? flatRoutes
: defineConventionalRoutes;
if (fse.existsSync(path.resolve(appDirectory, "routes"))) {
let conventionalRoutes = routesConvention(
appDirectory,
appConfig.ignoredRouteFiles
);
for (let route of Object.values(conventionalRoutes)) {
routes[route.id] = { ...route, parentId: route.parentId || "root" };
}
}
if (appConfig.routes) {
let manualRoutes = await appConfig.routes(defineRoutes);
for (let route of Object.values(manualRoutes)) {
routes[route.id] = { ...route, parentId: route.parentId || "root" };
}
}
let watchPaths: string[] = [];
if (typeof appConfig.watchPaths === "function") {
let directories = await appConfig.watchPaths();
watchPaths = watchPaths.concat(
Array.isArray(directories) ? directories : [directories]
);
} else if (appConfig.watchPaths) {
watchPaths = watchPaths.concat(
Array.isArray(appConfig.watchPaths)
? appConfig.watchPaths
: [appConfig.watchPaths]
);
}
let serverBuildTargetEntryModule = `export * from ${JSON.stringify(
serverBuildVirtualModule.id
)};`;
let serverDependenciesToBundle = appConfig.serverDependenciesToBundle || [];
// When tsconfigPath is undefined, the default "tsconfig.json" is not
// found in the root directory.
let tsconfigPath: string | undefined;
let rootTsconfig = path.resolve(rootDirectory, "tsconfig.json");
let rootJsConfig = path.resolve(rootDirectory, "jsconfig.json");
if (fse.existsSync(rootTsconfig)) {
tsconfigPath = rootTsconfig;
} else if (fse.existsSync(rootJsConfig)) {
tsconfigPath = rootJsConfig;
}
if (tsconfigPath) {
writeConfigDefaults(tsconfigPath);
}
let future: FutureConfig = {
unstable_cssModules: appConfig.future?.unstable_cssModules === true,
unstable_cssSideEffectImports:
appConfig.future?.unstable_cssSideEffectImports === true,
unstable_dev: appConfig.future?.unstable_dev ?? false,
unstable_postcss: appConfig.future?.unstable_postcss === true,
unstable_tailwind: appConfig.future?.unstable_tailwind === true,
unstable_vanillaExtract: appConfig.future?.unstable_vanillaExtract === true,
v2_errorBoundary: appConfig.future?.v2_errorBoundary === true,
v2_meta: appConfig.future?.v2_meta === true,
v2_routeConvention: appConfig.future?.v2_routeConvention === true,
};
return {
appDirectory,
cacheDirectory,
entryClientFile,
entryServerFile,
devServerPort,
devServerBroadcastDelay,
assetsBuildDirectory: absoluteAssetsBuildDirectory,
relativeAssetsBuildDirectory: assetsBuildDirectory,
publicPath,
rootDirectory,
routes,
serverBuildPath,
serverMode,
serverModuleFormat,
serverPlatform,
serverBuildTarget,
serverBuildTargetEntryModule,
serverEntryPoint: customServerEntryPoint,
serverDependenciesToBundle,
mdx,
watchPaths,
tsconfigPath,
future,
};
}
function addTrailingSlash(path: string): string {
return path.endsWith("/") ? path : path + "/";
}
const entryExts = [".js", ".jsx", ".ts", ".tsx"];
function findEntry(dir: string, basename: string): string | undefined {
for (let ext of entryExts) {
let file = path.resolve(dir, basename + ext);
if (fse.existsSync(file)) return path.relative(dir, file);
}
return undefined;
}
const configExts = [".js", ".cjs", ".mjs"];
function findConfig(dir: string, basename: string): string | undefined {
for (let ext of configExts) {
let file = path.resolve(dir, basename + ext);
if (fse.existsSync(file)) return file;
}
return undefined;
}