msw 2.0.12 → 2.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (404) hide show
  1. package/lib/browser/index.d.mts +104 -0
  2. package/lib/browser/index.d.ts +1 -1
  3. package/lib/browser/index.js +1 -0
  4. package/lib/browser/index.js.map +1 -0
  5. package/lib/browser/index.mjs +1 -0
  6. package/lib/browser/index.mjs.map +1 -0
  7. package/lib/core/{GraphQLHandler-da09c680.d.ts → GraphQLHandler-SHlRCcy4.d.ts} +2 -2
  8. package/lib/core/GraphQLHandler-zlmUDnN6.d.mts +97 -0
  9. package/lib/core/HttpResponse.d.mts +2 -0
  10. package/lib/core/HttpResponse.d.ts +1 -1
  11. package/lib/core/HttpResponse.js +1 -0
  12. package/lib/core/HttpResponse.js.map +1 -0
  13. package/lib/core/HttpResponse.mjs +1 -0
  14. package/lib/core/HttpResponse.mjs.map +1 -0
  15. package/lib/core/{RequestHandler-25f9cfd1.d.ts → RequestHandler-rBDJQrEf.d.ts} +1 -1
  16. package/lib/core/RequestHandler-vxZdj6Tw.d.mts +179 -0
  17. package/lib/core/SetupApi.d.mts +26 -0
  18. package/lib/core/SetupApi.d.ts +1 -1
  19. package/lib/core/SetupApi.js +1 -0
  20. package/lib/core/SetupApi.js.map +1 -0
  21. package/lib/core/SetupApi.mjs +1 -0
  22. package/lib/core/SetupApi.mjs.map +1 -0
  23. package/lib/core/bypass.d.mts +16 -0
  24. package/lib/core/bypass.d.ts +1 -1
  25. package/lib/core/bypass.js +1 -0
  26. package/lib/core/bypass.js.map +1 -0
  27. package/lib/core/bypass.mjs +1 -0
  28. package/lib/core/bypass.mjs.map +1 -0
  29. package/lib/core/delay.d.mts +18 -0
  30. package/lib/core/delay.d.ts +1 -1
  31. package/lib/core/delay.js +1 -0
  32. package/lib/core/delay.js.map +1 -0
  33. package/lib/core/delay.mjs +1 -0
  34. package/lib/core/delay.mjs.map +1 -0
  35. package/lib/core/graphql.d.mts +109 -0
  36. package/lib/core/graphql.d.ts +3 -3
  37. package/lib/core/graphql.js +1 -0
  38. package/lib/core/graphql.js.map +1 -0
  39. package/lib/core/graphql.mjs +1 -0
  40. package/lib/core/graphql.mjs.map +1 -0
  41. package/lib/core/handlers/GraphQLHandler.d.mts +5 -0
  42. package/lib/core/handlers/GraphQLHandler.d.ts +2 -2
  43. package/lib/core/handlers/GraphQLHandler.js +3 -2
  44. package/lib/core/handlers/GraphQLHandler.js.map +1 -0
  45. package/lib/core/handlers/GraphQLHandler.mjs +3 -2
  46. package/lib/core/handlers/GraphQLHandler.mjs.map +1 -0
  47. package/lib/core/handlers/HttpHandler.d.mts +62 -0
  48. package/lib/core/handlers/HttpHandler.d.ts +2 -2
  49. package/lib/core/handlers/HttpHandler.js +1 -0
  50. package/lib/core/handlers/HttpHandler.js.map +1 -0
  51. package/lib/core/handlers/HttpHandler.mjs +1 -0
  52. package/lib/core/handlers/HttpHandler.mjs.map +1 -0
  53. package/lib/core/handlers/RequestHandler.d.mts +2 -0
  54. package/lib/core/handlers/RequestHandler.d.ts +1 -1
  55. package/lib/core/handlers/RequestHandler.js +3 -2
  56. package/lib/core/handlers/RequestHandler.js.map +1 -0
  57. package/lib/core/handlers/RequestHandler.mjs +3 -2
  58. package/lib/core/handlers/RequestHandler.mjs.map +1 -0
  59. package/lib/core/http.d.mts +26 -0
  60. package/lib/core/http.d.ts +1 -1
  61. package/lib/core/http.js +1 -0
  62. package/lib/core/http.js.map +1 -0
  63. package/lib/core/http.mjs +1 -0
  64. package/lib/core/http.mjs.map +1 -0
  65. package/lib/core/index.d.mts +18 -0
  66. package/lib/core/index.d.ts +2 -2
  67. package/lib/core/index.js +1 -0
  68. package/lib/core/index.js.map +1 -0
  69. package/lib/core/index.mjs +1 -0
  70. package/lib/core/index.mjs.map +1 -0
  71. package/lib/core/passthrough.d.mts +17 -0
  72. package/lib/core/passthrough.js +1 -0
  73. package/lib/core/passthrough.js.map +1 -0
  74. package/lib/core/passthrough.mjs +1 -0
  75. package/lib/core/passthrough.mjs.map +1 -0
  76. package/lib/core/sharedOptions.d.mts +66 -0
  77. package/lib/core/sharedOptions.d.ts +2 -2
  78. package/lib/core/sharedOptions.js +1 -0
  79. package/lib/core/sharedOptions.js.map +1 -0
  80. package/lib/core/sharedOptions.mjs +1 -0
  81. package/lib/core/sharedOptions.mjs.map +1 -0
  82. package/lib/core/typeUtils.d.mts +7 -0
  83. package/lib/core/typeUtils.d.ts +1 -1
  84. package/lib/core/typeUtils.js +1 -0
  85. package/lib/core/typeUtils.js.map +1 -0
  86. package/lib/core/typeUtils.mjs +1 -0
  87. package/lib/core/typeUtils.mjs.map +1 -0
  88. package/lib/core/utils/HttpResponse/decorators.d.mts +12 -0
  89. package/lib/core/utils/HttpResponse/decorators.d.ts +2 -2
  90. package/lib/core/utils/HttpResponse/decorators.js +1 -0
  91. package/lib/core/utils/HttpResponse/decorators.js.map +1 -0
  92. package/lib/core/utils/HttpResponse/decorators.mjs +1 -0
  93. package/lib/core/utils/HttpResponse/decorators.mjs.map +1 -0
  94. package/lib/core/utils/getResponse.d.mts +2 -0
  95. package/lib/core/utils/getResponse.d.ts +1 -1
  96. package/lib/core/utils/getResponse.js +1 -0
  97. package/lib/core/utils/getResponse.js.map +1 -0
  98. package/lib/core/utils/getResponse.mjs +1 -0
  99. package/lib/core/utils/getResponse.mjs.map +1 -0
  100. package/lib/core/utils/handleRequest.d.mts +37 -0
  101. package/lib/core/utils/handleRequest.d.ts +2 -2
  102. package/lib/core/utils/handleRequest.js +1 -0
  103. package/lib/core/utils/handleRequest.js.map +1 -0
  104. package/lib/core/utils/handleRequest.mjs +1 -0
  105. package/lib/core/utils/handleRequest.mjs.map +1 -0
  106. package/lib/core/utils/internal/Disposable.d.mts +7 -0
  107. package/lib/core/utils/internal/Disposable.d.ts +1 -1
  108. package/lib/core/utils/internal/Disposable.js +1 -0
  109. package/lib/core/utils/internal/Disposable.js.map +1 -0
  110. package/lib/core/utils/internal/Disposable.mjs +1 -0
  111. package/lib/core/utils/internal/Disposable.mjs.map +1 -0
  112. package/lib/core/utils/internal/checkGlobals.d.mts +3 -0
  113. package/lib/core/utils/internal/checkGlobals.js +1 -0
  114. package/lib/core/utils/internal/checkGlobals.js.map +1 -0
  115. package/lib/core/utils/internal/checkGlobals.mjs +1 -0
  116. package/lib/core/utils/internal/checkGlobals.mjs.map +1 -0
  117. package/lib/core/utils/internal/devUtils.d.mts +19 -0
  118. package/lib/core/utils/internal/devUtils.js +1 -0
  119. package/lib/core/utils/internal/devUtils.js.map +1 -0
  120. package/lib/core/utils/internal/devUtils.mjs +1 -0
  121. package/lib/core/utils/internal/devUtils.mjs.map +1 -0
  122. package/lib/core/utils/internal/getCallFrame.d.mts +6 -0
  123. package/lib/core/utils/internal/getCallFrame.js +1 -0
  124. package/lib/core/utils/internal/getCallFrame.js.map +1 -0
  125. package/lib/core/utils/internal/getCallFrame.mjs +1 -0
  126. package/lib/core/utils/internal/getCallFrame.mjs.map +1 -0
  127. package/lib/core/utils/internal/isIterable.d.mts +6 -0
  128. package/lib/core/utils/internal/isIterable.js +1 -0
  129. package/lib/core/utils/internal/isIterable.js.map +1 -0
  130. package/lib/core/utils/internal/isIterable.mjs +1 -0
  131. package/lib/core/utils/internal/isIterable.mjs.map +1 -0
  132. package/lib/core/utils/internal/isObject.d.mts +6 -0
  133. package/lib/core/utils/internal/isObject.js +1 -0
  134. package/lib/core/utils/internal/isObject.js.map +1 -0
  135. package/lib/core/utils/internal/isObject.mjs +1 -0
  136. package/lib/core/utils/internal/isObject.mjs.map +1 -0
  137. package/lib/core/utils/internal/isStringEqual.d.mts +6 -0
  138. package/lib/core/utils/internal/isStringEqual.js +1 -0
  139. package/lib/core/utils/internal/isStringEqual.js.map +1 -0
  140. package/lib/core/utils/internal/isStringEqual.mjs +1 -0
  141. package/lib/core/utils/internal/isStringEqual.mjs.map +1 -0
  142. package/lib/core/utils/internal/jsonParse.d.mts +7 -0
  143. package/lib/core/utils/internal/jsonParse.js +1 -0
  144. package/lib/core/utils/internal/jsonParse.js.map +1 -0
  145. package/lib/core/utils/internal/jsonParse.mjs +1 -0
  146. package/lib/core/utils/internal/jsonParse.mjs.map +1 -0
  147. package/lib/core/utils/internal/mergeRight.d.mts +7 -0
  148. package/lib/core/utils/internal/mergeRight.js +1 -0
  149. package/lib/core/utils/internal/mergeRight.js.map +1 -0
  150. package/lib/core/utils/internal/mergeRight.mjs +1 -0
  151. package/lib/core/utils/internal/mergeRight.mjs.map +1 -0
  152. package/lib/core/utils/internal/parseGraphQLRequest.d.mts +5 -0
  153. package/lib/core/utils/internal/parseGraphQLRequest.d.ts +2 -2
  154. package/lib/core/utils/internal/parseGraphQLRequest.js +1 -0
  155. package/lib/core/utils/internal/parseGraphQLRequest.js.map +1 -0
  156. package/lib/core/utils/internal/parseGraphQLRequest.mjs +1 -0
  157. package/lib/core/utils/internal/parseGraphQLRequest.mjs.map +1 -0
  158. package/lib/core/utils/internal/parseMultipartData.d.mts +10 -0
  159. package/lib/core/utils/internal/parseMultipartData.d.ts +1 -1
  160. package/lib/core/utils/internal/parseMultipartData.js +1 -0
  161. package/lib/core/utils/internal/parseMultipartData.js.map +1 -0
  162. package/lib/core/utils/internal/parseMultipartData.mjs +1 -0
  163. package/lib/core/utils/internal/parseMultipartData.mjs.map +1 -0
  164. package/lib/core/utils/internal/pipeEvents.d.mts +8 -0
  165. package/lib/core/utils/internal/pipeEvents.js +1 -0
  166. package/lib/core/utils/internal/pipeEvents.js.map +1 -0
  167. package/lib/core/utils/internal/pipeEvents.mjs +1 -0
  168. package/lib/core/utils/internal/pipeEvents.mjs.map +1 -0
  169. package/lib/core/utils/internal/requestHandlerUtils.d.mts +8 -0
  170. package/lib/core/utils/internal/requestHandlerUtils.d.ts +1 -1
  171. package/lib/core/utils/internal/requestHandlerUtils.js +1 -0
  172. package/lib/core/utils/internal/requestHandlerUtils.js.map +1 -0
  173. package/lib/core/utils/internal/requestHandlerUtils.mjs +1 -0
  174. package/lib/core/utils/internal/requestHandlerUtils.mjs.map +1 -0
  175. package/lib/core/utils/internal/toReadonlyArray.d.mts +6 -0
  176. package/lib/core/utils/internal/toReadonlyArray.js +1 -0
  177. package/lib/core/utils/internal/toReadonlyArray.js.map +1 -0
  178. package/lib/core/utils/internal/toReadonlyArray.mjs +1 -0
  179. package/lib/core/utils/internal/toReadonlyArray.mjs.map +1 -0
  180. package/lib/core/utils/internal/tryCatch.d.mts +3 -0
  181. package/lib/core/utils/internal/tryCatch.js +1 -0
  182. package/lib/core/utils/internal/tryCatch.js.map +1 -0
  183. package/lib/core/utils/internal/tryCatch.mjs +1 -0
  184. package/lib/core/utils/internal/tryCatch.mjs.map +1 -0
  185. package/lib/core/utils/internal/uuidv4.d.mts +3 -0
  186. package/lib/core/utils/internal/uuidv4.js +1 -0
  187. package/lib/core/utils/internal/uuidv4.js.map +1 -0
  188. package/lib/core/utils/internal/uuidv4.mjs +1 -0
  189. package/lib/core/utils/internal/uuidv4.mjs.map +1 -0
  190. package/lib/core/utils/logging/getStatusCodeColor.d.mts +11 -0
  191. package/lib/core/utils/logging/getStatusCodeColor.js +1 -0
  192. package/lib/core/utils/logging/getStatusCodeColor.js.map +1 -0
  193. package/lib/core/utils/logging/getStatusCodeColor.mjs +1 -0
  194. package/lib/core/utils/logging/getStatusCodeColor.mjs.map +1 -0
  195. package/lib/core/utils/logging/getTimestamp.d.mts +6 -0
  196. package/lib/core/utils/logging/getTimestamp.js +1 -0
  197. package/lib/core/utils/logging/getTimestamp.js.map +1 -0
  198. package/lib/core/utils/logging/getTimestamp.mjs +1 -0
  199. package/lib/core/utils/logging/getTimestamp.mjs.map +1 -0
  200. package/lib/core/utils/logging/serializeRequest.d.mts +12 -0
  201. package/lib/core/utils/logging/serializeRequest.d.ts +1 -1
  202. package/lib/core/utils/logging/serializeRequest.js +1 -0
  203. package/lib/core/utils/logging/serializeRequest.js.map +1 -0
  204. package/lib/core/utils/logging/serializeRequest.mjs +1 -0
  205. package/lib/core/utils/logging/serializeRequest.mjs.map +1 -0
  206. package/lib/core/utils/logging/serializeResponse.d.mts +9 -0
  207. package/lib/core/utils/logging/serializeResponse.d.ts +1 -1
  208. package/lib/core/utils/logging/serializeResponse.js +1 -0
  209. package/lib/core/utils/logging/serializeResponse.js.map +1 -0
  210. package/lib/core/utils/logging/serializeResponse.mjs +1 -0
  211. package/lib/core/utils/logging/serializeResponse.mjs.map +1 -0
  212. package/lib/core/utils/matching/matchRequestUrl.d.mts +19 -0
  213. package/lib/core/utils/matching/matchRequestUrl.d.ts +1 -1
  214. package/lib/core/utils/matching/matchRequestUrl.js +1 -0
  215. package/lib/core/utils/matching/matchRequestUrl.js.map +1 -0
  216. package/lib/core/utils/matching/matchRequestUrl.mjs +1 -0
  217. package/lib/core/utils/matching/matchRequestUrl.mjs.map +1 -0
  218. package/lib/core/utils/matching/normalizePath.d.mts +12 -0
  219. package/lib/core/utils/matching/normalizePath.js +1 -0
  220. package/lib/core/utils/matching/normalizePath.js.map +1 -0
  221. package/lib/core/utils/matching/normalizePath.mjs +1 -0
  222. package/lib/core/utils/matching/normalizePath.mjs.map +1 -0
  223. package/lib/core/utils/request/getPublicUrlFromRequest.d.mts +7 -0
  224. package/lib/core/utils/request/getPublicUrlFromRequest.js +1 -0
  225. package/lib/core/utils/request/getPublicUrlFromRequest.js.map +1 -0
  226. package/lib/core/utils/request/getPublicUrlFromRequest.mjs +1 -0
  227. package/lib/core/utils/request/getPublicUrlFromRequest.mjs.map +1 -0
  228. package/lib/core/utils/request/getRequestCookies.d.mts +8 -0
  229. package/lib/core/utils/request/getRequestCookies.js +1 -0
  230. package/lib/core/utils/request/getRequestCookies.js.map +1 -0
  231. package/lib/core/utils/request/getRequestCookies.mjs +1 -0
  232. package/lib/core/utils/request/getRequestCookies.mjs.map +1 -0
  233. package/lib/core/utils/request/onUnhandledRequest.d.mts +12 -0
  234. package/lib/core/utils/request/onUnhandledRequest.d.ts +2 -2
  235. package/lib/core/utils/request/onUnhandledRequest.js +1 -0
  236. package/lib/core/utils/request/onUnhandledRequest.js.map +1 -0
  237. package/lib/core/utils/request/onUnhandledRequest.mjs +1 -0
  238. package/lib/core/utils/request/onUnhandledRequest.mjs.map +1 -0
  239. package/lib/core/utils/request/readResponseCookies.d.mts +3 -0
  240. package/lib/core/utils/request/readResponseCookies.js +1 -0
  241. package/lib/core/utils/request/readResponseCookies.js.map +1 -0
  242. package/lib/core/utils/request/readResponseCookies.mjs +1 -0
  243. package/lib/core/utils/request/readResponseCookies.mjs.map +1 -0
  244. package/lib/core/utils/toResponseInit.d.mts +3 -0
  245. package/lib/core/utils/toResponseInit.js +1 -0
  246. package/lib/core/utils/toResponseInit.js.map +1 -0
  247. package/lib/core/utils/toResponseInit.mjs +1 -0
  248. package/lib/core/utils/toResponseInit.mjs.map +1 -0
  249. package/lib/core/utils/url/cleanUrl.d.mts +7 -0
  250. package/lib/core/utils/url/cleanUrl.js +1 -0
  251. package/lib/core/utils/url/cleanUrl.js.map +1 -0
  252. package/lib/core/utils/url/cleanUrl.mjs +1 -0
  253. package/lib/core/utils/url/cleanUrl.mjs.map +1 -0
  254. package/lib/core/utils/url/getAbsoluteUrl.d.mts +6 -0
  255. package/lib/core/utils/url/getAbsoluteUrl.js +1 -0
  256. package/lib/core/utils/url/getAbsoluteUrl.js.map +1 -0
  257. package/lib/core/utils/url/getAbsoluteUrl.mjs +1 -0
  258. package/lib/core/utils/url/getAbsoluteUrl.mjs.map +1 -0
  259. package/lib/core/utils/url/isAbsoluteUrl.d.mts +6 -0
  260. package/lib/core/utils/url/isAbsoluteUrl.js +1 -0
  261. package/lib/core/utils/url/isAbsoluteUrl.js.map +1 -0
  262. package/lib/core/utils/url/isAbsoluteUrl.mjs +1 -0
  263. package/lib/core/utils/url/isAbsoluteUrl.mjs.map +1 -0
  264. package/lib/iife/index.js +20 -19
  265. package/lib/iife/index.js.map +1 -0
  266. package/lib/mockServiceWorker.js +1 -1
  267. package/lib/native/index.d.mts +75 -0
  268. package/lib/native/index.js +1 -0
  269. package/lib/native/index.js.map +1 -0
  270. package/lib/native/index.mjs +1 -0
  271. package/lib/native/index.mjs.map +1 -0
  272. package/lib/node/index.d.mts +75 -0
  273. package/lib/node/index.d.ts +1 -1
  274. package/lib/node/index.js +1 -0
  275. package/lib/node/index.js.map +1 -0
  276. package/lib/node/index.mjs +1 -0
  277. package/lib/node/index.mjs.map +1 -0
  278. package/package.json +5 -4
  279. package/src/browser/global.browser.d.ts +1 -0
  280. package/src/browser/index.ts +3 -0
  281. package/src/browser/setupWorker/glossary.ts +259 -0
  282. package/src/browser/setupWorker/setupWorker.node.test.ts +10 -0
  283. package/src/browser/setupWorker/setupWorker.ts +199 -0
  284. package/src/browser/setupWorker/start/createFallbackRequestListener.ts +67 -0
  285. package/src/browser/setupWorker/start/createFallbackStart.ts +21 -0
  286. package/src/browser/setupWorker/start/createRequestListener.ts +127 -0
  287. package/src/browser/setupWorker/start/createResponseListener.ts +58 -0
  288. package/src/browser/setupWorker/start/createStartHandler.ts +143 -0
  289. package/src/browser/setupWorker/start/utils/createMessageChannel.ts +32 -0
  290. package/src/browser/setupWorker/start/utils/enableMocking.ts +32 -0
  291. package/src/browser/setupWorker/start/utils/getWorkerByRegistration.ts +25 -0
  292. package/src/browser/setupWorker/start/utils/getWorkerInstance.ts +94 -0
  293. package/src/browser/setupWorker/start/utils/prepareStartHandler.test.ts +59 -0
  294. package/src/browser/setupWorker/start/utils/prepareStartHandler.ts +44 -0
  295. package/src/browser/setupWorker/start/utils/printStartMessage.test.ts +84 -0
  296. package/src/browser/setupWorker/start/utils/printStartMessage.ts +40 -0
  297. package/src/browser/setupWorker/start/utils/validateWorkerScope.ts +18 -0
  298. package/src/browser/setupWorker/stop/createFallbackStop.ts +11 -0
  299. package/src/browser/setupWorker/stop/createStop.ts +29 -0
  300. package/src/browser/setupWorker/stop/utils/printStopMessage.test.ts +26 -0
  301. package/src/browser/setupWorker/stop/utils/printStopMessage.ts +12 -0
  302. package/src/browser/tsconfig.browser.build.json +6 -0
  303. package/src/browser/tsconfig.browser.json +9 -0
  304. package/src/browser/utils/deferNetworkRequestsUntil.test.ts +48 -0
  305. package/src/browser/utils/deferNetworkRequestsUntil.ts +29 -0
  306. package/src/browser/utils/getAbsoluteWorkerUrl.test.ts +31 -0
  307. package/src/browser/utils/getAbsoluteWorkerUrl.ts +7 -0
  308. package/src/browser/utils/parseWorkerRequest.ts +15 -0
  309. package/src/browser/utils/pruneGetRequestBody.test.ts +53 -0
  310. package/src/browser/utils/pruneGetRequestBody.ts +21 -0
  311. package/src/browser/utils/requestIntegrityCheck.ts +23 -0
  312. package/src/browser/utils/supportsReadableStreamTransfer.ts +17 -0
  313. package/src/core/HttpResponse.test.ts +200 -0
  314. package/src/core/HttpResponse.ts +134 -0
  315. package/src/core/SetupApi.ts +95 -0
  316. package/src/core/bypass.test.ts +47 -0
  317. package/src/core/bypass.ts +36 -0
  318. package/src/core/delay.ts +70 -0
  319. package/src/core/graphql.test.ts +11 -0
  320. package/src/core/graphql.ts +138 -0
  321. package/src/core/handlers/GraphQLHandler.test.ts +820 -0
  322. package/src/core/handlers/GraphQLHandler.ts +263 -0
  323. package/src/core/handlers/HttpHandler.test.ts +218 -0
  324. package/src/core/handlers/HttpHandler.ts +169 -0
  325. package/src/core/handlers/RequestHandler.ts +338 -0
  326. package/src/core/http.test.ts +15 -0
  327. package/src/core/http.ts +51 -0
  328. package/src/core/index.ts +56 -0
  329. package/src/core/passthrough.test.ts +13 -0
  330. package/src/core/passthrough.ts +23 -0
  331. package/src/core/sharedOptions.ts +66 -0
  332. package/src/core/typeUtils.ts +20 -0
  333. package/src/core/utils/HttpResponse/decorators.ts +56 -0
  334. package/src/core/utils/getResponse.ts +55 -0
  335. package/src/core/utils/handleRequest.test.ts +554 -0
  336. package/src/core/utils/handleRequest.ts +132 -0
  337. package/src/core/utils/internal/Disposable.ts +9 -0
  338. package/src/core/utils/internal/checkGlobals.ts +17 -0
  339. package/src/core/utils/internal/devUtils.ts +31 -0
  340. package/src/core/utils/internal/getCallFrame.test.ts +154 -0
  341. package/src/core/utils/internal/getCallFrame.ts +35 -0
  342. package/src/core/utils/internal/isIterable.test.ts +23 -0
  343. package/src/core/utils/internal/isIterable.ts +12 -0
  344. package/src/core/utils/internal/isObject.test.ts +20 -0
  345. package/src/core/utils/internal/isObject.ts +6 -0
  346. package/src/core/utils/internal/isStringEqual.test.ts +45 -0
  347. package/src/core/utils/internal/isStringEqual.ts +6 -0
  348. package/src/core/utils/internal/jsonParse.test.ts +13 -0
  349. package/src/core/utils/internal/jsonParse.ts +13 -0
  350. package/src/core/utils/internal/mergeRight.test.ts +43 -0
  351. package/src/core/utils/internal/mergeRight.ts +27 -0
  352. package/src/core/utils/internal/parseGraphQLRequest.test.ts +99 -0
  353. package/src/core/utils/internal/parseGraphQLRequest.ts +205 -0
  354. package/src/core/utils/internal/parseMultipartData.test.ts +76 -0
  355. package/src/core/utils/internal/parseMultipartData.ts +104 -0
  356. package/src/core/utils/internal/pipeEvents.test.ts +14 -0
  357. package/src/core/utils/internal/pipeEvents.ts +25 -0
  358. package/src/core/utils/internal/requestHandlerUtils.ts +21 -0
  359. package/src/core/utils/internal/toReadonlyArray.test.ts +30 -0
  360. package/src/core/utils/internal/toReadonlyArray.ts +8 -0
  361. package/src/core/utils/internal/tryCatch.test.ts +29 -0
  362. package/src/core/utils/internal/tryCatch.ts +11 -0
  363. package/src/core/utils/internal/uuidv4.ts +3 -0
  364. package/src/core/utils/logging/getStatusCodeColor.test.ts +22 -0
  365. package/src/core/utils/logging/getStatusCodeColor.ts +20 -0
  366. package/src/core/utils/logging/getTimestamp.test.ts +18 -0
  367. package/src/core/utils/logging/getTimestamp.ts +12 -0
  368. package/src/core/utils/logging/serializeRequest.test.ts +23 -0
  369. package/src/core/utils/logging/serializeRequest.ts +23 -0
  370. package/src/core/utils/logging/serializeResponse.test.ts +77 -0
  371. package/src/core/utils/logging/serializeResponse.ts +31 -0
  372. package/src/core/utils/matching/matchRequestUrl.test.ts +114 -0
  373. package/src/core/utils/matching/matchRequestUrl.ts +73 -0
  374. package/src/core/utils/matching/normalizePath.node.test.ts +44 -0
  375. package/src/core/utils/matching/normalizePath.test.ts +50 -0
  376. package/src/core/utils/matching/normalizePath.ts +21 -0
  377. package/src/core/utils/request/getPublicUrlFromRequest.test.ts +26 -0
  378. package/src/core/utils/request/getPublicUrlFromRequest.ts +15 -0
  379. package/src/core/utils/request/getRequestCookies.node.test.ts +29 -0
  380. package/src/core/utils/request/getRequestCookies.test.ts +64 -0
  381. package/src/core/utils/request/getRequestCookies.ts +75 -0
  382. package/src/core/utils/request/onUnhandledRequest.test.ts +215 -0
  383. package/src/core/utils/request/onUnhandledRequest.ts +247 -0
  384. package/src/core/utils/request/readResponseCookies.ts +9 -0
  385. package/src/core/utils/toResponseInit.ts +7 -0
  386. package/src/core/utils/url/cleanUrl.test.ts +17 -0
  387. package/src/core/utils/url/cleanUrl.ts +12 -0
  388. package/src/core/utils/url/getAbsoluteUrl.node.test.ts +19 -0
  389. package/src/core/utils/url/getAbsoluteUrl.test.ts +29 -0
  390. package/src/core/utils/url/getAbsoluteUrl.ts +26 -0
  391. package/src/core/utils/url/isAbsoluteUrl.test.ts +32 -0
  392. package/src/core/utils/url/isAbsoluteUrl.ts +6 -0
  393. package/src/iife/index.ts +2 -0
  394. package/src/mockServiceWorker.js +287 -0
  395. package/src/native/index.ts +17 -0
  396. package/src/node/SetupServerApi.ts +113 -0
  397. package/src/node/glossary.ts +62 -0
  398. package/src/node/index.ts +3 -0
  399. package/src/node/setupServer.ts +21 -0
  400. package/src/node/utils/isNodeExceptionLike.ts +14 -0
  401. package/src/tsconfig.core.build.json +6 -0
  402. package/src/tsconfig.node.build.json +6 -0
  403. package/src/tsconfig.node.json +8 -0
  404. package/src/tsconfig.src.json +15 -0
