@@ -330,7 +330,7 @@ const patchFile = async ({
330
330
* The file we need has moved around a bit over the past few versions,
331
331
* so we iterate through the options until we find it
332
332
*/
333
- export const getServerFile = ( root : string , includeBase = true ) => {
333
+ const getServerFile = ( root : string , includeBase = true ) => {
334
334
const candidates = [ 'next/dist/server/next-server' , 'next/dist/next-server/server/next-server' ]
335
335
336
336
if ( includeBase ) {
@@ -340,6 +340,54 @@ export const getServerFile = (root: string, includeBase = true) => {
340
340
return findModuleFromBase ( { candidates, paths : [ root ] } )
341
341
}
342
342
343
+ /**
344
+ * Try to find next-server module in few locations (to support different next versions) and in few context (try to resolve from app location and from this module)
345
+ */
346
+ export const getNextServerModulePath = ( root : string ) : string | null => {
347
+ // first let's try to use app location directory to find next-server
348
+ try {
349
+ const nextServerModuleLocation = getServerFile ( root , false )
350
+ if ( nextServerModuleLocation ) {
351
+ return nextServerModuleLocation
352
+ }
353
+ } catch ( error ) {
354
+ if ( ! error . message . includes ( 'Cannot find module' ) ) {
355
+ // A different error, so rethrow it
356
+ throw error
357
+ }
358
+ }
359
+
360
+ // if we didn't find it, let's try to resolve "next" package from this module
361
+ try {
362
+ // next >= 11.0.1. Yay breaking changes in patch releases!
363
+ const nextServerModuleLocation = require . resolve ( 'next/dist/server/next-server' )
364
+ if ( nextServerModuleLocation ) {
365
+ return nextServerModuleLocation
366
+ }
367
+ } catch ( error ) {
368
+ if ( ! error . message . includes ( "Cannot find module 'next/dist/server/next-server'" ) ) {
369
+ // A different error, so rethrow it
370
+ throw error
371
+ }
372
+ // Probably an old version of next, so fall through and find it elsewhere.
373
+ }
374
+
375
+ try {
376
+ // next < 11.0.1
377
+ // eslint-disable-next-line n/no-missing-require
378
+ const nextServerModuleLocation = require . resolve ( 'next/dist/next-server/server/next-server' )
379
+ if ( nextServerModuleLocation ) {
380
+ return nextServerModuleLocation
381
+ }
382
+ } catch ( error ) {
383
+ if ( ! error . message . includes ( "Cannot find module 'next/dist/next-server/server/next-server'" ) ) {
384
+ throw error
385
+ }
386
+ }
387
+
388
+ return null
389
+ }
390
+
343
391
/**
344
392
* Find the source file for a given page route
345
393
*/
0 commit comments