Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
7.5 kB · 229 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230import { useEffect, useRef, useState } from "octane";import { Button } from "octane-kumo/components/button";import { LayerCard } from "octane-kumo/components/layer-card";
import { usePublisherSession } from "./PublisherQueryProvider";import { useInstallationQuery } from "./queries/use-installation-query";import { useProviderQuery } from "./queries/use-provider-query";import type { usePublisherIdentityQuery } from "./queries/use-publisher-identity-query";import { PublisherReadError } from "./publisher-request";
type State = "loading" | "confirm" | "provisioning" | "error" | "reconnect" | "success";
function safeMessage(status: number, code: unknown) { if (status === 403) return "You do not have permission to manage this installation."; if (status === 404) return "This installation could not be found. Check the setup link and try again."; if (status === 503 && code === "resource_conflict") return "OpenRouter setup conflicts with an existing Cloudflare resource. Resolve the conflicting resource, then retry."; if (status === 503 && code === "setup_required") return "This installation needs setup or an upgrade before OpenRouter can be enabled."; return "OpenRouter setup is temporarily unavailable. Try again.";}
async function responseJson( response: Response,): Promise<Record<string, unknown>> { try { const value = await response.json(); return typeof value === "object" && value !== null ? value : {}; } catch { return {}; }}
export function ProviderSetup({ installationId, identity,}: { installationId: string; identity: ReturnType<typeof usePublisherIdentityQuery>;}) { const [commandState, setState] = useState<State | null>(null); const [commandError, setError] = useState(""); const cache = usePublisherSession(); const epoch = cache.getSnapshot().epoch; const installation = useInstallationQuery({ id: installationId }); const query = useProviderQuery( installationId, installation.data?.installation.accountId ?? "", commandState !== "provisioning" && commandState !== "success", ); const details = query.data ?? null; const readError = identity.error ?? installation.error ?? query.error; const state: State = commandState ?? (cache.getSnapshot().signedOut || (readError instanceof PublisherReadError && readError.status === 401) ? "reconnect" : details ? "confirm" : readError ? "error" : "loading"); const error = commandError || (readError && state !== "reconnect" ? safeMessage( readError instanceof PublisherReadError ? readError.status : 0, readError instanceof PublisherReadError ? readError.code : null, ) : ""); const generation = useRef(0); const endpoint = `/api/installations/${installationId}/providers/openrouter`;
const load = () => { setState(null); setError(""); if (!cache.getSnapshot().ownerSubject) void identity.refetch(); else { if (!installation.data || installation.error) void installation.refetch(); if (installation.data) void query.refetch(); } }; useEffect( () => () => { generation.current++; }, [installationId], );
async function enable() { if ( state === "provisioning" || !navigator.onLine || !cache.getSnapshot().ownerSubject ) return; const version = ++generation.current; setState("provisioning"); setError(""); try { const response = await fetch(endpoint, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "", signal: AbortSignal.timeout(60_000), }); const data = await responseJson(response); if (version !== generation.current || cache.getSnapshot().epoch !== epoch) return; if (response.status === 401) return setState("reconnect"); if (!response.ok) { setError(safeMessage(response.status, data.error)); return setState("error"); } if (typeof data.returnTo !== "string" || !details) throw new Error("Invalid setup response"); const destination = new URL(data.returnTo); const runtime = new URL(details.runtimeOrigin); const localDevelopment = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1"; if ( destination.origin !== runtime.origin || destination.username || destination.password || destination.pathname !== "/settings" || destination.search || destination.hash || (destination.protocol !== "https:" && !( destination.protocol === "http:" && localDevelopment && ["localhost", "127.0.0.1"].includes(destination.hostname) )) ) throw new Error("Unsafe setup destination"); setState("success"); window.location.assign(destination.href); } catch { if ( version === generation.current && cache.getSnapshot().epoch === epoch ) { setError( "OpenRouter may not have been enabled. Check your connection and retry setup safely.", ); setState("error"); } } }
return ( <LayerCard className="connect-card"> <div className="intro"> <h2>Enable OpenRouter</h2> <p> Connect OpenRouter to this installation through Cloudflare AI Gateway. </p> </div> {state === "loading" && ( <p role="status">Checking installation access…</p> )} {state === "provisioning" && ( <p role="status">Enabling OpenRouter… Do not close this page.</p> )} {state === "success" && ( <p role="status">OpenRouter enabled. Returning to model settings…</p> )} {error && <p role="alert">{error}</p>} {state === "confirm" && details && ( <> <p> Confirm setup for installation {details.installationId.slice(0, 8)}{" "} in Cloudflare account {details.accountId}. </p> <div className="actions"> {readError && ( <Button variant="secondary" onClick={load}> Retry </Button> )} <Button variant="primary" onClick={() => void enable()}> Enable OpenRouter </Button> <a className="open-flarebot" href={new URL("/settings", details.runtimeOrigin).href} > Cancel </a> </div> </> )} {state === "error" && ( <div className="actions"> <Button variant="secondary" onClick={() => commandState === "error" && details ? void enable() : void load() } > Retry </Button> </div> )} {state === "reconnect" && ( <> <p role="alert"> Reconnect Cloudflare to confirm ownership and continue setup. </p> <form action="/auth/start" method="post"> <input type="hidden" name="providerInstallationId" value={installationId} /> <Button type="submit" variant="primary"> Reconnect Cloudflare </Button> </form> </> )} </LayerCard> );}