-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathrun-once.ts
35 lines (32 loc) · 1.2 KB
/
run-once.ts
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
import { invokeClerkAstroJSFunctions } from './invoke-clerk-astro-js-functions';
import { mountAllClerkAstroJSComponents } from './mount-clerk-astro-js-components';
import type { CreateClerkInstanceInternalFn } from './types';
/**
* Prevents mounting components multiple times when the `createClerkInstanceInternal` was been called twice without await first
* This is useful as the "integration" may call the function twice at the same time.
*/
const runOnce = (onFirst: CreateClerkInstanceInternalFn) => {
let hasRun = false;
return (params: Parameters<CreateClerkInstanceInternalFn>[0]) => {
if (hasRun) {
const clerkJSInstance = window.Clerk;
return new Promise(res => {
if (!clerkJSInstance) {
return res(false);
}
if (clerkJSInstance.loaded) {
mountAllClerkAstroJSComponents();
invokeClerkAstroJSFunctions();
}
return res(clerkJSInstance.loaded);
});
}
/**
* Probably html streaming has delayed the component from mounting immediately.
* In Astro, js modules will start executing only after html streaming has ended.
*/
hasRun = true;
return onFirst(params);
};
};
export { runOnce };