Skip to content

Commit 578e29e

Browse files
committed
[core] fix download postmessage logic
1 parent 2bb53b8 commit 578e29e

File tree

4 files changed

+23
-9
lines changed

4 files changed

+23
-9
lines changed

src/client/events.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export class ScramjetGlobalDownloadEvent extends Event {
55
type = "download";
66
constructor(
77
public filename: string,
8-
public body: ArrayBuffer
8+
public body: ReadableStream<Uint8Array>
99
) {
1010
super("download");
1111
}

src/controller/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { ScramjetFrame } from "@/controller/frame";
1010
import { MessageW2C } from "@/worker";
1111
import {
1212
ScramjetEvents,
13+
ScramjetGlobalDownloadEvent,
1314
ScramjetGlobalEvent,
1415
ScramjetGlobalEvents,
1516
} from "@client/events";
@@ -94,11 +95,14 @@ export class ScramjetController extends EventTarget {
9495
});
9596
dbg.log("config loaded");
9697

97-
serviceWorker.addEventListener("message", (e) => {
98+
navigator.serviceWorker.addEventListener("message", (e) => {
9899
if (!("scramjet$type" in e.data)) return;
99100
const data: MessageW2C = e.data;
100101

101102
if (data.scramjet$type === "download") {
103+
this.dispatchEvent(
104+
new ScramjetGlobalDownloadEvent(data.filename, data.body)
105+
);
102106
}
103107
});
104108
}

src/worker/fetch.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -479,14 +479,25 @@ async function handleResponse(
479479
}
480480
}
481481

482-
const ab = await response.arrayBuffer();
483-
client.postMessage(
482+
// there's no reliable way of finding the top level client that made the request
483+
// just take the first one and hope
484+
let clis = await clients.matchAll({
485+
type: "window",
486+
});
487+
// only want controller windows
488+
clis = clis.filter((e) => !e.url.includes(config.prefix));
489+
if (clis.length < 1) {
490+
throw Error(
491+
"couldn't find a controller client to dispatch download to"
492+
);
493+
}
494+
clis[0].postMessage(
484495
{
485496
scramjet$type: "download",
486497
filename,
487-
body: ab,
498+
body: response.body,
488499
} as MessageW2C,
489-
[ab]
500+
[response.body]
490501
);
491502

492503
// endless vortex reference

src/worker/index.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -161,12 +161,11 @@ type ConfigMessage = {
161161
};
162162

163163
type DownloadMessage = {
164-
$scramjet$type: "download";
164+
scramjet$type: "download";
165165
filename: string;
166-
body: ArrayBuffer;
166+
body: ReadableStream<Uint8Array>;
167167
};
168168
type MessageCommon = {
169-
scramjet$type: string;
170169
scramjet$token?: number;
171170
};
172171

0 commit comments

Comments
 (0)