droboticflow/scripts/lib/acceptance-client.mjs
2026-06-23 05:48:12 +08:00

186 lines
5.5 KiB
JavaScript

export function authenticationHeaders(apiToken = "") {
const token = String(apiToken || "").trim();
return token ? { Authorization: `Bearer ${token}` } : undefined;
}
export function validateSessionCredentials(email = "", password = "") {
if (Boolean(String(email || "").trim()) !== Boolean(password)) {
throw new Error("DROBOTICFLOW_ACCEPTANCE_EMAIL and DROBOTICFLOW_ACCEPTANCE_PASSWORD must be set together");
}
}
export function positiveIntegerEnv(name, fallback, env = process.env) {
const raw = String(env?.[name] ?? "").trim();
if (!raw) {
return fallback;
}
if (!/^[1-9][0-9]*$/.test(raw)) {
throw new Error(`${name} must be a positive integer`);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed)) {
throw new Error(`${name} must be a safe positive integer`);
}
return parsed;
}
export function booleanEnv(name, fallback = false, env = process.env) {
const raw = String(env?.[name] ?? "").trim().toLowerCase();
if (!raw) {
return fallback;
}
if (["1", "true", "yes", "on"].includes(raw)) {
return true;
}
if (["0", "false", "no", "off"].includes(raw)) {
return false;
}
throw new Error(`${name} must be a boolean`);
}
export function isCSRFProtectedMethod(method = "GET") {
return !["GET", "HEAD", "OPTIONS"].includes(String(method || "GET").toUpperCase());
}
export async function csrfTokenFromContext(context, baseURL) {
if (!context || !baseURL) {
return "";
}
const cookies = await context.cookies(baseURL);
const cookie = cookies.find((item) => item.name === "droboticflow_csrf");
return cookie?.value ? decodeURIComponent(cookie.value) : "";
}
export async function buildAcceptanceHeaders({
baseURL,
context,
method = "GET",
body,
headers = {},
apiToken = "",
} = {}) {
const requestHeaders = { ...headers };
const tokenHeaders = authenticationHeaders(apiToken);
if (tokenHeaders?.Authorization && !requestHeaders.Authorization) {
requestHeaders.Authorization = tokenHeaders.Authorization;
}
if (body !== undefined && !requestHeaders["Content-Type"]) {
requestHeaders["Content-Type"] = "application/json";
}
if (context && isCSRFProtectedMethod(method) && !requestHeaders["X-Droboticflow-CSRF-Token"]) {
const token = await csrfTokenFromContext(context, baseURL);
if (token) {
requestHeaders["X-Droboticflow-CSRF-Token"] = token;
}
}
return requestHeaders;
}
function encodedBody(body) {
if (body === undefined || body === null || typeof body === "string" || body instanceof Uint8Array) {
return body;
}
return JSON.stringify(body);
}
function responseStatus(response) {
return typeof response.status === "function" ? response.status() : response.status;
}
async function responseText(response) {
return typeof response.text === "function" ? response.text() : "";
}
async function sendRequest({ baseURL, context, fetchImpl, pathName, method, headers, body }) {
const url = `${baseURL}${pathName}`;
const payload = encodedBody(body);
if (context) {
return context.request.fetch(url, {
method,
headers,
data: payload,
});
}
return fetchImpl(url, {
method,
headers,
body: payload,
});
}
export function createAcceptanceAPIClient({
baseURL,
apiToken = "",
context = null,
fetchImpl = globalThis.fetch,
attempts = 6,
retryDelayMs = (attempt) => Math.min(attempt, 3) * 1000,
} = {}) {
const normalizedBaseURL = String(baseURL || "").replace(/\/+$/, "");
if (!normalizedBaseURL) {
throw new Error("baseURL is required");
}
if (!context && typeof fetchImpl !== "function") {
throw new Error("fetch implementation is required when no Playwright context is provided");
}
return {
async request(pathName, { method = "GET", body, headers = {}, expected = [200, 201, 202, 204] } = {}) {
const requestMethod = String(method || "GET").toUpperCase();
let lastError;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
const requestHeaders = await buildAcceptanceHeaders({
baseURL: normalizedBaseURL,
context,
method: requestMethod,
body,
headers,
apiToken,
});
const response = await sendRequest({
baseURL: normalizedBaseURL,
context,
fetchImpl,
pathName,
method: requestMethod,
headers: requestHeaders,
body,
});
const status = responseStatus(response);
const text = await responseText(response);
if (!expected.includes(status)) {
throw new Error(`${requestMethod} ${pathName} failed with ${status}: ${text}`);
}
return text ? JSON.parse(text) : null;
} catch (error) {
lastError = error;
if (attempt === attempts) {
break;
}
await new Promise((resolve) => setTimeout(resolve, retryDelayMs(attempt)));
}
}
throw lastError;
},
};
}
export async function loginIfConfigured(client, { email = "", password = "", label = "acceptance user" } = {}) {
const normalizedEmail = String(email || "").trim();
if (!normalizedEmail) {
return "";
}
const response = await client.request("/api/auth/login", {
method: "POST",
body: {
email: normalizedEmail,
password,
},
expected: [200],
});
const identifier = response?.email || response?.name || normalizedEmail;
console.log(`logged in ${label}: ${identifier}`);
return identifier;
}