Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

previewNavigationReadiness.ts

74 lines2.4 KB

1import {
2 type PreviewAutomationNavigateInput,
3 type PreviewAutomationRequest,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6​
7import { isCurrentPreviewRuntimeTab } from "~/browser/previewRuntimeTabId";
8import { readThreadPreviewState } from "~/previewStateStore";
9​
10import { previewBridge } from "./previewBridge";
11import {
12 PreviewAutomationNavigationTimeoutError,
13 PreviewAutomationTargetUnavailableError,
14} from "./previewAutomationErrors";
15​
16export function assertPreviewRuntimeCurrent(
17 threadRef: ScopedThreadRef,
18 tabId: string,
19 runtimeTabId: string,
20 request: Pick<PreviewAutomationRequest, "operation" | "requestId">,
21) {
22 const state = readThreadPreviewState(threadRef);
23 if (
24 state.sessions[tabId] &&
25 isCurrentPreviewRuntimeTab(threadRef, state.serverEpoch, tabId, runtimeTabId)
26 ) {
27 return state;
28 }
29 throw new PreviewAutomationTargetUnavailableError({
30 requestId: request.requestId,
31 operation: request.operation,
32 environmentId: threadRef.environmentId,
33 threadId: threadRef.threadId,
34 tabId,
35 bridgeAvailable: Boolean(previewBridge),
36 });
38​
39export async function waitForNavigationReadiness(
40 threadRef: ScopedThreadRef,
41 requestId: string,
42 tabId: string,
43 runtimeTabId: string,
44 operation: PreviewAutomationRequest["operation"],
45 readiness: PreviewAutomationNavigateInput["readiness"],
46 timeoutMs: number,
47): Promise<void> {
48 const targetReadiness = readiness ?? "load";
49 if (!previewBridge) return;
50 assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
51 if (targetReadiness === "none") return;
52 const deadline = Date.now() + timeoutMs;
53 while (Date.now() <= deadline) {
54 assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
55 if (targetReadiness === "domContentLoaded") {
56 const readyState = await previewBridge.automation.evaluate(runtimeTabId, {
57 expression: "document.readyState",
58 });
59 if (readyState === "interactive" || readyState === "complete") return;
60 } else {
61 const status = await previewBridge.automation.status(runtimeTabId);
62 if (status.available && !status.loading) return;
63 }
64 await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
65 }
66 throw new PreviewAutomationNavigationTimeoutError({
67 requestId,
68 environmentId: threadRef.environmentId,
69 threadId: threadRef.threadId,
70 tabId,
71 readiness: targetReadiness,
72 timeoutMs,
73 });