Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

10.0 KB
Raw Blame
<!doctype html>
<meta charset="utf-8">
<script src="/wpt/resources/testharness.js"></script>
<script src="/wpt/resources/testharnessreport.js"></script>
<script src="/wpt/resources/moli-wpt-adapter.js"></script>
<script>
const ECHO_BODY_URL = "/wpt/runtime/xhr/echo-body";

function byteLength(value) {
  return new TextEncoder().encode(value).length;
}

function uploadCompletionEvents(size) {
  return [
    `loadstart:true:true:true:0:${size}`,
    `progress:true:true:true:${size}:${size}`,
    `load:true:true:true:${size}:${size}`,
    `loadend:true:true:true:${size}:${size}`,
  ];
}

function send_upload_case(sendMode, payload) {
  const xhr = new XMLHttpRequest();
  const uploadEvents = [];
  const uploadOrder = [];
  const xhrEvents = [];

  ["loadstart", "progress", "load", "loadend"].forEach(function (type) {
    xhr.upload.addEventListener(type, function (event) {
      uploadOrder.push("listener-before:" + event.type);
    });
    xhr.upload["on" + type] = function (event) {
      uploadOrder.push("handler:" + event.type);
    };
    xhr.upload.addEventListener(type, function (event) {
      uploadEvents.push(
        [
          event.type,
          event.target === xhr.upload,
          event.currentTarget === xhr.upload,
          event.lengthComputable,
          event.loaded,
          event.total,
        ].join(":"),
      );
      uploadOrder.push("listener-after:" + event.type);
    });
  });
  const errorHandlerObject = {};
  xhr.upload.onerror = errorHandlerObject;

  return new Promise(function (resolve, reject) {
    xhr.onload = function () {
      xhrEvents.push("load");
    };
    xhr.onloadend = function () {
      xhrEvents.push("loadend");
      resolve({ xhr, uploadEvents, uploadOrder, xhrEvents, errorHandlerObject });
    };
    xhr.onerror = function () {
      reject(new Error("XMLHttpRequest failed"));
    };
    xhr.open("POST", ECHO_BODY_URL);
    xhr.responseType = "json";
    if (sendMode === "payload") {
      xhr.setRequestHeader("Content-Type", "text/plain;charset=utf-8");
      xhr.send(payload);
    } else if (sendMode === "blob") {
      xhr.send(new Blob(["blob-upload"], { type: "text/plain" }));
    } else if (sendMode === "buffer") {
      xhr.send(new Uint8Array([65, 66, 67, 0, 68]));
    } else if (sendMode === "formdata") {
      const data = new FormData();
      data.append("alpha", "one");
      data.append("file", new Blob(["blob-body"], { type: "text/plain" }));
      xhr.send(data);
    } else if (sendMode === "none") {
      xhr.send();
    } else if (sendMode === "null") {
      xhr.send(null);
    } else if (sendMode === "empty-string") {
      xhr.send("");
    } else {
      reject(new Error("unknown send mode: " + sendMode));
    }
  });
}

function abort_from_upload_event_case(abortEventType) {
  const xhr = new XMLHttpRequest();
  const uploadEvents = [];
  const xhrEvents = [];

  ["loadstart", "progress", "load", "abort", "loadend"].forEach(function (type) {
    xhr.upload.addEventListener(type, function (event) {
      uploadEvents.push(
        [
          event.type,
          event.target === xhr.upload,
          event.currentTarget === xhr.upload,
          event.lengthComputable,
          event.loaded,
          event.total,
        ].join(":"),
      );
      if (event.type === abortEventType) {
        xhr.abort();
      }
    });
  });

  return new Promise(function (resolve, reject) {
    xhr.onabort = function () {
      xhrEvents.push("abort");
    };
    xhr.onload = function () {
      xhrEvents.push("load");
    };
    xhr.onerror = function () {
      reject(new Error("XMLHttpRequest should not fail after abort()"));
    };
    xhr.onloadend = function () {
      xhrEvents.push("loadend");
      resolve({ xhr, uploadEvents, xhrEvents });
    };
    xhr.open("POST", ECHO_BODY_URL);
    xhr.responseType = "json";
    xhr.send("abort=upload");
  });
}

promise_test(async function () {
  const payload = "upload=alpha&count=2";
  const result = await send_upload_case("payload", payload);

  assert_array_equals(
    result.uploadEvents,
    [
      "loadstart:true:true:true:0:20",
      "progress:true:true:true:20:20",
      "load:true:true:true:20:20",
      "loadend:true:true:true:20:20",
    ],
    "upload should emit loadstart/progress/load/loadend against xhr.upload",
  );
  assert_array_equals(
    result.uploadOrder,
    [
      "listener-before:loadstart",
      "handler:loadstart",
      "listener-after:loadstart",
      "listener-before:progress",
      "handler:progress",
      "listener-after:progress",
      "listener-before:load",
      "handler:load",
      "listener-after:load",
      "listener-before:loadend",
      "handler:loadend",
      "listener-after:loadend",
    ],
    "upload event handler attributes should participate in listener registration order",
  );
  assert_array_equals(result.xhrEvents, ["load", "loadend"], "XHR should still complete normally");
  assert_equals(result.xhr.status, 200, "upload POST status");
  assert_equals(result.xhr.response.body, payload, "upload POST should still send the body");
  assert_equals(result.xhr.upload.onerror, result.errorHandlerObject, "object upload event handler should retain its identity");
  result.xhr.upload.onerror = 42;
  assert_equals(result.xhr.upload.onerror, null, "primitive upload event handler should store null");
  assert_array_equals(
    Object.getOwnPropertyNames(result.xhr.upload),
    [],
    "upload event handler storage should stay off the own-property surface",
  );
}, "XMLHttpRequestUpload emits progress completion events for request bodies");

