@@ -71,14 +71,21 @@ const sanitizeName = (name: string) => `next_${name.replace(/\W/g, '_')}`
71
71
/**
72
72
* Initialization added to the top of the edge function bundle
73
73
*/
74
- const bootstrap = /* js */ `
74
+ const preamble = /* js */ `
75
+
75
76
globalThis.process = { env: {...Deno.env.toObject(), NEXT_RUNTIME: 'edge', 'NEXT_PRIVATE_MINIMAL_MODE': '1' } }
76
- globalThis. _ENTRIES || = {}
77
+ let _ENTRIES = {}
77
78
// Deno defines "window", but naughty libraries think this means it's a browser
78
79
delete globalThis.window
79
-
80
+ // Next uses "self" as a function-scoped global-like object
81
+ const self = {}
80
82
`
81
83
84
+ // Slightly different spacing in different versions!
85
+ const IMPORT_UNSUPPORTED = [
86
+ `Object.defineProperty(globalThis,"__import_unsupported"` ,
87
+ ` Object.defineProperty(globalThis, "__import_unsupported"` ,
88
+ ]
82
89
/**
83
90
* Concatenates the Next edge function code with the required chunks and adds an export
84
91
*/
@@ -90,17 +97,20 @@ const getMiddlewareBundle = async ({
90
97
netlifyConfig : NetlifyConfig
91
98
} ) : Promise < string > => {
92
99
const { publish } = netlifyConfig . build
93
- const chunks : Array < string > = [ bootstrap ]
100
+ const chunks : Array < string > = [ preamble ]
94
101
for ( const file of edgeFunctionDefinition . files ) {
95
102
const filePath = join ( publish , file )
96
- const data = await fs . readFile ( filePath , 'utf8' )
103
+
104
+ let data = await fs . readFile ( filePath , 'utf8' )
105
+ // Next defines an immutable global variable, which is fine unless you have more than one in the bundle
106
+ // This adds a check to see if the global is already defined
107
+ data = IMPORT_UNSUPPORTED . reduce (
108
+ ( acc , val ) => acc . replace ( val , `('__import_unsupported' in globalThis)||${ val } ` ) ,
109
+ data ,
110
+ )
97
111
chunks . push ( '{' , data , '}' )
98
112
}
99
113
100
- const middleware = await fs . readFile ( join ( publish , `server` , `${ edgeFunctionDefinition . name } .js` ) , 'utf8' )
101
-
102
- chunks . push ( middleware )
103
-
104
114
const exports = /* js */ `export default _ENTRIES["middleware_${ edgeFunctionDefinition . name } "].default;`
105
115
chunks . push ( exports )
106
116
return chunks . join ( '\n' )
0 commit comments