@prosopo/procaptcha-puzzle 2.14.6 → 2.15.0

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 (47) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +5 -8
  2. package/.turbo/turbo-build$colon$tsc.log +19 -22
  3. package/.turbo/turbo-build.log +6 -12
  4. package/CHANGELOG.md +68 -0
  5. package/LICENSE +201 -0
  6. package/dist/cjs/components/procaptchaWidget.cjs +20 -5
  7. package/dist/cjs/components/puzzleCanvas.cjs +25 -4
  8. package/dist/cjs/services/Manager.cjs +18 -2
  9. package/dist/components/procaptchaWidget.d.ts.map +1 -1
  10. package/dist/components/procaptchaWidget.js +21 -6
  11. package/dist/components/procaptchaWidget.js.map +1 -1
  12. package/dist/components/puzzleCanvas.d.ts +2 -1
  13. package/dist/components/puzzleCanvas.d.ts.map +1 -1
  14. package/dist/components/puzzleCanvas.js +26 -5
  15. package/dist/components/puzzleCanvas.js.map +1 -1
  16. package/dist/services/Manager.d.ts +1 -0
  17. package/dist/services/Manager.d.ts.map +1 -1
  18. package/dist/services/Manager.js +18 -2
  19. package/dist/services/Manager.js.map +1 -1
  20. package/dist/tests/invisibleCanvasVisibility.unit.test.js +3 -1
  21. package/dist/tests/invisibleCanvasVisibility.unit.test.js.map +1 -1
  22. package/dist/tests/manager.unit.test.js +16 -0
  23. package/dist/tests/manager.unit.test.js.map +1 -1
  24. package/dist/tests/procaptchaPuzzle.test-d.js +1 -1
  25. package/dist/tests/procaptchaPuzzle.test-d.js.map +1 -1
  26. package/dist/tests/procaptchaWidget.unit.test.js +73 -0
  27. package/dist/tests/procaptchaWidget.unit.test.js.map +1 -1
  28. package/dist/tests/puzzleCanvas.unit.test.js +33 -0
  29. package/dist/tests/puzzleCanvas.unit.test.js.map +1 -1
  30. package/package.json +72 -71
  31. package/src/components/procaptchaPuzzle.ts +0 -54
  32. package/src/components/procaptchaWidget.ts +0 -422
  33. package/src/components/puzzleCanvas.ts +0 -658
  34. package/src/index.ts +0 -16
  35. package/src/services/Manager.ts +0 -508
  36. package/src/tests/domHarness.ts +0 -122
  37. package/src/tests/invisibleCanvasVisibility.unit.test.ts +0 -179
  38. package/src/tests/manager.unit.test.ts +0 -822
  39. package/src/tests/managerHarness.ts +0 -169
  40. package/src/tests/procaptchaPuzzle.test-d.ts +0 -212
  41. package/src/tests/procaptchaPuzzle.unit.test.ts +0 -138
  42. package/src/tests/procaptchaWidget.unit.test.ts +0 -765
  43. package/src/tests/puzzleCanvas.unit.test.ts +0 -662
  44. package/tsconfig.cjs.json +0 -43
  45. package/tsconfig.json +0 -44
  46. package/tsconfig.tsbuildinfo +0 -1
  47. package/tsconfig.types.json +0 -9
