AxiosHeaders.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. 'use strict';
  2. import utils from '../utils.js';
  3. import parseHeaders from '../helpers/parseHeaders.js';
  4. const $internals = Symbol('internals');
  5. function normalizeHeader(header) {
  6. return header && String(header).trim().toLowerCase();
  7. }
  8. function normalizeValue(value) {
  9. if (value === false || value == null) {
  10. return value;
  11. }
  12. return utils.isArray(value) ? value.map(normalizeValue) : String(value);
  13. }
  14. function parseTokens(str) {
  15. const tokens = Object.create(null);
  16. const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  17. let match;
  18. while ((match = tokensRE.exec(str))) {
  19. tokens[match[1]] = match[2];
  20. }
  21. return tokens;
  22. }
  23. const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
  24. function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
  25. if (utils.isFunction(filter)) {
  26. return filter.call(this, value, header);
  27. }
  28. if (isHeaderNameFilter) {
  29. value = header;
  30. }
  31. if (!utils.isString(value)) return;
  32. if (utils.isString(filter)) {
  33. return value.indexOf(filter) !== -1;
  34. }
  35. if (utils.isRegExp(filter)) {
  36. return filter.test(value);
  37. }
  38. }
  39. function formatHeader(header) {
  40. return header.trim()
  41. .toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
  42. return char.toUpperCase() + str;
  43. });
  44. }
  45. function buildAccessors(obj, header) {
  46. const accessorName = utils.toCamelCase(' ' + header);
  47. ['get', 'set', 'has'].forEach(methodName => {
  48. Object.defineProperty(obj, methodName + accessorName, {
  49. value: function(arg1, arg2, arg3) {
  50. return this[methodName].call(this, header, arg1, arg2, arg3);
  51. },
  52. configurable: true
  53. });
  54. });
  55. }
  56. class AxiosHeaders {
  57. constructor(headers) {
  58. headers && this.set(headers);
  59. }
  60. set(header, valueOrRewrite, rewrite) {
  61. const self = this;
  62. function setHeader(_value, _header, _rewrite) {
  63. const lHeader = normalizeHeader(_header);
  64. if (!lHeader) {
  65. throw new Error('header name must be a non-empty string');
  66. }
  67. const key = utils.findKey(self, lHeader);
  68. if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
  69. self[key || _header] = normalizeValue(_value);
  70. }
  71. }
  72. const setHeaders = (headers, _rewrite) =>
  73. utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
  74. if (utils.isPlainObject(header) || header instanceof this.constructor) {
  75. setHeaders(header, valueOrRewrite)
  76. } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
  77. setHeaders(parseHeaders(header), valueOrRewrite);
  78. } else if (utils.isHeaders(header)) {
  79. for (const [key, value] of header.entries()) {
  80. setHeader(value, key, rewrite);
  81. }
  82. } else {
  83. header != null && setHeader(valueOrRewrite, header, rewrite);
  84. }
  85. return this;
  86. }
  87. get(header, parser) {
  88. header = normalizeHeader(header);
  89. if (header) {
  90. const key = utils.findKey(this, header);
  91. if (key) {
  92. const value = this[key];
  93. if (!parser) {
  94. return value;
  95. }
  96. if (parser === true) {
  97. return parseTokens(value);
  98. }
  99. if (utils.isFunction(parser)) {
  100. return parser.call(this, value, key);
  101. }
  102. if (utils.isRegExp(parser)) {
  103. return parser.exec(value);
  104. }
  105. throw new TypeError('parser must be boolean|regexp|function');
  106. }
  107. }
  108. }
  109. has(header, matcher) {
  110. header = normalizeHeader(header);
  111. if (header) {
  112. const key = utils.findKey(this, header);
  113. return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
  114. }
  115. return false;
  116. }
  117. delete(header, matcher) {
  118. const self = this;
  119. let deleted = false;
  120. function deleteHeader(_header) {
  121. _header = normalizeHeader(_header);
  122. if (_header) {
  123. const key = utils.findKey(self, _header);
  124. if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
  125. delete self[key];
  126. deleted = true;
  127. }
  128. }
  129. }
  130. if (utils.isArray(header)) {
  131. header.forEach(deleteHeader);
  132. } else {
  133. deleteHeader(header);
  134. }
  135. return deleted;
  136. }
  137. clear(matcher) {
  138. const keys = Object.keys(this);
  139. let i = keys.length;
  140. let deleted = false;
  141. while (i--) {
  142. const key = keys[i];
  143. if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
  144. delete this[key];
  145. deleted = true;
  146. }
  147. }
  148. return deleted;
  149. }
  150. normalize(format) {
  151. const self = this;
  152. const headers = {};
  153. utils.forEach(this, (value, header) => {
  154. const key = utils.findKey(headers, header);
  155. if (key) {
  156. self[key] = normalizeValue(value);
  157. delete self[header];
  158. return;
  159. }
  160. const normalized = format ? formatHeader(header) : String(header).trim();
  161. if (normalized !== header) {
  162. delete self[header];
  163. }
  164. self[normalized] = normalizeValue(value);
  165. headers[normalized] = true;
  166. });
  167. return this;
  168. }
  169. concat(...targets) {
  170. return this.constructor.concat(this, ...targets);
  171. }
  172. toJSON(asStrings) {
  173. const obj = Object.create(null);
  174. utils.forEach(this, (value, header) => {
  175. value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
  176. });
  177. return obj;
  178. }
  179. [Symbol.iterator]() {
  180. return Object.entries(this.toJSON())[Symbol.iterator]();
  181. }
  182. toString() {
  183. return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  184. }
  185. get [Symbol.toStringTag]() {
  186. return 'AxiosHeaders';
  187. }
  188. static from(thing) {
  189. return thing instanceof this ? thing : new this(thing);
  190. }
  191. static concat(first, ...targets) {
  192. const computed = new this(first);
  193. targets.forEach((target) => computed.set(target));
  194. return computed;
  195. }
  196. static accessor(header) {
  197. const internals = this[$internals] = (this[$internals] = {
  198. accessors: {}
  199. });
  200. const accessors = internals.accessors;
  201. const prototype = this.prototype;
  202. function defineAccessor(_header) {
  203. const lHeader = normalizeHeader(_header);
  204. if (!accessors[lHeader]) {
  205. buildAccessors(prototype, _header);
  206. accessors[lHeader] = true;
  207. }
  208. }
  209. utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
  210. return this;
  211. }
  212. }
  213. AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
  214. // reserved names hotfix
  215. utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
  216. let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
  217. return {
  218. get: () => value,
  219. set(headerValue) {
  220. this[mapped] = headerValue;
  221. }
  222. }
  223. });
  224. utils.freezeMethods(AxiosHeaders);
  225. export default AxiosHeaders;