mockServiceWorker.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /* eslint-disable */
  2. /* tslint:disable */
  3. /**
  4. * Mock Service Worker (0.48.1).
  5. * @see https://github.com/mswjs/msw
  6. * - Please do NOT modify this file.
  7. * - Please do NOT serve this file on production.
  8. */
  9. const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
  10. const activeClientIds = new Set()
  11. self.addEventListener('install', function () {
  12. self.skipWaiting()
  13. })
  14. self.addEventListener('activate', function (event) {
  15. event.waitUntil(self.clients.claim())
  16. })
  17. self.addEventListener('message', async function (event) {
  18. const clientId = event.source.id
  19. if (!clientId || !self.clients) {
  20. return
  21. }
  22. const client = await self.clients.get(clientId)
  23. if (!client) {
  24. return
  25. }
  26. const allClients = await self.clients.matchAll({
  27. type: 'window',
  28. })
  29. switch (event.data) {
  30. case 'KEEPALIVE_REQUEST': {
  31. sendToClient(client, {
  32. type: 'KEEPALIVE_RESPONSE',
  33. })
  34. break
  35. }
  36. case 'INTEGRITY_CHECK_REQUEST': {
  37. sendToClient(client, {
  38. type: 'INTEGRITY_CHECK_RESPONSE',
  39. payload: INTEGRITY_CHECKSUM,
  40. })
  41. break
  42. }
  43. case 'MOCK_ACTIVATE': {
  44. activeClientIds.add(clientId)
  45. sendToClient(client, {
  46. type: 'MOCKING_ENABLED',
  47. payload: true,
  48. })
  49. break
  50. }
  51. case 'MOCK_DEACTIVATE': {
  52. activeClientIds.delete(clientId)
  53. break
  54. }
  55. case 'CLIENT_CLOSED': {
  56. activeClientIds.delete(clientId)
  57. const remainingClients = allClients.filter((client) => {
  58. return client.id !== clientId
  59. })
  60. // Unregister itself when there are no more clients
  61. if (remainingClients.length === 0) {
  62. self.registration.unregister()
  63. }
  64. break
  65. }
  66. }
  67. })
  68. self.addEventListener('fetch', function (event) {
  69. const { request } = event
  70. const accept = request.headers.get('accept') || ''
  71. // Bypass server-sent events.
  72. if (accept.includes('text/event-stream')) {
  73. return
  74. }
  75. // Bypass navigation requests.
  76. if (request.mode === 'navigate') {
  77. return
  78. }
  79. // Opening the DevTools triggers the "only-if-cached" request
  80. // that cannot be handled by the worker. Bypass such requests.
  81. if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
  82. return
  83. }
  84. // Bypass all requests when there are no active clients.
  85. // Prevents the self-unregistered worked from handling requests
  86. // after it's been deleted (still remains active until the next reload).
  87. if (activeClientIds.size === 0) {
  88. return
  89. }
  90. // Generate unique request ID.
  91. const requestId = Math.random().toString(16).slice(2)
  92. event.respondWith(
  93. handleRequest(event, requestId).catch((error) => {
  94. if (error.name === 'NetworkError') {
  95. console.warn(
  96. '[MSW] Successfully emulated a network error for the "%s %s" request.',
  97. request.method,
  98. request.url,
  99. )
  100. return
  101. }
  102. // At this point, any exception indicates an issue with the original request/response.
  103. console.error(
  104. `\
  105. [MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
  106. request.method,
  107. request.url,
  108. `${error.name}: ${error.message}`,
  109. )
  110. }),
  111. )
  112. })
  113. async function handleRequest(event, requestId) {
  114. const client = await resolveMainClient(event)
  115. const response = await getResponse(event, client, requestId)
  116. // Send back the response clone for the "response:*" life-cycle events.
  117. // Ensure MSW is active and ready to handle the message, otherwise
  118. // this message will pend indefinitely.
  119. if (client && activeClientIds.has(client.id)) {
  120. ;(async function () {
  121. const clonedResponse = response.clone()
  122. sendToClient(client, {
  123. type: 'RESPONSE',
  124. payload: {
  125. requestId,
  126. type: clonedResponse.type,
  127. ok: clonedResponse.ok,
  128. status: clonedResponse.status,
  129. statusText: clonedResponse.statusText,
  130. body:
  131. clonedResponse.body === null ? null : await clonedResponse.text(),
  132. headers: Object.fromEntries(clonedResponse.headers.entries()),
  133. redirected: clonedResponse.redirected,
  134. },
  135. })
  136. })()
  137. }
  138. return response
  139. }
  140. // Resolve the main client for the given event.
  141. // Client that issues a request doesn't necessarily equal the client
  142. // that registered the worker. It's with the latter the worker should
  143. // communicate with during the response resolving phase.
  144. async function resolveMainClient(event) {
  145. const client = await self.clients.get(event.clientId)
  146. if (client?.frameType === 'top-level') {
  147. return client
  148. }
  149. const allClients = await self.clients.matchAll({
  150. type: 'window',
  151. })
  152. return allClients
  153. .filter((client) => {
  154. // Get only those clients that are currently visible.
  155. return client.visibilityState === 'visible'
  156. })
  157. .find((client) => {
  158. // Find the client ID that's recorded in the
  159. // set of clients that have registered the worker.
  160. return activeClientIds.has(client.id)
  161. })
  162. }
  163. async function getResponse(event, client, requestId) {
  164. const { request } = event
  165. const clonedRequest = request.clone()
  166. function passthrough() {
  167. // Clone the request because it might've been already used
  168. // (i.e. its body has been read and sent to the client).
  169. const headers = Object.fromEntries(clonedRequest.headers.entries())
  170. // Remove MSW-specific request headers so the bypassed requests
  171. // comply with the server's CORS preflight check.
  172. // Operate with the headers as an object because request "Headers"
  173. // are immutable.
  174. delete headers['x-msw-bypass']
  175. return fetch(clonedRequest, { headers })
  176. }
  177. // Bypass mocking when the client is not active.
  178. if (!client) {
  179. return passthrough()
  180. }
  181. // Bypass initial page load requests (i.e. static assets).
  182. // The absence of the immediate/parent client in the map of the active clients
  183. // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
  184. // and is not ready to handle requests.
  185. if (!activeClientIds.has(client.id)) {
  186. return passthrough()
  187. }
  188. // Bypass requests with the explicit bypass header.
  189. // Such requests can be issued by "ctx.fetch()".
  190. if (request.headers.get('x-msw-bypass') === 'true') {
  191. return passthrough()
  192. }
  193. // Notify the client that a request has been intercepted.
  194. const clientMessage = await sendToClient(client, {
  195. type: 'REQUEST',
  196. payload: {
  197. id: requestId,
  198. url: request.url,
  199. method: request.method,
  200. headers: Object.fromEntries(request.headers.entries()),
  201. cache: request.cache,
  202. mode: request.mode,
  203. credentials: request.credentials,
  204. destination: request.destination,
  205. integrity: request.integrity,
  206. redirect: request.redirect,
  207. referrer: request.referrer,
  208. referrerPolicy: request.referrerPolicy,
  209. body: await request.text(),
  210. bodyUsed: request.bodyUsed,
  211. keepalive: request.keepalive,
  212. },
  213. })
  214. switch (clientMessage.type) {
  215. case 'MOCK_RESPONSE': {
  216. return respondWithMock(clientMessage.data)
  217. }
  218. case 'MOCK_NOT_FOUND': {
  219. return passthrough()
  220. }
  221. case 'NETWORK_ERROR': {
  222. const { name, message } = clientMessage.data
  223. const networkError = new Error(message)
  224. networkError.name = name
  225. // Rejecting a "respondWith" promise emulates a network error.
  226. throw networkError
  227. }
  228. }
  229. return passthrough()
  230. }
  231. function sendToClient(client, message) {
  232. return new Promise((resolve, reject) => {
  233. const channel = new MessageChannel()
  234. channel.port1.onmessage = (event) => {
  235. if (event.data && event.data.error) {
  236. return reject(event.data.error)
  237. }
  238. resolve(event.data)
  239. }
  240. client.postMessage(message, [channel.port2])
  241. })
  242. }
  243. function sleep(timeMs) {
  244. return new Promise((resolve) => {
  245. setTimeout(resolve, timeMs)
  246. })
  247. }
  248. async function respondWithMock(response) {
  249. await sleep(response.delay)
  250. return new Response(response.body, response)
  251. }