tryitout-4.38.0.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. window.abortControllers = {};
  2. function cacheAuthValue() {
  3. // Whenever the auth header is set for one endpoint, cache it for the others
  4. window.lastAuthValue = '';
  5. let authInputs = document.querySelectorAll(`.auth-value`)
  6. authInputs.forEach(el => {
  7. el.addEventListener('input', (event) => {
  8. window.lastAuthValue = event.target.value;
  9. authInputs.forEach(otherInput => {
  10. if (otherInput === el) return;
  11. // Don't block the main thread
  12. setTimeout(() => {
  13. otherInput.value = window.lastAuthValue;
  14. }, 0);
  15. });
  16. });
  17. });
  18. }
  19. window.addEventListener('DOMContentLoaded', cacheAuthValue);
  20. function getCookie(name) {
  21. if (!document.cookie) {
  22. return null;
  23. }
  24. const cookies = document.cookie.split(';')
  25. .map(c => c.trim())
  26. .filter(c => c.startsWith(name + '='));
  27. if (cookies.length === 0) {
  28. return null;
  29. }
  30. return decodeURIComponent(cookies[0].split('=')[1]);
  31. }
  32. function tryItOut(endpointId) {
  33. document.querySelector(`#btn-tryout-${endpointId}`).hidden = true;
  34. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = false;
  35. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`).hidden = false;
  36. executeBtn.disabled = false;
  37. // Show all input fields
  38. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  39. .forEach(el => el.style.display = 'block');
  40. if (document.querySelector(`#form-${endpointId}`).dataset.authed === "1") {
  41. const authElement = document.querySelector(`#auth-${endpointId}`);
  42. authElement && (authElement.hidden = false);
  43. }
  44. // Expand all nested fields
  45. document.querySelectorAll(`#form-${endpointId} details`)
  46. .forEach(el => el.open = true);
  47. }
  48. function cancelTryOut(endpointId) {
  49. if (window.abortControllers[endpointId]) {
  50. window.abortControllers[endpointId].abort();
  51. delete window.abortControllers[endpointId];
  52. }
  53. document.querySelector(`#btn-tryout-${endpointId}`).hidden = false;
  54. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  55. executeBtn.hidden = true;
  56. executeBtn.textContent = executeBtn.dataset.initialText;
  57. document.querySelector(`#btn-canceltryout-${endpointId}`).hidden = true;
  58. // Hide inputs
  59. document.querySelectorAll(`input[data-endpoint=${endpointId}],label[data-endpoint=${endpointId}]`)
  60. .forEach(el => el.style.display = 'none');
  61. document.querySelectorAll(`#form-${endpointId} details`)
  62. .forEach(el => el.open = false);
  63. const authElement = document.querySelector(`#auth-${endpointId}`);
  64. authElement && (authElement.hidden = true);
  65. document.querySelector('#execution-results-' + endpointId).hidden = true;
  66. document.querySelector('#execution-error-' + endpointId).hidden = true;
  67. // Revert to sample code blocks
  68. document.querySelector('#example-requests-' + endpointId).hidden = false;
  69. document.querySelector('#example-responses-' + endpointId).hidden = false;
  70. }
  71. function makeAPICall(method, path, body = {}, query = {}, headers = {}, endpointId = null) {
  72. console.log({endpointId, path, body, query, headers});
  73. if (!(body instanceof FormData) && typeof body !== "string") {
  74. body = JSON.stringify(body)
  75. }
  76. const url = new URL(window.tryItOutBaseUrl + '/' + path.replace(/^\//, ''));
  77. // We need this function because if you try to set an array or object directly to a URLSearchParams object,
  78. // you'll get [object Object] or the array.toString()
  79. function addItemToSearchParamsObject(key, value, searchParams) {
  80. if (Array.isArray(value)) {
  81. value.forEach((v, i) => {
  82. // Append {filters: [first, second]} as filters[0]=first&filters[1]second
  83. addItemToSearchParamsObject(key + '[' + i + ']', v, searchParams);
  84. })
  85. } else if (typeof value === 'object' && value !== null) {
  86. Object.keys(value).forEach((i) => {
  87. // Append {filters: {name: first}} as filters[name]=first
  88. addItemToSearchParamsObject(key + '[' + i + ']', value[i], searchParams);
  89. });
  90. } else {
  91. searchParams.append(key, value);
  92. }
  93. }
  94. Object.keys(query)
  95. .forEach(key => addItemToSearchParamsObject(key, query[key], url.searchParams));
  96. window.abortControllers[endpointId] = new AbortController();
  97. return fetch(url, {
  98. method,
  99. headers,
  100. body: method === 'GET' ? undefined : body,
  101. signal: window.abortControllers[endpointId].signal,
  102. referrer: window.tryItOutBaseUrl,
  103. mode: 'cors',
  104. credentials: 'same-origin',
  105. })
  106. .then(response => Promise.all([response.status, response.statusText, response.text(), response.headers]));
  107. }
  108. function hideCodeSamples(endpointId) {
  109. document.querySelector('#example-requests-' + endpointId).hidden = true;
  110. document.querySelector('#example-responses-' + endpointId).hidden = true;
  111. }
  112. function handleResponse(endpointId, response, status, headers) {
  113. hideCodeSamples(endpointId);
  114. // Hide error views
  115. document.querySelector('#execution-error-' + endpointId).hidden = true;
  116. const responseContentEl = document.querySelector('#execution-response-content-' + endpointId);
  117. // Check if the response contains Laravel's dd() default dump output
  118. const isLaravelDump = response.includes('Sfdump');
  119. // If it's a Laravel dd() dump, use innerHTML to render it safely
  120. if (isLaravelDump) {
  121. responseContentEl.innerHTML = response === '' ? responseContentEl.dataset.emptyResponseText : response;
  122. } else {
  123. // Otherwise, stick to textContent for regular responses
  124. responseContentEl.textContent = response === '' ? responseContentEl.dataset.emptyResponseText : response;
  125. }
  126. // Prettify it if it's JSON
  127. let isJson = false;
  128. try {
  129. const jsonParsed = JSON.parse(response);
  130. if (jsonParsed !== null) {
  131. isJson = true;
  132. response = JSON.stringify(jsonParsed, null, 4);
  133. responseContentEl.textContent = response;
  134. }
  135. } catch (e) {
  136. }
  137. isJson && window.hljs.highlightElement(responseContentEl);
  138. const statusEl = document.querySelector('#execution-response-status-' + endpointId);
  139. statusEl.textContent = ` (${status})`;
  140. document.querySelector('#execution-results-' + endpointId).hidden = false;
  141. statusEl.scrollIntoView({behavior: "smooth", block: "center"});
  142. }
  143. function handleError(endpointId, err) {
  144. hideCodeSamples(endpointId);
  145. // Hide response views
  146. document.querySelector('#execution-results-' + endpointId).hidden = true;
  147. // Show error views
  148. let errorMessage = err.message || err;
  149. const $errorMessageEl = document.querySelector('#execution-error-message-' + endpointId);
  150. $errorMessageEl.textContent = errorMessage + $errorMessageEl.textContent;
  151. const errorEl = document.querySelector('#execution-error-' + endpointId);
  152. errorEl.hidden = false;
  153. errorEl.scrollIntoView({behavior: "smooth", block: "center"});
  154. }
  155. async function executeTryOut(endpointId, form) {
  156. const executeBtn = document.querySelector(`#btn-executetryout-${endpointId}`);
  157. executeBtn.textContent = executeBtn.dataset.loadingText;
  158. executeBtn.disabled = true;
  159. executeBtn.scrollIntoView({behavior: "smooth", block: "center"});
  160. let body;
  161. let setter;
  162. if (form.dataset.hasfiles === "1") {
  163. body = new FormData();
  164. setter = (name, value) => body.append(name, value);
  165. } else if (form.dataset.isarraybody === "1") {
  166. body = [];
  167. setter = (name, value) => _.set(body, name, value);
  168. } else {
  169. body = {};
  170. setter = (name, value) => _.set(body, name, value);
  171. }
  172. const bodyParameters = form.querySelectorAll('input[data-component=body]');
  173. bodyParameters.forEach(el => {
  174. let value = el.value;
  175. if (el.type === 'number' && typeof value === 'string') {
  176. value = parseFloat(value);
  177. }
  178. if (el.type === 'file' && el.files[0]) {
  179. setter(el.name, el.files[0]);
  180. return;
  181. }
  182. if (el.type !== 'radio') {
  183. if (value === "" && el.required === false) {
  184. // Don't include empty optional values in the request
  185. return;
  186. }
  187. setter(el.name, value);
  188. return;
  189. }
  190. if (el.checked) {
  191. value = (value === 'false') ? false : true;
  192. setter(el.name, value);
  193. }
  194. });
  195. const query = {};
  196. const queryParameters = form.querySelectorAll('input[data-component=query]');
  197. queryParameters.forEach(el => {
  198. if (el.type !== 'radio' || (el.type === 'radio' && el.checked)) {
  199. if (el.value === '') {
  200. // Don't include empty values in the request
  201. return;
  202. }
  203. _.set(query, el.name, el.value);
  204. }
  205. });
  206. let path = form.dataset.path;
  207. const urlParameters = form.querySelectorAll('input[data-component=url]');
  208. urlParameters.forEach(el => (path = path.replace(new RegExp(`\\{${el.name}\\??}`), el.value)));
  209. const headers = Object.fromEntries(Array.from(form.querySelectorAll('input[data-component=header]'))
  210. .map(el => [el.name, el.value]));
  211. // When using FormData, the browser sets the correct content-type + boundary
  212. let method = form.dataset.method;
  213. if (body instanceof FormData) {
  214. delete headers['Content-Type'];
  215. // When using FormData with PUT or PATCH, use method spoofing so PHP can access the post body
  216. if (['PUT', 'PATCH'].includes(form.dataset.method)) {
  217. method = 'POST';
  218. setter('_method', form.dataset.method);
  219. }
  220. }
  221. let preflightPromise = Promise.resolve();
  222. if (window.useCsrf && window.csrfUrl) {
  223. preflightPromise = makeAPICall('GET', window.csrfUrl).then(() => {
  224. headers['X-XSRF-TOKEN'] = getCookie('XSRF-TOKEN');
  225. });
  226. }
  227. return preflightPromise.then(() => makeAPICall(method, path, body, query, headers, endpointId))
  228. .then(([responseStatus, statusText, responseContent, responseHeaders]) => {
  229. handleResponse(endpointId, responseContent, responseStatus, responseHeaders)
  230. })
  231. .catch(err => {
  232. if (err.name === "AbortError") {
  233. console.log("Request cancelled");
  234. return;
  235. }
  236. console.log("Error while making request: ", err);
  237. handleError(endpointId, err);
  238. })
  239. .finally(() => {
  240. executeBtn.disabled = false;
  241. executeBtn.textContent = executeBtn.dataset.initialText;
  242. });
  243. }