Bodies.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/PromiseCapability.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/Fetch/BodyInit.h>
  9. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  10. #include <LibWeb/WebIDL/Promise.h>
  11. namespace Web::Fetch::Infrastructure {
  12. Body::Body(JS::Handle<Streams::ReadableStream> stream)
  13. : m_stream(move(stream))
  14. {
  15. }
  16. Body::Body(JS::Handle<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
  17. : m_stream(move(stream))
  18. , m_source(move(source))
  19. , m_length(move(length))
  20. {
  21. }
  22. // https://fetch.spec.whatwg.org/#concept-body-clone
  23. WebIDL::ExceptionOr<Body> Body::clone() const
  24. {
  25. // To clone a body body, run these steps:
  26. auto& vm = Bindings::main_thread_vm();
  27. auto& realm = *vm.current_realm();
  28. // FIXME: 1. Let « out1, out2 » be the result of teeing body’s stream.
  29. // FIXME: 2. Set body’s stream to out1.
  30. auto* out2 = vm.heap().allocate<Streams::ReadableStream>(realm, realm);
  31. // 3. Return a body whose stream is out2 and other members are copied from body.
  32. return Body { JS::make_handle(out2), m_source, m_length };
  33. }
  34. // https://fetch.spec.whatwg.org/#fully-reading-body-as-promise
  35. JS::NonnullGCPtr<JS::PromiseCapability> Body::fully_read_as_promise() const
  36. {
  37. auto& vm = Bindings::main_thread_vm();
  38. auto& realm = *vm.current_realm();
  39. // FIXME: Implement the streams spec - this is completely made up for now :^)
  40. if (auto const* byte_buffer = m_source.get_pointer<ByteBuffer>()) {
  41. auto result = String::copy(*byte_buffer);
  42. return WebIDL::create_resolved_promise(realm, JS::js_string(vm, move(result)));
  43. }
  44. // Empty, Blob, FormData
  45. return WebIDL::create_rejected_promise(realm, JS::InternalError::create(realm, "Reading body isn't fully implemented"sv));
  46. }
  47. // https://fetch.spec.whatwg.org/#byte-sequence-as-a-body
  48. WebIDL::ExceptionOr<Body> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes)
  49. {
  50. // To get a byte sequence bytes as a body, return the body of the result of safely extracting bytes.
  51. auto [body, _] = TRY(safely_extract_body(realm, bytes));
  52. return body;
  53. }
  54. }