base.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import decodeComponent from 'decode-uri-component';
  2. import {includeKeys} from 'filter-obj';
  3. import splitOnFirst from 'split-on-first';
  4. const isNullOrUndefined = value => value === null || value === undefined;
  5. // eslint-disable-next-line unicorn/prefer-code-point
  6. const strictUriEncode = string => encodeURIComponent(string).replaceAll(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);
  7. const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');
  8. function encoderForArrayFormat(options) {
  9. switch (options.arrayFormat) {
  10. case 'index': {
  11. return key => (result, value) => {
  12. const index = result.length;
  13. if (
  14. value === undefined
  15. || (options.skipNull && value === null)
  16. || (options.skipEmptyString && value === '')
  17. ) {
  18. return result;
  19. }
  20. if (value === null) {
  21. return [
  22. ...result, [encode(key, options), '[', index, ']'].join(''),
  23. ];
  24. }
  25. return [
  26. ...result,
  27. [encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join(''),
  28. ];
  29. };
  30. }
  31. case 'bracket': {
  32. return key => (result, value) => {
  33. if (
  34. value === undefined
  35. || (options.skipNull && value === null)
  36. || (options.skipEmptyString && value === '')
  37. ) {
  38. return result;
  39. }
  40. if (value === null) {
  41. return [
  42. ...result,
  43. [encode(key, options), '[]'].join(''),
  44. ];
  45. }
  46. return [
  47. ...result,
  48. [encode(key, options), '[]=', encode(value, options)].join(''),
  49. ];
  50. };
  51. }
  52. case 'colon-list-separator': {
  53. return key => (result, value) => {
  54. if (
  55. value === undefined
  56. || (options.skipNull && value === null)
  57. || (options.skipEmptyString && value === '')
  58. ) {
  59. return result;
  60. }
  61. if (value === null) {
  62. return [
  63. ...result,
  64. [encode(key, options), ':list='].join(''),
  65. ];
  66. }
  67. return [
  68. ...result,
  69. [encode(key, options), ':list=', encode(value, options)].join(''),
  70. ];
  71. };
  72. }
  73. case 'comma':
  74. case 'separator':
  75. case 'bracket-separator': {
  76. const keyValueSeparator = options.arrayFormat === 'bracket-separator'
  77. ? '[]='
  78. : '=';
  79. return key => (result, value) => {
  80. if (
  81. value === undefined
  82. || (options.skipNull && value === null)
  83. || (options.skipEmptyString && value === '')
  84. ) {
  85. return result;
  86. }
  87. // Translate null to an empty string so that it doesn't serialize as 'null'
  88. value = value === null ? '' : value;
  89. if (result.length === 0) {
  90. return [[encode(key, options), keyValueSeparator, encode(value, options)].join('')];
  91. }
  92. return [[result, encode(value, options)].join(options.arrayFormatSeparator)];
  93. };
  94. }
  95. default: {
  96. return key => (result, value) => {
  97. if (
  98. value === undefined
  99. || (options.skipNull && value === null)
  100. || (options.skipEmptyString && value === '')
  101. ) {
  102. return result;
  103. }
  104. if (value === null) {
  105. return [
  106. ...result,
  107. encode(key, options),
  108. ];
  109. }
  110. return [
  111. ...result,
  112. [encode(key, options), '=', encode(value, options)].join(''),
  113. ];
  114. };
  115. }
  116. }
  117. }
  118. function parserForArrayFormat(options) {
  119. let result;
  120. switch (options.arrayFormat) {
  121. case 'index': {
  122. return (key, value, accumulator) => {
  123. result = /\[(\d*)]$/.exec(key);
  124. key = key.replace(/\[\d*]$/, '');
  125. if (!result) {
  126. accumulator[key] = value;
  127. return;
  128. }
  129. if (accumulator[key] === undefined) {
  130. accumulator[key] = {};
  131. }
  132. accumulator[key][result[1]] = value;
  133. };
  134. }
  135. case 'bracket': {
  136. return (key, value, accumulator) => {
  137. result = /(\[])$/.exec(key);
  138. key = key.replace(/\[]$/, '');
  139. if (!result) {
  140. accumulator[key] = value;
  141. return;
  142. }
  143. if (accumulator[key] === undefined) {
  144. accumulator[key] = [value];
  145. return;
  146. }
  147. accumulator[key] = [...accumulator[key], value];
  148. };
  149. }
  150. case 'colon-list-separator': {
  151. return (key, value, accumulator) => {
  152. result = /(:list)$/.exec(key);
  153. key = key.replace(/:list$/, '');
  154. if (!result) {
  155. accumulator[key] = value;
  156. return;
  157. }
  158. if (accumulator[key] === undefined) {
  159. accumulator[key] = [value];
  160. return;
  161. }
  162. accumulator[key] = [...accumulator[key], value];
  163. };
  164. }
  165. case 'comma':
  166. case 'separator': {
  167. return (key, value, accumulator) => {
  168. const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
  169. const isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));
  170. value = isEncodedArray ? decode(value, options) : value;
  171. const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : (value === null ? value : decode(value, options));
  172. accumulator[key] = newValue;
  173. };
  174. }
  175. case 'bracket-separator': {
  176. return (key, value, accumulator) => {
  177. const isArray = /(\[])$/.test(key);
  178. key = key.replace(/\[]$/, '');
  179. if (!isArray) {
  180. accumulator[key] = value ? decode(value, options) : value;
  181. return;
  182. }
  183. const arrayValue = value === null
  184. ? []
  185. : decode(value, options).split(options.arrayFormatSeparator);
  186. if (accumulator[key] === undefined) {
  187. accumulator[key] = arrayValue;
  188. return;
  189. }
  190. accumulator[key] = [...accumulator[key], ...arrayValue];
  191. };
  192. }
  193. default: {
  194. return (key, value, accumulator) => {
  195. if (accumulator[key] === undefined) {
  196. accumulator[key] = value;
  197. return;
  198. }
  199. accumulator[key] = [...[accumulator[key]].flat(), value];
  200. };
  201. }
  202. }
  203. }
  204. function validateArrayFormatSeparator(value) {
  205. if (typeof value !== 'string' || value.length !== 1) {
  206. throw new TypeError('arrayFormatSeparator must be single character string');
  207. }
  208. }
  209. function encode(value, options) {
  210. if (options.encode) {
  211. return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
  212. }
  213. return value;
  214. }
  215. function decode(value, options) {
  216. if (options.decode) {
  217. return decodeComponent(value);
  218. }
  219. return value;
  220. }
  221. function keysSorter(input) {
  222. if (Array.isArray(input)) {
  223. return input.sort();
  224. }
  225. if (typeof input === 'object') {
  226. return keysSorter(Object.keys(input))
  227. .sort((a, b) => Number(a) - Number(b))
  228. .map(key => input[key]);
  229. }
  230. return input;
  231. }
  232. function removeHash(input) {
  233. const hashStart = input.indexOf('#');
  234. if (hashStart !== -1) {
  235. input = input.slice(0, hashStart);
  236. }
  237. return input;
  238. }
  239. function getHash(url) {
  240. let hash = '';
  241. const hashStart = url.indexOf('#');
  242. if (hashStart !== -1) {
  243. hash = url.slice(hashStart);
  244. }
  245. return hash;
  246. }
  247. function parseValue(value, options, type) {
  248. if (type === 'string' && typeof value === 'string') {
  249. return value;
  250. }
  251. if (typeof type === 'function' && typeof value === 'string') {
  252. return type(value);
  253. }
  254. if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
  255. return value.toLowerCase() === 'true';
  256. }
  257. if (type === 'number' && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {
  258. return Number(value);
  259. }
  260. if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {
  261. return Number(value);
  262. }
  263. return value;
  264. }
  265. export function extract(input) {
  266. input = removeHash(input);
  267. const queryStart = input.indexOf('?');
  268. if (queryStart === -1) {
  269. return '';
  270. }
  271. return input.slice(queryStart + 1);
  272. }
  273. export function parse(query, options) {
  274. options = {
  275. decode: true,
  276. sort: true,
  277. arrayFormat: 'none',
  278. arrayFormatSeparator: ',',
  279. parseNumbers: false,
  280. parseBooleans: false,
  281. types: Object.create(null),
  282. ...options,
  283. };
  284. validateArrayFormatSeparator(options.arrayFormatSeparator);
  285. const formatter = parserForArrayFormat(options);
  286. // Create an object with no prototype
  287. const returnValue = Object.create(null);
  288. if (typeof query !== 'string') {
  289. return returnValue;
  290. }
  291. query = query.trim().replace(/^[?#&]/, '');
  292. if (!query) {
  293. return returnValue;
  294. }
  295. for (const parameter of query.split('&')) {
  296. if (parameter === '') {
  297. continue;
  298. }
  299. const parameter_ = options.decode ? parameter.replaceAll('+', ' ') : parameter;
  300. let [key, value] = splitOnFirst(parameter_, '=');
  301. if (key === undefined) {
  302. key = parameter_;
  303. }
  304. // Missing `=` should be `null`:
  305. // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
  306. value = value === undefined ? null : (['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options));
  307. formatter(decode(key, options), value, returnValue);
  308. }
  309. for (const [key, value] of Object.entries(returnValue)) {
  310. if (typeof value === 'object' && value !== null && options.types[key] !== 'string') {
  311. for (const [key2, value2] of Object.entries(value)) {
  312. const type = options.types[key] ? options.types[key].replace('[]', '') : undefined;
  313. value[key2] = parseValue(value2, options, type);
  314. }
  315. } else if (typeof value === 'object' && value !== null && options.types[key] === 'string') {
  316. returnValue[key] = Object.values(value).join(options.arrayFormatSeparator);
  317. } else {
  318. returnValue[key] = parseValue(value, options, options.types[key]);
  319. }
  320. }
  321. if (options.sort === false) {
  322. return returnValue;
  323. }
  324. // TODO: Remove the use of `reduce`.
  325. // eslint-disable-next-line unicorn/no-array-reduce
  326. return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key) => {
  327. const value = returnValue[key];
  328. result[key] = Boolean(value) && typeof value === 'object' && !Array.isArray(value) ? keysSorter(value) : value;
  329. return result;
  330. }, Object.create(null));
  331. }
  332. export function stringify(object, options) {
  333. if (!object) {
  334. return '';
  335. }
  336. options = {
  337. encode: true,
  338. strict: true,
  339. arrayFormat: 'none',
  340. arrayFormatSeparator: ',',
  341. ...options,
  342. };
  343. validateArrayFormatSeparator(options.arrayFormatSeparator);
  344. const shouldFilter = key => (
  345. (options.skipNull && isNullOrUndefined(object[key]))
  346. || (options.skipEmptyString && object[key] === '')
  347. );
  348. const formatter = encoderForArrayFormat(options);
  349. const objectCopy = {};
  350. for (const [key, value] of Object.entries(object)) {
  351. if (!shouldFilter(key)) {
  352. objectCopy[key] = value;
  353. }
  354. }
  355. const keys = Object.keys(objectCopy);
  356. if (options.sort !== false) {
  357. keys.sort(options.sort);
  358. }
  359. return keys.map(key => {
  360. const value = object[key];
  361. if (value === undefined) {
  362. return '';
  363. }
  364. if (value === null) {
  365. return encode(key, options);
  366. }
  367. if (Array.isArray(value)) {
  368. if (value.length === 0 && options.arrayFormat === 'bracket-separator') {
  369. return encode(key, options) + '[]';
  370. }
  371. return value
  372. .reduce(formatter(key), [])
  373. .join('&');
  374. }
  375. return encode(key, options) + '=' + encode(value, options);
  376. }).filter(x => x.length > 0).join('&');
  377. }
  378. export function parseUrl(url, options) {
  379. options = {
  380. decode: true,
  381. ...options,
  382. };
  383. let [url_, hash] = splitOnFirst(url, '#');
  384. if (url_ === undefined) {
  385. url_ = url;
  386. }
  387. return {
  388. url: url_?.split('?')?.[0] ?? '',
  389. query: parse(extract(url), options),
  390. ...(options && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}),
  391. };
  392. }
  393. export function stringifyUrl(object, options) {
  394. options = {
  395. encode: true,
  396. strict: true,
  397. [encodeFragmentIdentifier]: true,
  398. ...options,
  399. };
  400. const url = removeHash(object.url).split('?')[0] || '';
  401. const queryFromUrl = extract(object.url);
  402. const query = {
  403. ...parse(queryFromUrl, {sort: false}),
  404. ...object.query,
  405. };
  406. let queryString = stringify(query, options);
  407. queryString &&= `?${queryString}`;
  408. let hash = getHash(object.url);
  409. if (typeof object.fragmentIdentifier === 'string') {
  410. const urlObjectForFragmentEncode = new URL(url);
  411. urlObjectForFragmentEncode.hash = object.fragmentIdentifier;
  412. hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`;
  413. }
  414. return `${url}${queryString}${hash}`;
  415. }
  416. export function pick(input, filter, options) {
  417. options = {
  418. parseFragmentIdentifier: true,
  419. [encodeFragmentIdentifier]: false,
  420. ...options,
  421. };
  422. const {url, query, fragmentIdentifier} = parseUrl(input, options);
  423. return stringifyUrl({
  424. url,
  425. query: includeKeys(query, filter),
  426. fragmentIdentifier,
  427. }, options);
  428. }
  429. export function exclude(input, filter, options) {
  430. const exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);
  431. return pick(input, exclusionFilter, options);
  432. }