Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix supervisor onLoaded race condition and reduce burden on apps #960

Merged
merged 2 commits into from
Dec 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class Supervisor {
);
}

private onLoadPromise?: (value?: unknown) => void;
private onLoadPromiseResolvers: ((value?: unknown) => void)[] = [];

constructor(public options?: Options) {
this.supervisorSrc =
Expand All @@ -69,13 +69,13 @@ export class Supervisor {
setupSupervisorIFrame(this.supervisorSrc);
}

listenToRawMessages() {
private listenToRawMessages() {
window.addEventListener("message", (event) =>
this.handleRawEvent(event),
);
}

handleRawEvent(messageEvent: MessageEvent) {
private handleRawEvent(messageEvent: MessageEvent) {
if (
messageEvent.origin !== myOrigin &&
messageEvent.origin !== this.supervisorSrc
Expand Down Expand Up @@ -106,14 +106,12 @@ export class Supervisor {
}
}

onSupervisorInitialized() {
private onSupervisorInitialized() {
this.isSupervisorInitialized = true;
if (this.onLoadPromise) {
this.onLoadPromise();
}
this.onLoadPromiseResolvers.forEach((resolver) => resolver());
}

onFunctionCallResponse(response: FunctionCallResponse) {
private onFunctionCallResponse(response: FunctionCallResponse) {
const pendingRequest = this.pendingRequests.find(
(req) => req.id === response.id,
);
Expand Down Expand Up @@ -171,7 +169,8 @@ export class Supervisor {
return iframe;
}

functionCall(args: FunctionCallArgs) {
public async functionCall(args: FunctionCallArgs) {
await this.onLoaded();
const iframe = this.getSupervisorIframe();

const fqArgs: QualifiedFunctionCallArgs = {
Expand Down Expand Up @@ -201,14 +200,15 @@ export class Supervisor {
});
}

async onLoaded() {
public async onLoaded() {
if (this.isSupervisorInitialized) return;
return new Promise((resolve) => {
this.onLoadPromise = resolve;
this.onLoadPromiseResolvers.push(resolve);
});
}

preLoadPlugins(plugins: PluginId[]) {
public async preLoadPlugins(plugins: PluginId[]) {
await this.onLoaded();
// Fully qualify any plugins with default values
const fqPlugins: QualifiedPluginId[] = plugins.map((plugin) => ({
...plugin,
Expand Down
Loading