import path from 'path' ; import fs from 'fs/promises' ; import { createHash } from 'crypto' ; import { once } from 'lodash' ; import { HttpResources , HttpResponseOptions , PackageInfo } from '../../../../../src/core/server' ; const MINUTE = 60 ; const HOUR = 60 * MINUTE ; const DAY = 24 * HOUR ; internal export const FULLSTORY_LIBRARY_PATH = path . join ( __dirname , '..' , 'assets' , 'fullstory_library.js' ) ; internal export const renderFullStoryLibraryFactory = ( dist = true ) => once ( async ( ) : Promise < { body : Buffer ; headers : HttpResponseOptions [ 'headers' ] ; } > => { const srcBuffer = await fs . readFile ( FULLSTORY_LIBRARY_PATH ) ; const hash = createHash ( 'sha1' ) ; hash . update ( srcBuffer ) ; const hashDigest = hash . digest ( 'hex' ) ; return { body : srcBuffer , headers : dist ? { 'cache-control' : `max-age=${ DAY * 365 }` } : { 'cache-control' : 'must-revalidate' , etag : hashDigest } , } ; } ) ; export const registerFullstoryRoute = ( { httpResources , packageInfo , } ) => { const renderFullStoryLibrary = renderFullStoryLibraryFactory ( packageInfo . dist ) ; /**
     * Register a custom JS endpoint in order to acheive best caching possible with `max-age` similar to plugin bundles.
     */ httpResources . register ( { path : `/internal/cloud/${ packageInfo . buildNum }/fullstory.js` , validate : false , options : { authRequired : false , } , } , async ( context , req , res ) => { try { return res . renderJs ( await renderFullStoryLibrary ( ) ) ; } catch ( e ) { return res . customError ( { body : `Could not load FullStory library from disk due to error: ${ e . toString ( ) }` , statusCode : 500 , } ) ; } } ) ; } ;