mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-22 08:21:35 +01:00
Add Bruno imports and a file-tree importer API (#706)
This commit is contained in:
1 parent
46464cfacf
commit
aa10c44a45
109 files changed
+4684
-879
No files matched your search
@@ -0,0 +1,27 @@
|
||||
# Bruno importer
|
||||
|
||||
Import Bruno's **Single File (YAML)** or **Bruno Collection (ZIP)** exports, or select a collection directory. Both OpenCollection `1.0.0` YAML collections and legacy `.bru` collections are supported. Individual `.bru` request files also work. A directory/ZIP must contain one collection root (`opencollection.yml`, `opencollection.yaml`, or `bruno.json`); a wrapper directory in the ZIP is allowed. Use **Choose folder** for an on-disk collection, rather than selecting its configuration file alone.
|
||||
|
||||
The importer consumes the shared [file-tree API](../../packages/plugin-runtime-types/IMPORTERS.md). It skips `.git`, `node_modules`, `__MACOSX`, and hidden entries. It does not install dependencies, load dotenv files, or run collection scripts.
|
||||
|
||||
Supported:
|
||||
|
||||
- Nested folders, ordering, descriptions, collection/folder headers, and variables.
|
||||
- Environments, disabled variables, typed values, and secret placeholders. Environment inheritance is flattened into each selectable environment because Yaak does not have nested selectable environments.
|
||||
- HTTP URLs, query/path parameters, headers, raw bodies, URL-encoded forms, multipart files, and selected binary files.
|
||||
- GraphQL query and variables in Yaak's sendable body shape.
|
||||
- gRPC URL, service/method, metadata, and selected message; WebSocket URL, headers, and selected message.
|
||||
- Explicit auth inheritance, no auth, basic, bearer, digest, NTLM, API key, AWS credentials, common OAuth 1.0 header signing, and OAuth 2.0 flows with header tokens.
|
||||
- Plain `{{variable}}` references converted to Yaak templates. Expressions, dynamic variables, and `process.env` references stay unchanged.
|
||||
|
||||
Scripts, assertions, actions, request-scoped variables, examples, advanced settings, and unsupported authentication configurations are retained in resource descriptions for manual migration, not executed. Alternative bodies/messages use the selected variant (or the first when unspecified); retained source variants remain in descriptions. File paths are preserved without reading files; relative paths and gRPC proto files may need to be configured after import. External secret providers, certificates, proxies, OAuth token caches, and WebSocket binary messages are not activated by the importer.
|
||||
|
||||
OpenCollection does not export persistent resource IDs, so Yaak derives the import source keys using its existing fallback matching.
|
||||
|
||||
Implementation references:
|
||||
|
||||
- [OpenCollection types and schema](https://github.com/opencollection-dev/opencollection)
|
||||
- [Bruno's bundled export converter](https://github.com/usebruno/bruno/blob/main/packages/bruno-converters/src/opencollection/bruno-to-opencollection.ts)
|
||||
- [Bruno's Share exporter](https://github.com/usebruno/bruno/blob/main/packages/bruno-app/src/utils/exporters/opencollection.js)
|
||||
|
||||
Legacy `.bru` parsing uses Bruno's official `@usebruno/filestore` (backed by `@usebruno/lang`). Its YAML serializers normalize parsed collections to OpenCollection before they enter the same Yaak conversion path. YAML collections are assembled directly to preserve their fields.
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"name": "@yaak/importer-bruno",
|
||||
"displayName": "Bruno Importer",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Import Bruno collections",
|
||||
"scripts": {
|
||||
"build": "yaakcli build",
|
||||
"dev": "yaakcli dev",
|
||||
"test": "vp test --run tests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@usebruno/filestore": "^0.12.0",
|
||||
"yaml": "^2.8.3"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
}));
|
||||
}
|
||||
@@ -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 },
|
||||
};
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Context, ImportFiles } from "@yaakapp/api";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import { createImportFiles, runImporter } from "../../../packages/plugin-runtime/src/importFiles";
|
||||
import { plugin } from "../src";
|
||||
import { readBrunoCollection } from "../src/files";
|
||||
|
||||
const ctx = {} as Context;
|
||||
|
||||
describe.each(["opencollection", "legacy"])("Bruno %s file tree", (name) => {
|
||||
test("imports the same resources from a ZIP or directory, including nested folders and environments", async () => {
|
||||
const directory = fileURLToPath(new URL(`./fixtures/${name}/Demo`, import.meta.url));
|
||||
const bytes = await readFile(new URL(`./fixtures/${name}.zip`, import.meta.url));
|
||||
const zipped = await runImporter(plugin.importer!, ctx, {
|
||||
content: "",
|
||||
source: { type: "file", name: `${name}.zip`, base64: bytes.toString("base64") },
|
||||
});
|
||||
const unzipped = await runImporter(plugin.importer!, ctx, {
|
||||
content: "",
|
||||
source: { type: "directory", path: directory },
|
||||
});
|
||||
expect(zipped).toEqual(unzipped);
|
||||
expect(zipped?.resources.workspaces[0]?.name).toBe(
|
||||
name === "legacy" ? "Legacy Bruno" : "Directory YAML",
|
||||
);
|
||||
expect(zipped?.resources.httpRequests).toHaveLength(2);
|
||||
expect(zipped?.resources.httpRequests.find((r) => r.name === "Get Users")).toMatchObject({
|
||||
url: "${[ host ]}/users",
|
||||
authenticationType: null,
|
||||
});
|
||||
expect(zipped?.resources.httpRequests.find((r) => r.name === "Query")).toMatchObject({
|
||||
bodyType: "graphql",
|
||||
body: { query: "query { users { id } }" },
|
||||
});
|
||||
expect(zipped?.resources.environments[0]?.variables).toContainEqual({
|
||||
name: "host",
|
||||
value: "https://example.com",
|
||||
enabled: true,
|
||||
});
|
||||
expect(zipped?.resources.environments[1]?.variables).toContainEqual({
|
||||
name: "token",
|
||||
value: "sample",
|
||||
enabled: true,
|
||||
});
|
||||
expect(zipped?.resources.folders.find((f) => f.name === "Users")).toMatchObject({
|
||||
sortPriority: 3,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test("still imports a bundled YAML file through the new runtime entry point", async () => {
|
||||
const bytes = await readFile(new URL("./fixtures/collection.yaml", import.meta.url));
|
||||
const result = await runImporter(plugin.importer!, ctx, {
|
||||
content: bytes.toString(),
|
||||
source: { type: "file", name: "collection.yaml", base64: bytes.toString("base64") },
|
||||
});
|
||||
expect(result?.resources.workspaces[0]?.name).toBe("Example API");
|
||||
});
|
||||
|
||||
test("imports pasted YAML through the file hook's virtual input file", async () => {
|
||||
const content = await readFile(new URL("./fixtures/collection.yaml", import.meta.url), "utf8");
|
||||
const result = await runImporter(plugin.importer!, ctx, { content });
|
||||
expect(result?.resources.workspaces[0]?.name).toBe("Example API");
|
||||
});
|
||||
|
||||
test("supports an individual .bru request", async () => {
|
||||
const bytes = await readFile(new URL("./fixtures/legacy/Demo/Users/get.bru", import.meta.url));
|
||||
const result = await runImporter(plugin.importer!, ctx, {
|
||||
content: bytes.toString(),
|
||||
source: { type: "file", name: "get.bru", base64: bytes.toString("base64") },
|
||||
});
|
||||
expect(result?.resources.httpRequests[0]?.name).toBe("Get Users");
|
||||
});
|
||||
|
||||
test("does not claim an unrelated binary file", async () => {
|
||||
expect(
|
||||
await runImporter(plugin.importer!, ctx, {
|
||||
content: "",
|
||||
source: { type: "file", name: "body.bin", base64: "/w==" },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test("rejects a folder of collections before reading their contents", async () => {
|
||||
const files: ImportFiles = {
|
||||
name: "collections",
|
||||
kind: "directory",
|
||||
async readDir(dir = "") {
|
||||
return dir === ""
|
||||
? ["a", "b"].map((name) => ({ name, path: name, type: "directory" as const }))
|
||||
: [{ name: "bruno.json", path: `${dir}/bruno.json`, type: "file" }];
|
||||
},
|
||||
async readFile() {
|
||||
throw new Error("should not read");
|
||||
},
|
||||
async readTextFile() {
|
||||
throw new Error("should not read");
|
||||
},
|
||||
};
|
||||
await expect(readBrunoCollection(files)).rejects.toThrow("Select the collection directory");
|
||||
});
|
||||
|
||||
test("reports parse errors with the relative file path", async () => {
|
||||
const session = await createImportFiles({
|
||||
content: "meta { invalid",
|
||||
source: {
|
||||
type: "file",
|
||||
name: "broken.bru",
|
||||
base64: Buffer.from("meta { invalid").toString("base64"),
|
||||
},
|
||||
});
|
||||
try {
|
||||
await expect(readBrunoCollection(session.files)).rejects.toThrow();
|
||||
} finally {
|
||||
session.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
# Synthetic bundled export following Bruno's OpenCollection 1.0.0 exporter.
|
||||
opencollection: 1.0.0
|
||||
info:
|
||||
name: Example API
|
||||
request:
|
||||
auth:
|
||||
type: bearer
|
||||
token: "{{token}}"
|
||||
headers:
|
||||
- name: X-Collection
|
||||
value: "{{client}}"
|
||||
variables:
|
||||
- name: host
|
||||
value: https://example.com
|
||||
- name: client
|
||||
value: yaak
|
||||
config:
|
||||
environments:
|
||||
- name: Development
|
||||
extends: Shared
|
||||
variables:
|
||||
- name: host
|
||||
value: https://dev.example.com
|
||||
- name: token
|
||||
secret: true
|
||||
- name: disabled
|
||||
value: ignored
|
||||
disabled: true
|
||||
- name: Shared
|
||||
color: "#123456"
|
||||
variables:
|
||||
- name: count
|
||||
value:
|
||||
type: number
|
||||
data: "42"
|
||||
items:
|
||||
- info:
|
||||
name: Users
|
||||
type: folder
|
||||
seq: 2
|
||||
request:
|
||||
auth: inherit
|
||||
variables:
|
||||
- name: userId
|
||||
value: "123"
|
||||
items:
|
||||
- info:
|
||||
name: Get User
|
||||
type: http
|
||||
seq: 3
|
||||
description: Fetch one user
|
||||
http:
|
||||
method: GET
|
||||
url: "{{host}}/users/:id?expand=profile&keep=1#details"
|
||||
auth: inherit
|
||||
params:
|
||||
- name: id
|
||||
value: "{{userId}}"
|
||||
type: path
|
||||
- name: expand
|
||||
value: profile
|
||||
type: query
|
||||
- name: inactive
|
||||
value: "true"
|
||||
type: query
|
||||
disabled: true
|
||||
headers:
|
||||
- name: X-Disabled
|
||||
value: ignored
|
||||
disabled: true
|
||||
settings:
|
||||
timeout: 2000
|
||||
followRedirects: false
|
||||
- info:
|
||||
name: GraphQL
|
||||
type: graphql
|
||||
seq: 1
|
||||
graphql:
|
||||
method: POST
|
||||
url: "{{host}}/graphql"
|
||||
auth:
|
||||
type: basic
|
||||
username: "{{client}}"
|
||||
password: example
|
||||
body:
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }"
|
||||
variables: '{"id":"{{userId}}"}'
|
||||
- info:
|
||||
name: Public
|
||||
type: http
|
||||
seq: 1
|
||||
http:
|
||||
method: GET
|
||||
url: "{{host}}/status"
|
||||
- info:
|
||||
name: Upload
|
||||
type: http
|
||||
http:
|
||||
method: POST
|
||||
url: "{{host}}/upload"
|
||||
body:
|
||||
type: multipart-form
|
||||
data:
|
||||
- name: label
|
||||
type: text
|
||||
value: "{{client}}"
|
||||
- name: files
|
||||
type: file
|
||||
value: [./first.txt, ./second.txt]
|
||||
contentType: text/plain
|
||||
- info:
|
||||
name: Hello RPC
|
||||
type: grpc
|
||||
grpc:
|
||||
url: localhost:50051
|
||||
method: /example.Greeter/SayHello
|
||||
message: '{"name":"{{client}}"}'
|
||||
metadata:
|
||||
- name: authorization
|
||||
value: "Bearer {{token}}"
|
||||
- info:
|
||||
name: Events
|
||||
type: websocket
|
||||
websocket:
|
||||
url: wss://example.com/events
|
||||
auth: inherit
|
||||
message:
|
||||
type: json
|
||||
data: '{"subscribe":"{{client}}"}'
|
||||
docs:
|
||||
type: text/markdown
|
||||
content: Synthetic migration fixture.
|
||||
bundled: true
|
||||
extensions:
|
||||
bruno:
|
||||
exportedUsing: Bruno/3.0.0
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
meta {
|
||||
name: Users
|
||||
seq: 3
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
meta {
|
||||
name: Get Users
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
get {
|
||||
url: {{host}}/users
|
||||
body: none
|
||||
auth: inherit
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
meta {
|
||||
name: Query
|
||||
type: graphql
|
||||
seq: 2
|
||||
}
|
||||
post {
|
||||
url: {{host}}/graphql
|
||||
body: graphql
|
||||
auth: none
|
||||
}
|
||||
body:graphql {
|
||||
query { users { id } }
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "version": "1", "name": "Legacy Bruno", "type": "collection" }
|
||||
@@ -0,0 +1,9 @@
|
||||
vars:pre-request {
|
||||
host: https://example.com
|
||||
}
|
||||
auth {
|
||||
mode: bearer
|
||||
}
|
||||
auth:bearer {
|
||||
token: {{token}}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
token: sample
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
info:
|
||||
name: Users
|
||||
type: folder
|
||||
seq: 3
|
||||
request:
|
||||
auth: inherit
|
||||
@@ -0,0 +1,8 @@
|
||||
info:
|
||||
name: Get Users
|
||||
type: http
|
||||
seq: 1
|
||||
http:
|
||||
method: GET
|
||||
url: "{{host}}/users"
|
||||
auth: inherit
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
info:
|
||||
name: Query
|
||||
type: graphql
|
||||
graphql:
|
||||
url: "{{host}}/graphql"
|
||||
body:
|
||||
query: "query { users { id } }"
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
name: Local
|
||||
variables:
|
||||
- name: token
|
||||
value: sample
|
||||
@@ -0,0 +1,7 @@
|
||||
opencollection: 1.0.0
|
||||
info:
|
||||
name: Directory YAML
|
||||
request:
|
||||
variables:
|
||||
- name: host
|
||||
value: https://example.com
|
||||
@@ -0,0 +1,22 @@
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 Anoop M D, Anusree P S and Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Upstream Bruno fixtures
|
||||
|
||||
These two complete fixture directories are copied byte-for-byte from
|
||||
[usebruno/bruno](https://github.com/usebruno/bruno) at commit
|
||||
[`4eb7e585f0fb318b2ef8d88b34635da633f3acf4`](https://github.com/usebruno/bruno/commit/4eb7e585f0fb318b2ef8d88b34635da633f3acf4).
|
||||
|
||||
- `bru-migration/`: [`tests/collection/migrate-to-yml/fixtures/collection`](https://github.com/usebruno/bruno/tree/4eb7e585f0fb318b2ef8d88b34635da633f3acf4/tests/collection/migrate-to-yml/fixtures/collection). Exercises collection/folder headers, environments, request variables, JSON bodies, and retained scripts/assertions.
|
||||
- `yaml-docs/`: [`packages/bruno-cli/tests/commands/docs/fixtures/yml-collection`](https://github.com/usebruno/bruno/tree/4eb7e585f0fb318b2ef8d88b34635da633f3acf4/packages/bruno-cli/tests/commands/docs/fixtures/yml-collection). Exercises YAML collection metadata, ordering, and repeated request names in different folders.
|
||||
|
||||
The upstream MIT license is preserved in [LICENSE.md](./LICENSE.md). This directory
|
||||
is excluded from formatting so upstream inputs remain unchanged. To refresh,
|
||||
copy both complete directories from a new pinned revision and update these links;
|
||||
do not edit the inputs to accommodate importer behavior.
|
||||
|
||||
The tests only import the fixtures. They do not send requests or execute the
|
||||
embedded Bruno scripts. Existing synthetic fixtures cover additional edge cases.
|
||||
@@ -0,0 +1,7 @@
|
||||
meta {
|
||||
name: api
|
||||
}
|
||||
|
||||
headers {
|
||||
X-Folder-Header: api-folder
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
meta {
|
||||
name: get-users
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{host}}/api/echo/json
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Accept: application/json
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
// pre-request script in folder request
|
||||
bru.setVar("requestVar", "test");
|
||||
}
|
||||
|
||||
assert {
|
||||
res.status: eq 200
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": "1",
|
||||
"name": "migration-test",
|
||||
"type": "collection",
|
||||
"collectionVersion": "v9.9.9",
|
||||
"ignore": [
|
||||
"node_modules",
|
||||
".git"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
headers {
|
||||
X-Collection-Header: migration-test
|
||||
}
|
||||
|
||||
script:pre-request {
|
||||
// collection pre-request script
|
||||
bru.setVar("collectionVar", "hello");
|
||||
}
|
||||
|
||||
docs {
|
||||
# Migration Test Collection
|
||||
This collection is used to test bru to yml migration.
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
host: http://localhost:8081
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
vars {
|
||||
host: https://api.example.com
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
meta {
|
||||
name: ping
|
||||
type: http
|
||||
seq: 1
|
||||
}
|
||||
|
||||
get {
|
||||
url: {{host}}/ping
|
||||
body: none
|
||||
auth: none
|
||||
}
|
||||
|
||||
assert {
|
||||
res.status: eq 200
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
meta {
|
||||
name: post-json
|
||||
type: http
|
||||
seq: 2
|
||||
}
|
||||
|
||||
post {
|
||||
url: {{host}}/api/echo/json
|
||||
body: json
|
||||
auth: none
|
||||
}
|
||||
|
||||
headers {
|
||||
Content-Type: application/json
|
||||
}
|
||||
|
||||
body:json {
|
||||
{
|
||||
"message": "hello from migration test"
|
||||
}
|
||||
}
|
||||
|
||||
assert {
|
||||
res.status: eq 200
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
info:
|
||||
name: folder_1
|
||||
type: folder
|
||||
seq: 1
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
info:
|
||||
name: request_1
|
||||
type: http
|
||||
seq: 1
|
||||
|
||||
http:
|
||||
method: GET
|
||||
url: https://api.example.com/folder-1/one
|
||||
@@ -0,0 +1,4 @@
|
||||
info:
|
||||
name: folder_2
|
||||
type: folder
|
||||
seq: 2
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
info:
|
||||
name: request_1
|
||||
type: http
|
||||
seq: 1
|
||||
|
||||
http:
|
||||
method: GET
|
||||
url: https://api.example.com/folder-2/one
|
||||
@@ -0,0 +1,4 @@
|
||||
opencollection: "1.0.0"
|
||||
info:
|
||||
name: ymlcollection
|
||||
version: "3.4.0"
|
||||
@@ -0,0 +1,8 @@
|
||||
info:
|
||||
name: request_1
|
||||
type: http
|
||||
seq: 1
|
||||
|
||||
http:
|
||||
method: GET
|
||||
url: https://api.example.com/one
|
||||
@@ -0,0 +1,8 @@
|
||||
info:
|
||||
name: request_2
|
||||
type: http
|
||||
seq: 2
|
||||
|
||||
http:
|
||||
method: GET
|
||||
url: https://api.example.com/two
|
||||
@@ -0,0 +1,459 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, test } from "vite-plus/test";
|
||||
import YAML from "yaml";
|
||||
import { convertBruno } from "../src";
|
||||
import { auth } from "../src/auth";
|
||||
import { body, urlAndParams } from "../src/body";
|
||||
import { template, variables } from "../src/common";
|
||||
|
||||
function collection(items: unknown[] = [], extra: Record<string, unknown> = {}) {
|
||||
return { opencollection: "1.0.0", info: { name: "Test" }, bundled: true, items, ...extra };
|
||||
}
|
||||
const fixture = readFileSync(new URL("./fixtures/collection.yaml", import.meta.url), "utf8");
|
||||
|
||||
describe("Bruno OpenCollection importer", () => {
|
||||
test("imports a bundled export with folders, scopes, disabled rows, and all four request types", () => {
|
||||
const imported = convertBruno(fixture)!;
|
||||
const {
|
||||
workspaces: [workspace],
|
||||
folders: [folder],
|
||||
environments,
|
||||
httpRequests,
|
||||
grpcRequests: [grpc],
|
||||
websocketRequests: [ws],
|
||||
} = imported.resources;
|
||||
expect(workspace).toMatchObject({
|
||||
name: "Example API",
|
||||
authenticationType: "bearer",
|
||||
authentication: { token: "${[ token ]}" },
|
||||
description: "Synthetic migration fixture.",
|
||||
});
|
||||
expect(folder).toMatchObject({ name: "Users", sortPriority: 2, authenticationType: null });
|
||||
const [base, dev, shared, folderEnv] = environments;
|
||||
expect(base).toMatchObject({
|
||||
parentModel: "workspace",
|
||||
parentId: null,
|
||||
variables: [
|
||||
{ name: "host", value: "https://example.com" },
|
||||
{ name: "client", value: "yaak" },
|
||||
],
|
||||
});
|
||||
expect(dev).toMatchObject({
|
||||
parentModel: "environment",
|
||||
parentId: null,
|
||||
variables: [
|
||||
{ name: "count", value: "42" },
|
||||
{ name: "host" },
|
||||
{ name: "token", value: "" },
|
||||
{ name: "disabled", enabled: false },
|
||||
],
|
||||
});
|
||||
expect(shared).toMatchObject({ color: "#123456", variables: [{ name: "count", value: "42" }] });
|
||||
expect(folderEnv).toMatchObject({ parentModel: "folder", parentId: folder!.id });
|
||||
const [get, graphql, publicRequest, upload] = httpRequests;
|
||||
expect(get).toMatchObject({
|
||||
folderId: folder!.id,
|
||||
authenticationType: null,
|
||||
sortPriority: 3,
|
||||
url: "${[ host ]}/users/:id?keep=1#details",
|
||||
urlParameters: [
|
||||
{ name: ":id", value: "${[ userId ]}", enabled: true },
|
||||
{ name: "expand", value: "profile", enabled: true },
|
||||
{ name: "inactive", value: "true", enabled: false },
|
||||
],
|
||||
headers: [{ name: "X-Disabled", value: "ignored", enabled: false }],
|
||||
settingFollowRedirects: { enabled: true, value: false },
|
||||
settingRequestTimeout: { enabled: true, value: 2000 },
|
||||
});
|
||||
expect(graphql).toMatchObject({
|
||||
bodyType: "graphql",
|
||||
method: "POST",
|
||||
authenticationType: "basic",
|
||||
authentication: { username: "${[ client ]}" },
|
||||
body: {
|
||||
query: "query Get($id: ID!) { node(id: $id) { id } }",
|
||||
variables: '{"id":"${[ userId ]}"}',
|
||||
},
|
||||
headers: [{ name: "Content-Type", value: "application/json", enabled: true }],
|
||||
});
|
||||
expect(publicRequest).toMatchObject({ authenticationType: "none", folderId: null });
|
||||
expect(upload?.body?.form).toEqual([
|
||||
{ name: "label", value: "${[ client ]}", enabled: true },
|
||||
{ name: "files", file: "./first.txt", contentType: "text/plain", enabled: true },
|
||||
{ name: "files", file: "./second.txt", contentType: "text/plain", enabled: true },
|
||||
]);
|
||||
expect(grpc).toMatchObject({
|
||||
service: "example.Greeter",
|
||||
method: "SayHello",
|
||||
message: '{"name":"${[ client ]}"}',
|
||||
});
|
||||
expect(ws).toMatchObject({
|
||||
message: '{"subscribe":"${[ client ]}"}',
|
||||
authenticationType: null,
|
||||
});
|
||||
const all = Object.values(imported.resources).flat();
|
||||
expect(new Set(all.map((r) => r.id)).size).toBe(all.length);
|
||||
expect(
|
||||
all.filter((r) => r.model !== "workspace").every((r) => r.workspaceId === workspace!.id),
|
||||
).toBe(true);
|
||||
expect(imported.sourceKeys).toBeUndefined();
|
||||
expect(convertBruno(fixture)).toEqual(imported);
|
||||
});
|
||||
|
||||
test("accepts JSON serialization and inline collections without a bundled flag", () => {
|
||||
expect(convertBruno(JSON.stringify(YAML.parse(fixture)))).toEqual(convertBruno(fixture));
|
||||
expect(
|
||||
convertBruno(JSON.stringify({ opencollection: "1.0.0", items: [] }))?.resources.workspaces,
|
||||
).toHaveLength(1);
|
||||
expect(convertBruno(JSON.stringify(collection()))?.resources.httpRequests).toHaveLength(0);
|
||||
});
|
||||
|
||||
test.each([
|
||||
"",
|
||||
"not: [valid",
|
||||
"null",
|
||||
"[]",
|
||||
"openapi: 3.1.0",
|
||||
'{"info":{"name":"Postman"},"item":[]}',
|
||||
"meta { name: Test }",
|
||||
"opencollection: 1.0.0\nbundled: true\nitems: &items [*items]",
|
||||
])("ignores unrelated, malformed, or cyclic input: %s", (input) => {
|
||||
expect(convertBruno(input)).toBeNull();
|
||||
});
|
||||
|
||||
test("rejects directory config and unknown format versions with actionable errors", () => {
|
||||
expect(() => convertBruno("opencollection: 1.0.0\ninfo:\n name: Directory")).toThrow(
|
||||
"Share menu",
|
||||
);
|
||||
expect(() => convertBruno(JSON.stringify(collection([], { bundled: false })))).toThrow(
|
||||
"single YAML file",
|
||||
);
|
||||
expect(() => convertBruno(JSON.stringify(collection([], { opencollection: "2.0.0" })))).toThrow(
|
||||
"Unsupported Bruno collection format version",
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects missing and cyclic environment parents", () => {
|
||||
for (const environments of [
|
||||
[{ name: "A", extends: "missing" }],
|
||||
[{ name: "A", extends: "A" }],
|
||||
[
|
||||
{ name: "A", extends: "B" },
|
||||
{ name: "B", extends: "A" },
|
||||
],
|
||||
]) {
|
||||
expect(() =>
|
||||
convertBruno(JSON.stringify(collection([], { config: { environments } }))),
|
||||
).toThrow(/environment/);
|
||||
}
|
||||
});
|
||||
|
||||
test("retains scripts, request variables, unsupported authentication, and unknown items for manual migration", () => {
|
||||
const result = convertBruno(
|
||||
JSON.stringify(
|
||||
collection([
|
||||
{
|
||||
info: { name: "Scripted", type: "http" },
|
||||
http: { url: "{{host}}", auth: { type: "wsse", username: "test" } },
|
||||
runtime: {
|
||||
scripts: [{ code: "bru.setVar('token', 'example');\n```" }],
|
||||
variables: [{ name: "host", value: "https://example.com" }],
|
||||
},
|
||||
},
|
||||
{ info: { name: "App", type: "app" }, code: "example" },
|
||||
]),
|
||||
),
|
||||
)!;
|
||||
expect(result.resources.httpRequests[0]).toMatchObject({ authenticationType: "none" });
|
||||
const desc = result.resources.httpRequests[0]!.description;
|
||||
expect(desc).toContain("not executed");
|
||||
expect(desc).toContain("bru.setVar");
|
||||
expect(desc).toContain("variables:");
|
||||
expect(desc).toContain("wsse");
|
||||
expect(desc).toContain("````yaml");
|
||||
expect(result.resources.folders[0]?.description).toContain("unsupportedItem:");
|
||||
});
|
||||
|
||||
test("does not override a collection Content-Type with a generated body header", () => {
|
||||
const result = convertBruno(
|
||||
JSON.stringify(
|
||||
collection(
|
||||
[{ info: { name: "JSON", type: "http" }, http: { body: { type: "json", data: "{}" } } }],
|
||||
{
|
||||
request: { headers: [{ name: "content-type", value: "application/vnd.example+json" }] },
|
||||
},
|
||||
),
|
||||
),
|
||||
)!;
|
||||
expect(result.resources.httpRequests[0]?.headers).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("request conversion", () => {
|
||||
test.each([
|
||||
["json", "application/json", "application/json"],
|
||||
["xml", "application/xml", "application/xml"],
|
||||
["text", "other", "text/plain"],
|
||||
["sparql", "other", "application/sparql-query"],
|
||||
])("imports %s bodies with a default content type", (type, bodyType, contentType) => {
|
||||
expect(body({ type, data: "{{value}}" }, false, [])).toEqual({
|
||||
bodyType,
|
||||
body: { text: "${[ value ]}" },
|
||||
headers: [{ name: "Content-Type", value: contentType, enabled: true }],
|
||||
});
|
||||
});
|
||||
test("preserves explicit and disabled Content-Type headers", () => {
|
||||
expect(
|
||||
body({ type: "json", data: "{}" }, false, [
|
||||
{ name: "CONTENT-type", value: "custom", disabled: true },
|
||||
]).headers,
|
||||
).toEqual([{ name: "CONTENT-type", value: "custom", enabled: false }]);
|
||||
});
|
||||
test("imports form fields and the selected file or body variant", () => {
|
||||
expect(
|
||||
body(
|
||||
{ type: "form-urlencoded", data: [{ name: "field", value: "{{value}}", disabled: true }] },
|
||||
false,
|
||||
[],
|
||||
).body,
|
||||
).toEqual({ form: [{ name: "field", value: "${[ value ]}", enabled: false }] });
|
||||
expect(
|
||||
body(
|
||||
{
|
||||
type: "file",
|
||||
data: [
|
||||
{ filePath: "wrong", selected: false },
|
||||
{ filePath: "./correct.bin", selected: true, contentType: "application/octet-stream" },
|
||||
],
|
||||
},
|
||||
false,
|
||||
[],
|
||||
),
|
||||
).toMatchObject({ bodyType: "binary", body: { filePath: "./correct.bin" } });
|
||||
expect(
|
||||
body(
|
||||
[
|
||||
{ title: "A", body: { type: "json", data: "a" } },
|
||||
{ title: "B", selected: true, body: { type: "json", data: "b" } },
|
||||
],
|
||||
false,
|
||||
[],
|
||||
).body,
|
||||
).toEqual({ text: "b" });
|
||||
expect(
|
||||
body({ type: "file", data: [{ filePath: "disabled", selected: false }] }, false, []).bodyType,
|
||||
).toBeNull();
|
||||
});
|
||||
test("imports raw GraphQL variables without parsing expressions and preserves operationName", () => {
|
||||
expect(
|
||||
body(
|
||||
{ query: "query Get { me }", variables: '{"id": {{id}}}', operationName: "Get" },
|
||||
true,
|
||||
[],
|
||||
).body,
|
||||
).toEqual({ query: "query Get { me }", variables: '{"id": ${[ id ]}}', operationName: "Get" });
|
||||
expect(body({ query: "{ me }", variables: { id: "{{id}}" } }, true, []).body.variables).toBe(
|
||||
'{\n "id": "${[ id ]}"\n}',
|
||||
);
|
||||
});
|
||||
test("avoids duplicate encoded query keys without losing unrelated query entries or fragments", () => {
|
||||
expect(
|
||||
urlAndParams("{{host}}/a?some%20key=old&some+key=old&keep=%2F#part", [
|
||||
{ type: "query", name: "some key", value: "new" },
|
||||
]),
|
||||
).toMatchObject({
|
||||
url: "${[ host ]}/a?keep=%2F#part",
|
||||
urlParameters: [{ name: "some key", value: "new" }],
|
||||
});
|
||||
expect(urlAndParams("{{host}}/a?x=1", []).url).toBe("${[ host ]}/a?x=1");
|
||||
});
|
||||
test("converts plain variables and preserves unsupported expressions", () => {
|
||||
expect(
|
||||
template(
|
||||
"{{ host }} {{user.id}} {{process.env.TOKEN}} {{$randomUUID}} {{a + b}} {{true}} {{null}}",
|
||||
),
|
||||
).toBe(
|
||||
"${[ host ]} ${[ user.id ]} {{process.env.TOKEN}} {{$randomUUID}} {{a + b}} {{true}} {{null}}",
|
||||
);
|
||||
expect(
|
||||
variables([
|
||||
{ name: "secret", secret: true, value: "must not import" },
|
||||
{
|
||||
name: "variant",
|
||||
value: [{ value: "a" }, { selected: true, value: { type: "object", data: '{"x":1}' } }],
|
||||
},
|
||||
]),
|
||||
).toEqual([
|
||||
{ name: "secret", value: "", enabled: true },
|
||||
{ name: "variant", value: '{"x":1}', enabled: true },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("authentication", () => {
|
||||
test("distinguishes request no-auth from explicit and folder inheritance", () => {
|
||||
expect(auth(undefined).authenticationType).toBe("none");
|
||||
expect(auth("inherit").authenticationType).toBeNull();
|
||||
expect(auth(undefined, true).authenticationType).toBeNull();
|
||||
});
|
||||
test.each([
|
||||
["basic", "basic"],
|
||||
["digest", "digest"],
|
||||
["ntlm", "windows"],
|
||||
["bearer", "bearer"],
|
||||
["awsv4", "awsv4"],
|
||||
])("imports %s auth", (type, expected) => {
|
||||
expect(auth({ type, username: "{{user}}", token: "{{token}}" }).authenticationType).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
test("maps API key placement and OAuth client credentials/PKCE", () => {
|
||||
expect(auth({ type: "apikey", key: "key", value: "{{token}}", placement: "query" })).toEqual({
|
||||
authenticationType: "apikey",
|
||||
authentication: { key: "key", value: "${[ token ]}", location: "query" },
|
||||
});
|
||||
expect(
|
||||
auth({
|
||||
type: "oauth2",
|
||||
flow: "authorization_code",
|
||||
credentials: { clientId: "{{client}}", placement: "basic_auth_header" },
|
||||
callbackUrl: "http://localhost/callback",
|
||||
pkce: { method: "S256" },
|
||||
tokenConfig: { placement: { header: "Token" } },
|
||||
}).authentication,
|
||||
).toMatchObject({
|
||||
grantType: "authorization_code",
|
||||
clientId: "${[ client ]}",
|
||||
credentials: "basic",
|
||||
redirectUri: "http://localhost/callback",
|
||||
usePkce: true,
|
||||
pkceChallengeMethod: "S256",
|
||||
headerPrefix: "Token",
|
||||
});
|
||||
expect(
|
||||
auth({
|
||||
type: "oauth2",
|
||||
flow: "resource_owner_password_credentials",
|
||||
resourceOwner: { username: "a", password: "b" },
|
||||
}).authentication,
|
||||
).toMatchObject({ grantType: "password", username: "a", password: "b" });
|
||||
expect(auth({ type: "oauth2", flow: "client_credentials" }).authentication).toMatchObject({
|
||||
grantType: "client_credentials",
|
||||
credentials: "body",
|
||||
usePkce: false,
|
||||
});
|
||||
});
|
||||
test.each([
|
||||
{ type: "awsv4", profileName: "local" },
|
||||
{ type: "oauth2", flow: "client_credentials", tokenConfig: { placement: { query: "token" } } },
|
||||
{ type: "oauth2", flow: "unknown" },
|
||||
{ type: "wsse" },
|
||||
])("does not silently inherit auth for unsupported configurations", (value) => {
|
||||
expect(auth(value).authenticationType).toBe("none");
|
||||
});
|
||||
});
|
||||
|
||||
describe("scope and unsupported-field regressions", () => {
|
||||
test("flattens multi-level environments without disabled overrides hiding inherited values", () => {
|
||||
const environments = [
|
||||
{
|
||||
name: "Child",
|
||||
extends: "Middle",
|
||||
variables: [
|
||||
{ name: "a", value: "disabled", disabled: true },
|
||||
{ name: "b", value: "child" },
|
||||
],
|
||||
},
|
||||
{ name: "Middle", extends: "Root", variables: [{ name: "a", value: "middle" }] },
|
||||
{
|
||||
name: "Root",
|
||||
variables: [
|
||||
{ name: "a", value: "root" },
|
||||
{ name: "b", value: "root" },
|
||||
{ name: "off", value: "ignored", disabled: true },
|
||||
],
|
||||
},
|
||||
];
|
||||
const result = convertBruno(JSON.stringify(collection([], { config: { environments } })))!;
|
||||
const child = result.resources.environments[1]!;
|
||||
expect(child.parentId).toBeNull();
|
||||
expect(child.variables).toEqual([
|
||||
{ name: "a", value: "middle", enabled: true },
|
||||
{ name: "a", value: "disabled", enabled: false },
|
||||
{ name: "b", value: "child", enabled: true },
|
||||
]);
|
||||
});
|
||||
|
||||
test("distinguishes an empty folder from folder request defaults with no auth", () => {
|
||||
const result = convertBruno(
|
||||
JSON.stringify(
|
||||
collection([
|
||||
{ info: { type: "folder", name: "Empty" } },
|
||||
{ info: { type: "folder", name: "No auth" }, request: { headers: [] } },
|
||||
{ info: { type: "folder", name: "Inherited" }, request: { auth: "inherit" } },
|
||||
]),
|
||||
),
|
||||
)!;
|
||||
expect(result.resources.folders.map((f) => f.authenticationType)).toEqual([null, "none", null]);
|
||||
});
|
||||
|
||||
test("retains external environment settings and unknown bodies, and does not turn binary WS data into text", () => {
|
||||
const result = convertBruno(
|
||||
JSON.stringify(
|
||||
collection(
|
||||
[
|
||||
{
|
||||
info: { type: "http", name: "Unknown body" },
|
||||
http: { body: { type: "future", data: "original" } },
|
||||
},
|
||||
{
|
||||
info: { type: "websocket", name: "Binary" },
|
||||
websocket: { message: { type: "binary", data: "AA==" } },
|
||||
},
|
||||
],
|
||||
{
|
||||
config: {
|
||||
environments: [
|
||||
{
|
||||
name: "Vault",
|
||||
externalSecrets: { type: "aws-secrets-manager" },
|
||||
dotEnvFilePath: "./.env",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
),
|
||||
),
|
||||
)!;
|
||||
expect(result.resources.workspaces[0]?.description).toContain("aws-secrets-manager");
|
||||
expect(result.resources.workspaces[0]?.description).toContain("./.env");
|
||||
expect(result.resources.httpRequests[0]?.description).toContain("original");
|
||||
expect(result.resources.websocketRequests[0]?.message).toBe("");
|
||||
expect(result.resources.websocketRequests[0]?.description).toContain("AA==");
|
||||
});
|
||||
|
||||
test("maps OAuth 1.0 credentials and keeps unsupported private-key files inactive", () => {
|
||||
expect(
|
||||
auth({
|
||||
type: "oauth1",
|
||||
consumerKey: "{{key}}",
|
||||
accessToken: "token",
|
||||
accessTokenSecret: "secret",
|
||||
privateKey: { type: "text", value: "pem" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
authenticationType: "oauth1",
|
||||
authentication: {
|
||||
consumerKey: "${[ key ]}",
|
||||
tokenKey: "token",
|
||||
tokenSecret: "secret",
|
||||
privateKey: "pem",
|
||||
signatureMethod: "HMAC-SHA1",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
auth({ type: "oauth1", privateKey: { type: "file", value: "./key.pem" } }).authenticationType,
|
||||
).toBe("none");
|
||||
expect(auth({ type: "oauth1", placement: "query" }).authenticationType).toBe("none");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { Context } from "@yaakapp/api";
|
||||
import { expect, test } from "vite-plus/test";
|
||||
import { runImporter } from "../../../packages/plugin-runtime/src/importFiles";
|
||||
import { plugin } from "../src";
|
||||
|
||||
// Inputs come unchanged from Bruno, not from this importer's model of its formats.
|
||||
// See fixtures/upstream/README.md for the pinned revision and original paths.
|
||||
async function importFixture(name: string) {
|
||||
const path = fileURLToPath(new URL(`./fixtures/upstream/${name}`, import.meta.url));
|
||||
const result = await runImporter(plugin.importer!, {} as Context, {
|
||||
content: "",
|
||||
source: { type: "directory", path },
|
||||
});
|
||||
expect(result).not.toBeNull();
|
||||
return result!.resources;
|
||||
}
|
||||
|
||||
test("imports Bruno's .bru migration collection with scoped headers, environments, and JSON body", async () => {
|
||||
const resources = await importFixture("bru-migration");
|
||||
const [workspace] = resources.workspaces;
|
||||
expect(resources.workspaces).toHaveLength(1);
|
||||
expect(workspace).toMatchObject({
|
||||
name: "migration-test",
|
||||
headers: [{ name: "X-Collection-Header", value: "migration-test", enabled: true }],
|
||||
});
|
||||
expect(workspace?.description).toContain("Migration Test Collection");
|
||||
expect(workspace?.description).toContain("collectionVar");
|
||||
expect(resources.environments).toHaveLength(3);
|
||||
expect(resources.environments.find((e) => e.name === "Local")?.variables).toEqual([
|
||||
{ name: "host", value: "http://localhost:8081", enabled: true },
|
||||
]);
|
||||
expect(resources.environments.find((e) => e.name === "Production")?.variables).toEqual([
|
||||
{ name: "host", value: "https://api.example.com", enabled: true },
|
||||
]);
|
||||
expect(resources.folders).toHaveLength(1);
|
||||
const [folder] = resources.folders;
|
||||
expect(folder).toMatchObject({
|
||||
name: "api",
|
||||
folderId: null,
|
||||
workspaceId: workspace!.id,
|
||||
headers: [{ name: "X-Folder-Header", value: "api-folder", enabled: true }],
|
||||
});
|
||||
expect(resources.httpRequests).toHaveLength(3);
|
||||
const getUsers = resources.httpRequests.find((r) => r.name === "get-users");
|
||||
expect(getUsers).toMatchObject({
|
||||
folderId: folder!.id,
|
||||
method: "GET",
|
||||
url: "${[ host ]}/api/echo/json",
|
||||
authenticationType: "none",
|
||||
headers: [{ name: "Accept", value: "application/json", enabled: true }],
|
||||
});
|
||||
expect(getUsers?.description).toContain("requestVar");
|
||||
expect(getUsers?.description).toContain("res.status");
|
||||
expect(resources.httpRequests.find((r) => r.name === "ping")).toMatchObject({
|
||||
folderId: null,
|
||||
url: "${[ host ]}/ping",
|
||||
method: "GET",
|
||||
sortPriority: 1,
|
||||
});
|
||||
const post = resources.httpRequests.find((r) => r.name === "post-json");
|
||||
expect(post).toMatchObject({
|
||||
folderId: null,
|
||||
method: "POST",
|
||||
url: "${[ host ]}/api/echo/json",
|
||||
sortPriority: 2,
|
||||
bodyType: "application/json",
|
||||
headers: [{ name: "Content-Type", value: "application/json", enabled: true }],
|
||||
});
|
||||
expect(JSON.parse(post!.body!.text as string)).toEqual({
|
||||
message: "hello from migration test",
|
||||
});
|
||||
});
|
||||
|
||||
test("imports Bruno's YAML docs collection without conflating repeated request names", async () => {
|
||||
const resources = await importFixture("yaml-docs");
|
||||
expect(resources.workspaces).toHaveLength(1);
|
||||
expect(resources.workspaces[0]?.name).toBe("ymlcollection");
|
||||
expect(resources.folders).toHaveLength(2);
|
||||
expect(resources.httpRequests).toHaveLength(4);
|
||||
for (const n of [1, 2]) {
|
||||
const folder = resources.folders.find((f) => f.name === `folder_${n}`);
|
||||
expect(folder).toMatchObject({ folderId: null, sortPriority: n });
|
||||
expect(resources.httpRequests.filter((r) => r.folderId === folder!.id)).toEqual([
|
||||
expect.objectContaining({
|
||||
name: "request_1",
|
||||
method: "GET",
|
||||
url: `https://api.example.com/folder-${n}/one`,
|
||||
sortPriority: 1,
|
||||
}),
|
||||
]);
|
||||
}
|
||||
expect(resources.httpRequests.filter((r) => r.folderId === null)).toEqual([
|
||||
expect.objectContaining({
|
||||
name: "request_1",
|
||||
method: "GET",
|
||||
url: "https://api.example.com/one",
|
||||
sortPriority: 1,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "request_2",
|
||||
method: "GET",
|
||||
url: "https://api.example.com/two",
|
||||
sortPriority: 2,
|
||||
}),
|
||||
]);
|
||||
expect(new Set(resources.httpRequests.map((r) => r.id)).size).toBe(4);
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json"
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
Folder,
|
||||
HttpRequest,
|
||||
HttpUrlParameter,
|
||||
ImportSource,
|
||||
PluginDefinition,
|
||||
Workspace,
|
||||
} from "@yaakapp/api";
|
||||
@@ -86,9 +87,10 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "cURL",
|
||||
description: "Import cURL commands",
|
||||
onImport(_ctx: Context, args: { text: string }) {
|
||||
onImportSource(_ctx: Context, { source }: { source: ImportSource }) {
|
||||
if (source.type !== "text") return null;
|
||||
// oxlint-disable-next-line no-explicit-any
|
||||
return convertCurl(args.text) as any;
|
||||
return convertCurl(source.text) as any;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Context, PluginDefinition } from "@yaakapp/api";
|
||||
import type { Context, ImportSource, PluginDefinition } from "@yaakapp/api";
|
||||
import YAML from "yaml";
|
||||
import { deleteUndefinedAttrs, isJSObject } from "./common";
|
||||
import { convertInsomniaV4 } from "./v4";
|
||||
@@ -8,8 +8,9 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "Insomnia",
|
||||
description: "Import Insomnia workspaces",
|
||||
async onImport(_ctx: Context, args: { text: string }) {
|
||||
return convertInsomnia(args.text);
|
||||
async onImportSource(_ctx: Context, { source }: { source: ImportSource }) {
|
||||
if (source.type !== "text") return null;
|
||||
return convertInsomnia(source.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
HttpRequest,
|
||||
HttpRequestHeader,
|
||||
HttpUrlParameter,
|
||||
ImportSource,
|
||||
PartialImportResources,
|
||||
PluginDefinition,
|
||||
Workspace,
|
||||
@@ -46,8 +47,9 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "OpenAPI",
|
||||
description: "Import OpenAPI collections",
|
||||
onImport(_ctx: Context, args: { text: string }) {
|
||||
return convertOpenApi(args.text);
|
||||
onImportSource(_ctx: Context, { source }: { source: ImportSource }) {
|
||||
if (source.type !== "text") return null;
|
||||
return convertOpenApi(source.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import type {
|
||||
Context,
|
||||
Environment,
|
||||
ImportSource,
|
||||
PartialImportResources,
|
||||
PluginDefinition,
|
||||
Workspace,
|
||||
@@ -19,8 +20,9 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "Postman Environment",
|
||||
description: "Import postman environment exports",
|
||||
onImport(_ctx: Context, args: { text: string }) {
|
||||
return convertPostmanEnvironment(args.text);
|
||||
onImportSource(_ctx: Context, { source }: { source: ImportSource }) {
|
||||
if (source.type !== "text") return null;
|
||||
return convertPostmanEnvironment(source.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
HttpRequest,
|
||||
HttpRequestHeader,
|
||||
HttpUrlParameter,
|
||||
ImportSource,
|
||||
PartialImportResources,
|
||||
PluginDefinition,
|
||||
Workspace,
|
||||
@@ -56,8 +57,9 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "Postman",
|
||||
description: "Import postman collections",
|
||||
onImport(_ctx: Context, args: { text: string }) {
|
||||
return convertPostman(args.text);
|
||||
onImportSource(_ctx: Context, { source }: { source: ImportSource }) {
|
||||
if (source.type !== "text") return null;
|
||||
return convertPostman(source.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,8 +4,9 @@ export const plugin: PluginDefinition = {
|
||||
importer: {
|
||||
name: "Yaak",
|
||||
description: "Yaak official format",
|
||||
onImport(_ctx, args) {
|
||||
return migrateImport(args.text);
|
||||
onImportSource(_ctx, { source }) {
|
||||
if (source.type !== "text") return null;
|
||||
return migrateImport(source.text);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user