content-disposition-attachment
Version:
A library to parse "attachment"s in Content-Disposition.
1 lines • 2.43 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ContentDispositionAttachment={})}(this,(function(e){"use strict";class t extends Error{constructor(e){super(e),"captureStackTrace"in Error&&Error.captureStackTrace(this,t)}}class s{constructor(e){this.code=e,this.chunk=""}expect(e,s){if(!e)throw new t(s);return e}eat(e){const t=e.exec(this.chunk);return t?(this.chunk=this.chunk.slice(t[0].length),t):[]}eat$0(e){return this.eat(e)[0]}eatSpaces(){return this.eat$0(/^\s*/)}parseAttachment(){return this.eat$0(/^attachment/i)}parseToken(){return this.eat$0(/^[!#$%&'*+\-.\w^`|~]+/)}parseQuotedString(){if(!this.eat$0(/^"/))return;const e=this.eat$0(/^(:?([ !\x23-\x5b\x5d-\x7e\x80-\xff]|\r\n(?:[ \t])+)*|\\[\u0000-\u007f])*/);return this.expect(this.eat$0(/^"/),"expect '\"'"),e.replace(/\\([\u0000-\u007f])/g,"$1")}parseValue(){return this.parseToken()||this.parseQuotedString()}parseValueChars(e){let t=this.expect(this.eat$0(/^(?:%[0-9a-fA-F]{2}|[\w!#$&+\-.^`|~])*/),"expect value-chars");switch(e.toLowerCase()){case"utf-8":try{t=decodeURIComponent(t)}catch(e){this.expect(!1,"invalid utf-8 string")}break;case"iso-8859-1":t=t.replace(/%([0-9a-fA-F]{2})/g,((e,t)=>String.fromCharCode(parseInt(t,16)))),this.expect(!/[^\x20-\x7e\xa0-\xff]/.test(t),"invalid iso-8859-1 string")}return t}parseExtValue(){const e=this.expect(this.eat$0(/^(?:UTF-8|ISO-8859-1)/i),"unsupported charset");return this.expect(this.eat$0(/^'[a-zA-Z-]*'/),"expect ' [ language ] '"),this.parseValueChars(e)}parseParm(){const e=this.expect(this.parseToken(),"expect token");this.expect(this.eat$0(/^\s*=\s*/),"expect '='");return{key:e,value:/\*$/.test(e)?this.expect(this.parseExtValue(),"expect ext-value"):this.expect(this.parseValue(),"expect value")}}parse(){if(this.chunk=String(this.code),!this.parseAttachment())return{attachment:!1};const e={},s={};for(this.eatSpaces();this.eat$0(/^;/);){this.eatSpaces();let{key:r,value:a}=this.parseParm(),i=!1;/\*$/.test(r)&&(r=r.slice(0,-1),i=!0),/^filename$/i.test(r)&&(r=r.toLowerCase());const n=i?s:e;if(r in n)throw new t(`duplicated field '${r}'`);n[r]=a}if(this.chunk.length)throw new t("expect EOF");return Object.assign(Object.assign({attachment:!0},e),s)}}e.ParseError=t,e.parse=e=>new s(e).parse(),Object.defineProperty(e,"__esModule",{value:!0})}));