import { GATE_CREATE_DELEGATE_NSID } from "#lib/api/delegation.ts";
import { installFetch } from "#storybook/installFetch.ts";
export const gateUrl = "https://gate.example.test";
export const handleDomain = "orgs.example.test";
export const delegationConfig = {
delegationUrl: gateUrl,
delegationDid: "did:web:gate.example.test",
delegationHandleDomain: handleDomain
};
export type Answer = (handle: string) => Promise<Response>;
export const created =
(did: string, controllerDid = "did:plc:alice"): Answer =>
(handle) =>
Promise.resolve(Response.json({ did, handle, controllerDid }));
export const refused =
(status: number, error: string, message?: string): Answer =>
() =>
Promise.resolve(Response.json({ error, message }, { status }));
export const offline: Answer = () => Promise.reject(new TypeError("Failed to fetch"));
export const pdsAnswers =
(answers: { serviceAuth?: number; getRecord?: number } = {}) =>
(pathname: string): Response => {
if (pathname.includes("getServiceAuth")) {
return answers.serviceAuth
? Response.json({ error: "AuthRequired" }, { status: answers.serviceAuth })
: Response.json({ token: "service-auth-jwt" });
}
if (pathname.includes("getRecord") && answers.getRecord) {
return Response.json(
{ error: "InternalServerError", message: "Repo is not ready yet" },
{ status: answers.getRecord }
);
}
return new Response(null, { status: 404 });
};
export const orgNameOf = (parameters: Record<string, unknown>): string =>
(parameters.orgName as string | undefined) ?? "acme";
export const installGateFetch = ({ parameters }: { parameters: Record<string, unknown> }) => {
const answer = parameters.gate as Answer | undefined;
const handle = `${orgNameOf(parameters)}.${handleDomain}`;
return installFetch((url, init) => {
if (!answer || !url.pathname.includes(GATE_CREATE_DELEGATE_NSID)) return;
const requested = (JSON.parse(String(init?.body)) as { handle?: string }).handle;
if (requested === handle) return answer(handle);
});
};