From fba8bc46b042c54165fe44b4551a49ad0cbbc0c4 Mon Sep 17 00:00:00 2001 From: Michael van Tellingen Date: Mon, 23 Nov 2026 17:05:32 +0100 Subject: [PATCH] feat(bruno): add a yml format for OpenCollection collections A Bruno collection with an opencollection.yml does not load .bru files, so the generated requests did not show up in it. format: "yml" writes them as OpenCollection requests instead; the default stays bru. clean now removes generated requests of both formats, so switching leaves none behind. --- .changeset/bruno-opencollection-format.md | 5 + packages/bruno/README.md | 3 +- packages/bruno/package.json | 3 +- .../yml/mutations/UpdateCustomer.yml | 34 +++++++ .../__snapshots__/yml/queries/GetCustomer.yml | 38 ++++++++ .../__snapshots__/yml/queries/GetProduct.yml | 25 +++++ .../yml/subscriptions/CustomerUpdated.yml | 35 +++++++ packages/bruno/src/bruno.ts | 7 +- packages/bruno/src/index.test.ts | 94 +++++++++++++++++++ packages/bruno/src/index.ts | 29 ++++-- packages/bruno/src/opencollection.ts | 75 +++++++++++++++ pnpm-lock.yaml | 3 + 12 files changed, 340 insertions(+), 11 deletions(-) create mode 100644 .changeset/bruno-opencollection-format.md create mode 100644 packages/bruno/src/__snapshots__/yml/mutations/UpdateCustomer.yml create mode 100644 packages/bruno/src/__snapshots__/yml/queries/GetCustomer.yml create mode 100644 packages/bruno/src/__snapshots__/yml/queries/GetProduct.yml create mode 100644 packages/bruno/src/__snapshots__/yml/subscriptions/CustomerUpdated.yml create mode 100644 packages/bruno/src/opencollection.ts diff --git a/.changeset/bruno-opencollection-format.md b/.changeset/bruno-opencollection-format.md new file mode 100644 index 0000000..4dee295 --- /dev/null +++ b/.changeset/bruno-opencollection-format.md @@ -0,0 +1,5 @@ +--- +"@labdigital/graphql-codegen-bruno": minor +--- + +Add the `format` option: `yml` writes the requests in the OpenCollection (YAML) format, for a Bruno collection with an `opencollection.yml`, which does not load `.bru` files. The default stays `bru`. `clean` now also removes previously generated `.yml` requests (except `folder.yml`). diff --git a/packages/bruno/README.md b/packages/bruno/README.md index 8191500..b0fc920 100644 --- a/packages/bruno/README.md +++ b/packages/bruno/README.md @@ -87,11 +87,12 @@ environment, or set `url` to match your environment variables. | Option | Type | Default | Description | | ------ | ---- | ------- | ----------- | -| `clean` | `boolean` | `false` | Remove the previously generated requests before generating: the `.bru` files in the `queries/`, `mutations/` and `subscriptions/` folders of the output directory (except `folder.bru`), and those folders when they are empty afterwards. Other files, such as `bruno.json`, `collection.bru` or environments, are never removed. | +| `clean` | `boolean` | `false` | Remove the previously generated requests before generating: the `.bru` and `.yml` files in the `queries/`, `mutations/` and `subscriptions/` folders of the output directory (except `folder.bru` and `folder.yml`), and those folders when they are empty afterwards. Other files, such as `bruno.json`, `collection.bru` or environments, are never removed. | | `url` | `string` | `"{{graphql-gateway}}/graphql"` | URL of every request. May use Bruno variables. | | `auth` | `string` | `"none"` | Auth mode of every request. Use `inherit` to use the auth configured on the collection or folder. | | `headers` | `Record` | `{}` | Headers added to the `headers` block of every request. Values may use Bruno variables, such as `{{token}}`. | | `defaults` | `Record` | `{}` | Values for operation variables, by variable name. A default replaces the generated example value of a top-level variable with the same name; variables that the operation does not declare are ignored. | +| `format` | `"bru" \| "yml"` | `"bru"` | File format of the requests. Use `yml` for a collection in the OpenCollection format (an `opencollection.yml` in its root), which does not load `.bru` files. `clean` removes generated requests of both formats, so switching format leaves no old requests behind. | ## Example output diff --git a/packages/bruno/package.json b/packages/bruno/package.json index 99fbb6b..5a418c8 100644 --- a/packages/bruno/package.json +++ b/packages/bruno/package.json @@ -46,7 +46,8 @@ "publint": "^0.3.25", "tsdown": "^0.23.1", "typescript": "^7.0.2", - "vitest": "5.0.3" + "vitest": "5.0.3", + "yaml": "2.9.1" }, "peerDependencies": { "graphql": "^16.0.0 || ^17.0.0" diff --git a/packages/bruno/src/__snapshots__/yml/mutations/UpdateCustomer.yml b/packages/bruno/src/__snapshots__/yml/mutations/UpdateCustomer.yml new file mode 100644 index 0000000..02dad6c --- /dev/null +++ b/packages/bruno/src/__snapshots__/yml/mutations/UpdateCustomer.yml @@ -0,0 +1,34 @@ +info: + name: "UpdateCustomer" + type: graphql + seq: 1 + +graphql: + method: POST + url: "{{graphql-gateway}}/graphql" + body: + query: |- + mutation UpdateCustomer($id: ID!, $firstName: String) { + updateCustomer(id: $id, firstName: $firstName) { + id + ...CustomerDetails + } + } + + fragment CustomerDetails on Customer { + firstName + email + addresses { + ...AddressDetails + } + } + + fragment AddressDetails on Address { + id + city + } + variables: |- + { + "id": "example-id", + "firstName": "example" + } diff --git a/packages/bruno/src/__snapshots__/yml/queries/GetCustomer.yml b/packages/bruno/src/__snapshots__/yml/queries/GetCustomer.yml new file mode 100644 index 0000000..836fbb1 --- /dev/null +++ b/packages/bruno/src/__snapshots__/yml/queries/GetCustomer.yml @@ -0,0 +1,38 @@ +info: + name: "GetCustomer" + type: graphql + seq: 1 + +graphql: + method: POST + url: "{{graphql-gateway}}/graphql" + body: + query: |- + query GetCustomer($info: CustomerInfo!) { + customer(info: $info) { + ...CustomerDetails + } + } + + fragment CustomerDetails on Customer { + firstName + email + addresses { + ...AddressDetails + } + } + + fragment AddressDetails on Address { + id + city + } + variables: |- + { + "info": { + "credentials": { + "email": "example", + "password": "example" + }, + "authMethod": "EMAIL" + } + } diff --git a/packages/bruno/src/__snapshots__/yml/queries/GetProduct.yml b/packages/bruno/src/__snapshots__/yml/queries/GetProduct.yml new file mode 100644 index 0000000..fe0fa4a --- /dev/null +++ b/packages/bruno/src/__snapshots__/yml/queries/GetProduct.yml @@ -0,0 +1,25 @@ +info: + name: "GetProduct" + type: graphql + seq: 2 + +graphql: + method: POST + url: "{{graphql-gateway}}/graphql" + body: + query: |- + query GetProduct($id: ID!) { + product(id: $id) { + ...ProductFields + } + } + + fragment ProductFields on Product { + id + name + price + } + variables: |- + { + "id": "example-id" + } diff --git a/packages/bruno/src/__snapshots__/yml/subscriptions/CustomerUpdated.yml b/packages/bruno/src/__snapshots__/yml/subscriptions/CustomerUpdated.yml new file mode 100644 index 0000000..0067a8a --- /dev/null +++ b/packages/bruno/src/__snapshots__/yml/subscriptions/CustomerUpdated.yml @@ -0,0 +1,35 @@ +info: + name: "CustomerUpdated" + type: graphql + seq: 1 + +graphql: + method: POST + url: "{{graphql-gateway}}/graphql" + body: + query: |- + subscription CustomerUpdated($id: ID!) { + customerUpdated(id: $id) { + id + ... on Customer { + ...CustomerDetails + } + } + } + + fragment CustomerDetails on Customer { + firstName + email + addresses { + ...AddressDetails + } + } + + fragment AddressDetails on Address { + id + city + } + variables: |- + { + "id": "example-id" + } diff --git a/packages/bruno/src/bruno.ts b/packages/bruno/src/bruno.ts index 72092f1..ec2383c 100644 --- a/packages/bruno/src/bruno.ts +++ b/packages/bruno/src/bruno.ts @@ -24,6 +24,11 @@ export interface BrunoPluginConfig { * collection. Defaults to `none`. */ auth?: string; + /** + * File format of the requests: `bru` for a collection with a `bruno.json`, + * `yml` for a collection with an `opencollection.yml`. Defaults to `bru`. + */ + format?: "bru" | "yml"; } export const asBruno = ( @@ -56,7 +61,7 @@ export const asBruno = ( return file.toString(); }; -const mergeDefaults = ( +export const mergeDefaults = ( vars: Record, defaults: Record, ) => { diff --git a/packages/bruno/src/index.test.ts b/packages/bruno/src/index.test.ts index b73749c..e14ad90 100644 --- a/packages/bruno/src/index.test.ts +++ b/packages/bruno/src/index.test.ts @@ -5,6 +5,7 @@ import type { Types } from "@graphql-codegen/plugin-helpers"; import { GraphQLFileLoader } from "@graphql-tools/graphql-file-loader"; import { loadDocumentsSync, loadSchemaSync } from "@graphql-tools/load"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { parse as parseYaml } from "yaml"; import type { BrunoPluginConfig } from "./bruno"; import { plugin } from "./index"; @@ -152,7 +153,100 @@ describe("Bruno Plugin", () => { expect(getProduct).toContain('"id": "product-1"'); }); + describe("format: yml", () => { + const ymlConfig: BrunoPluginConfig = { ...defaultConfig, format: "yml" }; + + it("writes OpenCollection requests", async () => { + const data = await plugin(schema, documents, ymlConfig, { outputFile }); + + expect(JSON.parse(data as string).GetProduct.filename).toBe( + "GetProduct.yml", + ); + expect(listFiles(outputDir)).toEqual([ + path.join("mutations", "UpdateCustomer.yml"), + path.join("queries", "GetCustomer.yml"), + path.join("queries", "GetProduct.yml"), + path.join("subscriptions", "CustomerUpdated.yml"), + ]); + for (const file of listFiles(outputDir)) { + await expect(read(file)).toMatchFileSnapshot( + path.join(snapshotDir, "yml", file), + ); + } + }); + + it("parses to the operation, its fragments and variables", async () => { + await plugin( + schema, + documents, + { + ...ymlConfig, + url: "{{baseUrl}}/api/graphql", + auth: "inherit", + headers: { Authorization: "Bearer {{token}}", "X-Note": 'a: "b"' }, + defaults: { id: "product-1" }, + }, + { outputFile }, + ); + + const request = parseYaml(read(path.join("queries", "GetProduct.yml"))); + expect(request.info).toEqual({ + name: "GetProduct", + type: "graphql", + seq: 2, + }); + expect(request.graphql.url).toBe("{{baseUrl}}/api/graphql"); + expect(request.graphql.auth).toBe("inherit"); + expect(request.graphql.headers).toEqual([ + { name: "Authorization", value: "Bearer {{token}}" }, + { name: "X-Note", value: 'a: "b"' }, + ]); + expect(request.graphql.body.query).toContain("query GetProduct"); + expect(request.graphql.body.query).toContain("fragment ProductFields"); + expect(JSON.parse(request.graphql.body.variables)).toEqual({ + id: "product-1", + }); + }); + + it("leaves auth out for none, and writes another mode as its type", async () => { + await plugin(schema, documents, ymlConfig, { outputFile }); + const none = parseYaml(read(path.join("queries", "GetProduct.yml"))); + expect(none.graphql.auth).toBeUndefined(); + + await plugin( + schema, + documents, + { ...ymlConfig, auth: "bearer" }, + { outputFile }, + ); + const bearer = parseYaml(read(path.join("queries", "GetProduct.yml"))); + expect(bearer.graphql.auth).toEqual({ type: "bearer" }); + }); + }); + describe("clean", () => { + it("removes requests generated in the other format", async () => { + const writeFile = (file: string) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, ""); + }; + writeFile(path.join(outputDir, "queries", "Removed.yml")); + writeFile(path.join(outputDir, "queries", "folder.yml")); + + await plugin( + schema, + documents, + { ...defaultConfig, clean: true }, + { outputFile }, + ); + + expect(listFiles(path.join(outputDir, "queries"))).toEqual([ + "GetCustomer.bru", + "GetProduct.bru", + "folder.yml", + ]); + }); + const writeFile = (file: string, content = "") => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); diff --git a/packages/bruno/src/index.ts b/packages/bruno/src/index.ts index 61ab092..b61188b 100644 --- a/packages/bruno/src/index.ts +++ b/packages/bruno/src/index.ts @@ -3,6 +3,7 @@ import path from "node:path"; import type { PluginFunction, Types } from "@graphql-codegen/plugin-helpers"; import type { GraphQLSchema, OperationTypeNode } from "graphql"; import { asBruno, type BrunoPluginConfig } from "./bruno"; +import { asOpenCollection } from "./opencollection"; import { extractOperations } from "./operations"; export const plugin: PluginFunction = async ( @@ -22,16 +23,25 @@ export const plugin: PluginFunction = async ( const operations = extractOperations(schema, documents).sort((a, b) => a.name.localeCompare(b.name), ); + const format = config.format ?? "bru"; + const seqs: Partial> = {}; const result: Record> = {}; for (const operation of operations) { - const fileName = `${operation.name}.bru`; + const fileName = `${operation.name}.${format}`; const outputPath = path.join( outputDir, OPERATION_FOLDERS[operation.kind], fileName, ); + const seq = (seqs[operation.kind] ?? 0) + 1; + seqs[operation.kind] = seq; - outputFileSync(outputPath, asBruno(operation, config)); + outputFileSync( + outputPath, + format === "yml" + ? asOpenCollection(operation, config, seq) + : asBruno(operation, config), + ); result[operation.name] = { filename: fileName, source: operation.location @@ -49,11 +59,14 @@ const OPERATION_FOLDERS: Record = { subscription: "subscriptions", }; +const GENERATED_EXTENSIONS = new Set([".bru", ".yml"]); +const FOLDER_SETTINGS = new Set(["folder.bru", "folder.yml"]); + /** - * Removes the requests generated by a previous run: the `.bru` files in the - * folders this plugin writes to, and those folders when they are empty - * afterwards. Other files, such as `bruno.json`, environments or a - * `folder.bru` with folder settings, are kept. + * Removes the requests generated by a previous run, in either format: the + * `.bru` and `.yml` files in the folders this plugin writes to, and those + * folders when they are empty afterwards. Other files, such as `bruno.json`, + * environments or a `folder.bru`/`folder.yml` with folder settings, are kept. */ function cleanGeneratedFiles(outputDir: string): void { for (const folder of Object.values(OPERATION_FOLDERS)) { @@ -64,8 +77,8 @@ function cleanGeneratedFiles(outputDir: string): void { for (const entry of nodeFs.readdirSync(dirPath, { withFileTypes: true })) { if ( entry.isFile() && - entry.name.endsWith(".bru") && - entry.name !== "folder.bru" + GENERATED_EXTENSIONS.has(path.extname(entry.name)) && + !FOLDER_SETTINGS.has(entry.name) ) { nodeFs.rmSync(path.join(dirPath, entry.name)); } diff --git a/packages/bruno/src/opencollection.ts b/packages/bruno/src/opencollection.ts new file mode 100644 index 0000000..6414d22 --- /dev/null +++ b/packages/bruno/src/opencollection.ts @@ -0,0 +1,75 @@ +import { + type BrunoPluginConfig, + DEFAULT_AUTH, + DEFAULT_URL, + mergeDefaults, +} from "./bruno"; +import type { FileContent } from "./operations"; + +/** + * Renders an operation as an OpenCollection (YAML) request, the format of a + * Bruno collection with an `opencollection.yml` in its root. Such a collection + * does not load `.bru` files. + */ +export const asOpenCollection = ( + operation: FileContent, + config: BrunoPluginConfig, + seq: number, +): string => { + const vars = mergeDefaults(operation.vars, config.defaults ?? {}); + const lines: string[] = [ + "info:", + ` name: ${scalar(operation.name)}`, + " type: graphql", + ` seq: ${seq}`, + "", + "graphql:", + " method: POST", + ` url: ${scalar(config.url ?? DEFAULT_URL)}`, + ]; + + const headers = Object.entries(config.headers ?? {}); + if (headers.length > 0) { + lines.push(" headers:"); + for (const [name, value] of headers) { + lines.push( + ` - name: ${scalar(name)}`, + ` value: ${scalar(value)}`, + ); + } + } + + lines.push( + " body:", + " query: |-", + ...block(operation.content, 6), + " variables: |-", + ...block(JSON.stringify(vars, null, 2), 6), + ); + lines.push(...auth(config.auth ?? DEFAULT_AUTH)); + + return `${lines.join("\n")}\n`; +}; + +/** + * `none` is the absence of auth, so it is left out; `inherit` is a value of its + * own; any other mode becomes `{ type: }`. + */ +const auth = (mode: string): string[] => { + if (mode === "none") { + return []; + } + if (mode === "inherit") { + return [" auth: inherit"]; + } + return [" auth:", ` type: ${scalar(mode)}`]; +}; + +/** A JSON string is a valid YAML double-quoted scalar, so any value is safe. */ +const scalar = (value: string): string => JSON.stringify(value); + +/** The lines of a block scalar; empty lines stay empty, without indentation. */ +const block = (text: string, indent: number): string[] => + text + .split("\n") + .map((line) => (line.trim() === "" ? "" : `${" ".repeat(indent)}${line}`)); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 133b216..00d3941 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -221,6 +221,9 @@ importers: vitest: specifier: 5.0.3 version: 5.0.3(@types/node@26.6.5)(@vitest/coverage-v8@5.0.3)(vite@8.3.4(@types/node@26.6.5)(yaml@2.9.1)) + yaml: + specifier: 2.9.1 + version: 2.9.1 packages/k6: dependencies: