complete_length_worker.js (2013B)
1 "use strict"; 2 3 let client; 4 function is(got, expected, name) { 5 client.postMessage({ type: "is", got, expected, name }); 6 } 7 8 self.onactivate = e => 9 e.waitUntil( 10 (async () => { 11 await self.clients.claim(); 12 const allClients = await self.clients.matchAll(); 13 client = allClients[0]; 14 is(allClients.length, 1, "allClients.length"); 15 })() 16 ); 17 18 let expected_start = 0; 19 let response_data = [ 20 // One Array element for each response in order: 21 { 22 complete_length: "*", 23 body: "O", 24 }, 25 { 26 complete_length: "3", 27 body: "g", 28 }, 29 { 30 // Extend length to test that the remainder is fetched. 31 complete_length: "6", 32 body: "g", 33 }, 34 { 35 // Reduce length to test that no more is fetched. 36 complete_length: "4", 37 body: "S", 38 }, 39 ]; 40 41 self.onfetch = e => { 42 if (!e.request.url.endsWith("/media-resource")) { 43 return; // fall back to network fetch 44 } 45 is( 46 response_data.length >= 1, 47 true, 48 `response_data.length (${response_data.length}) > 0` 49 ); 50 const { complete_length, body } = response_data.shift(); 51 const range = e.request.headers.get("Range"); 52 const match = range.match(/^bytes=(\d+)-/); 53 is(Array.isArray(match), true, `Array.isArray(match) for ${range}`); 54 const first = parseInt(match[1]); 55 is(first, expected_start, "first"); 56 const last = first + body.length - 1; // inclusive 57 expected_start = last + 1; 58 const init = { 59 status: 206, // Partial Content 60 headers: { 61 "Accept-Ranges": "bytes", 62 "Content-Type": "audio/ogg", 63 "Content-Range": `bytes ${first}-${last}/${complete_length}`, 64 "Content-Length": body.length, 65 }, 66 }; 67 e.respondWith(new Response(body, init)); 68 }; 69 70 self.onmessage = e => { 71 switch (e.data.type) { 72 case "got error event": 73 // Check that all expected requests were received. 74 is(response_data.length, 0, "missing fetch count"); 75 client.postMessage({ type: "done" }); 76 return; 77 default: 78 is(e.data.type, "__KNOWN__", "e.data.type"); 79 } 80 };