copyResponse.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2019 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { canConstructResponseFromBodyStream } from './_private/canConstructResponseFromBodyStream.js';
  8. import { WorkboxError } from './_private/WorkboxError.js';
  9. import './_version.js';
  10. /**
  11. * Allows developers to copy a response and modify its `headers`, `status`,
  12. * or `statusText` values (the values settable via a
  13. * [`ResponseInit`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#Syntax}
  14. * object in the constructor).
  15. * To modify these values, pass a function as the second argument. That
  16. * function will be invoked with a single object with the response properties
  17. * `{headers, status, statusText}`. The return value of this function will
  18. * be used as the `ResponseInit` for the new `Response`. To change the values
  19. * either modify the passed parameter(s) and return it, or return a totally
  20. * new object.
  21. *
  22. * This method is intentionally limited to same-origin responses, regardless of
  23. * whether CORS was used or not.
  24. *
  25. * @param {Response} response
  26. * @param {Function} modifier
  27. * @memberof workbox-core
  28. */
  29. async function copyResponse(response, modifier) {
  30. let origin = null;
  31. // If response.url isn't set, assume it's cross-origin and keep origin null.
  32. if (response.url) {
  33. const responseURL = new URL(response.url);
  34. origin = responseURL.origin;
  35. }
  36. if (origin !== self.location.origin) {
  37. throw new WorkboxError('cross-origin-copy-response', { origin });
  38. }
  39. const clonedResponse = response.clone();
  40. // Create a fresh `ResponseInit` object by cloning the headers.
  41. const responseInit = {
  42. headers: new Headers(clonedResponse.headers),
  43. status: clonedResponse.status,
  44. statusText: clonedResponse.statusText,
  45. };
  46. // Apply any user modifications.
  47. const modifiedResponseInit = modifier ? modifier(responseInit) : responseInit;
  48. // Create the new response from the body stream and `ResponseInit`
  49. // modifications. Note: not all browsers support the Response.body stream,
  50. // so fall back to reading the entire body into memory as a blob.
  51. const body = canConstructResponseFromBodyStream()
  52. ? clonedResponse.body
  53. : await clonedResponse.blob();
  54. return new Response(body, modifiedResponseInit);
  55. }
  56. export { copyResponse };