Add Bruno imports and a file-tree importer API (#706)

This commit is contained in:
Gregory Schier authored and GitHub committed 2026-09-24 14:50:44 -07:00
1 parent 46464cfacf
commit aa10c44a45
109 files changed
+4684 -879

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
import type { HttpRequest } from "@yaakapp/api";
import { object, template, text, type Obj } from "./common";
type Authentication = Pick<HttpRequest, "authentication" | "authenticationType">;
export function auth(value: unknown, inheritWhenAbsent = false): Authentication {
// Bruno omits auth for 'none'. A folder without request defaults inherits from its parent.
if (value === "inherit" || (inheritWhenAbsent && value == null))
return { authenticationType: null, authentication: {} };
const a = object(value);
const type = text(a.type);
const fields = (names: string[]) =>
Object.fromEntries(names.map((name) => [name, template(a[name])]));
switch (type) {
case "basic":
case "digest":
return { authenticationType: type, authentication: fields(["username", "password"]) };
case "bearer":
return { authenticationType: type, authentication: fields(["token"]) };
case "ntlm":
return {
authenticationType: "windows",
authentication: fields(["username", "password", "domain"]),
};
case "awsv4":
if (a.profileName) break;
return {
authenticationType: type,
authentication: fields([
"accessKeyId",
"secretAccessKey",
"sessionToken",
"region",
"service",
]),
};
case "apikey":
return {
authenticationType: type,
authentication: {
...fields(["key", "value"]),
location: a.placement === "query" ? "query" : "header",
},
};
case "oauth1": {
const privateKey = object(a.privateKey);
if (
(a.placement != null && a.placement !== "header") ||
a.includeBodyHash === true ||
privateKey.type === "file"
)
break;
return {
authenticationType: type,
authentication: {
...fields([
"consumerKey",
"consumerSecret",
"verifier",
"timestamp",
"nonce",
"version",
"realm",
]),
signatureMethod: text(a.signatureMethod) || "HMAC-SHA1",
tokenKey: template(a.accessToken),
tokenSecret: template(a.accessTokenSecret),
callback: template(a.callbackUrl),
privateKey: template(typeof a.privateKey === "string" ? a.privateKey : privateKey.value),
},
};
}
case "oauth2": {
const flow = text(a.flow);
const token = object(a.tokenConfig);
const placement = object(token.placement);
// Yaak currently places OAuth tokens in a header and uses the access token.
if (
placement.query != null ||
token.source === "id_token" ||
![
"authorization_code",
"client_credentials",
"resource_owner_password_credentials",
"implicit",
].includes(flow)
)
break;
const credentials = object(a.credentials);
const owner = object(a.resourceOwner);
const pkce = object(a.pkce);
return {
authenticationType: type,
authentication: {
...fields(["authorizationUrl", "accessTokenUrl", "scope", "state"]),
grantType: flow === "resource_owner_password_credentials" ? "password" : flow,
clientId: template(credentials.clientId),
clientSecret: template(credentials.clientSecret),
credentials: credentials.placement === "basic_auth_header" ? "basic" : "body",
redirectUri: template(a.callbackUrl),
username: template(owner.username),
password: template(owner.password),
usePkce: a.pkce != null && pkce.disabled !== true,
pkceChallengeMethod: pkce.method === "plain" ? "plain" : "S256",
headerPrefix: placement.header == null ? "Bearer" : template(placement.header),
},
};
}
}
return { authenticationType: "none", authentication: {} };
}
export function manualAuth(value: unknown): Obj | undefined {
const a = object(value);
if (!Object.keys(a).length) return;
if (auth(value).authenticationType === "none") return a;
// OAuth settings beyond the core flow are retained for manual migration.
if (a.type === "oauth2" && (a.additionalParameters || a.refreshTokenUrl || a.settings)) return a;
}
+109
View File
@@ -0,0 +1,109 @@
import type { HttpRequest, HttpRequestHeader } from "@yaakapp/api";
import { headers, object, rows, selected, template, text } from "./common";
export function body(
value: unknown,
graphql: boolean,
rawHeaders: unknown,
inheritedHeaders: HttpRequestHeader[] = [],
): Pick<HttpRequest, "body" | "bodyType" | "headers"> {
const b = object(selected(value, "body"));
const requestHeaders = headers(rawHeaders);
const result = (bodyType: string | null, data: Record<string, unknown>, contentType = "") => {
if (
contentType &&
![...inheritedHeaders, ...requestHeaders].some((h) => h.name.toLowerCase() === "content-type")
) {
requestHeaders.push({ name: "Content-Type", value: contentType, enabled: true });
}
return { bodyType, body: data, headers: requestHeaders };
};
if (graphql) {
return result(
"graphql",
{
query: template(b.query),
variables: template(
typeof b.variables === "object" && b.variables != null
? JSON.stringify(b.variables, null, 2)
: b.variables,
),
...(typeof b.operationName === "string"
? { operationName: template(b.operationName) }
: {}),
},
"application/json",
);
}
const types: Record<string, [string, string]> = {
json: ["application/json", "application/json"],
xml: ["application/xml", "application/xml"],
text: ["other", "text/plain"],
sparql: ["other", "application/sparql-query"],
};
const type = text(b.type);
const rawType = Object.hasOwn(types, type) ? types[type] : undefined;
if (rawType) return result(rawType[0], { text: template(b.data) }, rawType[1]);
if (type === "form-urlencoded")
return result(
"application/x-www-form-urlencoded",
{ form: headers(b.data) },
"application/x-www-form-urlencoded",
);
if (type === "multipart-form") {
const form = rows(b.data).flatMap<Record<string, unknown>>((v) => {
const base = {
name: template(v.name),
enabled: v.disabled !== true,
...(v.contentType ? { contentType: template(v.contentType) } : {}),
};
return v.type === "file"
? (Array.isArray(v.value) ? v.value : [v.value]).map((file: unknown) => ({
...base,
file: template(file),
}))
: [{ ...base, value: template(v.value) }];
});
return result("multipart/form-data", { form }, "multipart/form-data");
}
if (type === "file") {
const file = rows(b.data).find((v) => v.selected === true);
return file
? result("binary", { filePath: template(file.filePath) }, text(file.contentType))
: result(null, {});
}
return result(null, {});
}
export function urlAndParams(url: unknown, value: unknown) {
const params = rows(value);
const urlParameters = params.map((p) => ({
name: `${p.type === "path" ? ":" : ""}${template(p.name)}`,
value: template(p.value),
enabled: p.disabled !== true,
}));
// Bruno stores query parameters in both the URL and the editor rows. Yaak appends rows.
const names = new Set(params.filter((p) => p.type !== "path").map((p) => text(p.name)));
const raw = text(url);
const hash = raw.indexOf("#");
const fragment = hash < 0 ? "" : raw.slice(hash);
const base = hash < 0 ? raw : raw.slice(0, hash);
const q = base.indexOf("?");
if (q < 0 || names.size === 0) return { url: template(raw), urlParameters };
const query = base
.slice(q + 1)
.split("&")
.filter((pair) => {
const key = pair.split("=")[0] ?? "";
try {
return !names.has(decodeURIComponent(key.replaceAll("+", " ")));
} catch {
return !names.has(key);
}
})
.join("&");
return {
url: template(`${base.slice(0, q)}${query ? `?${query}` : ""}${fragment}`),
urlParameters,
};
}
+69
View File
@@ -0,0 +1,69 @@
import type { EnvironmentVariable, HttpRequestHeader } from "@yaakapp/api";
import YAML from "yaml";
export type Obj = Record<string, unknown>;
export function object(value: unknown): Obj {
return value != null && typeof value === "object" && !Array.isArray(value) ? (value as Obj) : {};
}
export function rows(value: unknown): Obj[] {
return Array.isArray(value) ? value.map(object) : [];
}
export function text(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
return "";
}
export function template(value: unknown): string {
return text(value).replace(/{{\s*([^{}]+?)\s*}}/g, (full, name: string) => {
// Bruno's expressions, process.env and dynamic variables have different semantics.
if (
name.startsWith("process.env.") ||
["true", "false", "null"].includes(name) ||
!/^[\p{L}_][\p{L}\p{N}_.-]*$/u.test(name)
)
return full;
return `\${[ ${name} ]}`;
});
}
export function selected(value: unknown, key: string): unknown {
if (!Array.isArray(value)) return value;
const variants = rows(value);
return (variants.find((v) => v.selected === true) ?? variants[0])?.[key];
}
export function variables(value: unknown): EnvironmentVariable[] {
return rows(value).map((v) => {
const raw = selected(v.value, "value");
return {
name: text(v.name),
value: v.secret === true ? "" : template(typeof raw === "object" ? object(raw).data : raw),
enabled: v.disabled !== true,
};
});
}
export function headers(value: unknown): HttpRequestHeader[] {
return rows(value).map((h) => ({
name: template(h.name),
value: template(h.value),
enabled: h.disabled !== true,
}));
}
export function description(item: Obj, manual: Obj = {}): string {
const info = object(item.info);
const content = (v: unknown) => (typeof v === "string" ? v : text(object(v).content));
const parts = [content(info.description), content(item.docs)].filter(Boolean);
const retained = Object.fromEntries(Object.entries(manual).filter(([, v]) => v != null));
if (Object.keys(retained).length) {
// Keep unsupported executable features as inert text for manual migration.
const yaml = YAML.stringify(retained).trimEnd();
const fence = "`".repeat(Math.max(3, ...[...yaml.matchAll(/`+/g)].map((m) => m[0].length + 1)));
parts.push(
`Bruno source fields for manual review (scripts are not executed):\n\n${fence}yaml\n${yaml}\n${fence}`,
);
}
return parts.join("\n\n");
}
@@ -0,0 +1,39 @@
import type { PartialImportResources } from "@yaakapp/api";
import { rows, text, variables, type Obj } from "./common";
export function environments(
value: unknown,
workspaceId: string,
id: () => string,
): PartialImportResources["environments"] {
const source = rows(value);
const byName = new Map(source.map((e) => [text(e.name), e]));
const resolve = (env: Obj, seen = new Set<Obj>()): ReturnType<typeof variables> => {
if (seen.has(env)) throw new Error("Bruno environment inheritance contains a cycle");
if (seen.size > 100) throw new Error("Bruno environment inheritance is too deeply nested");
seen.add(env);
const own = variables(env.variables);
const parentName = text(env.extends);
if (!parentName) return own;
const parent = byName.get(parentName);
if (!parent)
throw new Error(
`Bruno environment "${text(env.name)}" extends missing environment "${parentName}"`,
);
const overrides = new Set(own.filter((v) => v.enabled).map((v) => v.name));
return [...resolve(parent, seen).filter((v) => v.enabled && !overrides.has(v.name)), ...own];
};
// Yaak has one level of selectable environments. Flatten Bruno's extends chain so
// inheritance survives the host clearing environment parent IDs during import.
return source.map((e, sortPriority) => ({
model: "environment",
id: id(),
workspaceId,
name: text(e.name) || "Environment",
parentModel: "environment",
parentId: null,
variables: resolve(e),
color: text(e.color) || null,
sortPriority,
}));
}
+187
View File
@@ -0,0 +1,187 @@
import path from "node:path";
import {
parseCollection,
parseEnvironment,
parseFolder,
parseRequest,
stringifyCollection,
stringifyEnvironment,
stringifyFolder,
stringifyRequest,
} from "@usebruno/filestore";
import type { ImportFileEntry, ImportFiles } from "@yaakapp/api";
import YAML from "yaml";
import { object, rows, text, type Obj } from "./common";
const ignored = new Set([".git", "node_modules", "__MACOSX"]);
const yaml = (value: string) => object(YAML.parse(value, { maxAliasCount: 0 }));
/** Assemble a collection from the virtual file tree. No direct filesystem access in the plugin. */
export function isBruRequestFile(fileName: string): boolean {
return /\.bru$/i.test(fileName) && !["collection.bru", "folder.bru"].includes(fileName);
}
/** A lone .bru request, wrapped as a one-request bundled collection */
export function singleBruRequest(contents: string, fileName: string): Obj {
return {
opencollection: "1.0.0",
bundled: true,
info: { name: fileName.replace(/\.bru$/i, "") },
items: [yaml(stringifyRequest(parseRequest(contents, { format: "bru" }), { format: "yml" }))],
};
}
const markerNames = ["bruno.json", "opencollection.yml", "opencollection.yaml"];
export async function readBrunoCollection(files: ImportFiles): Promise<Obj | null> {
const listings = new Map<string, ImportFileEntry[]>();
const list = async (dir: string) => {
let entries = listings.get(dir);
if (entries == null) {
entries = (await files.readDir(dir)).filter(
(e) => !ignored.has(e.name) && !e.name.startsWith("."),
);
listings.set(dir, entries);
}
return entries;
};
const has = async (dir: string, name: string) =>
(await list(dir)).some((e) => e.type === "file" && e.name === name);
const hasMarker = async (dir: string) => {
for (const name of markerNames) if (await has(dir, name)) return true;
return false;
};
// The selected directory must be the collection itself. Subfolders are only checked to give a
// better error than "not supported" when the user picked the folder above it.
const rootPath = "";
if (!(await hasMarker(rootPath))) {
const top = await list(rootPath);
const [only] = top;
if (top.length === 1 && only?.type === "file" && isBruRequestFile(only.name)) {
return singleBruRequest(await files.readTextFile(only.path), only.name);
}
for (const entry of top) {
if (entry.type === "directory" && (await hasMarker(entry.path))) {
throw new Error(
"This folder contains Bruno collections. Select the collection directory itself.",
);
}
}
return null;
}
const at = (name: string) => name;
const yamlMarker = (await has(rootPath, "opencollection.yml"))
? at("opencollection.yml")
: (await has(rootPath, "opencollection.yaml"))
? at("opencollection.yaml")
: undefined;
const isYaml = yamlMarker != null;
const root = isYaml
? yaml(await files.readTextFile(yamlMarker))
: object(JSON.parse(await files.readTextFile(at("bruno.json"))));
if (isYaml && root.opencollection !== "1.0.0")
throw new Error(`Unsupported Bruno collection format version: ${text(root.opencollection)}`);
const load = async (p: string, parse: (s: string) => Obj) => {
try {
return parse(await files.readTextFile(p));
} catch (error) {
throw new Error(
`Unable to import ${p}: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
const assemble = async (dir: string): Promise<Obj[]> => {
const items: Obj[] = [];
for (const entry of await list(dir)) {
if (dir === rootPath && entry.name === "environments") continue;
if (entry.type === "directory") {
let configPath: string | undefined;
for (const name of isYaml ? ["folder.yml", "folder.yaml"] : ["folder.bru"]) {
if (await has(entry.path, name)) {
configPath = `${entry.path}/${name}`;
break;
}
}
const folder = configPath
? await load(configPath, (s) =>
isYaml
? yaml(s)
: yaml(stringifyFolder(parseFolder(s, { format: "bru" }), { format: "yml" })),
)
: {};
const children = await assemble(entry.path);
items.push({
...folder,
info: { name: entry.name, ...object(folder.info), type: "folder" },
items: children,
});
} else if (
isYaml &&
/\.ya?ml$/i.test(entry.name) &&
!["opencollection.yml", "opencollection.yaml", "folder.yml", "folder.yaml"].includes(
entry.name,
)
) {
const item = await load(entry.path, yaml);
if (object(item.info).type || item.http || item.graphql || item.grpc || item.websocket)
items.push(item);
} else if (
!isYaml &&
/\.bru$/i.test(entry.name) &&
!["collection.bru", "folder.bru"].includes(entry.name)
) {
items.push(
await load(entry.path, (s) =>
yaml(stringifyRequest(parseRequest(s, { format: "bru" }), { format: "yml" })),
),
);
}
}
return items;
};
const environments: Obj[] = [];
const hasEnvDir = (await list(rootPath)).some(
(e) => e.type === "directory" && e.name === "environments",
);
const envFiles = hasEnvDir
? (await list(at("environments"))).filter(
(e) => e.type === "file" && (isYaml ? /\.ya?ml$/i.test(e.name) : /\.bru$/i.test(e.name)),
)
: [];
for (const p of envFiles.map((e) => e.path)) {
const env = await load(p, (s) =>
isYaml
? yaml(s)
: yaml(stringifyEnvironment(parseEnvironment(s, { format: "bru" }), { format: "yml" })),
);
environments.push({ ...env, name: path.posix.basename(p).replace(/\.(?:bru|ya?ml)$/i, "") });
}
const items = await assemble(rootPath);
if (isYaml)
return {
...root,
bundled: true,
items: [...rows(root.items), ...items],
config: {
...object(root.config),
environments: [...rows(object(root.config).environments), ...environments],
},
};
const collectionRoot = (await has(rootPath, "collection.bru"))
? parseCollection(await files.readTextFile(at("collection.bru")), { format: "bru" })
: undefined;
const normalized = yaml(
stringifyCollection(
collectionRoot ?? {},
{ ...root, name: text(root.name) || files.name },
{ format: "yml" },
),
);
return {
...normalized,
bundled: true,
items,
config: { ...object(normalized.config), environments },
};
}
+227
View File
@@ -0,0 +1,227 @@
import type { HttpRequestHeader, PartialImportResources, PluginDefinition } from "@yaakapp/api";
import type { ImportPluginResponse } from "@yaakapp/api/lib/plugins/ImporterPlugin";
import YAML from "yaml";
import { auth, manualAuth } from "./auth";
import { body, urlAndParams } from "./body";
import { environments } from "./environments";
import { isBruRequestFile, readBrunoCollection, singleBruRequest } from "./files";
import {
description,
headers,
object,
rows,
selected,
template,
text,
variables,
type Obj,
} from "./common";
export const plugin: PluginDefinition = {
importer: {
name: "Bruno",
description: "Import Bruno collections",
async onImportSource(_ctx, { source }) {
if (source.type === "text") {
return isBruRequestFile(source.name)
? convertBruno(YAML.stringify(singleBruRequest(source.text, source.name)))
: convertBruno(source.text);
}
const root = await readBrunoCollection(source.files);
return root ? convertBruno(YAML.stringify(root)) : null;
},
},
};
export function convertBruno(contents: string): ImportPluginResponse {
let root: Obj;
try {
// Bundled exports don't need aliases. Disallow cycles before walking the item tree.
root = object(YAML.parse(contents, { maxAliasCount: 0 }));
} catch {
return null;
}
if (typeof root.opencollection !== "string") return null;
if (root.opencollection !== "1.0.0")
throw new Error(`Unsupported Bruno collection format version: ${root.opencollection}`);
if (root.bundled === false || (!Array.isArray(root.items) && root.bundled !== true)) {
throw new Error(
"Select the collection using Choose folder, or export a single YAML file from Bruno's Share menu. A collection configuration file alone does not contain the requests.",
);
}
const resources: PartialImportResources = {
workspaces: [],
environments: [],
folders: [],
httpRequests: [],
grpcRequests: [],
websocketRequests: [],
};
let nextId = 0;
const id = () => `GENERATE_ID::${++nextId}`;
const workspaceId = id();
const defaults = object(root.request);
const config = object(root.config);
const environmentSettings = rows(config.environments)
.map((e) => ({
name: e.name,
externalSecrets: e.externalSecrets,
dotEnvFilePath: e.dotEnvFilePath,
clientCertificates: e.clientCertificates,
}))
.filter((e) => e.externalSecrets || e.dotEnvFilePath || e.clientCertificates);
resources.workspaces.push({
model: "workspace",
id: workspaceId,
name: text(object(root.info).name) || "Bruno Import",
headers: headers(defaults.headers),
...auth(defaults.auth),
description: description(root, {
scripts: defaults.scripts,
actions: defaults.actions,
settings: defaults.settings,
auth: manualAuth(defaults.auth),
...(environmentSettings.length ? { environmentSettings } : {}),
...Object.fromEntries(Object.entries(config).filter(([key]) => key !== "environments")),
}),
});
resources.environments.push({
model: "environment",
id: id(),
workspaceId,
name: "Base Environment",
parentModel: "workspace",
parentId: null,
variables: variables(defaults.variables),
});
resources.environments.push(...environments(config.environments, workspaceId, id));
const visit = (
items: unknown,
folderId: string | null,
depth = 0,
inheritedHeaders: HttpRequestHeader[] = headers(defaults.headers),
) => {
if (depth > 100) throw new Error("Bruno folders are nested too deeply");
for (const [index, item] of rows(items).entries()) {
const info = object(item.info);
const type = text(info.type);
const common = {
id: id(),
workspaceId,
folderId,
name: text(info.name) || "Untitled",
sortPriority: typeof info.seq === "number" && Number.isFinite(info.seq) ? info.seq : index,
};
if (type === "folder" || (type === "" && Array.isArray(item.items))) {
const request = object(item.request);
resources.folders.push({
...common,
model: "folder",
headers: headers(request.headers),
...auth(request.auth, item.request == null),
description: description(item, {
scripts: request.scripts,
actions: request.actions,
settings: request.settings,
auth: manualAuth(request.auth),
}),
});
if (Array.isArray(request.variables) && request.variables.length) {
resources.environments.push({
model: "environment",
id: id(),
workspaceId,
name: "Folder Environment",
parentModel: "folder",
parentId: common.id,
variables: variables(request.variables),
});
}
visit(item.items, common.id, depth + 1, [...inheritedHeaders, ...headers(request.headers)]);
continue;
}
const r = object(item[type]);
const settings = object(item.settings);
const desc = description(item, {
runtime: item.runtime,
examples: item.examples,
settings: item.settings,
auth: manualAuth(r.auth),
...(Array.isArray(r.body) || object(r.body).type === "file"
? { bodyVariants: r.body }
: type === "http" &&
r.body != null &&
!["json", "xml", "text", "sparql", "form-urlencoded", "multipart-form"].includes(
text(object(r.body).type),
)
? { unsupportedBody: r.body }
: {}),
});
if (type === "http" || type === "graphql") {
resources.httpRequests.push({
...common,
model: "http_request",
description: desc,
...urlAndParams(r.url, r.params),
method: text(r.method) || (type === "graphql" ? "POST" : "GET"),
...auth(r.auth),
...body(r.body, type === "graphql", r.headers, inheritedHeaders),
...(typeof settings.followRedirects === "boolean"
? { settingFollowRedirects: { enabled: true, value: settings.followRedirects } }
: {}),
...(typeof settings.timeout === "number" &&
Number.isInteger(settings.timeout) &&
settings.timeout >= 0 &&
settings.timeout <= 2147483647
? { settingRequestTimeout: { enabled: true, value: settings.timeout } }
: {}),
});
} else if (type === "grpc") {
const [service, method] = text(r.method).replace(/^\//, "").split("/");
resources.grpcRequests.push({
...common,
model: "grpc_request",
url: template(r.url),
service: service || null,
method: method || null,
message: template(selected(r.message, "message")),
metadata: headers(r.metadata),
...auth(r.auth),
description: description(item, {
runtime: item.runtime,
protoFilePath: r.protoFilePath,
messageVariants: Array.isArray(r.message) ? r.message : undefined,
auth: manualAuth(r.auth),
}),
});
} else if (type === "websocket") {
const message = object(selected(r.message, "message"));
resources.websocketRequests.push({
...common,
model: "websocket_request",
url: template(r.url),
headers: headers(r.headers),
...auth(r.auth),
message: message.type === "binary" ? "" : template(message.data),
description: description(item, {
runtime: item.runtime,
settings: item.settings,
message: r.message,
auth: manualAuth(r.auth),
}),
});
} else {
// Unknown items remain visible in the import instead of silently disappearing.
resources.folders.push({
...common,
model: "folder",
description: description(item, { unsupportedItem: item }),
});
}
}
};
visit(root.items, null);
// OpenCollection has no persistent resource IDs. Let the host derive source keys.
return { resources };
}