import{GetObjectCommand,S3Client}from"@aws-sdk/client-s3";importSharpfrom'sharp';constS3=newS3Client({region:'ap-northeast-2'});constBUCKET='wsi-static-arco';constsupportImageTypes=['jpg','jpeg','png','webp','gif','avif','tiff'];exportconsthandler=async(event,context,callback)=>{const{request,response}=event.Records[0].cf;const{uri}=request;constObjectKey=decodeURIComponent(uri).substring(1);constparams=newURLSearchParams(request.querystring);letwidth=params.get('width');letheight=params.get('height');if(!(width||height)){returncallback(null,response);}constextension=uri.match(/\/?(.*)\.(.*)/)[2].toLowerCase();width=parseInt(width,10)||null;height=parseInt(height,10)||null;letformat=extension.toLowerCase();format=format==='jpg'?'jpeg':format;lets3Object;letresizedImage;if(!supportImageTypes.some(type=>type===extension)){responseHandler(403,'Forbidden','Unsupported image type',[{key:'Content-Type',value:'text/plain'}],);returncallback(null,response);}console.log(`width: ${width}, height: ${height}`);console.log('S3 Object key:',ObjectKey);try{constcommand=newGetObjectCommand({Bucket:BUCKET,Key:ObjectKey});s3Object=awaitS3.send(command);}catch(error){responseHandler(404,'Not Found','The image does not exist.',[{key:'Content-Type',value:'text/plain'}],);returncallback(null,response);}try{constimageBuffer=Buffer.concat(awaits3Object.Body.toArray());resizedImage=awaitSharp(imageBuffer).resize(width,height).toFormat(format).withMetadata().toBuffer();}catch(error){responseHandler(500,'Internal Server Error','Fail to resize image.',[{key:'Content-Type',value:'text/plain'}],);returncallback(null,response);}responseHandler(200,'OK',resizedImage.toString('base64'),[{key:'Content-Type',value:`image/${format}`},{key:'Content-Length',value:resizedImage.length.toString()}],'base64');functionresponseHandler(status,statusDescription,body,headers,bodyEncoding){response.status=status;response.statusDescription=statusDescription;response.body=body;response.headers=headers.reduce((acc,header)=>{acc[header.key.toLowerCase()]=[{key:header.key,value:header.value}];returnacc;},{});if(bodyEncoding){response.bodyEncoding=bodyEncoding;}}console.log('Success resizing image');returncallback(null,response);};