File: file_service_worker_fetch_synthetic.js

package info (click to toggle)
thunderbird 1%3A143.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 4,703,968 kB
  • sloc: cpp: 7,770,492; javascript: 5,943,842; ansic: 3,918,754; python: 1,418,263; xml: 653,354; asm: 474,045; java: 183,079; sh: 111,238; makefile: 20,410; perl: 14,359; objc: 13,059; yacc: 4,583; pascal: 3,405; lex: 1,720; ruby: 999; exp: 762; sql: 715; awk: 580; php: 436; lisp: 430; sed: 69; csh: 10
file content (59 lines) | stat: -rw-r--r-- 2,078 bytes parent folder | download | duplicates (18)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
addEventListener("install", function (evt) {
  evt.waitUntil(self.skipWaiting());
});

/**
 * Given a multipart/form-data encoded string that we know to have only a single
 * part, return the contents of the part.  (MIME multipart encoding is too
 * exciting to delve into.)
 */
function extractBlobFromMultipartFormData(text) {
  const lines = text.split(/\r\n/g);
  const firstBlank = lines.indexOf("");
  const foo = lines.slice(firstBlank + 1, -2).join("\n");
  return foo;
}

self.addEventListener("fetch", event => {
  const url = new URL(event.request.url);
  const mode = url.searchParams.get("mode");

  if (mode === "synthetic") {
    event.respondWith(
      (async () => {
        // This works even if there wasn't a body explicitly associated with the
        // request.  We just get a zero-length string in that case.
        const requestBodyContents = await event.request.text();
        const blobContents =
          extractBlobFromMultipartFormData(requestBodyContents);

        return new Response(
          `<!DOCTYPE HTML><head><meta charset="utf-8"/></head><body>
          <h1 id="url">${event.request.url}</h1>
          <div id="source">ServiceWorker</div>
          <div id="blob">${blobContents}</div>
        </body>`,
          { headers: { "Content-Type": "text/html" } }
        );
      })()
    );
  } else if (mode === "fetch") {
    event.respondWith(fetch(event.request));
  } else if (mode === "clone") {
    // In order for the act of cloning to be interesting, we want the original
    // request to remain alive so that any pipes end up having to buffer.
    self.originalRequest = event.request;
    event.respondWith(fetch(event.request.clone()));
  } else {
    event.respondWith(
      new Response(
        `<!DOCTYPE HTML><head><meta charset="utf-8"/></head><body>
          <h1 id="error">Bad mode: ${mode}</h1>
          <div id="source">ServiceWorker::Error</div>
          <div id="blob">No, this is an error.</div>
        </body>`,
        { headers: { "Content-Type": "text/html" }, status: 400 }
      )
    );
  }
});