upup-react-file-uploader
Version:
21 lines • 6.4 kB
JavaScript
var y=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var Y=Object.getOwnPropertyNames;var Z=Object.prototype.hasOwnProperty;var J=(e,r)=>{for(var t in r)y(e,t,{get:r[t],enumerable:!0})},ee=(e,r,t,i)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Y(r))!Z.call(e,n)&&n!==t&&y(e,n,{get:()=>r[n],enumerable:!(i=Q(r,n))||i.enumerable});return e};var te=e=>ee(y({},"__esModule",{value:!0}),e);var le={};J(le,{UpupProvider:()=>S,azureGenerateSasUrl:()=>x,s3GeneratePresignedUrl:()=>D,s3GenerateSignedUrl:()=>O});module.exports=te(le);var w=require("@aws-sdk/client-s3"),M=require("@aws-sdk/s3-request-presigner"),z=require("uuid");var S=(n=>(n.AWS="aws",n.Azure="azure",n.BackBlaze="backblaze",n.DigitalOcean="digitalocean",n))(S||{});var l=class extends Error{constructor(t,i="UNKNOWN_UPLOAD_ERROR",n=!1,o){super(t);this.type=i;this.retryable=n;this.status=o;this.DEFAULT_ERROR_STATUS_CODE=500;this.name="UploadError",this.status=o??this.DEFAULT_ERROR_STATUS_CODE}};function U(e,r){var o;let t=r.type;if(!e)return!1;if(t){let[s,g]=t.split("/");if(s&&g){let a=e.split(",").map(c=>c.trim());if(a.includes("*")||a.some(c=>{if(c.includes("/*")){let[p]=c.split("/");return t.startsWith(p)}return c.toLowerCase()===t.toLowerCase()}))return!0}}let i=r.name??"";if(!i)return!1;let n=((o=i.split(".").pop())==null?void 0:o.toLowerCase())||"";return!!(n&&e.split(",").map(a=>a.trim().toLowerCase()).some(a=>a.startsWith(".")?a.slice(1)===n:!1))}function E(e){let t=["name","type","size"].filter(g=>!e[g]);if(t.length>0)throw new l(`Missing required file param: ${t.join(", ")}`,"FILE_VALIDATION_ERROR",!1,400);let{type:i,accept:n="*",size:o,maxFileSize:s=e.maxFileSize}=e;if(!U(n,e))throw new l(`File type ${i} not allowed. Accepted types: ${n}`,"FILE_VALIDATION_ERROR",!1,400);if(s&&o>s)throw new l(`File size: ${o} exceeds maximum limit of ${s/(1024*1024)}MB`,"FILE_VALIDATION_ERROR",!1,413)}var h=require("@aws-sdk/client-s3"),L=require("@aws-sdk/s3-request-presigner");var re=3600*24*3;async function O(e,r,t,i=re){try{let n=new h.S3Client(e);return await(0,L.getSignedUrl)(n,new h.GetObjectCommand({Bucket:t,Key:r}),{expiresIn:i})}catch(n){throw new l(n.message,"SIGNED_URL_ERROR",!1)}}var f=require("crypto");function P(e,r){return(0,f.createHmac)("sha256",e).update(r).digest()}function N(e){return(0,f.createHash)("sha256").update(e).digest("hex")}function ne(e,r,t,i){let n=P(`AWS4${e}`,r),o=P(n,t),s=P(o,i);return P(s,"aws4_request")}function ie(e){return(0,f.createHash)("md5").update(e).digest("base64")}function oe(e,r,{endpoint:t,region:i}){switch(r){case"aws":return`${e}.s3.${i}.amazonaws.com`;case"backblaze":return t.split("https://")[1];case"digitalocean":return`${e}.${i}.digitaloceanspaces.com`;default:return""}}function F(e,r,{region:t,credentials:{accessKeyId:i,secretAccessKey:n},endpoint:o},s){let g="s3",a=oe(r,s,{endpoint:o,region:t}),d=ie(e),p=new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),m=p.slice(0,8),R="PUT",W={aws:"/",backblaze:`/${r}/`,digitalocean:"/",azure:""}[s],H={aws:"cors=",backblaze:"cors=null",digitalocean:"cors=",azure:""}[s],_=N(e),k=`content-md5:${d}
content-type:application/xml
host:${a}
x-amz-content-sha256:${_}
x-amz-date:${p}
`,v="content-md5;content-type;host;x-amz-content-sha256;x-amz-date",V=[R,W,H,k,v,_].join(`
`),b="AWS4-HMAC-SHA256",B=`${m}/${t}/${g}/aws4_request`,K=[b,p,B,N(V)].join(`
`),j=ne(n,m,t,g),q=(0,f.createHmac)("sha256",j).update(K).digest("hex"),X=`${b} Credential=${i}/${B}, SignedHeaders=${v}, Signature=${q}`;return{"Content-Type":"application/xml","Content-MD5":d,Authorization:X,"x-amz-content-sha256":_,"x-amz-date":p,Host:a}}async function I(e,r,t,i){let o={aws:`https://${r}.s3.${t.region}.amazonaws.com/?cors`,backblaze:`${t.endpoint}/${r}/?cors=null`,digitalocean:`https://${r}.${t.region}.digitaloceanspaces.com/?cors`,azure:""}[i],s=`<?xml version="1.0" encoding="UTF-8"?><CORSConfiguration>
<CORSRule>
<ID>Allow S3 Operations from my site: ${e}</ID>
<AllowedOrigin>${e}</AllowedOrigin>
<AllowedHeader>*</AllowedHeader>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<ExposeHeader>ETag</ExposeHeader>
<MaxAgeSeconds>3600</MaxAgeSeconds>
</CORSRule>
</CORSConfiguration>`,g=F(s,r,t,i),a=await fetch(o,{method:"PUT",body:s,headers:g});if(!a.ok){let c=await a.text();throw new l(c,"CORS_CONFIG_ERROR",!1,a.status)}return await a.text()}var se=3600;function ae(e){let r=(e==null?void 0:e.Message)??e.message,t=(e==null?void 0:e.Code)??"PRESIGNED_URL_ERROR";return{message:r,errorType:t}}async function D({fileParams:e,bucketName:r,s3ClientConfig:t,expiresIn:i=se,origin:n,provider:o,enableAutoCorsConfig:s=!1}){let{name:g,type:a,size:d}=e;try{E(e),s&&await I(n,r,t,o);let c=new w.S3Client(t),p=`${(0,z.v4)()}-${g}`,m=new w.PutObjectCommand({Bucket:r,Key:p,ContentType:a,ContentLength:d}),R=await(0,M.getSignedUrl)(c,m,{expiresIn:i,signableHeaders:new Set(["content-type","content-length"])}),T=await O(t,p,r);return{key:p,publicUrl:T,uploadUrl:R,expiresIn:i}}catch(c){if(c instanceof l)throw c;let{message:p,errorType:m}=ae(c);throw new l(p,m,!1,500)}}var $=require("@azure/identity"),u=require("@azure/storage-blob"),G=require("uuid");async function A(e,r=3600){try{let t=new Date,i=new Date(t);return i.setMinutes(t.getMinutes()+r/60),await e.getUserDelegationKey(t,i)}catch(t){throw new l(t.message,"TEMPORARY_CREDENTIALS_ERROR",!1,500)}}async function x({fileParams:e,containerName:r,credentials:t,expiresIn:i=3600}){try{E(e);let n=new $.ClientSecretCredential(t.tenantId,t.clientId,t.clientSecret),o=new u.BlobServiceClient(`https://${t.storageAccount}.blob.core.windows.net`,n),s=await A(o),{name:g,type:a}=e,d=`${(0,G.v4)()}-${g}`,p=o.getContainerClient(r).getBlobClient(d),m=(0,u.generateBlobSASQueryParameters)({containerName:r,blobName:d,permissions:u.BlobSASPermissions.parse("racw"),startsOn:new Date,expiresOn:new Date(Date.now()+i*1e3),protocol:u.SASProtocol.Https,contentType:a},s,t.storageAccount).toString(),R=`${p.url}?${m}`;return{key:d,publicUrl:p.url,uploadUrl:R,expiresIn:i}}catch(n){throw n instanceof l?n:new l(n.message,"PRESIGNED_URL_ERROR",!1,500)}}0&&(module.exports={UpupProvider,azureGenerateSasUrl,s3GeneratePresignedUrl,s3GenerateSignedUrl});
//# sourceMappingURL=index.node.js.map
;