Repository navigation
refactor: Separate pure OpenAPI helpers from documentation I/O #37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sidneyswift
wants to merge
2
commits into
main
Choose a base branch
from
codex/untangle-openapi-2026-11-09
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import contextSpec from "../../../content/docs/source/api-reference/openapi/context.json"; | ||
| import { buildCurl } from "../buildCurl"; | ||
|
|
||
| const guestClaim = contextSpec.paths["/api/context/guest/claim"].post; | ||
|
|
||
| function claimCurl(operation = guestClaim) { | ||
| return buildCurl({ method: "POST", endpoint: "/api/context/guest/claim", spec: contextSpec, operation }); | ||
| } | ||
|
|
||
| describe("curl security requirements", () => { | ||
| it("renders both the guest cookie and bearer token required by the published claim operation", () => { | ||
| const curl = claimCurl(); | ||
| expect(curl).toContain("--cookie 'recoup_context_guest=YOUR_API_KEY'"); | ||
| expect(curl).toContain("--header 'Authorization: Bearer YOUR_TOKEN'"); | ||
| expect(curl).toContain("--header 'Origin: YOUR_VALUE'"); | ||
| expect(curl).not.toContain("--header 'recoup_context_guest:"); | ||
| expect(curl).not.toContain("--header 'x-api-key:"); | ||
| }); | ||
|
|
||
| it("renders the published guest read as cookie-only authentication", () => { | ||
| const curl = buildCurl({ method: "GET", endpoint: "/api/context/guest", spec: contextSpec, operation: contextSpec.paths["/api/context/guest"].get }); | ||
| expect(curl).toContain("--cookie 'recoup_context_guest=YOUR_API_KEY'"); | ||
| expect(curl).not.toContain("--header"); | ||
| }); | ||
|
|
||
| it("selects only the first OR alternative while retaining all of its required schemes", () => { | ||
| const curl = claimCurl({ ...guestClaim, security: [...guestClaim.security].reverse() }); | ||
| expect(curl).toContain("--cookie 'recoup_context_guest=YOUR_API_KEY'"); | ||
| expect(curl).toContain("--header 'x-api-key: YOUR_API_KEY'"); | ||
| expect(curl).not.toContain("Authorization:"); | ||
| }); | ||
|
|
||
| it("keeps standalone API-key, bearer, implicit legacy auth and explicit public examples", () => { | ||
| const render = (operation: object) => buildCurl({ method: "GET", endpoint: "/fixture", spec: contextSpec, operation }); | ||
| expect(render({ security: [{ ApiKey: [] }] })).toContain("--header 'x-api-key: YOUR_API_KEY'"); | ||
| expect(render({ security: [{ BearerAuth: [] }] })).toContain("--header 'Authorization: Bearer YOUR_TOKEN'"); | ||
| expect(buildCurl({ method: "GET", endpoint: "/fixture", spec: {}, operation: {} })).toContain("--header 'x-api-key: YOUR_API_KEY'"); | ||
| expect(render({ security: [] })).not.toContain("--header"); | ||
| expect(render({ security: [{}, { BearerAuth: [] }] })).not.toContain("--header"); | ||
| }); | ||
|
|
||
| it("places query keys in the URL, combines required cookies, and keeps shell arguments quoted", () => { | ||
| const spec = { | ||
| security: [{ queryKey: [], cookieA: [], cookieB: [], headerKey: [] }], | ||
| components: { securitySchemes: { | ||
| queryKey: { type: "apiKey", in: "query", name: "access key" }, | ||
| cookieA: { type: "apiKey", in: "cookie", name: "session" }, | ||
| cookieB: { type: "apiKey", in: "cookie", name: "tenant's-session" }, | ||
| headerKey: { type: "apiKey", in: "header", name: "x-custom-key" }, | ||
| } }, | ||
| }; | ||
| const operation = { parameters: [ | ||
| { in: "query", name: "q", required: true, example: "artist & song" }, | ||
| { in: "header", name: "X-CUSTOM-KEY", required: true }, | ||
| ] }; | ||
| const curl = buildCurl({ method: "GET", endpoint: "/fixture", spec, operation }); | ||
| expect(curl).toContain("?q=artist+%26+song&access+key=YOUR_API_KEY'"); | ||
| expect(curl).toContain("--cookie 'session=YOUR_API_KEY; tenant'\"'\"'s-session=YOUR_API_KEY'"); | ||
| expect(curl.match(/--cookie/g)).toHaveLength(1); | ||
| expect(curl).toContain("--header 'x-custom-key: YOUR_API_KEY'"); | ||
| expect(curl).not.toContain("--header 'X-CUSTOM-KEY:"); | ||
| expect(curl).not.toContain("--header 'access key:"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { resolveReference } from "../resolveReference"; | ||
|
|
||
| describe("OpenAPI local references", () => { | ||
| it("resolves escaped pointer names and retains use-site descriptions without mutating the source", () => { | ||
| const shared = { type: "string", description: "Shared description", maxLength: 50 }; | ||
| const spec = { components: { schemas: { "artist/name~label": shared } } }; | ||
| const reference = { $ref: "#/components/schemas/artist~1name~0label", description: "Name used on this request" }; | ||
| expect(resolveReference(reference, spec)).toEqual({ type: "string", description: "Name used on this request", maxLength: 50 }); | ||
| expect(shared.description).toBe("Shared description"); | ||
| expect(reference.$ref).toBe("#/components/schemas/artist~1name~0label"); | ||
| }); | ||
|
|
||
| it.each(["#/components/schemas/Missing", "https://example.com/schema.json#/Artist"])("leaves unresolved reference %s visible", ($ref) => { | ||
| const reference = { $ref, description: "Unresolved schema" }; | ||
| expect(resolveReference(reference, {})).toEqual(reference); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { schemaExample } from "../schemaExample"; | ||
|
|
||
| describe("OpenAPI request examples", () => { | ||
| it("combines required fields from composed request schemas and keeps the first alternative", () => { | ||
| const spec = { components: { schemas: { | ||
| Artist: { type: "object", required: ["artist_id"], properties: { artist_id: { type: "string", format: "uuid" }, note: { type: "string" } } }, | ||
| } } }; | ||
| const schema = { allOf: [ | ||
| { $ref: "#/components/schemas/Artist" }, | ||
| { oneOf: [ | ||
| { type: "object", properties: { action: { enum: ["claim"] }, enabled: { type: "boolean", default: false } } }, | ||
| { type: "object", properties: { action: { enum: ["release"] } } }, | ||
| ] }, | ||
| ] }; | ||
| expect(schemaExample(schema, spec)).toEqual({ artist_id: "YOUR_ID", action: "claim", enabled: false }); | ||
| }); | ||
|
|
||
| it.each([null, false, 0, ""])("does not replace an explicit %j example with a default", (example) => { | ||
| expect(schemaExample({ example, default: "fallback" }, {})).toBe(example); | ||
| }); | ||
|
|
||
| it("produces a serializable example for a recursive schema without recursing forever", () => { | ||
| const node = { type: "object", required: ["label", "child"], properties: { label: { example: "node" }, child: { $ref: "#/components/schemas/Node" } } }; | ||
| const spec = { components: { schemas: { Node: node } } }; | ||
| const example = schemaExample({ $ref: "#/components/schemas/Node" }, spec); | ||
| expect(example).toMatchObject({ label: "node", child: { label: "node" } }); | ||
| expect(() => JSON.stringify(example)).not.toThrow(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| // OpenAPI is intentionally open-ended; the full source remains downloadable, including vendor extensions. | ||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| export type ApiObject = Record<string, any>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import type { ApiObject } from "./apiObject.ts"; | ||
| import { resolveReference } from "./resolveReference.ts"; | ||
| import { schemaExample } from "./schemaExample.ts"; | ||
|
|
||
| function shellQuote(value:string) { return `'${value.replace(/'/g, `'"'"'`)}'`; } | ||
| export function buildCurl({method,endpoint,spec,operation,pathItem={}}:{method:string;endpoint:string;spec:ApiObject;operation:ApiObject;pathItem?:ApiObject}):string { | ||
| const parameters=[...(pathItem.parameters||[]),...(operation.parameters||[])].map(parameter=>resolveReference(parameter,spec)); | ||
| const base=(operation.servers||pathItem.servers||spec.servers)?.[0]?.url||'https://api.recoupable.dev'; | ||
| const route=endpoint.replace(/\{([^}]+)\}/g,(_match,name)=>`YOUR_${name.replace(/([a-z])([A-Z])/g,'$1_$2').toUpperCase()}`); | ||
| const query=new URLSearchParams(); | ||
| for(const parameter of parameters.filter(parameter=>parameter.in==='query'&¶meter.required)) { | ||
| const value=parameter.example??parameter.schema?.example??parameter.schema?.default??`YOUR_${parameter.name.toUpperCase()}`; | ||
| query.append(parameter.name,typeof value==='object'?JSON.stringify(value):String(value)); | ||
| } | ||
| const security = operation.security ?? spec.security; | ||
| const schemes = security == null | ||
| ? [{ type: 'apiKey', in: 'header', name: 'x-api-key' }] | ||
| : Object.keys(security[0] ?? {}).map(name => resolveReference(spec.components?.securitySchemes?.[name], spec)); | ||
| const authHeaders = new Map<string, string>(); | ||
| const cookies = new Map<string, string>(); | ||
| for (const scheme of schemes) { | ||
| if (scheme.scheme === 'bearer') { | ||
| authHeaders.set('Authorization', 'Bearer YOUR_TOKEN'); | ||
| } else if (scheme.type === 'apiKey' && scheme.in === 'query') { | ||
| query.set(scheme.name, 'YOUR_API_KEY'); | ||
| } else if (scheme.type === 'apiKey' && scheme.in === 'cookie') { | ||
| cookies.set(scheme.name, 'YOUR_API_KEY'); | ||
| } else { | ||
| authHeaders.set(scheme.name || 'x-api-key', 'YOUR_API_KEY'); | ||
| } | ||
| } | ||
| const lines=[`curl --request ${method}`,` --url ${shellQuote(base+route+(query.size?`?${query}`:''))}`]; | ||
| for (const [name, value] of authHeaders) lines.push(` --header ${shellQuote(`${name}: ${value}`)}`); | ||
| if (cookies.size) lines.push(` --cookie ${shellQuote([...cookies].map(([name, value]) => `${name}=${value}`).join('; '))}`); | ||
| const authHeaderNames = new Set([...authHeaders.keys()].map(name => name.toLowerCase())); | ||
| for(const parameter of parameters.filter(parameter=>parameter.in==='header'&¶meter.required&&!authHeaderNames.has(parameter.name.toLowerCase())&¶meter.name.toLowerCase()!=='x-api-key'))lines.push(` --header ${shellQuote(`${parameter.name}: ${parameter.example??parameter.schema?.example??'YOUR_VALUE'}`)}`); | ||
| const body=resolveReference(operation.requestBody,spec); | ||
| const mediaType=body.content?.['application/json']?'application/json':Object.keys(body.content||{})[0]; | ||
| const media=body.content?.[mediaType]; | ||
| const schema=resolveReference(media?.schema,spec); | ||
| const example=media?.example??(media?.examples?resolveReference(Object.values(media.examples)[0] as ApiObject,spec).value:undefined)??(media?.schema?schemaExample(media.schema,spec):undefined); | ||
| if(mediaType==='multipart/form-data'||mediaType==='application/x-www-form-urlencoded') { | ||
| for(const [name,raw] of Object.entries(schema.properties||{})) { | ||
| if(schema.required&&!schema.required.includes(name))continue; | ||
| const property=resolveReference(raw as ApiObject,spec); | ||
| const value=property.format==='binary'||property.items?.format==='binary'?'@YOUR_FILE_PATH':(example as ApiObject)?.[name]??schemaExample(property,spec)??'YOUR_VALUE'; | ||
| lines.push(` ${mediaType==='multipart/form-data'?'--form':'--data-urlencode'} ${shellQuote(`${name}=${typeof value==='object'?JSON.stringify(value):String(value)}`)}`); | ||
| } | ||
| } else if(mediaType) { | ||
| lines.push(` --header ${shellQuote(`Content-Type: ${mediaType}`)}`); | ||
| if(example!==undefined)lines.push(` --data ${shellQuote(typeof example==='string'?example:JSON.stringify(example,null,2))}`); | ||
| } | ||
| return lines.join(' \\\n'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import type { ApiObject } from "./apiObject.ts"; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: This new module has no direct unit test. Add Prompt for AI agents |
||
|
|
||
| export function resolveReference(value:ApiObject|undefined,spec:ApiObject):ApiObject { | ||
| if(!value)return {}; | ||
| if(!value.$ref)return value; | ||
| if(!value.$ref.startsWith('#/'))return value; | ||
| let resolved:ApiObject=spec; | ||
| for(const part of value.$ref.slice(2).split('/'))resolved=resolved?.[part.replace(/~1/g,'/').replace(/~0/g,'~')]; | ||
| return resolved ? {...resolved,...Object.fromEntries(Object.entries(value).filter(([key])=>key!=='$ref'))}:value; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3: Bearer detection is case-sensitive. A spec declaring
"scheme": "Bearer"(valid per OpenAPI, which treats the value case-insensitively) falls through to thex-api-keyheader. Compare withString(scheme.scheme).toLowerCase().Prompt for AI agents