promise_test(async function () {
  const blob = await send_upload_case("blob");
  assert_array_equals(
    blob.uploadEvents,
    uploadCompletionEvents(byteLength("blob-upload")),
    "Blob request bodies should dispatch upload completion events with byte totals",
  );
  assert_equals(blob.xhr.response.body, "blob-upload", "Blob upload body should be sent");

  const buffer = await send_upload_case("buffer");
  assert_array_equals(
    buffer.uploadEvents,
    uploadCompletionEvents(5),
    "BufferSource request bodies should dispatch upload completion events with byte totals",
  );
  assert_equals(buffer.xhr.response.body, "ABC\u0000D", "BufferSource upload body should be sent");

  const formdata = await send_upload_case("formdata");
  assert_equals(formdata.xhr.status, 200, "FormData upload POST status");
  assert_array_equals(
    formdata.uploadEvents,
    uploadCompletionEvents(byteLength(formdata.xhr.response.body)),
    "FormData request bodies should dispatch upload completion events with multipart byte totals",
  );
  assert_true(
    formdata.xhr.response.body.includes('Content-Disposition: form-data; name="alpha"'),
    "FormData upload body should include string fields",
  );
  assert_true(
    formdata.xhr.response.body.includes('Content-Disposition: form-data; name="file"; filename="blob"'),
    "FormData upload body should include Blob file parts",
  );
}, "XMLHttpRequestUpload emits completion events for Blob, BufferSource, and FormData bodies");

promise_test(async function () {
  const noArgument = await send_upload_case("none");
  assert_array_equals(
    noArgument.uploadEvents,
    [],
    "send() without an argument should not dispatch upload events",
  );
  assert_equals(noArgument.xhr.status, 200, "send() without an argument should complete");
  assert_equals(noArgument.xhr.response.body, "", "send() without an argument should send no body");

  const nullBody = await send_upload_case("null");
  assert_array_equals(
    nullBody.uploadEvents,
    [],
    "send(null) should not dispatch upload events",
  );
  assert_equals(nullBody.xhr.status, 200, "send(null) should complete");
  assert_equals(nullBody.xhr.response.body, "", "send(null) should send no body");
}, "XMLHttpRequestUpload does not dispatch upload events when no request body is supplied");

promise_test(async function () {
  const result = await send_upload_case("empty-string");

  assert_array_equals(
    result.uploadEvents,
    [
      "loadstart:true:true:false:0:0",
      "progress:true:true:false:0:0",
      "load:true:true:false:0:0",
      "loadend:true:true:false:0:0",
    ],
    "send(\"\") should dispatch upload completion events with zero-byte totals",
  );
  assert_array_equals(result.xhrEvents, ["load", "loadend"], "empty upload XHR should complete");
  assert_equals(result.xhr.status, 200, "empty upload POST status");
  assert_equals(result.xhr.response.body, "", "empty string body should be sent as a zero-byte body");
}, "XMLHttpRequestUpload dispatches zero-byte upload events for an empty string request body");

promise_test(async function () {
  const result = await abort_from_upload_event_case("loadstart");

  assert_array_equals(
    result.uploadEvents,
    [
      "loadstart:true:true:true:0:12",
      "abort:true:true:false:0:0",
      "loadend:true:true:false:0:0",
    ],
    "aborting from upload loadstart should stop upload completion and emit upload abort/loadend",
  );
  assert_array_equals(
    result.xhrEvents,
    ["abort", "loadend"],
    "aborting from upload loadstart should terminate the XHR without load/error",
  );
  assert_equals(result.xhr.readyState, XMLHttpRequest.UNSENT, "abort resets readyState");
  assert_equals(result.xhr.status, 0, "abort resets status");
}, "XMLHttpRequestUpload aborts cleanly when abort() is called during upload loadstart");

promise_test(async function () {
  const result = await abort_from_upload_event_case("progress");

  assert_array_equals(
    result.uploadEvents,
    [
      "loadstart:true:true:true:0:12",
      "progress:true:true:true:12:12",
      "abort:true:true:false:0:0",
      "loadend:true:true:false:0:0",
    ],
    "aborting from upload progress should stop upload completion and emit upload abort/loadend",
  );
  assert_array_equals(
    result.xhrEvents,
    ["abort", "loadend"],
    "aborting from upload progress should terminate the XHR without load/error",
  );
  assert_equals(result.xhr.readyState, XMLHttpRequest.UNSENT, "abort resets readyState");
  assert_equals(result.xhr.status, 0, "abort resets status");
}, "XMLHttpRequestUpload aborts cleanly when abort() is called during upload progress");
</script>