@ehven/messaging-form-adapter-astro 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/mount.mjs +26 -19
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ehven/messaging-form-adapter-astro",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Astro components for the portable Ehven messaging form.",
package/src/mount.mjs CHANGED
@@ -1,36 +1,43 @@
1
1
  import { enhanceMessagingForm } from '@ehven/messaging-form-core/browser';
2
2
 
3
3
  const scriptUrl = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
4
+ const onloadName = 'ehvenMessagingFormTurnstileLoaded';
4
5
  const forms = new Map();
5
6
  let loader;
6
7
 
7
8
  function loadTurnstile() {
8
9
  loader ??= new Promise((resolve, reject) => {
9
- const timeout = setTimeout(() => reject(new Error('Turnstile took too long to initialize.')), 15_000);
10
- function ready() {
11
- const api = window.turnstile;
12
- if (typeof api?.ready !== 'function') {
13
- failed();
14
- return;
15
- }
16
- api.ready(() => {
17
- clearTimeout(timeout);
18
- resolve(api);
19
- });
10
+ if (typeof window.turnstile?.render === 'function') {
11
+ resolve(window.turnstile);
12
+ return;
20
13
  }
21
- function failed() {
14
+
15
+ function cleanup() {
22
16
  clearTimeout(timeout);
23
- reject(new Error('Turnstile could not load.'));
17
+ if (window[onloadName] === loaded) delete window[onloadName];
24
18
  }
25
- if (window.turnstile) {
26
- ready();
27
- return;
19
+
20
+ function fail(message) {
21
+ cleanup();
22
+ reject(new Error(message));
28
23
  }
24
+
25
+ function loaded() {
26
+ const api = window.turnstile;
27
+ if (typeof api?.render !== 'function') {
28
+ fail('Turnstile could not load.');
29
+ return;
30
+ }
31
+ cleanup();
32
+ resolve(api);
33
+ }
34
+
35
+ const timeout = setTimeout(() => fail('Turnstile took too long to initialize.'), 15_000);
36
+ window[onloadName] = loaded;
29
37
  const script = document.createElement('script');
30
- script.src = scriptUrl;
38
+ script.src = `${scriptUrl}&onload=${onloadName}`;
31
39
  script.async = true;
32
- script.addEventListener('load', ready, { once: true });
33
- script.addEventListener('error', failed, { once: true });
40
+ script.addEventListener('error', () => fail('Turnstile could not load.'), { once: true });
34
41
  document.head.append(script);
35
42
  });
36
43
  return loader;