2022-03-25 16:08:02 +00:00
import type { AstroAdapter , AstroIntegration , AstroConfig } from 'astro' ;
import fs from 'fs' ;
export function getAdapter ( site : string | undefined ) : AstroAdapter {
return {
name : '@astrojs/netlify' ,
serverEntrypoint : '@astrojs/netlify/netlify-functions.js' ,
exports : [ 'handler' ] ,
2022-03-25 16:08:51 +00:00
args : { site } ,
2022-03-25 16:08:02 +00:00
} ;
}
interface NetlifyFunctionsOptions {
dist? : URL ;
}
function netlifyFunctions ( { dist } : NetlifyFunctionsOptions = { } ) : AstroIntegration {
let _config : AstroConfig ;
let entryFile : string ;
return {
name : '@astrojs/netlify' ,
hooks : {
'astro:config:setup' : ( { config } ) = > {
2022-03-25 16:08:51 +00:00
if ( dist ) {
2022-04-02 18:29:59 +00:00
config . outDir = dist ;
2022-03-25 16:08:02 +00:00
} else {
2022-04-02 18:29:59 +00:00
config . outDir = new URL ( './netlify/' , config . root ) ;
2022-03-25 16:08:02 +00:00
}
} ,
'astro:config:done' : ( { config , setAdapter } ) = > {
2022-04-05 15:25:48 +00:00
let site = null ;
try {
site = new URL ( config . base , config . site ) ;
} catch {
throw new Error (
'The Netlify adapter requires a deployment URL. Ensure a "site" is specified in your astro.config. If you provided a "base" in your astro.config, ensure it is a valid path.'
) ;
}
setAdapter ( getAdapter ( site . toString ( ) ) ) ;
2022-03-25 16:08:02 +00:00
_config = config ;
} ,
2022-03-25 16:08:51 +00:00
'astro:build:start' : async ( { buildConfig } ) = > {
2022-03-25 16:08:02 +00:00
entryFile = buildConfig . serverEntry . replace ( /\.m?js/ , '' ) ;
2022-04-02 18:29:59 +00:00
buildConfig . client = _config . outDir ;
buildConfig . server = new URL ( './functions/' , _config . outDir ) ;
2022-03-25 16:08:02 +00:00
} ,
'astro:build:done' : async ( { routes , dir } ) = > {
const _redirectsURL = new URL ( './_redirects' , dir ) ;
// Create the redirects file that is used for routing.
let _redirects = '' ;
2022-03-25 16:08:51 +00:00
for ( const route of routes ) {
if ( route . pathname ) {
2022-03-25 16:08:02 +00:00
_redirects += `
2022-03-25 16:08:51 +00:00
$ { route . pathname } / . netlify / functions / $ { entryFile } 200 ` ;
2022-03-25 16:08:02 +00:00
}
}
2022-03-25 16:08:51 +00:00
if ( fs . existsSync ( _redirects ) ) {
2022-03-25 16:08:02 +00:00
await fs . promises . appendFile ( _redirectsURL , _redirects , 'utf-8' ) ;
} else {
await fs . promises . writeFile ( _redirectsURL , _redirects , 'utf-8' ) ;
}
2022-03-25 16:08:51 +00:00
} ,
2022-03-25 16:08:02 +00:00
} ,
} ;
}
2022-03-25 16:08:51 +00:00
export { netlifyFunctions , netlifyFunctions as default } ;