@@ -1,508 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { stringToHex } from "@polkadot/util/string";
16
- import { ProviderApi } from "@prosopo/api";
17
- import { ProsopoEnvError } from "@prosopo/common";
18
- import {
19
- ExtensionLoader,
20
- buildClientMetaData,
21
- buildUpdateState,
22
- getDefaultEvents,
23
- getProcaptchaRandomActiveProvider,
24
- getSimdReadingsForSubmit,
25
- pickIpMode,
26
- providerRetry,
27
- } from "@prosopo/procaptcha-common";
28
- import {
29
- type Account,
30
- ApiParams,
31
- CaptchaType,
32
- type FrictionlessState,
33
- type GetPuzzleCaptchaResponse,
34
- type ProcaptchaCallbacks,
35
- type ProcaptchaClientConfigInput,
36
- ProcaptchaConfigSchema,
37
- type ProcaptchaState,
38
- type ProcaptchaStateUpdateFn,
39
- type PuzzleEvent,
40
- encodeProcaptchaOutput,
41
- } from "@prosopo/types";
42
- import { embedData, sleep } from "@prosopo/util";
43
- import { randomAsHex } from "@prosopo/util-crypto";
44
-
45
- interface PuzzleManagerHandle {
46
- start: (
47
- x?: number,
48
- y?: number,
49
- ) => Promise<GetPuzzleCaptchaResponse | undefined>;
50
- submitSolution: (
51
- finalX: number,
52
- finalY: number,
53
- puzzleEvents: PuzzleEvent[],
54
- ) => Promise<boolean>;
55
- resetState: (frictionlessRestart?: () => void) => void;
56
- }
57
-
58
- export const Manager = (
59
- configInput: ProcaptchaClientConfigInput,
60
- state: ProcaptchaState,
61
- onStateUpdate: ProcaptchaStateUpdateFn,
62
- callbacks: ProcaptchaCallbacks,
63
- frictionlessState?: FrictionlessState,
64
- // Reads the live honeypot input value at submit time. Returns undefined
65
- // when the honeypot is disabled or the input hasn't been filled.
66
- getHoneypotValue?: () => string | undefined,
67
- ): PuzzleManagerHandle => {
68
- const events = getDefaultEvents(callbacks);
69
-
70
- // Closure variables to share state between start and submitSolution
71
- let storedChallengeResponse: GetPuzzleCaptchaResponse | undefined;
72
- let storedProviderApi: ProviderApi | undefined;
73
- let storedProviderUrl: string | undefined;
74
- let storedUser: Account | undefined;
75
- // Checkbox click coords, captured by start() and embedded into the
76
- // solution salt at submit time — same shape as the POW flow so the
77
- // provider records identical entry-point telemetry for both types.
78
- let storedClickX: number | undefined;
79
- let storedClickY: number | undefined;
80
-
81
- // URL of the provider used on the previous attempt. Kept outside the
82
- // resetState-cleared closure state so a retry can exclude it from the
83
- // candidate pool and land on a different provider.
84
- let previousProviderUrl: string | undefined;
85
- // The sessionId this manager has already exchanged for a challenge. The
86
- // provider consumes a session the moment it issues a challenge against it
87
- // (`checkAndRemoveSession`), so asking for a second challenge with the same
88
- // id is a guaranteed 400 CAPTCHA.NO_SESSION_FOUND. Mirrors the image
89
- // manager's guard: the id lives on `frictionlessState`, which `resetState()`
90
- // does not own, so every path that re-enters `start()` — a wrong answer, a
91
- // providerRetry after a late failure, a `procaptcha:execute` event — would
92
- // otherwise re-send it.
93
- let spentSessionId: string | undefined;
94
-
95
- const defaultState = (): Partial<ProcaptchaState> => {
96
- return {
97
- // note order matters! see buildUpdateState. These fields are set in order, so disable modal first, then set loading to false, etc.
98
- showModal: false,
99
- loading: false,
100
- index: 0,
101
- challenge: undefined,
102
- solutions: undefined,
103
- isHuman: false,
104
- captchaApi: undefined,
105
- account: undefined,
106
- // don't handle timeout here, this should be handled by the state management
107
- };
108
- };
109
-
110
- const clearTimeout = () => {
111
- // clear the timeout
112
- window.clearTimeout(Number(state.timeout));
113
- // then clear the timeout from the state
114
- updateState({ timeout: undefined });
115
- };
116
-
117
- const onFailed = () => {
118
- updateState({
119
- isHuman: false,
120
- loading: false,
121
- });
122
- events.onFailed();
123
- resetState(frictionlessState?.restart);
124
- };
125
-
126
- const clearSuccessfulChallengeTimeout = () => {
127
- // clear the timeout
128
- window.clearTimeout(Number(state.successfullChallengeTimeout));
129
- // then clear the timeout from the state
130
- updateState({ successfullChallengeTimeout: undefined });
131
- };
132
-
133
- const getConfig = () => {
134
- const config: ProcaptchaClientConfigInput = {
135
- userAccountAddress: configInput.userAccountAddress || "",
136
- ...configInput,
137
- };
138
-
139
- // overwrite the account in use with the one in state if it exists. Reduces likelihood of bugs where the user
140
- // changes account in the middle of the captcha process.
141
- if (state.account) {
142
- config.userAccountAddress = state.account.account.address;
143
- }
144
-
145
- return ProcaptchaConfigSchema.parse(config);
146
- };
147
-
148
- const getAccount = () => {
149
- if (!state.account) {
150
- throw new ProsopoEnvError("GENERAL.ACCOUNT_NOT_FOUND", {
151
- context: { error: "Account not loaded" },
152
- });
153
- }
154
- const account: Account = state.account;
155
- return { account };
156
- };
157
-
158
- const getDappAccount = () => {
159
- if (!state.dappAccount) {
160
- throw new ProsopoEnvError("GENERAL.SITE_KEY_MISSING");
161
- }
162
-
163
- const dappAccount: string = state.dappAccount;
164
- return dappAccount;
165
- };
166
-
167
- // get the state update mechanism
168
- const updateState = buildUpdateState(state, onStateUpdate);
169
-
170
- const resetState = (frictionlessRestart?: () => void) => {
171
- // clear timeout just in case a timer is still active (shouldn't be)
172
- clearTimeout();
173
- clearSuccessfulChallengeTimeout();
174
- updateState(defaultState());
175
- events.onReset();
176
- // reset the frictionless state if necessary
177
- if (frictionlessRestart) {
178
- frictionlessRestart();
179
- }
180
- // clear closure state
181
- storedChallengeResponse = undefined;
182
- storedProviderApi = undefined;
183
- storedProviderUrl = undefined;
184
- storedUser = undefined;
185
- storedClickX = undefined;
186
- storedClickY = undefined;
187
- };
188
-
189
- const setValidChallengeTimeout = () => {
190
- const timeMillis: number = getConfig().captchas.puzzle.solutionTimeout;
191
- const successfullChallengeTimeout = setTimeout(() => {
192
- // Human state expired, disallow user's claim to be human
193
- updateState({ isHuman: false });
194
-
195
- events.onExpired();
196
- resetState(frictionlessState?.restart);
197
- }, timeMillis);
198
-
199
- updateState({ successfullChallengeTimeout });
200
- };
201
-
202
- const start = async (
203
- x = 0,
204
- y = 0,
205
- ): Promise<GetPuzzleCaptchaResponse | undefined> => {
206
- await providerRetry(
207
- async () => {
208
- if (state.loading) {
209
- return;
210
- }
211
- if (state.isHuman) {
212
- return;
213
- }
214
-
215
- // reset the state to defaults - do not reset the frictionless state
216
- resetState();
217
-
218
- // Persist click coords on every entry so retries inherit the
219
- // trusted coordinates captured by the widget on initial click.
220
- // Set after the reset, which clears the closure state: setting
221
- // them before it meant the salt never carried the coordinates.
222
- storedClickX = x;
223
- storedClickY = y;
224
-
225
- // set the loading flag to true (allow UI to show some sort of loading / pending indicator while we get the captcha process going)
226
- updateState({
227
- loading: true,
228
- });
229
- updateState({ attemptCount: state.attemptCount + 1 });
230
-
231
- const config = getConfig();
232
-
233
- // check if account exists in extension
234
- const selectAccount = async () => {
235
- if (frictionlessState) {
236
- return frictionlessState.userAccount;
237
- }
238
- const ext = new (await ExtensionLoader(config.web2))();
239
- return ext.getAccount(config);
240
- };
241
-
242
- // use the passed in account (could be web3) or create a new account
243
- const user = await selectAccount();
244
- const userAccount = user.account.address;
245
-
246
- // set the account created or injected by the extension
247
- updateState({
248
- account: { account: { address: userAccount } },
249
- });
250
-
251
- // snapshot the config into the state
252
- updateState({ dappAccount: config.account.address });
253
-
254
- // allow UI to catch up with the loading state
255
- await sleep(100);
256
-
257
- // check if account has been provided in config (doesn't matter in web2 mode)
258
- if (!config.web2 && !config.userAccountAddress) {
259
- throw new ProsopoEnvError("GENERAL.ACCOUNT_NOT_FOUND", {
260
- context: {
261
- error: "Account address has not been set for web3 mode",
262
- },
263
- });
264
- }
265
-
266
- let getRandomProviderResponse = undefined;
267
-
268
- if (frictionlessState?.provider) {
269
- getRandomProviderResponse = frictionlessState.provider;
270
- } else {
271
- const currentConfig = getConfig();
272
- getRandomProviderResponse = await getProcaptchaRandomActiveProvider(
273
- currentConfig.defaultEnvironment,
274
- pickIpMode(currentConfig),
275
- { attempt: state.attemptCount, excludeUrl: previousProviderUrl },
276
- );
277
- }
278
-
279
- const providerUrl = getRandomProviderResponse.provider.url;
280
- previousProviderUrl = providerUrl;
281
-
282
- const providerApi = new ProviderApi(providerUrl, getDappAccount());
283
-
284
- // Short-circuit a challenge fetch we already know the provider
285
- // will reject, and route straight to the recovery path the
286
- // wrapper listens for — re-minting a session is the only way
287
- // forward, and the doomed round trip only delays it.
288
- const challengeSessionId = frictionlessState?.sessionId;
289
- if (challengeSessionId && challengeSessionId === spentSessionId) {
290
- updateState({
291
- loading: false,
292
- error: {
293
- message: "No session found",
294
- key: "CAPTCHA.NO_SESSION_FOUND",
295
- },
296
- });
297
- events.onError(new Error("No session found"));
298
- return;
299
- }
300
-
301
- // Non-blocking check — attach SIMD readings only if the
302
- // prefetched benchmark has already resolved.
303
- const simdReadingsOnChallenge = frictionlessState?.getSimdReadings
304
- ? await frictionlessState.getSimdReadings(0)
305
- : undefined;
306
- const challenge = await providerApi.getPuzzleCaptchaChallenge(
307
- userAccount,
308
- getDappAccount(),
309
- challengeSessionId,
310
- simdReadingsOnChallenge,
311
- );
312
- // The provider answered, so it has seen the id and consumed it —
313
- // a challenge and a 4xx mean the same thing here. Marked after
314
- // the await rather than before it on purpose: a throw is the one
315
- // case where the request may never have landed, and that is
316
- // exactly when `providerRetry` re-enters `start()` to fail over
317
- // onto a different provider. Marking it spent up front would
318
- // turn every transport blip into "No session found".
319
- if (challengeSessionId) spentSessionId = challengeSessionId;
320
-
321
- if (challenge.error) {
322
- updateState({
323
- loading: false,
324
- error: {
325
- message: challenge.error.message,
326
- key: challenge.error.key || "API.UNKNOWN_ERROR",
327
- },
328
- });
329
- return;
330
- }
331
-
332
- // Store closure state for submitSolution
333
- storedChallengeResponse = challenge;
334
- storedProviderApi = providerApi;
335
- storedProviderUrl = providerUrl;
336
- storedUser = user;
337
-
338
- // Set loading to false to signal the widget to show the puzzle canvas
339
- updateState({
340
- loading: false,
341
- });
342
- },
343
- async () => {
344
- // Carry the original coords into the retry: re-entering with the
345
- // defaults would replace the user's real click with (0, 0).
346
- await start(x, y);
347
- },
348
- () => {
349
- resetState();
350
- },
351
- state.attemptCount,
352
- 3,
353
- );
354
-
355
- // Return the stored challenge so retries (which re-enter `start`)
356
- // still surface the resolved challenge to the original caller.
357
- return storedChallengeResponse;
358
- };
359
-
360
- const submitSolution = async (
361
- finalX: number,
362
- finalY: number,
363
- puzzleEvents: PuzzleEvent[],
364
- ): Promise<boolean> => {
365
- if (
366
- !storedChallengeResponse ||
367
- !storedProviderApi ||
368
- !storedProviderUrl ||
369
- !storedUser
370
- ) {
371
- throw new ProsopoEnvError("GENERAL.ACCOUNT_NOT_FOUND", {
372
- context: { error: "No challenge data available. Call start() first." },
373
- });
374
- }
375
-
376
- updateState({ loading: true });
377
-
378
- try {
379
- const challenge = storedChallengeResponse;
380
- const providerApi = storedProviderApi;
381
- const providerUrl = storedProviderUrl;
382
- const user = storedUser;
383
- const config = getConfig();
384
-
385
- const signer = user.extension?.signer;
386
-
387
- if (!signer || !signer.signRaw) {
388
- throw new ProsopoEnvError("GENERAL.CANT_FIND_KEYRINGPAIR", {
389
- context: {
390
- error:
391
- "Signer is not defined, cannot sign message to prove account ownership",
392
- },
393
- });
394
- }
395
-
396
- const userTimestampSignature = await signer.signRaw({
397
- address: user.account.address,
398
- data: stringToHex(challenge[ApiParams.timestamp].toString()),
399
- type: "bytes",
400
- });
401
-
402
- let encryptedBehavioralData: string | undefined;
403
-
404
- // Collect and encrypt behavioral data before submission
405
- if (
406
- frictionlessState?.encryptBehavioralData &&
407
- (frictionlessState?.behaviorCollector1 ||
408
- frictionlessState?.behaviorCollector2 ||
409
- frictionlessState?.behaviorCollector3 ||
410
- frictionlessState?.behaviorCollector4)
411
- ) {
412
- try {
413
- const behavioralData = {
414
- collector1: frictionlessState.behaviorCollector1?.getData() || [],
415
- collector2: frictionlessState.behaviorCollector2?.getData() || [],
416
- collector3: frictionlessState.behaviorCollector3?.getData() || [],
417
- collector4: frictionlessState.behaviorCollector4?.getData() || [],
418
- deviceCapability: frictionlessState.deviceCapability || "unknown",
419
- };
420
-
421
- // Pack the behavioral data before stringifying
422
- const dataToEncrypt = frictionlessState.packBehavioralData
423
- ? frictionlessState.packBehavioralData(behavioralData)
424
- : behavioralData;
425
-
426
- encryptedBehavioralData =
427
- await frictionlessState.encryptBehavioralData(
428
- JSON.stringify(dataToEncrypt),
429
- );
430
- } catch {
431
- // Silently ignore behavioral data errors - captcha should still work
432
- }
433
- }
434
-
435
- // Encode the checkbox click coordinates into a random salt, same
436
- // shape as the POW flow. The provider decodes this on submit and
437
- // records the (x, y) on the puzzle captcha record for telemetry.
438
- let salt: string | undefined;
439
- if (storedClickX !== undefined && storedClickY !== undefined) {
440
- const coords = [storedClickX, storedClickY];
441
- const randomSalt = randomAsHex(
442
- coords
443
- .map((coord) => coord.toString(16).length + 4)
444
- .reduce((acc, curr) => acc + curr, 0),
445
- );
446
- salt = embedData(randomSalt, coords);
447
- }
448
-
449
- // Wait 5 secs for ongoing SIMD, else submit without
450
- const simdReadings = await getSimdReadingsForSubmit(frictionlessState);
451
- const clientMetaData = buildClientMetaData(
452
- getHoneypotValue?.(),
453
- getConfig().clientSessionId,
454
- );
455
- const verifiedSolution = await providerApi.submitPuzzleCaptchaSolution(
456
- challenge,
457
- getAccount().account.account.address,
458
- getDappAccount(),
459
- finalX,
460
- finalY,
461
- puzzleEvents,
462
- userTimestampSignature.signature.toString(),
463
- encryptedBehavioralData,
464
- salt,
465
- simdReadings,
466
- clientMetaData,
467
- );
468
-
469
- if (verifiedSolution[ApiParams.verified]) {
470
- updateState({
471
- isHuman: true,
472
- loading: false,
473
- });
474
-
475
- events.onHuman(
476
- encodeProcaptchaOutput({
477
- [ApiParams.providerUrl]: providerUrl,
478
- [ApiParams.user]: getAccount().account.account.address,
479
- [ApiParams.dapp]: getDappAccount(),
480
- [ApiParams.challenge]: challenge.challenge,
481
- [ApiParams.timestamp]: challenge.timestamp,
482
- [ApiParams.signature]: {
483
- [ApiParams.provider]: challenge.signature.provider,
484
- [ApiParams.user]: {
485
- [ApiParams.timestamp]:
486
- userTimestampSignature.signature.toString(),
487
- },
488
- },
489
- [ApiParams.captchaType]: CaptchaType.puzzle,
490
- }),
491
- );
492
- setValidChallengeTimeout();
493
- return true;
494
- }
495
- onFailed();
496
- return false;
497
- } catch (error) {
498
- updateState({ loading: false });
499
- throw error;
500
- }
501
- };
502
-
503
- return {
504
- start,
505
- submitSolution,
506
- resetState,
507
- };
508
- };
@@ -1,122 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- /**
16
- * A minimal mount/unmount harness. The suite deliberately drives real DOM
17
- * events rather than calling handlers directly, because every interactive
18
- * element in this package drops untrusted events — behaviour that only shows
19
- * up when a real event carries the flag.
20
- */
21
- export interface Mounted {
22
- container: HTMLDivElement;
23
- unmount: () => void;
24
- }
25
-
26
- export const mount = (): Mounted => {
27
- const container = document.createElement("div");
28
- document.body.appendChild(container);
29
- return {
30
- container,
31
- unmount: () => {
32
- container.remove();
33
- },
34
- };
35
- };
36
-
37
- interface FireOptions {
38
- trusted?: boolean;
39
- clientX?: number;
40
- clientY?: number;
41
- touches?: { clientX: number; clientY: number }[];
42
- key?: string;
43
- }
44
-
45
- /**
46
- * jsdom marks everything it dispatches untrusted, and exposes `isTrusted` as a
47
- * non-configurable accessor onto its internal implementation object, so the
48
- * flag has to be set there rather than shadowed on the event. Anything the
49
- * components filter on untrusted events is untestable otherwise.
50
- */
51
- const setTrusted = (event: Event, trusted: boolean): void => {
52
- for (const symbol of Object.getOwnPropertySymbols(event)) {
53
- const impl: unknown = Reflect.get(event, symbol);
54
- if (impl && typeof impl === "object" && "isTrusted" in impl) {
55
- // A plain assignment would not survive: dispatchEvent stamps
56
- // isTrusted back to false on the way in, so the flag is pinned with
57
- // an accessor that swallows the write.
58
- Object.defineProperty(impl, "isTrusted", {
59
- configurable: true,
60
- get: () => trusted,
61
- set: () => undefined,
62
- });
63
- return;
64
- }
65
- }
66
- throw new Error("could not reach the jsdom event implementation");
67
- };
68
-
69
- const build = (type: string, options: FireOptions): Event => {
70
- if (undefined !== options.key) {
71
- return new KeyboardEvent(type, {
72
- bubbles: true,
73
- cancelable: true,
74
- key: options.key,
75
- });
76
- }
77
- return new MouseEvent(type, {
78
- bubbles: true,
79
- cancelable: true,
80
- clientX: options.clientX ?? 0,
81
- clientY: options.clientY ?? 0,
82
- });
83
- };
84
-
85
- /**
86
- * Dispatches a real event at the element. Touch points are plain objects:
87
- * jsdom has no Touch constructor.
88
- */
89
- export const fire = (
90
- element: Element,
91
- type: string,
92
- options: FireOptions = {},
93
- ): void => {
94
- fireAndReturn(element, type, options);
95
- };
96
-
97
- /** Like `fire`, but hands back the event so a test can inspect what the
98
- * handler did to it — whether it prevented the default form submission, say. */
99
- export const fireAndReturn = (
100
- element: Element,
101
- type: string,
102
- options: FireOptions = {},
103
- ): Event => {
104
- const event = build(type, options);
105
- setTrusted(event, options.trusted ?? true);
106
- if (options.touches) {
107
- Object.defineProperty(event, "touches", { value: options.touches });
108
- }
109
- element.dispatchEvent(event);
110
- return event;
111
- };
112
-
113
- /**
114
- * Renders coalesce onto the microtask queue, so a state change is not visible
115
- * in the DOM until it has drained.
116
- */
117
- export const settle = async (): Promise<void> => {
118
- // A macrotask turn, so a pending dynamic import resolves too — draining the
119
- // microtask queue alone is not enough for the code-split boundaries.
120
- await new Promise<void>((resolve: () => void) => setTimeout(resolve, 0));
121
- await Promise.resolve();
122
- };