@@ -0,0 +1,25 @@
1
+ import { FindWorker } from '../../glossary'
2
+
3
+ /**
4
+ * Attempts to resolve a Service Worker instance from a given registration,
5
+ * regardless of its state (active, installing, waiting).
6
+ */
7
+ export function getWorkerByRegistration(
8
+ registration: ServiceWorkerRegistration,
9
+ absoluteWorkerUrl: string,
10
+ findWorker: FindWorker,
11
+ ): ServiceWorker | null {
12
+ const allStates = [
13
+ registration.active,
14
+ registration.installing,
15
+ registration.waiting,
16
+ ]
17
+ const relevantStates = allStates.filter((state): state is ServiceWorker => {
18
+ return state != null
19
+ })
20
+ const worker = relevantStates.find((worker) => {
21
+ return findWorker(worker.scriptURL, absoluteWorkerUrl)
22
+ })
23
+
24
+ return worker || null
25
+ }
@@ -0,0 +1,94 @@
1
+ import { until } from '@open-draft/until'
2
+ import { devUtils } from '~/core/utils/internal/devUtils'
3
+ import { getAbsoluteWorkerUrl } from '../../../utils/getAbsoluteWorkerUrl'
4
+ import { getWorkerByRegistration } from './getWorkerByRegistration'
5
+ import { ServiceWorkerInstanceTuple, FindWorker } from '../../glossary'
6
+
7
+ /**
8
+ * Returns an active Service Worker instance.
9
+ * When not found, registers a new Service Worker.
10
+ */
11
+ export const getWorkerInstance = async (
12
+ url: string,
13
+ options: RegistrationOptions = {},
14
+ findWorker: FindWorker,
15
+ ): Promise<ServiceWorkerInstanceTuple> => {
16
+ // Resolve the absolute Service Worker URL.
17
+ const absoluteWorkerUrl = getAbsoluteWorkerUrl(url)
18
+
19
+ const mockRegistrations = await navigator.serviceWorker
20
+ .getRegistrations()
21
+ .then((registrations) =>
22
+ registrations.filter((registration) =>
23
+ getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
24
+ ),
25
+ )
26
+ if (!navigator.serviceWorker.controller && mockRegistrations.length > 0) {
27
+ // Reload the page when it has associated workers, but no active controller.
28
+ // The absence of a controller can mean either:
29
+ // - page has no Service Worker associated with it
30
+ // - page has been hard-reloaded and its workers won't be used until the next reload.
31
+ // Since we've checked that there are registrations associated with this page,
32
+ // at this point we are sure it's hard reload that falls into this clause.
33
+ location.reload()
34
+ }
35
+
36
+ const [existingRegistration] = mockRegistrations
37
+
38
+ if (existingRegistration) {
39
+ // When the Service Worker is registered, update it and return the reference.
40
+ return existingRegistration.update().then(() => {
41
+ return [
42
+ getWorkerByRegistration(
43
+ existingRegistration,
44
+ absoluteWorkerUrl,
45
+ findWorker,
46
+ ),
47
+ existingRegistration,
48
+ ]
49
+ })
50
+ }
51
+
52
+ // When the Service Worker wasn't found, register it anew and return the reference.
53
+ const registrationResult = await until<Error, ServiceWorkerInstanceTuple>(
54
+ async () => {
55
+ const registration = await navigator.serviceWorker.register(url, options)
56
+ return [
57
+ // Compare existing worker registration by its worker URL,
58
+ // to prevent irrelevant workers to resolve here (such as Codesandbox worker).
59
+ getWorkerByRegistration(registration, absoluteWorkerUrl, findWorker),
60
+ registration,
61
+ ]
62
+ },
63
+ )
64
+
65
+ // Handle Service Worker registration errors.
66
+ if (registrationResult.error) {
67
+ const isWorkerMissing = registrationResult.error.message.includes('(404)')
68
+
69
+ // Produce a custom error message when given a non-existing Service Worker url.
70
+ // Suggest developers to check their setup.
71
+ if (isWorkerMissing) {
72
+ const scopeUrl = new URL(options?.scope || '/', location.href)
73
+
74
+ throw new Error(
75
+ devUtils.formatMessage(`\
76
+ Failed to register a Service Worker for scope ('${scopeUrl.href}') with script ('${absoluteWorkerUrl}'): Service Worker script does not exist at the given path.
77
+
78
+ Did you forget to run "npx msw init <PUBLIC_DIR>"?
79
+
80
+ Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init`),
81
+ )
82
+ }
83
+
84
+ // Fallback error message for any other registration errors.
85
+ throw new Error(
86
+ devUtils.formatMessage(
87
+ 'Failed to register the Service Worker:\n\n%s',
88
+ registrationResult.error.message,
89
+ ),
90
+ )
91
+ }
92
+
93
+ return registrationResult.data
94
+ }
@@ -0,0 +1,59 @@
1
+ import { SetupWorkerInternalContext, StartOptions } from '../../glossary'
2
+ import {
3
+ DEFAULT_START_OPTIONS,
4
+ resolveStartOptions,
5
+ prepareStartHandler,
6
+ } from './prepareStartHandler'
7
+
8
+ describe('resolveStartOptions', () => {
9
+ test('returns default options given no custom start options', () => {
10
+ expect(resolveStartOptions()).toEqual(DEFAULT_START_OPTIONS)
11
+ expect(resolveStartOptions(undefined)).toEqual(DEFAULT_START_OPTIONS)
12
+ expect(resolveStartOptions({})).toEqual(DEFAULT_START_OPTIONS)
13
+ })
14
+
15
+ test('deeply merges the default and custom start options', () => {
16
+ expect(
17
+ resolveStartOptions({
18
+ quiet: true,
19
+ serviceWorker: {
20
+ url: './custom.js',
21
+ },
22
+ }),
23
+ ).toEqual({
24
+ ...DEFAULT_START_OPTIONS,
25
+ quiet: true,
26
+ serviceWorker: {
27
+ url: './custom.js',
28
+ options: null,
29
+ },
30
+ })
31
+ })
32
+ })
33
+
34
+ describe('prepareStartHandler', () => {
35
+ test('exposes resolved start options to the generated star handler', () => {
36
+ const createStartHandler = vi.fn()
37
+ const context: SetupWorkerInternalContext = {} as any
38
+ const startHandler = prepareStartHandler(createStartHandler, context)
39
+ expect(startHandler).toBeInstanceOf(Function)
40
+
41
+ const initialOptions: StartOptions = {
42
+ quiet: true,
43
+ serviceWorker: {
44
+ url: './custom.js',
45
+ },
46
+ }
47
+ const resolvedOptions = resolveStartOptions(initialOptions)
48
+ startHandler(initialOptions)
49
+
50
+ // Calls the handler creator with both resolved and initial options.
51
+ expect(createStartHandler).toHaveBeenCalledWith(
52
+ resolvedOptions,
53
+ initialOptions,
54
+ )
55
+
56
+ // Sets the resolved options on the internal context.
57
+ expect(context).toHaveProperty('startOptions', resolvedOptions)
58
+ })
59
+ })
@@ -0,0 +1,44 @@
1
+ import { RequiredDeep } from '~/core/typeUtils'
2
+ import { mergeRight } from '~/core/utils/internal/mergeRight'
3
+ import {
4
+ SetupWorker,
5
+ SetupWorkerInternalContext,
6
+ StartHandler,
7
+ StartOptions,
8
+ } from '../../glossary'
9
+
10
+ export const DEFAULT_START_OPTIONS: RequiredDeep<StartOptions> = {
11
+ serviceWorker: {
12
+ url: '/mockServiceWorker.js',
13
+ options: null as any,
14
+ },
15
+ quiet: false,
16
+ waitUntilReady: true,
17
+ onUnhandledRequest: 'warn',
18
+ findWorker(scriptURL, mockServiceWorkerUrl) {
19
+ return scriptURL === mockServiceWorkerUrl
20
+ },
21
+ }
22
+
23
+ /**
24
+ * Returns resolved worker start options, merging the default options
25
+ * with the given custom options.
26
+ */
27
+ export function resolveStartOptions(
28
+ initialOptions?: StartOptions,
29
+ ): RequiredDeep<StartOptions> {
30
+ return mergeRight(
31
+ DEFAULT_START_OPTIONS,
32
+ initialOptions || {},
33
+ ) as RequiredDeep<StartOptions>
34
+ }
35
+
36
+ export function prepareStartHandler(
37
+ handler: StartHandler,
38
+ context: SetupWorkerInternalContext,
39
+ ): SetupWorker['start'] {
40
+ return (initialOptions) => {
41
+ context.startOptions = resolveStartOptions(initialOptions)
42
+ return handler(context.startOptions, initialOptions || {})
43
+ }
44
+ }
@@ -0,0 +1,84 @@
1
+ import { printStartMessage } from './printStartMessage'
2
+
3
+ beforeEach(() => {
4
+ vi.spyOn(console, 'groupCollapsed').mockImplementation(() => void 0)
5
+ vi.spyOn(console, 'log').mockImplementation(() => void 0)
6
+ })
7
+
8
+ afterEach(() => {
9
+ vi.restoreAllMocks()
10
+ })
11
+
12
+ test('prints out a default start message into console', () => {
13
+ printStartMessage({
14
+ workerScope: 'http://localhost:3000/',
15
+ workerUrl: 'http://localhost:3000/worker.js',
16
+ })
17
+
18
+ expect(console.groupCollapsed).toHaveBeenCalledWith(
19
+ '%c[MSW] Mocking enabled.',
20
+ expect.anything(),
21
+ )
22
+
23
+ // Includes a link to the documentation.
24
+ expect(console.log).toHaveBeenCalledWith(
25
+ '%cDocumentation: %chttps://mswjs.io/docs',
26
+ expect.anything(),
27
+ expect.anything(),
28
+ )
29
+
30
+ // Includes a link to the GitHub issues page.
31
+ expect(console.log).toHaveBeenCalledWith(
32
+ 'Found an issue? https://github.com/mswjs/msw/issues',
33
+ )
34
+
35
+ // Includes service worker scope.
36
+ expect(console.log).toHaveBeenCalledWith(
37
+ 'Worker scope:',
38
+ 'http://localhost:3000/',
39
+ )
40
+
41
+ // Includes service worker script location.
42
+ expect(console.log).toHaveBeenCalledWith(
43
+ 'Worker script URL:',
44
+ 'http://localhost:3000/worker.js',
45
+ )
46
+ })
47
+
48
+ test('supports printing a custom start message', () => {
49
+ printStartMessage({ message: 'Custom start message' })
50
+
51
+ expect(console.groupCollapsed).toHaveBeenCalledWith(
52
+ '%c[MSW] Custom start message',
53
+ expect.anything(),
54
+ )
55
+ })
56
+
57
+ test('does not print any messages when log level is quiet', () => {
58
+ printStartMessage({ quiet: true })
59
+
60
+ expect(console.groupCollapsed).not.toHaveBeenCalled()
61
+ expect(console.log).not.toHaveBeenCalled()
62
+ })
63
+
64
+ test('prints a worker scope in the start message', () => {
65
+ printStartMessage({
66
+ workerScope: 'http://localhost:3000/user',
67
+ })
68
+
69
+ expect(console.log).toHaveBeenCalledWith(
70
+ 'Worker scope:',
71
+ 'http://localhost:3000/user',
72
+ )
73
+ })
74
+
75
+ test('prints a worker script url in the start message', () => {
76
+ printStartMessage({
77
+ workerUrl: 'http://localhost:3000/mockServiceWorker.js',
78
+ })
79
+
80
+ expect(console.log).toHaveBeenCalledWith(
81
+ 'Worker script URL:',
82
+ 'http://localhost:3000/mockServiceWorker.js',
83
+ )
84
+ })
@@ -0,0 +1,40 @@
1
+ import { devUtils } from '~/core/utils/internal/devUtils'
2
+
3
+ export interface PrintStartMessageArgs {
4
+ quiet?: boolean
5
+ message?: string
6
+ workerUrl?: string
7
+ workerScope?: string
8
+ }
9
+
10
+ /**
11
+ * Prints a worker activation message in the browser's console.
12
+ */
13
+ export function printStartMessage(args: PrintStartMessageArgs = {}) {
14
+ if (args.quiet) {
15
+ return
16
+ }
17
+
18
+ const message = args.message || 'Mocking enabled.'
19
+
20
+ console.groupCollapsed(
21
+ `%c${devUtils.formatMessage(message)}`,
22
+ 'color:orangered;font-weight:bold;',
23
+ )
24
+ console.log(
25
+ '%cDocumentation: %chttps://mswjs.io/docs',
26
+ 'font-weight:bold',
27
+ 'font-weight:normal',
28
+ )
29
+ console.log('Found an issue? https://github.com/mswjs/msw/issues')
30
+
31
+ if (args.workerUrl) {
32
+ console.log('Worker script URL:', args.workerUrl)
33
+ }
34
+
35
+ if (args.workerScope) {
36
+ console.log('Worker scope:', args.workerScope)
37
+ }
38
+
39
+ console.groupEnd()
40
+ }
@@ -0,0 +1,18 @@
1
+ import { devUtils } from '~/core/utils/internal/devUtils'
2
+ import { StartOptions } from '../../glossary'
3
+
4
+ export function validateWorkerScope(
5
+ registration: ServiceWorkerRegistration,
6
+ options?: StartOptions,
7
+ ): void {
8
+ if (!options?.quiet && !location.href.startsWith(registration.scope)) {
9
+ devUtils.warn(
10
+ `\
11
+ Cannot intercept requests on this page because it's outside of the worker's scope ("${registration.scope}"). If you wish to mock API requests on this page, you must resolve this scope issue.
12
+
13
+ - (Recommended) Register the worker at the root level ("/") of your application.
14
+ - Set the "Service-Worker-Allowed" response header to allow out-of-scope workers.\
15
+ `,
16
+ )
17
+ }
18
+ }
@@ -0,0 +1,11 @@
1
+ import { SetupWorkerInternalContext, StopHandler } from '../glossary'
2
+ import { printStopMessage } from './utils/printStopMessage'
3
+
4
+ export function createFallbackStop(
5
+ context: SetupWorkerInternalContext,
6
+ ): StopHandler {
7
+ return function stop() {
8
+ context.fallbackInterceptor?.dispose()
9
+ printStopMessage({ quiet: context.startOptions?.quiet })
10
+ }
11
+ }
@@ -0,0 +1,29 @@
1
+ import { devUtils } from '~/core/utils/internal/devUtils'
2
+ import { SetupWorkerInternalContext, StopHandler } from '../glossary'
3
+ import { printStopMessage } from './utils/printStopMessage'
4
+
5
+ export const createStop = (
6
+ context: SetupWorkerInternalContext,
7
+ ): StopHandler => {
8
+ return function stop() {
9
+ // Warn developers calling "worker.stop()" more times than necessary.
10
+ // This likely indicates a mistake in their code.
11
+ if (!context.isMockingEnabled) {
12
+ devUtils.warn(
13
+ 'Found a redundant "worker.stop()" call. Note that stopping the worker while mocking already stopped has no effect. Consider removing this "worker.stop()" call.',
14
+ )
15
+ return
16
+ }
17
+
18
+ /**
19
+ * Signal the Service Worker to disable mocking for this client.
20
+ * Use this an an explicit way to stop the mocking, while preserving
21
+ * the worker-client relation. Does not affect the worker's lifecycle.
22
+ */
23
+ context.workerChannel.send('MOCK_DEACTIVATE')
24
+ context.isMockingEnabled = false
25
+ window.clearInterval(context.keepAliveInterval)
26
+
27
+ printStopMessage({ quiet: context.startOptions?.quiet })
28
+ }
29
+ }
@@ -0,0 +1,26 @@
1
+ import { printStopMessage } from './printStopMessage'
2
+
3
+ beforeAll(() => {
4
+ vi.spyOn(global.console, 'log').mockImplementation(() => void 0)
5
+ })
6
+
7
+ afterEach(() => {
8
+ vi.resetAllMocks()
9
+ })
10
+
11
+ afterAll(() => {
12
+ vi.restoreAllMocks()
13
+ })
14
+
15
+ test('prints a stop message to the console', () => {
16
+ printStopMessage()
17
+ expect(console.log).toHaveBeenCalledWith(
18
+ '%c[MSW] Mocking disabled.',
19
+ 'color:orangered;font-weight:bold;',
20
+ )
21
+ })
22
+
23
+ test('does not print any message when log level is quiet', () => {
24
+ printStopMessage({ quiet: true })
25
+ expect(console.log).not.toHaveBeenCalled()
26
+ })
@@ -0,0 +1,12 @@
1
+ import { devUtils } from '~/core/utils/internal/devUtils'
2
+
3
+ export function printStopMessage(args: { quiet?: boolean } = {}): void {
4
+ if (args.quiet) {
5
+ return
6
+ }
7
+
8
+ console.log(
9
+ `%c${devUtils.formatMessage('Mocking disabled.')}`,
10
+ 'color:orangered;font-weight:bold;',
11
+ )
12
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "./tsconfig.browser.json",
3
+ "compilerOptions": {
4
+ "composite": false
5
+ }
6
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../tsconfig.src.json",
3
+ "compilerOptions": {
4
+ // Expose browser-specific libraries only for the
5
+ // source code under the "src/browser" directory.
6
+ "lib": ["DOM", "WebWorker"]
7
+ },
8
+ "include": ["../../global.d.ts", "./global.browser.d.ts", "./**/*.ts"]
9
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+ import { deferNetworkRequestsUntil } from './deferNetworkRequestsUntil'
5
+
6
+ beforeAll(() => {
7
+ // Stubs native `fetch` function to remove any external
8
+ // asynchronicity from this test suite.
9
+ window.fetch = vi.fn().mockImplementation(() => {
10
+ return Promise.resolve({
11
+ json: () => ({
12
+ response: 'body',
13
+ }),
14
+ })
15
+ })
16
+ })
17
+
18
+ afterAll(() => {
19
+ vi.restoreAllMocks()
20
+ })
21
+
22
+ test('defers any requests that happen while a given promise is pending', async () => {
23
+ const events: string[] = []
24
+
25
+ // Emulate a Service Worker registration Promise.
26
+ const workerPromise = new Promise<null>((resolve) => {
27
+ setTimeout(resolve, 1000)
28
+ })
29
+
30
+ workerPromise.then(() => {
31
+ events.push('promise resolved')
32
+ })
33
+
34
+ // Calling this functions intercepts all requests that happen while
35
+ // the given promise is pending, and defers their execution
36
+ // until the promise is resolved.
37
+ deferNetworkRequestsUntil(workerPromise)
38
+
39
+ // Perform a request.
40
+ const requestPromise = fetch('/user').then(() => {
41
+ events.push('response received')
42
+ })
43
+
44
+ await Promise.all([workerPromise, requestPromise])
45
+
46
+ // Assert the order of resolved events.
47
+ expect(events).toEqual(['promise resolved', 'response received'])
48
+ })
@@ -0,0 +1,29 @@
1
+ import { until } from '@open-draft/until'
2
+
3
+ /**
4
+ * Intercepts and defers any requests on the page
5
+ * until the Service Worker instance is ready.
6
+ * Must only be used in a browser.
7
+ */
8
+ export function deferNetworkRequestsUntil(predicatePromise: Promise<any>) {
9
+ // Defer any `XMLHttpRequest` requests until the Service Worker is ready.
10
+ const originalXhrSend = window.XMLHttpRequest.prototype.send
11
+ window.XMLHttpRequest.prototype.send = function (
12
+ ...args: Parameters<XMLHttpRequest['send']>
13
+ ) {
14
+ // Keep this function synchronous to comply with `XMLHttpRequest.prototype.send`,
15
+ // because that method is always synchronous.
16
+ until(() => predicatePromise).then(() => {
17
+ window.XMLHttpRequest.prototype.send = originalXhrSend
18
+ this.send(...args)
19
+ })
20
+ }
21
+
22
+ // Defer any `fetch` requests until the Service Worker is ready.
23
+ const originalFetch = window.fetch
24
+ window.fetch = async (...args) => {
25
+ await until(() => predicatePromise)
26
+ window.fetch = originalFetch
27
+ return window.fetch(...args)
28
+ }
29
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+ import { getAbsoluteWorkerUrl } from './getAbsoluteWorkerUrl'
5
+
6
+ const rawLocation = window.location
7
+
8
+ afterAll(() => {
9
+ Object.defineProperty(window, 'location', {
10
+ value: rawLocation,
11
+ })
12
+ })
13
+
14
+ it('returns absolute worker url relatively to the root', () => {
15
+ expect(getAbsoluteWorkerUrl('./worker.js')).toBe('http://localhost/worker.js')
16
+ })
17
+
18
+ it('returns an absolute worker url relatively to the current path', () => {
19
+ Object.defineProperty(window, 'location', {
20
+ value: {
21
+ href: 'http://localhost/path/to/page',
22
+ },
23
+ })
24
+
25
+ expect(getAbsoluteWorkerUrl('./worker.js')).toBe(
26
+ 'http://localhost/path/to/worker.js',
27
+ )
28
+
29
+ // Leading slash must still resolve to the root.
30
+ expect(getAbsoluteWorkerUrl('/worker.js')).toBe('http://localhost/worker.js')
31
+ })
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Returns an absolute Service Worker URL based on the given
3
+ * relative URL (known during the registration).
4
+ */
5
+ export function getAbsoluteWorkerUrl(workerUrl: string): string {
6
+ return new URL(workerUrl, location.href).href
7
+ }
@@ -0,0 +1,15 @@
1
+ import { pruneGetRequestBody } from './pruneGetRequestBody'
2
+ import type { ServiceWorkerIncomingRequest } from '../setupWorker/glossary'
3
+
4
+ /**
5
+ * Converts a given request received from the Service Worker
6
+ * into a Fetch `Request` instance.
7
+ */
8
+ export function parseWorkerRequest(
9
+ incomingRequest: ServiceWorkerIncomingRequest,
10
+ ): Request {
11
+ return new Request(incomingRequest.url, {
12
+ ...incomingRequest,
13
+ body: pruneGetRequestBody(incomingRequest),
14
+ })
15
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+ import { TextEncoder } from 'util'
5
+ import { pruneGetRequestBody } from './pruneGetRequestBody'
6
+
7
+ test('sets empty GET request body to undefined', () => {
8
+ expect(
9
+ pruneGetRequestBody({
10
+ method: 'GET',
11
+ }),
12
+ ).toBeUndefined()
13
+
14
+ expect(
15
+ pruneGetRequestBody({
16
+ method: 'GET',
17
+ // There's no such thing as a GET request with a body.
18
+ body: new ArrayBuffer(5),
19
+ }),
20
+ ).toBeUndefined()
21
+ })
22
+
23
+ test('sets HEAD request body to undefined', () => {
24
+ expect(
25
+ pruneGetRequestBody({
26
+ method: 'HEAD',
27
+ }),
28
+ ).toBeUndefined()
29
+
30
+ expect(
31
+ pruneGetRequestBody({
32
+ method: 'HEAD',
33
+ body: new ArrayBuffer(5),
34
+ }),
35
+ ).toBeUndefined()
36
+ })
37
+
38
+ test('ignores requests of the other methods than GET', () => {
39
+ const body = new TextEncoder().encode('hello world')
40
+ expect(
41
+ pruneGetRequestBody({
42
+ method: 'POST',
43
+ body,
44
+ }),
45
+ ).toEqual(body)
46
+
47
+ expect(
48
+ pruneGetRequestBody({
49
+ method: 'PUT',
50
+ body,
51
+ }),
52
+ ).toEqual(body)
53
+ })
@@ -0,0 +1,21 @@
1
+ import type { ServiceWorkerIncomingRequest } from '../setupWorker/glossary'
2
+
3
+ type Input = Pick<ServiceWorkerIncomingRequest, 'method' | 'body'>
4
+
5
+ /**
6
+ * Ensures that an empty GET request body is always represented as `undefined`.
7
+ */
8
+ export function pruneGetRequestBody(
9
+ request: Input,
10
+ ): ServiceWorkerIncomingRequest['body'] {
11
+ // Force HEAD/GET request body to always be empty.
12
+ // The worker reads any request's body as ArrayBuffer,
13
+ // and you cannot re-construct a GET/HEAD Request
14
+ // with an ArrayBuffer, even if empty. Also note that
15
+ // "request.body" is always undefined in the worker.
16
+ if (['HEAD', 'GET'].includes(request.method)) {
17
+ return undefined
18
+ }
19
+
20
+ return request.body
21
+ }