{"version":3,"file":"utils.js","names":["_contentType3","require","_logger","_utils","_errors","timeoutSignal","ms","controller","AbortController","setTimeout","abort","signal","anySignal","signals","cleanup","removeEventListener","onAbort","aborted","addEventListener","parseErrorResponse","response","body","_contentType","_contentType2","contentType","getResponseContentType","e","type","MatrixError","JSON","parse","status","isXhr","responseURL","url","HTTPError","getResponseHeader","headers","get","parseContentType","Error","retryNetworkOperation","maxAttempts","callback","attempts","lastConnectionError","timeout","Math","pow","logger","log","sleep","err","ConnectionError"],"sources":["../../src/http-api/utils.ts"],"sourcesContent":["/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { parse as parseContentType, ParsedMediaType } from \"content-type\";\n\nimport { logger } from \"../logger\";\nimport { sleep } from \"../utils\";\nimport { ConnectionError, HTTPError, MatrixError } from \"./errors\";\n\n// Ponyfill for https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout\nexport function timeoutSignal(ms: number): AbortSignal {\n const controller = new AbortController();\n setTimeout(() => {\n controller.abort();\n }, ms);\n\n return controller.signal;\n}\n\nexport function anySignal(signals: AbortSignal[]): {\n signal: AbortSignal;\n cleanup(): void;\n} {\n const controller = new AbortController();\n\n function cleanup(): void {\n for (const signal of signals) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n function onAbort(): void {\n controller.abort();\n cleanup();\n }\n\n for (const signal of signals) {\n if (signal.aborted) {\n onAbort();\n break;\n }\n signal.addEventListener(\"abort\", onAbort);\n }\n\n return {\n signal: controller.signal,\n cleanup,\n };\n}\n\n/**\n * Attempt to turn an HTTP error response into a Javascript Error.\n *\n * If it is a JSON response, we will parse it into a MatrixError. Otherwise\n * we return a generic Error.\n *\n * @param response - response object\n * @param body - raw body of the response\n * @returns\n */\nexport function parseErrorResponse(response: XMLHttpRequest | Response, body?: string): Error {\n let contentType: ParsedMediaType | null;\n try {\n contentType = getResponseContentType(response);\n } catch (e) {\n return e;\n }\n\n if (contentType?.type === \"application/json\" && body) {\n return new MatrixError(\n JSON.parse(body),\n response.status,\n isXhr(response) ? response.responseURL : response.url,\n );\n }\n if (contentType?.type === \"text/plain\") {\n return new HTTPError(`Server returned ${response.status} error: ${body}`, response.status);\n }\n return new HTTPError(`Server returned ${response.status} error`, response.status);\n}\n\nfunction isXhr(response: XMLHttpRequest | Response): response is XMLHttpRequest {\n return \"getResponseHeader\" in response;\n}\n\n/**\n * extract the Content-Type header from the response object, and\n * parse it to a `{type, parameters}` object.\n *\n * returns null if no content-type header could be found.\n *\n * @param response - response object\n * @returns parsed content-type header, or null if not found\n */\nfunction getResponseContentType(response: XMLHttpRequest | Response): ParsedMediaType | null {\n let contentType: string | null;\n if (isXhr(response)) {\n contentType = response.getResponseHeader(\"Content-Type\");\n } else {\n contentType = response.headers.get(\"Content-Type\");\n }\n\n if (!contentType) return null;\n\n try {\n return parseContentType(contentType);\n } catch (e) {\n throw new Error(`Error parsing Content-Type '${contentType}': ${e}`);\n }\n}\n\n/**\n * Retries a network operation run in a callback.\n * @param maxAttempts - maximum attempts to try\n * @param callback - callback that returns a promise of the network operation. If rejected with ConnectionError, it will be retried by calling the callback again.\n * @returns the result of the network operation\n * @throws {@link ConnectionError} If after maxAttempts the callback still throws ConnectionError\n */\nexport async function retryNetworkOperation(maxAttempts: number, callback: () => Promise): Promise {\n let attempts = 0;\n let lastConnectionError: ConnectionError | null = null;\n while (attempts < maxAttempts) {\n try {\n if (attempts > 0) {\n const timeout = 1000 * Math.pow(2, attempts);\n logger.log(`network operation failed ${attempts} times, retrying in ${timeout}ms...`);\n await sleep(timeout);\n }\n return await callback();\n } catch (err) {\n if (err instanceof ConnectionError) {\n attempts += 1;\n lastConnectionError = err;\n } else {\n throw err;\n }\n }\n }\n throw lastConnectionError;\n}\n"],"mappings":";;;;;;;;;AAgBA,IAAAA,aAAA,GAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,MAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AApBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAQA;AACO,SAASI,aAAaA,CAACC,EAAU,EAAe;EACnD,MAAMC,UAAU,GAAG,IAAIC,eAAe,EAAE;EACxCC,UAAU,CAAC,MAAM;IACbF,UAAU,CAACG,KAAK,EAAE;EACtB,CAAC,EAAEJ,EAAE,CAAC;EAEN,OAAOC,UAAU,CAACI,MAAM;AAC5B;AAEO,SAASC,SAASA,CAACC,OAAsB,EAG9C;EACE,MAAMN,UAAU,GAAG,IAAIC,eAAe,EAAE;EAExC,SAASM,OAAOA,CAAA,EAAS;IACrB,KAAK,MAAMH,MAAM,IAAIE,OAAO,EAAE;MAC1BF,MAAM,CAACI,mBAAmB,CAAC,OAAO,EAAEC,OAAO,CAAC;IAChD;EACJ;EAEA,SAASA,OAAOA,CAAA,EAAS;IACrBT,UAAU,CAACG,KAAK,EAAE;IAClBI,OAAO,EAAE;EACb;EAEA,KAAK,MAAMH,MAAM,IAAIE,OAAO,EAAE;IAC1B,IAAIF,MAAM,CAACM,OAAO,EAAE;MAChBD,OAAO,EAAE;MACT;IACJ;IACAL,MAAM,CAACO,gBAAgB,CAAC,OAAO,EAAEF,OAAO,CAAC;EAC7C;EAEA,OAAO;IACHL,MAAM,EAAEJ,UAAU,CAACI,MAAM;IACzBG;EACJ,CAAC;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAASK,kBAAkBA,CAACC,QAAmC,EAAEC,IAAa,EAAS;EAAA,IAAAC,YAAA,EAAAC,aAAA;EA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