1import $ from 'jquery';
2
3export function initFomanticApiPatch() {
4 //
5 // Fomantic API module has some very buggy behaviors:
6 //
7 // If encodeParameters=true, it calls `urlEncodedValue` to encode the parameter.
8 // However, `urlEncodedValue` just tries to "guess" whether the parameter is already encoded, by decoding the parameter and encoding it again.
9 //
10 // There are 2 problems:
11 // 1. It may guess wrong, and skip encoding a parameter which looks like encoded.
12 // 2. If the parameter can't be decoded, `decodeURIComponent` will throw an error, and the whole request will fail.
13 //
14 // This patch only fixes the second error behavior at the moment.
15 //
16 const patchKey = '_giteaFomanticApiPatch';
17 const oldApi = $.api;
18 $.api = $.fn.api = function(...args) {
19 const apiCall = oldApi.bind(this);
20 const ret = oldApi.apply(this, args);
21
22 if (typeof args[0] !== 'string') {
23 const internalGet = apiCall('internal', 'get');
24 if (!internalGet.urlEncodedValue[patchKey]) {
25 const oldUrlEncodedValue = internalGet.urlEncodedValue;
26 internalGet.urlEncodedValue = function (value) {
27 try {
28 return oldUrlEncodedValue(value);
29 } catch {
30 // if Fomantic API module's `urlEncodedValue` throws an error, we encode it by ourselves.
31 return encodeURIComponent(value);
32 }
33 };
34 internalGet.urlEncodedValue[patchKey] = true;
35 }
36 }
37 return ret;
38 };
39 $.api.settings = oldApi.settings;
40}