forked from freshframework/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuilder.ts
More file actions
422 lines (364 loc) · 11.5 KB
/
Copy pathbuilder.ts
File metadata and controls
422 lines (364 loc) · 11.5 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
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
import {
App,
createOnListen,
type ListenOptions,
setBuildCache,
} from "../app.ts";
import { fsAdapter } from "../fs.ts";
import * as path from "@std/path";
import * as colors from "@std/fmt/colors";
import { bundleJs, type FreshBundleOptions } from "./esbuild.ts";
import { liveReload } from "./middlewares/live_reload.ts";
import {
cssAssetHash,
FileTransformer,
type OnTransformOptions,
} from "./file_transformer.ts";
import type { TransformFn } from "./file_transformer.ts";
import {
type DevBuildCache,
DiskBuildCache,
type FsRoute,
MemoryBuildCache,
} from "./dev_build_cache.ts";
import { BUILD_ID } from "@fresh/build-id";
import { updateCheck } from "./update_check.ts";
import { devErrorOverlay } from "./middlewares/error_overlay/middleware.tsx";
import { automaticWorkspaceFolders } from "./middlewares/automatic_workspace_folders.ts";
import { parseDirPath } from "../config.ts";
import { pathToExportName, UniqueNamer } from "../utils.ts";
import { checkDenoCompilerOptions } from "./check.ts";
import { crawlFsItem } from "./fs_crawl.ts";
import { TEST_FILE_PATTERN, UPDATE_INTERVAL } from "../constants.ts";
export interface BuildOptions {
/**
* This sets the target environment for the generated code. Newer
* language constructs will be transformed to match the specified
* support range. See https://esbuild.github.io/api/#target
* @default {"es2022"}
*/
target?: string | string[];
/**
* The root directory of the Fresh project.
*
* Other paths, such as `build.outDir`, `staticDir`, and `fsRoutes()`
* are resolved relative to this directory.
* @default Deno.cwd()
*/
root?: string;
/**
* The directory to write generated files to when `dev.ts build` is run.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "_fresh"
*/
outDir?: string;
/**
* The directory to serve static files from.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "static"
*/
staticDir?: string;
/**
* The directory which contains islands.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "islands"
*/
islandDir?: string;
/**
* The directory which contains routes.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "routes"
*/
routeDir?: string;
/**
* The entrypoint for your server.
*
* This can be an absolute path, a file URL or a relative path.
* Relative paths are resolved against the `root` option.
* @default "main.ts"
*/
serverEntry?: string;
/**
* File paths which should be ignored when crawling the file system.
*/
ignore?: RegExp[];
/**
* Control if/how production source maps should be handled.
* See https://esbuild.github.io/api/#source-maps for more information.
*/
sourceMap?: FreshBundleOptions["sourceMap"];
}
/**
* The final resolved Builder configuration.
*/
export type ResolvedBuildConfig = Required<Omit<BuildOptions, "sourceMap">> & {
mode: "development" | "production";
buildId: string;
sourceMap?: FreshBundleOptions["sourceMap"];
};
// deno-lint-ignore no-explicit-any
export class Builder<State = any> {
#transformer: FileTransformer;
#addedInternalTransforms = false;
config: ResolvedBuildConfig;
#islandSpecifiers = new Set<string>();
#fsRoutes: FsRoute<State>;
#ready = Promise.withResolvers<void>();
constructor(options?: BuildOptions) {
const root = parseDirPath(options?.root ?? ".", Deno.cwd());
const serverEntry = parseDirPath(options?.serverEntry ?? "main.ts", root);
const outDir = parseDirPath(options?.outDir ?? "_fresh", root);
const staticDir = parseDirPath(options?.staticDir ?? "static", root);
const islandDir = parseDirPath(options?.islandDir ?? "islands", root);
const routeDir = parseDirPath(options?.routeDir ?? "routes", root);
this.#fsRoutes = { dir: routeDir, files: [], id: "default" };
this.#transformer = new FileTransformer(fsAdapter, root);
this.config = {
serverEntry,
target: options?.target ?? ["chrome99", "firefox99", "safari15"],
root,
outDir,
staticDir,
islandDir,
routeDir,
ignore: options?.ignore ?? [TEST_FILE_PATTERN],
mode: "production",
buildId: BUILD_ID,
sourceMap: options?.sourceMap,
};
}
registerIsland(specifier: string): void {
this.#islandSpecifiers.add(specifier);
}
onTransformStaticFile(
options: OnTransformOptions,
callback: TransformFn,
): void {
this.#transformer.onTransform(options, callback);
}
async listen(
importApp: () => Promise<{ app: App<State> } | App<State>>,
options: ListenOptions = {},
): Promise<void> {
// Run update check in background
updateCheck(UPDATE_INTERVAL).catch(() => {});
this.config.mode = "development";
await this.#crawlFsItems();
let app = await importApp();
if (!(app instanceof App) && "app" in app) {
app = app.app;
}
const buildCache = new MemoryBuildCache<State>(
this.config,
this.#fsRoutes,
this.#transformer,
);
await buildCache.prepare();
app.config.root = this.config.root;
app.config.mode = "development";
setBuildCache(app, buildCache, "development");
const appHandler = app.handler();
// Store original basePath for display purposes
const originalBasePath = app.config.basePath;
const devConfig = { ...app.config, basePath: "" };
const devApp = new App<State>(devConfig)
.use(liveReload())
.use(devErrorOverlay())
.use(automaticWorkspaceFolders(this.config.root))
// Wait for islands to be ready
.use(async (ctx) => {
await this.#ready.promise;
return ctx.next();
})
.all("*", (ctx) => appHandler(ctx.req, ctx.info));
devApp.config.root = this.config.root;
devApp.config.mode = "development";
setBuildCache(devApp, buildCache, "development");
// Boot in parallel to spin up the server quicker. We'll hold
// requests until the required assets are processed.
await Promise.all([
devApp.listen({
...options,
onListen: options.onListen ??
createOnListen(originalBasePath, options),
}),
this.#build(buildCache, true),
]);
return;
}
/**
* Build optimized assets for your app. By default this will create
* a production build.
*
* This can also be used for testing to apply a snapshot to a particular
* {@linkcode App} instance.
*
* @example Testing
* ```ts
* const builder = new Builder();
* const applySnapshot = await builder.build({ snapshot: "memory" });
*
* Deno.test("My Test", () => {
* const app = new App()
* .get("/", () => new Response("hello"))
*
* applySnapshot(app)
*
* // ... your usual testing
* })
* ```
* @param options
* @returns Apply a snapshot to a particular {@linkcode App} instance.
*/
async build(
options?: {
mode?: ResolvedBuildConfig["mode"];
snapshot?: "disk" | "memory";
},
): Promise<(app: App<State>) => void> {
this.config.mode = options?.mode ?? "production";
await this.#crawlFsItems();
const buildCache = options?.snapshot === "memory"
? new MemoryBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
)
: new DiskBuildCache(
this.config,
this.#fsRoutes,
this.#transformer,
);
await this.#build(buildCache, this.config.mode === "development");
await buildCache.prepare();
return (app) => {
setBuildCache(app, buildCache, app.config.mode);
};
}
async #crawlFsItems() {
const { islands, routes } = await crawlFsItem(
{
islandDir: this.config.islandDir,
routeDir: this.config.routeDir,
ignore: this.config.ignore,
},
);
for (let i = 0; i < islands.length; i++) {
this.registerIsland(islands[i]);
}
this.#fsRoutes.files = routes;
}
async #build<T>(buildCache: DevBuildCache<T>, dev: boolean): Promise<void> {
const { target, outDir, root } = this.config;
const staticOutDir = path.join(outDir, "static");
const { denoJson, jsxImportSource } = await checkDenoCompilerOptions(root);
if (!this.#addedInternalTransforms) {
this.#addedInternalTransforms = true;
cssAssetHash(this.#transformer);
}
try {
await Deno.remove(staticOutDir);
} catch {
// Ignore
}
const runtimePath = dev
? "../runtime/client/dev.ts"
: "../runtime/client/mod.ts";
const entryPoints: Record<string, string> = {
"fresh-runtime": new URL(runtimePath, import.meta.url).href,
};
const namer = new UniqueNamer();
for (const spec of this.#islandSpecifiers) {
const specName = specToName(spec);
const name = namer.getUniqueName(specName);
entryPoints[name] = spec;
buildCache.islandModNameToChunk.set(name, {
name,
server: spec,
browser: null,
css: [],
});
}
const output = await bundleJs({
cwd: root,
outDir: staticOutDir,
dev: dev ?? false,
target,
buildId: BUILD_ID,
entryPoints,
jsxImportSource,
denoJsonPath: denoJson,
sourceMap: this.config.sourceMap,
});
const prefix = `/_fresh/js/${BUILD_ID}/`;
for (const name of buildCache.islandModNameToChunk.keys()) {
const chunkName = output.entryToChunk.get(name);
if (chunkName === undefined) {
throw new Error(`Could not find chunk for island ${name}`);
}
const pathname = `${prefix}${chunkName}`;
buildCache.islandModNameToChunk.get(name)!.browser = pathname;
}
for (let i = 0; i < output.files.length; i++) {
const file = output.files[i];
const pathname = `${prefix}${file.path}`;
await buildCache.addProcessedFile(pathname, file.contents, file.hash);
}
await buildCache.flush();
if (!dev) {
// deno-lint-ignore no-console
console.log(
`Assets written to: ${colors.cyan(outDir)}`,
);
}
this.#ready.resolve();
}
}
export function specToName(spec: string): string {
if (/^(https?:|file:)/.test(spec)) {
const url = new URL(spec);
if (url.pathname === "/") {
return pathToExportName(url.hostname);
}
const idx = spec.lastIndexOf("/");
return pathToExportName(spec.slice(idx + 1));
} else if (spec.startsWith("jsr:")) {
const match = spec.match(
/jsr:@([^/]+)\/([^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[5] === undefined) {
return pathToExportName(`${match[1]}_${match[2]}`);
}
return pathToExportName(match[5]);
} else if (spec.startsWith("npm:")) {
const match = spec.match(
/npm:(@([^/]+)\/([^@/]+)|[^@/]+)(@[\^~]?\d+\.\d+\.\d+([^/]+)?)?(\/.*)?$/,
)!;
if (match[6] === undefined) {
if (match[2] === undefined) {
return pathToExportName(match[1]);
}
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[6]);
}
const match = spec.match(/^(@([^/]+)\/([^@/]+)|[^@/]+)(\/.*)?$/);
if (match !== null) {
if (match[4] === undefined) {
if (match[2] !== undefined) {
return pathToExportName(`${match[2]}_${match[3]}`);
}
return pathToExportName(match[1]);
}
return pathToExportName(match[4]);
}
return pathToExportName(spec);
}