@@ -23,6 +23,61 @@ function addonUrl(addonUrls, req) {
2323 return addonUrl ? `${ addonUrl } ${ m [ 2 ] } ` : null ;
2424}
2525
26+ // Used as an optimization to avoid dual lookups for missing assets
27+ const assetExtensionRegExp = / \. ( h t m l ? | p n g | j p g | j s | c s s | s v g | g i f | i c o | w o f f | w o f f 2 ) $ /
28+
29+ function alternativePathsFor ( url ) {
30+ const paths = [ ]
31+ if ( url [ url . length - 1 ] === '/' ) {
32+ const end = url . length - 1
33+ if ( url !== '/' ) {
34+ paths . push ( url . slice ( 0 , end ) + '.html' )
35+ paths . push ( url . slice ( 0 , end ) + '.htm' )
36+ }
37+ paths . push ( url + 'index.html' )
38+ paths . push ( url + 'index.htm' )
39+ } else if ( ! url . match ( assetExtensionRegExp ) ) {
40+ paths . push ( url + '.html' )
41+ paths . push ( url + '.htm' )
42+ paths . push ( url + '/index.html' )
43+ paths . push ( url + '/index.htm' )
44+ }
45+
46+ return paths
47+ }
48+
49+ function initializeProxy ( port ) {
50+ const proxy = httpProxy . createProxyServer ( {
51+ selfHandleResponse : true ,
52+ target : {
53+ host : 'localhost' ,
54+ port : port
55+ }
56+ } )
57+
58+ proxy . on ( 'proxyRes' , ( proxyRes , req , res ) => {
59+ if ( proxyRes . statusCode === 404 && req . alternativePaths && req . alternativePaths . length ) {
60+ req . url = req . alternativePaths . shift ( )
61+ return proxy . web ( req , res , req . proxyOptions )
62+ }
63+ res . writeHead ( proxyRes . statusCode , proxyRes . headers )
64+ proxyRes . on ( 'data' , function ( data ) {
65+ res . write ( data )
66+ } )
67+ proxyRes . on ( 'end' , function ( ) {
68+ res . end ( )
69+ } )
70+ } )
71+
72+ return {
73+ web : ( req , res , options ) => {
74+ req . proxyOptions = options
75+ req . alternativePaths = alternativePathsFor ( req . url )
76+ return proxy . web ( req , res , options )
77+ }
78+ }
79+ }
80+
2681async function startProxy ( settings , addonUrls ) {
2782 const rulesProxy = require ( "@netlify/rules-proxy" ) ;
2883
0 commit comments