### openapi2insomnia config file JSON example Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Example configuration file for openapi2insomnia. Without it, a single collection is generated using the spec's server URL as base_url. With it, you can generate one collection per environment, each with its own URL, OAuth2 credentials, and generation options. The example shows global options and one environment named DEV. ```json { "minimal_endpoints": false, "generate_oneOf_anyOf": false, "examples": { "correct": { "string": "goodstring", "integer": 1, "number": 1.0, "boolean": true, "date": "2020-01-01", "date-time": "2020-01-01T23:59:59" }, "wrong": { "string": "badstring", "integer": "badstring", "number": "badstring", "boolean": "badboolean", "date": "2020-40-40", "date-time": "2020-40-40T00:00:00" } }, "environments": [ { "name": "DEV", "base_url": "https://dev.api.example.com/v1", "host_server_pattern": "%dev%", "token_url": "https://dev.keycloak.example.com/token", "authorization_url": "https://dev.keycloak.example.com/auth", "client_id": "my-client-dev", "client_secret": "", "target_folder": "out", "microcks_headers": true, "read_only": false, "has_scopes": true, "application_token": true, "number_of_scopes": 2 } ] } ``` -------------------------------- ### Basic usage of generateExample with nested object and array Source: https://github.com/apiaddicts/openapi2insomnia Shows how to call generateExample with an object schema containing properties of various types. The resulting example uses the schema.example value for 'name', 0 for integer, an array with the example item, and the format-based string for email. ```TypeScript import { generateExample } from './src/core/schema-example.js' import type { OASchema } from './src/core/openapi-types.js' const schema: OASchema = { type: 'object', required: ['name'], properties: { name: { type: 'string', example: 'Alice' }, age: { type: 'integer' }, tags: { type: 'array', items: { type: 'string', example: 'tag' } }, email: { type: 'string', format: 'email' }, }, } const example = generateExample(schema) // { name: 'Alice', age: 0, tags: ['tag'], email: 'user@example.com' } ``` -------------------------------- ### Set up development environment with pnpm Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Clones the repository, installs dependencies, and builds the project. Requires pnpm >= 9 for development. ```bash git clone https://github.com/apiaddicts/openapi2insomnia cd openapi2insomnia pnpm install pnpm build ``` -------------------------------- ### Install openapi2insomnia globally via npm Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Installs the openapi2insomnia package globally using npm. Requires Node.js >= 20. ```bash npm install -g openapi2insomnia ``` -------------------------------- ### Example Config from tests/fixtures/o2i.config.json Source: https://github.com/apiaddicts/openapi2insomnia Shows a full configuration file with minimal_endpoints and generate_oneOf_anyOf flags, example values for correct and wrong data, and three environments (DEV, PRE, PROD) with base URLs, token/authorization URLs, client IDs, target folders, and various flags like microcks_headers, read_only, has_scopes, application_token, and number_of_scopes. ```json { "minimal_endpoints": false, "generate_oneOf_anyOf": false, "examples": { "correct": { "string": "goodstring", "integer": 1, "number": 1, "boolean": true, "date": "2020-01-01", "date-time": "2020-01-01T23:59:59" }, "wrong": { "string": "badstring", "integer": "badstring", "number": "badstring", "boolean": "badboolean", "date": "2020-40-40", "date-time": "2020-40-40T00:00:00" } }, "environments": [ { "name": "DEV", "base_url": "https://dev.petstore.example.com/v1", "host_server_pattern": "%dev%", "token_url": "https://dev.keycloak.example.com/realms/petstore/protocol/openid-connect/token", "authorization_url": "https://dev.keycloak.example.com/realms/petstore/protocol/openid-connect/auth", "client_id": "petstore-client-dev", "client_secret": "", "target_folder": "tests/fixtures/collections", "microcks_headers": true, "read_only": false, "has_scopes": true, "application_token": true, "number_of_scopes": 2 }, { "name": "PRE", "base_url": "https://pre.petstore.example.com/v1", "token_url": "https://pre.keycloak.example.com/realms/petstore/protocol/openid-connect/token", "authorization_url": "https://pre.keycloak.example.com/realms/petstore/protocol/openid-connect/auth", "client_id": "petstore-client-pre", "client_secret": "", "target_folder": "tests/fixtures/collections", "microcks_headers": false, "read_only": false, "has_scopes": true, "application_token": false, "number_of_scopes": 2 }, { "name": "PROD", "base_url": "https://petstore.example.com/v1", "host_server_pattern": "%petstore.example.com/v1%", "token_url": "https://keycloak.example.com/realms/petstore/protocol/openid-connect/token", "authorization_url": "https://keycloak.example.com/realms/petstore/protocol/openid-connect/auth", "client_id": "petstore-client-prod", "client_secret": "", "target_folder": "tests/fixtures/collections", "microcks_headers": false, "read_only": true, "has_scopes": false, "application_token": false, "number_of_scopes": 0 } ] } ``` -------------------------------- ### Example usage of buildOAuth2Folder Source: https://github.com/apiaddicts/openapi2insomnia Example usage: parses a spec and builds the OAuth2 folder, logging child names or 'no oauth2'. ```TypeScript import { buildOAuth2Folder, buildBaseEnvData } from './src/core/converter.js' import { parseSpec } from './src/core/parser.js' const doc = await parseSpec('./secured-api.yaml') const oauth2Folder = buildOAuth2Folder(doc) console.log(oauth2Folder ? oauth2Folder.children.map((c) => c.name) : 'no oauth2') ``` -------------------------------- ### Convert OpenAPI spec with various options Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Shows four usage examples: output to stdout, output to a file, with a config file, and from a remote URL. Demonstrates the -o and -c flags. ```bash # Output to stdout o2i convert -i openapi.yaml # Output to a file o2i convert -i openapi.yaml -o collection.yaml # With config (generates one file per environment) o2i convert -i openapi.yaml -c o2i.config.json # From a remote URL o2i convert -i https://api.example.com/openapi.yaml -o collection.yaml ``` -------------------------------- ### Non-trivial usage: allOf merging and oneOf first-variant selection Source: https://github.com/apiaddicts/openapi2insomnia Demonstrates how generateExample handles allOf by merging sub-schemas and oneOf by expanding only the first variant. The oneOf example shows that branch 'b' is never explored, which is why generate_oneOf_anyOf: true is needed for full variant coverage. ```TypeScript import { generateExample } from './src/core/schema-example.js' // allOf: merged object const merged = generateExample({ allOf: [ { type: 'object', properties: { id: { type: 'integer', example: 1 } } }, { type: 'object', properties: { name: { type: 'string', example: 'Alice' } } }, ], }) // { id: 1, name: 'Alice' } // oneOf: only the first branch is expanded const variant = generateExample({ oneOf: [ { type: 'object', properties: { kind: { type: 'string' }, a: { type: 'string' } } }, { type: 'object', properties: { kind: { type: 'string' }, b: { type: 'integer' } } }, ], }) // { kind: '', a: '' } — branch "b" is never explored here ``` -------------------------------- ### convertFolders usage example Source: https://github.com/apiaddicts/openapi2insomnia Example usage of convertFolders with parseSpec. Demonstrates passing expandOpts with minimalEndpoints, generateOneOfAnyOf, hasScopes, applicationToken, and numberOfScopes. Logs folder names and TC env var count. ```TypeScript import { convertFolders } from './src/core/converter.js' import { parseSpec } from './src/core/parser.js' const doc = await parseSpec('./petstore.yaml') const { folders, tcVars } = convertFolders(doc, undefined, false, false, { minimalEndpoints: true, generateOneOfAnyOf: false, hasScopes: false, applicationToken: false, numberOfScopes: 0, }) console.log(folders.map((f) => f.name)) // e.g. ['users', 'orders'] console.log(Object.keys(tcVars).length) // TC env vars for query/path params ``` -------------------------------- ### generateExample(schema: OASchema): unknown Source: https://github.com/apiaddicts/openapi2insomnia Generates a concrete example value from an OpenAPI schema. It is used for request bodies, path-parameter defaults, and oneOf/anyOf variant bodies. ```APIDOC ## generateExample(schema: OASchema): unknown ### Description Generates a concrete example value from an OpenAPI schema. It is used for request bodies, path-parameter defaults, and oneOf/anyOf variant bodies. ### Parameters - **schema** (OASchema) - Required - Schema node; `[key: string]: unknown` extras are ignored ### Returns `unknown` — the generated example. Value selection precedence, exactly as coded (lines 3–31): | Priority | Condition | Value | |----------|-----------|-------| | 1 | `schema.example !== undefined` | `schema.example` (verbatim, any type) | | 2 | `schema.allOf?.length` | `mergeSchemas(schema.allOf)` — object merging results of each sub-schema (non-null, non-array objects `Object.assign`ed) | | 3 | `schema.oneOf ?? schema.anyOf` has a first element | `generateExample(composites[0])` — only the **first** variant | | 4 | `type === 'object'` **or** `schema.properties` present | object with one key per property, value `generateExample(propSchema)` | | 5 | `type === 'array'` | `[generateExample(schema.items)]` when `items` exists, else `[]` | | 6 | `schema.default !== undefined` | `schema.default` | | 7 | `schema.enum?.length` | `schema.enum[0]` | | 8 | `type === 'string'` | `exampleString(schema.format)` | | 9 | `type === 'integer'` | `0` | | 10 | `type === 'number'` | `0.0` | | 11 | `type === 'boolean'` | `false` | | 12 | otherwise | `null` | `exampleString` format map (lines 48–60): | format | value | |--------|-------| | `'date-time'` | `'2024-01-01T00:00:00Z'` | | `'date'` | `'2024-01-01'` | | `'time'` | `'00:00:00'` | | `'email'` | `'user@example.com'` | | `'uri'` | `'https://example.com'` | | `'uuid'` | `'00000000-0000-0000-0000-000000000000'` | | `'password'` | `'********'` | | (other) | `''` | ### Throws None. Note the behavior when `type` is `'object'` but no `properties` and no other branch applies — the object branch returns `{}`. ### Request Example ```ts import { generateExample } from './src/core/schema-example.js' import type { OASchema } from './src/core/openapi-types.js' const schema: OASchema = { type: 'object', required: ['name'], properties: { name: { type: 'string', example: 'Alice' }, age: { type: 'integer' }, tags: { type: 'array', items: { type: 'string', example: 'tag' } }, email: { type: 'string', format: 'email' }, }, } const example = generateExample(schema) // { name: 'Alice', age: 0, tags: ['tag'], email: 'user@example.com' } ``` ### Request Example ```ts import { generateExample } from './src/core/schema-example.js' // allOf: merged object const merged = generateExample({ allOf: [ { type: 'object', properties: { id: { type: 'integer', example: 1 } } }, { type: 'object', properties: { name: { type: 'string', example: 'Alice' } } }, ], }) // { id: 1, name: 'Alice' } // oneOf: only the first branch is expanded const variant = generateExample({ oneOf: [ { type: 'object', properties: { kind: { type: 'string' }, a: { type: 'string' } } }, { type: 'object', properties: { kind: { type: 'string' }, b: { type: 'integer' } } }, ], }) // { kind: '', a: '' } — branch "b" is never explored here ``` ``` -------------------------------- ### resolveBaseUrl usage example Source: https://github.com/apiaddicts/openapi2insomnia Example of calling resolveBaseUrl with a hostServerPattern '%pre%' and a servers list. It returns 'https://pre.api.example.com/v1' because that server matches the pattern. ```typescript import { resolveBaseUrl } from './src/core/converter.js' const url = resolveBaseUrl( { base_url: '', hostServerPattern: '%pre%' }, [{ url: 'https://dev.api.example.com/v1' }, { url: 'https://pre.api.example.com/v1' }], ) // 'https://pre.api.example.com/v1' ``` -------------------------------- ### ExampleValues interface (src/core/tc-expander.ts:31) Source: https://github.com/apiaddicts/openapi2insomnia Defines correct and wrong example values for various data types. Defaults (DEFAULT_EXAMPLE_VALUES) are merged per field from config-file examples. ```TypeScript export interface ExampleValues { correct: { string: string integer: number number: number boolean: boolean date: string 'date-time': string } wrong: { string: string integer: string number: string boolean: string date: string 'date-time': string } } ``` -------------------------------- ### CLI usage examples Source: https://github.com/apiaddicts/openapi2insomnia Shows expected output for o2i --version, o2i --help, and o2i convert --help. The version prints 1.0.1; help shows usage banners with options. ```bash o2i --version # 1.0.1 o2i --help # Usage: openapi2insomnia [options] [command] # ... o2i convert --help # Usage: openapi2insomnia convert [options] # ... -i, --input ... ``` -------------------------------- ### End-to-End Orchestration Example Source: https://github.com/apiaddicts/openapi2insomnia Demonstrates how to orchestrate the conversion from an OpenAPI spec to an Insomnia collection using the core functions. This is a usage example, not a direct API call. ```APIDOC ## End-to-End Orchestration Example ### Description Demonstrates how to orchestrate the conversion from an OpenAPI spec to an Insomnia collection using the core functions. This is a usage example, not a direct API call. ### Method Example ### Request Example ```ts import { parseSpec } from './src/core/parser.js' import { convertFolders, buildBaseEnvData, buildEnvironmentForConfig, resolveBaseUrl, buildOAuth2Folder } from './src/core/converter.js' import { buildCollection } from './src/core/generator.js' import { loadConfig } from './src/core/config.js' import { dump } from 'js-yaml' const doc = await parseSpec('./openapi.yaml') const config = loadConfig('./o2i.config.json') const baseData = buildBaseEnvData(doc) const oauth2Folder = buildOAuth2Folder(doc) for (const env of config.environments) { const baseUrl = resolveBaseUrl(env, doc.servers ?? []) const environment = buildEnvironmentForConfig({ ...env, base_url: baseUrl }, baseData, Date.now()) const { folders, tcVars } = convertFolders(doc, config.examples, env.microcksHeaders, env.readOnly, { minimalEndpoints: config.minimalEndpoints, generateOneOfAnyOf: config.generateOneOfAnyOf, hasScopes: env.hasScopes, applicationToken: env.applicationToken, numberOfScopes: env.numberOfScopes, }) environment.data = { ...environment.data, ...tcVars } const collection = buildCollection(doc.info, environment, oauth2Folder ? [oauth2Folder, ...folders] : folders) console.log(dump(collection, { indent: 2, lineWidth: -1, noRefs: true })) } ``` ``` -------------------------------- ### Convert OpenAPI spec using globally installed CLI Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Runs the o2i convert command with an input file or URL. The -i flag is required. ```bash o2i convert -i [options] ``` -------------------------------- ### Root commander program setup Source: https://github.com/apiaddicts/openapi2insomnia Constructs the root commander Command, sets the name, description, and version, adds the convert subcommand, and parses process.argv. Running without arguments prints help/usage and exits. ```TypeScript const program = new Command() program .name('openapi2insomnia') .description('Convert OpenAPI 3.0.x specs to Insomnia v5 collections') .version(__VERSION__) program.addCommand(convertCommand) program.parse() ``` -------------------------------- ### Stable workspace and folder IDs example Source: https://github.com/apiaddicts/openapi2insomnia Shows deterministic IDs for workspace and folder. Same content yields same ID; console.log demonstrates equality. ```TypeScript import { makeId } from './src/core/utils.js' const workspaceId = makeId('wrk', 'Petstore Minimal') // 'wrk_' + md5('Petstore Minimal') const folderId = makeId('fld', 'users') // 'fld_' + md5('users') console.log(workspaceId, folderId) // Deterministic across calls: console.log(makeId('fld', 'users') === folderId) // true ``` -------------------------------- ### generateExample function signature Source: https://github.com/apiaddicts/openapi2insomnia Declares the exported function that derives a concrete example value from an OpenAPI OASchema. Used for request bodies, path-parameter defaults, and oneOf/anyOf variant bodies. ```TypeScript export function generateExample(schema: OASchema): unknown ``` -------------------------------- ### Example: building full TC name and vars Source: https://github.com/apiaddicts/openapi2insomnia Shows how to combine padIndex, toLetter, tcRequestName, tcVarName, and tcVarNameWrong to generate a TC name and environment variable references for an operation. ```TypeScript import { padIndex, toLetter, tcRequestName, tcVarName, tcVarNameWrong } from './src/core/tc-namer.js' const fi = padIndex(1) // '01' const oi = padIndex(2) // '02' // Success TC with a variant letter const name = tcRequestName(fi, oi, '200', toLetter(0), undefined) // 'TC.01.02.200a' // 400 TC for a wrong query value const badName = tcRequestName(fi, oi, '400', toLetter(1), 'queryString limit wrong') // 'TC.01.02.400b queryString limit wrong' // Env var references used inside the request params const varName = tcVarName(fi, oi, 'limit') // 'TC_01_02_limit' const varWrong = tcVarNameWrong(fi, oi, 'limit') // 'TC_01_02_limit_wrong' console.log(`{{ _.${varName} }}`, `{{ _.${varWrong} }}`) ``` -------------------------------- ### Example: sequence of letters Source: https://github.com/apiaddicts/openapi2insomnia Demonstrates toLetter output for indices 0, 1, 25, 26, 27, producing 'a, b, z, aa, ab'. ```TypeScript import { toLetter } from './src/core/tc-namer.js' console.log([0, 1, 25, 26, 27].map(toLetter).join(', ')) // 'a, b, z, aa, ab' ``` -------------------------------- ### End-to-End Orchestration Example Source: https://github.com/apiaddicts/openapi2insomnia Complete workflow that parses an OpenAPI spec, loads configuration, builds base environment data, creates an OAuth2 folder, and for each environment resolves the base URL, builds the environment, converts folders, and outputs the collection as YAML. ```typescript import { parseSpec } from './src/core/parser.js' import { convertFolders, buildBaseEnvData, buildEnvironmentForConfig, resolveBaseUrl, buildOAuth2Folder } from './src/core/converter.js' import { buildCollection } from './src/core/generator.js' import { loadConfig } from './src/core/config.js' import { dump } from 'js-yaml' const doc = await parseSpec('./openapi.yaml') const config = loadConfig('./o2i.config.json') const baseData = buildBaseEnvData(doc) const oauth2Folder = buildOAuth2Folder(doc) for (const env of config.environments) { const baseUrl = resolveBaseUrl(env, doc.servers ?? []) const environment = buildEnvironmentForConfig({ ...env, base_url: baseUrl }, baseData, Date.now()) const { folders, tcVars } = convertFolders(doc, config.examples, env.microcksHeaders, env.readOnly, { minimalEndpoints: config.minimalEndpoints, generateOneOfAnyOf: config.generateOneOfAnyOf, hasScopes: env.hasScopes, applicationToken: env.applicationToken, numberOfScopes: env.numberOfScopes, }) environment.data = { ...environment.data, ...tcVars } const collection = buildCollection(doc.info, environment, oauth2Folder ? [oauth2Folder, ...folders] : folders) console.log(dump(collection, { indent: 2, lineWidth: -1, noRefs: true })) } ``` -------------------------------- ### convertFolders(doc, examples?, microcksHeaders?, readOnly?, expandOpts?): ConvertFoldersResult Source: https://github.com/apiaddicts/openapi2insomnia Converts the OpenAPI document into tag-level folders with sub-folders per operation, along with other structures. ```APIDOC ## convertFolders(doc, examples?, microcksHeaders?, readOnly?, expandOpts?): ConvertFoldersResult ### Description Converts the OpenAPI document into tag-level folders with sub-folders per operation, along with other structures. ### Parameters - `doc` (OADocument) - Required - The OpenAPI document. - `examples` (optional) - Examples to include. - `microcksHeaders` (optional) - Microcks headers. - `readOnly` (optional) - Whether to include read-only operations. - `expandOpts` (optional) - Expansion options. ### Returns `ConvertFoldersResult` - The result of the conversion. ``` -------------------------------- ### ExampleValues interface and DEFAULT_EXAMPLE_VALUES constant Source: https://github.com/apiaddicts/openapi2insomnia Defines correct and wrong example values for OpenAPI types. The wrong values intentionally use invalid strings for integer, number, and boolean, and invalid dates for date and date-time. ```TypeScript export interface ExampleValues { correct: { string: string integer: number number: number boolean: boolean date: string 'date-time': string } wrong: { string: string integer: string number: string boolean: string date: string 'date-time': string } } export const DEFAULT_EXAMPLE_VALUES: ExampleValues = { correct: { string: 'goodstring', integer: 1, number: 1.0, boolean: true, date: '2020-01-01', 'date-time': '2020-01-01T23:59:59' }, wrong: { string: 'badstring', integer: 'badstring', number: 'badstring', boolean: 'badboolean', date: '2020-40-40', 'date-time': '2020-40-40T00:00:00' }, } ``` -------------------------------- ### O2IConfig interface definition Source: https://github.com/apiaddicts/openapi2insomnia Defines the shape of the configuration object used by the CLI. All fields are required; `examples` is always fully populated via merge with `DEFAULT_EXAMPLE_VALUES`, `environments` defaults to `[]` when omitted, and `minimalEndpoints` and `generateOneOfAnyOf` default to `false`. ```TypeScript export interface O2IConfig { examples: ExampleValues environments: EnvironmentConfig[] minimalEndpoints: boolean generateOneOfAnyOf: boolean } ``` -------------------------------- ### Request-level ID example Source: https://github.com/apiaddicts/openapi2insomnia Generates a request ID using the format used by expandOperation: '01:01:200:a:queryString limit'. ```TypeScript import { makeId } from './src/core/utils.js' const id = makeId('req', '01:01:200:a:queryString limit') console.log(id) // 'req_' ``` -------------------------------- ### Basic usage: expandOperation with default example values Source: https://github.com/apiaddicts/openapi2insomnia Expands a single operation into test case subfolders and environment variables. The output shows generated folder names like '01.List users' and env vars such as TC_01_01_limit with value 1 and TC_01_01_limit_wrong with 'badstring'. ```TypeScript import { expandOperation, DEFAULT_EXAMPLE_VALUES, DEFAULT_EXPAND_OPTIONS } from './src/core/tc-expander.js' import type { OADocument, OAOperation } from './src/core/openapi-types.js' const doc: OADocument = { info: { title: 'Test', version: '1' } } const op: OAOperation = { summary: 'List users', parameters: [ { name: 'limit', in: 'query', schema: { type: 'integer' } }, { name: 'q', in: 'query', schema: { type: 'string' } }, ], responses: { '200': { description: 'ok' }, '400': { description: 'bad request' }, '401': { description: 'unauthorized' }, }, } const { subFolder, envVars } = expandOperation('/users', 'get', op, doc, '01', '01', DEFAULT_EXAMPLE_VALUES) console.log(subFolder.name) // '01.List users' console.log(subFolder.children.map((c) => 'name' in c ? c.name : '')) // ['TC.01.01.200a', 'TC.01.01.200b queryString limit', 'TC.01.01.200c queryString q', // 'TC.01.01.400a queryString limit wrong', 'TC.01.01.400b queryString q wrong', // 'TC.01.01.401'] console.log(envVars['TC_01_01_limit']) // 1 console.log(envVars['TC_01_01_limit_wrong']) // 'badstring' ``` -------------------------------- ### Basic usage example for generateAfterResponseScripts Source: https://github.com/apiaddicts/openapi2insomnia Compiles scripts for an operation with a 200 response (with JSON schema) and a 404 response (status-only). The 'default' response is skipped. Output keys are ['200', '404']. ```TypeScript import { generateAfterResponseScripts } from './src/core/script-generator.js' import type { OAOperation } from './src/core/openapi-types.js' const operation: OAOperation = { summary: 'Get user', responses: { '200': { description: 'A user', content: { 'application/json': { schema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } } }, }, '404': { description: 'Not found' }, // no JSON schema → status-only script 'default': { description: 'error' }, // skipped }, } const scripts = generateAfterResponseScripts(operation) console.log(Object.keys(scripts)) // ['200', '404'] console.log(scripts['200'].includes('response matches schema')) // true console.log(scripts['404'].includes('function validate(')) // false (status-only) ``` -------------------------------- ### Typing a converter call chain with OADocument, OAOperation, OASchema Source: https://github.com/apiaddicts/openapi2insomnia Shows how to type a converter call chain using the core OpenAPI types. Imports OADocument, OAOperation, and OASchema from './src/core/openapi-types.js' and generateExample from './src/core/schema-example.js'. The function summarizeOperation accesses the operation via doc.paths?.[path]?.[method], checks for a request body schema, and logs the path, method, and either the generated example or 'no body schema'. ```TypeScript import type { OADocument, OAOperation, OASchema } from './src/core/openapi-types.js' import { generateExample } from './src/core/schema-example.js' function summarizeOperation(doc: OADocument, path: string, method: 'get' | 'post'): void { const op: OAOperation | undefined = doc.paths?.[path]?.[method] if (!op) return const schema: OASchema | undefined = op.requestBody?.content['application/json']?.schema console.log(path, method, schema ? generateExample(schema) : 'no body schema') } ``` -------------------------------- ### Catching ConfigError in consumer code Source: https://github.com/apiaddicts/openapi2insomnia Example of importing loadConfig and ConfigError, then catching ConfigError to log the exit code and message. Non-ConfigError exceptions are rethrown. ```TypeScript import { loadConfig, ConfigError } from './src/core/config.js' import { resolve } from 'node:path' try { const config = loadConfig(resolve('o2i.config.json')) console.log(config.environments.map((e) => e.name)) } catch (err) { if (err instanceof ConfigError) { console.error(`Config error (exit ${err.exitCode}): ${err.message}`) } else { throw err } } ``` -------------------------------- ### parseSpec implementation Source: https://github.com/apiaddicts/openapi2insomnia Throws Error('only HTTPS URLs are supported') if input starts with http://. Uses SwaggerParser.dereference to resolve all $refs inline; rejects on file not found, invalid YAML/JSON, or invalid OpenAPI document. ```TypeScript import SwaggerParser from '@apidevtools/swagger-parser' import type { OADocument } from './openapi-types.js' export async function parseSpec(input: string): Promise { if (input.startsWith('http://')) { throw new Error('only HTTPS URLs are supported') } const doc = await SwaggerParser.dereference(input) return doc as OADocument } ``` -------------------------------- ### convertFolders function signature Source: https://github.com/apiaddicts/openapi2insomnia Converts an OpenAPI document into folders and test case variables. Parameters include doc, examples, microcksHeaders, readOnly, and expandOpts. Throws JSON.parse failures from generate400 only if body text is malformed, unreachable through buildBody. ```TypeScript export function convertFolders( doc: OADocument, examples: ExampleValues = DEFAULT_EXAMPLE_VALUES, microcksHeaders = false, readOnly = false, expandOpts: ExpandOptions = DEFAULT_EXPAND_OPTIONS, ): ConvertFoldersResult ``` -------------------------------- ### Convert OpenAPI spec using local development build Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Runs the conversion command from the local dist directory during development. ```bash node dist/index.js convert -i [options] ``` -------------------------------- ### Example usage of type guards Source: https://github.com/apiaddicts/openapi2insomnia Walks a collection of items, printing folder names and request methods using the type guards. Imports from './src/core/insomnia-types.js'. ```TypeScript import { isInsomniaFolder, isInsomniaRequest, type InsomniaV5CollectionItem } from './src/core/insomnia-types.js' function walk(items: InsomniaV5CollectionItem[], depth = 0): void { for (const item of items) { if (isInsomniaFolder(item)) { console.log(' '.repeat(depth) + `[folder] ${item.name}`) walk(item.children, depth + 1) } else if (isInsomniaRequest(item)) { console.log(' '.repeat(depth) + `${item.method} ${item.name}`) } } } ``` -------------------------------- ### CLI entry point src/index.ts Source: https://github.com/apiaddicts/openapi2insomnia Builds the commander program, registers the convert subcommand, and parses argv. Uses __VERSION__ injected at build time. ```TypeScript import { Command } from 'commander' import { convertCommand } from './commands/convert.js' declare const __VERSION__: string const program = new Command() program .name('openapi2insomnia') .description('Convert OpenAPI 3.0.x specs to Insomnia v5 collections') .version(__VERSION__) program.addCommand(convertCommand) program.parse() ``` -------------------------------- ### Development Commands Source: https://github.com/apiaddicts/openapi2insomnia/blob/main/README.md Run these commands in the project root to build, watch, test, or type-check the TypeScript code. The build command compiles to dist/, dev runs in watch mode, test runs unit tests, and typecheck checks types without emitting. ```bash pnpm build # compile TypeScript → dist/ pnpm dev # compile in watch mode pnpm test # run unit tests pnpm typecheck # type-check without emitting ``` -------------------------------- ### Get Token request object Source: https://github.com/apiaddicts/openapi2insomnia The token request object created for each oauth2 scheme. Uses '{{ _.token_url }}' as URL and stores access_token/refresh_token via afterResponse script. ```TypeScript { url: '{{ _.token_url }}', name: `Get Token — ${schemeName}`, method: 'POST', headers: [{ name: 'Content-Type', value: 'application/x-www-form-urlencoded', disabled: false }], body: { mimeType: 'application/x-www-form-urlencoded', params }, scripts: { afterResponse: '...' }, // stores access_token / refresh_token into the environment settings: DEFAULT_REQUEST_SETTINGS, } ``` -------------------------------- ### Full implementation of buildCollection Source: https://github.com/apiaddicts/openapi2insomnia Complete implementation of buildCollection. Sets meta.id via makeId('wrk', info.title), meta.description to info.description ?? '', and passes environments and collection through untouched. No validation or error paths. ```TypeScript export function buildCollection( info: OAInfo, environments: InsomniaV5RootEnvironment, collection: InsomniaV5CollectionItem[], ): InsomniaV5Collection { const now = Date.now() return { type: 'collection.insomnia.rest/5.0', schema_version: '5.1', name: info.title, meta: { id: makeId('wrk', info.title), created: now, modified: now, description: info.description ?? '', }, collection, environments, } } ``` -------------------------------- ### expandOperation function signature Source: https://github.com/apiaddicts/openapi2insomnia Expands an OpenAPI operation into a TC sub-folder. Requires the full document for securitySchemes resolution and correct/wrong example values. Optional microcksHeaders adds X-Microcks-Response-Name header. ```TypeScript export function expandOperation( path: string, method: OAHttpMethod, operation: OAOperation, doc: OADocument, fi: string, oi: string, examples: ExampleValues, microcksHeaders = false, options: ExpandOptions = DEFAULT_EXPAND_OPTIONS, ): TcExpandResult ``` -------------------------------- ### buildEnvironmentForConfig(env: EnvironmentConfig, baseData: Record, now: number): InsomniaV5RootEnvironment Source: https://github.com/apiaddicts/openapi2insomnia Builds a root environment for a given configuration, using the base data and a timestamp. ```APIDOC ## buildEnvironmentForConfig(env: EnvironmentConfig, baseData: Record, now: number): InsomniaV5RootEnvironment ### Description Builds a root environment for a given configuration, using the base data and a timestamp. ### Parameters - `env` (EnvironmentConfig) - Required - The environment configuration. - `baseData` (Record) - Required - The base environment data. - `now` (number) - Required - The current timestamp. ### Returns `InsomniaV5RootEnvironment` - The constructed root environment. ``` -------------------------------- ### Load config and iterate environments Source: https://github.com/apiaddicts/openapi2insomnia Loads a configuration file and iterates over its environments, logging each environment's properties and global flags. ```TypeScript import { loadConfig } from './src/core/config.js' const config = loadConfig('./o2i.config.json') for (const env of config.environments) { console.log(`${env.name}: ${env.base_url} → ${env.targetFolder}`) console.log(` scopes=${env.numberOfScopes}, appToken=${env.applicationToken}`) } console.log('minimal:', config.minimalEndpoints, 'oneOf/anyOf:', config.generateOneOfAnyOf) ``` -------------------------------- ### buildOAuth2Folder(doc: OADocument): InsomniaV5Folder | null Source: https://github.com/apiaddicts/openapi2insomnia Builds an OAuth2 folder from the OpenAPI document, or returns null if no OAuth2 schemes are present. ```APIDOC ## buildOAuth2Folder(doc: OADocument): InsomniaV5Folder | null ### Description Builds an OAuth2 folder from the OpenAPI document, or returns null if no OAuth2 schemes are present. ### Parameters - `doc` (OADocument) - Required - The OpenAPI document. ### Returns `InsomniaV5Folder | null` - The OAuth2 folder or null. ``` -------------------------------- ### Invoke embedded VALIDATOR_FN directly in Node Source: https://github.com/apiaddicts/openapi2insomnia Example showing how to import `VALIDATOR_FN` and execute it directly in Node by wrapping it with `new Function` and appending `'\nreturn validate;'`. Demonstrates expected outputs for valid, missing required field, and type mismatch cases. ```TypeScript import { VALIDATOR_FN } from './src/core/script-generator.js' const validate = new Function(VALIDATOR_FN + '\nreturn validate;')() as ( data: unknown, schema: Record, ) => { valid: boolean; error?: string } const schema = { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } console.log(validate({ id: 'a' }, schema)) // { valid: true } console.log(validate({}, schema)) // { valid: false, error: 'missing required field: "id"' } console.log(validate({ id: 1 }, schema)) // { valid: false, error: '"id": expected string, got number' } ``` -------------------------------- ### resolveBaseUrl Source: https://github.com/apiaddicts/openapi2insomnia Resolves the base URL for an environment based on priority: first matching server pattern, then env.base_url, then the first server URL. Returns a string. ```APIDOC ## resolveBaseUrl ### Description Resolves the base URL for an environment based on priority: first matching server pattern, then env.base_url, then the first server URL. Returns a string. ### Method Function ### Signature ```ts export function resolveBaseUrl( env: { base_url: string; hostServerPattern?: string }, servers: OAServer[], ): string ``` ### Parameters - `env` ({ base_url: string; hostServerPattern?: string }) - Required - Environment URL hints - `servers` (OAServer[]) - Required - Spec `servers` list ### Returns `string`, by priority: 1. First `servers[]` entry matching `env.hostServerPattern` (if pattern set) 2. `env.base_url` if non-empty 3. `servers[0]?.url ?? ''` ### Request Example ```ts import { resolveBaseUrl } from './src/core/converter.js' const url = resolveBaseUrl( { base_url: '', hostServerPattern: '%pre%' }, [{ url: 'https://dev.api.example.com/v1' }, { url: 'https://pre.api.example.com/v1' }], ) // 'https://pre.api.example.com/v1' ``` ``` -------------------------------- ### Programmatic conversion pipeline Source: https://github.com/apiaddicts/openapi2insomnia Equivalent programmatic use of the underlying steps, importing internal modules. Parses the spec, converts folders and environments, builds the collection, and writes YAML to stdout. ```ts import { parseSpec } from '../core/parser.js' import { loadConfig } from '../core/config.js' import { convertFolders, convertEnvironments } from '../core/converter.js' import { buildCollection } from '../core/generator.js' import { dump } from 'js-yaml' const doc = await parseSpec('petstore.yaml') const { folders, tcVars } = convertFolders(doc) const environments = convertEnvironments(doc) environments.data = { ...environments.data, ...tcVars } const collection = buildCollection(doc.info, environments, folders) process.stdout.write(dump(collection, { indent: 2, lineWidth: -1, noRefs: true })) ``` -------------------------------- ### loadConfig full implementation Source: https://github.com/apiaddicts/openapi2insomnia Complete implementation of `loadConfig`. Throws `ConfigError` with exit code 1 for missing file, invalid JSON, or Zod validation failure; re-throws other `readFileSync` errors unchanged. The normalization logic is omitted in the source (indicated by `// ...normalize into O2IConfig...`). ```TypeScript export function loadConfig(configPath: string): O2IConfig { const resolved = resolve(configPath) if (!existsSync(resolved)) { throw new ConfigError(`Config file not found: ${resolved}`, 1) } let raw: unknown try { raw = JSON.parse(readFileSync(resolved, 'utf-8')) } catch { throw new ConfigError(`Config file is not valid JSON: ${resolved}`, 1) } const result = ConfigSchema.safeParse(raw) if (!result.success) { const msg = result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ') throw new ConfigError(`Invalid config: ${msg}`, 1) } // ...normalize into O2IConfig... } ``` -------------------------------- ### buildOAuth2Folder(doc) Source: https://github.com/apiaddicts/openapi2insomnia Builds an Insomnia folder for OAuth2 token requests from an OpenAPI document. Returns null if no oauth2 security schemes are declared, otherwise a folder named 'OAuth2' containing one POST request per scheme. ```APIDOC ## buildOAuth2Folder(doc) ### Description Builds an Insomnia folder for OAuth2 token requests from an OpenAPI document. Returns null if no oauth2 security schemes are declared, otherwise a folder named 'OAuth2' containing one POST request per scheme. ### Method Function call ### Endpoint N/A (SDK function) ### Parameters #### Function Parameters - **doc** (OADocument) - Required - Dereferenced spec ### Returns - **InsomniaV5Folder | null** - null when the spec declares no oauth2 security schemes; otherwise a folder named 'OAuth2' with meta.sortKey = Number.MIN_SAFE_INTEGER (pinned first) containing one "Get Token — " POST request per oauth2 scheme. ### Request Example ```ts import { buildOAuth2Folder, buildBaseEnvData } from './src/core/converter.js' import { parseSpec } from './src/core/parser.js' const doc = await parseSpec('./secured-api.yaml') const oauth2Folder = buildOAuth2Folder(doc) console.log(oauth2Folder ? oauth2Folder.children.map((c) => c.name) : 'no oauth2') ``` ``` -------------------------------- ### CLI convert command usage Source: https://github.com/apiaddicts/openapi2insomnia Shows the command-line syntax for the o2i convert command. The -i flag is required and accepts a local file path or HTTPS URL; -o and -c are optional. Exit code 0 indicates success, 1 indicates user errors, and 2 indicates unexpected errors. ```bash o2i convert -i [options] ``` -------------------------------- ### matchesServerPattern(url: string, pattern: string): boolean Source: https://github.com/apiaddicts/openapi2insomnia Checks if a URL matches a server pattern. ```APIDOC ## matchesServerPattern(url: string, pattern: string): boolean ### Description Checks if a URL matches a server pattern. ### Parameters - `url` (string) - Required - The URL to check. - `pattern` (string) - Required - The pattern to match. ### Returns `boolean` - True if the URL matches the pattern. ``` -------------------------------- ### OAInfo interface Source: https://github.com/apiaddicts/openapi2insomnia Defines API metadata. Consumed by buildCollection. ```TypeScript export interface OAInfo { title: string description?: string version: string } ```