|
| 1 | +import { promises } from 'fs' |
| 2 | +import { join } from 'path' |
| 3 | + |
| 4 | +import { build } from '@netlify/esbuild' |
| 5 | +import { FSWatcher, watch } from 'chokidar' |
| 6 | + |
| 7 | +// For more information on Next.js middleware, see https://nextjs.org/docs/advanced-features/middleware |
| 8 | + |
| 9 | +// These are the locations that a middleware file can exist in a Next.js application |
| 10 | +// If other possible locations are added by Next.js, they should be added here. |
| 11 | +const MIDDLEWARE_FILE_LOCATIONS: Readonly<string[]> = [ |
| 12 | + 'middleware.js', |
| 13 | + 'middleware.ts', |
| 14 | + 'src/middleware.js', |
| 15 | + 'src/middleware.ts', |
| 16 | +] |
| 17 | + |
| 18 | +const toFileList = (watched: Record<string, Array<string>>) => |
| 19 | + Object.entries(watched).flatMap(([dir, files]) => files.map((file) => join(dir, file))) |
| 20 | + |
| 21 | +/** |
| 22 | + * Compile the middleware file using esbuild |
| 23 | + */ |
| 24 | + |
| 25 | +const buildMiddlewareFile = async (entryPoints: Array<string>, base: string) => { |
| 26 | + try { |
| 27 | + await build({ |
| 28 | + entryPoints, |
| 29 | + outfile: join(base, '.netlify', 'middleware.js'), |
| 30 | + bundle: true, |
| 31 | + format: 'esm', |
| 32 | + target: 'esnext', |
| 33 | + absWorkingDir: base, |
| 34 | + }) |
| 35 | + } catch (error) { |
| 36 | + console.error(error.toString()) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * We only compile middleware if there's exactly one file. If there's more than one, we log a warning and don't compile. |
| 42 | + */ |
| 43 | +const shouldFilesBeCompiled = (watchedFiles: Array<string>, isFirstRun: boolean) => { |
| 44 | + if (watchedFiles.length === 0) { |
| 45 | + if (!isFirstRun) { |
| 46 | + // Only log on subsequent builds, because having it on first build makes it seem like a warning, when it's a normal state |
| 47 | + console.log('No middleware found') |
| 48 | + } |
| 49 | + return false |
| 50 | + } |
| 51 | + if (watchedFiles.length > 1) { |
| 52 | + console.log('Multiple middleware files found:') |
| 53 | + console.log(watchedFiles.join('\n')) |
| 54 | + console.log('This is not supported.') |
| 55 | + return false |
| 56 | + } |
| 57 | + return true |
| 58 | +} |
| 59 | + |
| 60 | +const updateWatchedFiles = async (watcher: FSWatcher, base: string, isFirstRun = false) => { |
| 61 | + try { |
| 62 | + // Start by deleting the old file. If we error out, we don't want to leave the old file around |
| 63 | + await promises.unlink(join(base, '.netlify', 'middleware.js')) |
| 64 | + } catch { |
| 65 | + // Ignore, because it's fine if it didn't exist |
| 66 | + } |
| 67 | + // The list of watched files is an object with the directory as the key and an array of files as the value. |
| 68 | + // We need to flatten this into a list of files |
| 69 | + const watchedFiles = toFileList(watcher.getWatched()) |
| 70 | + if (!shouldFilesBeCompiled(watchedFiles, isFirstRun)) { |
| 71 | + watcher.emit('build') |
| 72 | + return |
| 73 | + } |
| 74 | + console.log(`${isFirstRun ? 'Building' : 'Rebuilding'} middleware ${watchedFiles[0]}...`) |
| 75 | + await buildMiddlewareFile(watchedFiles, base) |
| 76 | + console.log('...done') |
| 77 | + watcher.emit('build') |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * Watch for changes to the middleware file location. When a change is detected, recompile the middleware file. |
| 82 | + * |
| 83 | + * @param base The base directory to watch |
| 84 | + * @returns a file watcher and a promise that resolves when the initial scan is complete. |
| 85 | + */ |
| 86 | +export const watchForMiddlewareChanges = (base: string) => { |
| 87 | + const watcher = watch(MIDDLEWARE_FILE_LOCATIONS, { |
| 88 | + // Try and ensure renames just emit one event |
| 89 | + atomic: true, |
| 90 | + // Don't emit for every watched file, just once after the scan is done |
| 91 | + ignoreInitial: true, |
| 92 | + cwd: base, |
| 93 | + }) |
| 94 | + |
| 95 | + watcher |
| 96 | + .on('change', (path) => { |
| 97 | + console.log(`File ${path} has been changed`) |
| 98 | + updateWatchedFiles(watcher, base) |
| 99 | + }) |
| 100 | + .on('add', (path) => { |
| 101 | + console.log(`File ${path} has been added`) |
| 102 | + updateWatchedFiles(watcher, base) |
| 103 | + }) |
| 104 | + .on('unlink', (path) => { |
| 105 | + console.log(`File ${path} has been removed`) |
| 106 | + updateWatchedFiles(watcher, base) |
| 107 | + }) |
| 108 | + |
| 109 | + return { |
| 110 | + watcher, |
| 111 | + isReady: new Promise<void>((resolve) => { |
| 112 | + watcher.on('ready', async () => { |
| 113 | + console.log('Initial scan for middleware file complete. Ready for changes.') |
| 114 | + // This only happens on the first scan |
| 115 | + await updateWatchedFiles(watcher, base, true) |
| 116 | + console.log('Ready') |
| 117 | + resolve() |
| 118 | + }) |
| 119 | + }), |
| 120 | + nextBuild: () => |
| 121 | + new Promise<void>((resolve) => { |
| 122 | + watcher.once('build', resolve) |
| 123 | + }), |
| 124 | + } |
| 125 | +} |
0 commit comments