包详细信息

@scalar/openapi-parser

scalar336.9kMIT0.18.0

modern OpenAPI parser written in TypeScript

openapi, scalar, swagger, parser

自述文件

Scalar OpenAPI Parser

Version Downloads License Discord

Modern OpenAPI parser written in TypeScript with support for OpenAPI 3.1, OpenAPI 3.0 and Swagger 2.0.

Installation

npm add @scalar/openapi-parser

Usage

Validate

import { validate } from '@scalar/openapi-parser'

const file = `{
  "openapi": "3.1.0",
  "info": {
    "title": "Hello World",
    "version": "1.0.0"
  },
  "paths": {}
}`

const { valid, errors } = await validate(file)

console.log(valid)

if (!valid) {
  console.log(errors)
}

Resolve references

import { dereference } from '@scalar/openapi-parser'

const specification = `{
  "openapi": "3.1.0",
  "info": {
    "title": "Hello World",
    "version": "1.0.0"
  },
  "paths": {}
}`

const { schema, errors } = await dereference(specification)

Bundle external references

The OpenAPI specification allows to point to external files (URLs or files). But sometimes, you just want to combine all files into one.

Plugins

If you are on a browser environment import plugins from @scalar/openapi-parser/plugins-browser while if you are on a node environment you can import from @scalar/openapi-parser/plugins

fetchUrls

This plugins handles all external urls. It works for both node.js and browser environment

import { bundle } from '@scalar/openapi-parser'
import { fetchUrls } from '@scalar/openapi-parser/plugins-browser'

const document = {
  openapi: '3.1.0',
  info: { title: 'Bundled API', version: '1.0.0' },
  paths: {},
  components: {
    schemas: {
      User: { $ref: 'https://example.com/user-schema.json#' }
    }
  }
}

// This will bundle all external documents and turn all references from external into internal
await bundle(document, {
  plugins: [fetchUrls()],
  treeShake: true  // <------  This flag will try to remove any unused part of the external document
})

console.log(document)
Limiting the number of concurrent requests
await bundle(document, {
  plugins: [
    fetchUrls({
      limit: 10, // it should run at most 10 requests at the same time
    }),
  ],
  treeShake: false
})
Custom headers

To pass custom headers to requests for specific domains you can configure the fetch plugin like the example

await bundle(
  document,
  {
    plugins: [
      fetchUrls({
        // Pass custom headers
        // The header will only be attached to the list of domains
        headers: [
          {
            domains: ['example.com'],
            headers: {
              'Authorization': 'Bearer <TOKEN>'
            }
          }
        ]
      }),
      readFiles(),
    ],
    treeShake: false
  },
)
Custom fetch function

For advanced use cases like proxying requests or implementing custom network logic, you can provide your own fetch implementation. This allows you to handle things like CORS restrictions, custom authentication flows, or request/response transformations.

await bundle(
  document,
  {
    plugins: [
      fetchUrls({
        // Custom fetcher function
        fetch: async (input, init) => {
          console.log('Custom fetch logic')
          return fetch(input, init)
        },
      })
      readFiles(),
    ],
    treeShake: false
  },
)
Bundle from remote url
const result = await bundle(
  'https://example.com/openapi.json',
  {
    plugins: [
      fetchUrls(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
readFiles

This plugins handles local files. Only works on node.js environment

import { bundle } from '@scalar/openapi-parser'
import { readFiles } from '@scalar/openapi-parser/plugins-browser'

const document = {
  openapi: '3.1.0',
  info: { title: 'Bundled API', version: '1.0.0' },
  paths: {},
  components: {
    schemas: {
      User: { $ref: './user-schema.json#' }
    }
  }
}

// This will bundle all external documents and turn all references from external into internal
await bundle(document, {
  plugins: [readFiles()],
  treeShake: false
})

console.log(document)
Bundle from local file

You can pass the file path directly but make sure to have the correct plugins to handle reading from the local files

const result = await bundle(
  './input.json',
  {
    plugins: [
      readFiles(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
parseJson

You can pass raw json string as input

import { bundle } from '@scalar/openapi-parser'
import { parseJson } from '@scalar/openapi-parser/plugins-browser'

const result = await bundle(
  '{ "openapi": "3.1.1" }',
  {
    plugins: [
      parseJson(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
parseYaml

You can pass raw yaml string as input

import { bundle } from '@scalar/openapi-parser'
import { parseYaml } from '@scalar/openapi-parser/plugins-browser'

const result = await bundle(
  'openapi: "3.1.1"\n',
  {
    plugins: [
      parseYaml(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)

Track references

The dereference function accepts an onDereference callback option that gets called whenever a reference is resolved. This can be useful for tracking which schemas are being dereferenced:

import { dereference } from '@scalar/openapi-parser'

const { schema, errors } = await dereference(specification, {
  onDereference: ({ schema, ref }) => {
    //
  },
})

Modify an OpenAPI document

import { filter } from '@scalar/openapi-parser'

const specification = `{
  "openapi": "3.1.0",
  "info": {
    "title": "Hello World",
    "version": "1.0.0"
  },
  "paths": {}
}`

const { specification } = filter(
  specification,
  (schema) => !schema?.['x-internal'],
)

Upgrade your OpenAPI document

There’s an upgrade command to upgrade all your OpenAPI documents to the latest OpenAPI version.

import { upgrade } from '@scalar/openapi-parser'

const { specification } = upgrade({
  swagger: '2.0',
  info: {
    title: 'Hello World',
    version: '1.0.0',
  },
  paths: {},
})

console.log(specification.openapi)
// Output: 3.1.0

Sanitize your OpenAPI document

The sanitize() utility helps ensure your OpenAPI document is valid and complete. It automatically adds any missing required properties like the OpenAPI version and info object, collects operation tags and adds them to the global tags array and normalizes security scheme types.

This makes your document as OpenAPI-compliant as possible with minimal effort, handling many common specification requirements automatically.

⚠️ This doesn’t support Swagger 2.0 documents.

import { sanitize } from '@scalar/openapi-parser'

const result = sanitize({
  info: {
    title: 'Hello World',
  },
})

console.log(result)

Then/Catch syntax

If you’re more the then/catch type of guy, that’s fine:

import { validate } from '@scalar/openapi-parser'

const specification = …

validate(specification, {
  throwOnError: true,
})
.then(result => {
  // Success
})
.catch(error => {
  // Failure
})

TypeScript

If you just look for our types, you can install the package separately:

npm add @scalar/openapi-types

And use it like this:

import type { OpenAPI } from '@scalar/openapi-types'

const file: OpenAPI.Document = {
  openapi: '3.1.0',
  info: {
    title: 'Hello World',
    version: '1.0.0',
  },
  paths: {},
}

Advanced: URL and file references

You can reference other files, too. To do that, the parser needs to know what files are available.

import { dereference, load } from '@scalar/openapi-parser'
import { fetchUrls } from '@scalar/openapi-parser/plugins/fetch-urls'
import { readFiles } from '@scalar/openapi-parser/plugins/read-files'

// Load a file and all referenced files
const { filesystem } = await load('./openapi.yaml', {
  plugins: [
    readFiles(),
    fetchUrls({
      limit: 5,
    }),
  ],
})

// Instead of just passing a single specification, pass the whole “filesystem”
const result = await dereference(filesystem)

As you see, load() supports plugins. You can write your own plugin, if you’d like to fetch API defintions from another data source, for example your database. Look at the source code of the readFiles to learn how this could look like.

Directly load URLs

Once the fetchUrls plugin is loaded, you can also just pass an URL:

import { dereference, load } from '@scalar/openapi-parser'
import { fetchUrls } from '@scalar/openapi-parser/plugins/fetch-urls'

// Load a file and all referenced files
const { filesystem } = await load(
  'https://cdn.jsdelivr.net/npm/@scalar/galaxy/dist/latest.yaml',
  {
    plugins: [fetchUrls()],
  },
)

Intercept HTTP requests

If you’re using the package in a browser environment, you may run into CORS issues when fetching from URLs. You can intercept the requests, for example to use a proxy, though:

import { dereference, load } from '@scalar/openapi-parser'
import { fetchUrls } from '@scalar/openapi-parser/plugins/fetch-urls'

// Load a file and all referenced files
const { filesystem } = await load(
  'https://cdn.jsdelivr.net/npm/@scalar/galaxy/dist/latest.yaml',
  {
    plugins: [
      fetchUrls({
        fetch: (url) => fetch(url.replace('BANANA.net', 'jsdelivr.net')),
      }).get('https://cdn.BANANA.net/npm/@scalar/galaxy/dist/latest.yaml'),
    ],
  },
)

Community

We are API nerds. You too? Let’s chat on Discord: https://discord.gg/scalar

Thank you!

Thanks a ton for all the help and inspiration:

License

The source code in this repository is licensed under MIT.

更新日志

@scalar/openapi-parser

0.18.0

Minor Changes

  • 291f09d: feat(openapi-parser): ensure unique hashes and support custom compression

0.17.0

Minor Changes

  • f823d45: feat(openapi-parser): introduce parseJson and parseYaml plugins for bundler

Patch Changes

  • 166e298: feat(openapi-parser): correctly set the base origin for string inputs for the bundler
  • 4156f1d: Expand workspace store integration
  • 37c90b8: feat: add x-webhooks upgrade to the upgrader

0.16.0

Minor Changes

  • 11fabae: fix(openapi-parser): webpack bundle errors because of the barrel files

0.15.0

Minor Changes

  • b9dacba: fix(openapi-parser): multi entry build for bundler plugins
  • a73e9be: chore(openapi-parser): bring back pipeline syntax
  • f4332eb: feat: external reference resolution and partial bundle of the openapi document

Patch Changes

  • 17bc0d8: fix: collectionFormat is not migrated to new style and explode keywords
  • 49c04cf: fix(openapi-parser): use dynamic imports inside the plugin

0.14.0

Minor Changes

  • ee3eb77: feat(openapi-parser): bundle openapi documents

0.13.0

Minor Changes

  • 1e87feb: fix: normalize doesn’t handle empty documents well

0.12.0

Minor Changes

  • edf694b: feat: remove wildcard exports

0.11.1

Patch Changes

  • ea20eb4: fix: swagger upgrade fails if you pass something that is not an object

0.11.0

Minor Changes

  • 483ca93: chore: require Node 20 (or above)

Patch Changes

  • bd602d3: chore: mark pipeline syntax as deprecated
  • 1d1470c: feat: speed up the upgrade utility

0.10.17

Patch Changes

  • 8c7bad8: chore: move build tooling to esbuild

0.10.16

Patch Changes

  • c5047ee: fix: hotfix to revert the external reference commit

0.10.15

Patch Changes

  • 4abe4f8: feat: add resolveInternalRefs to bundle documents
  • 4abe4f8: feat: external $ref’s (absolute and relative URLs)

0.10.14

Patch Changes

  • cf5bf65: fix: migrate file type, basic auth, parameters and responses headers correctly

0.10.13

Patch Changes

  • d5a687f: fix: byte format is ignored when upgrading from OpenAPI 3.0 to OpenAPI 3.1

0.10.12

Patch Changes

  • cbc1d08: fix: swagger 2.0 basePath is ignored, if there’s no host

0.10.11

Patch Changes

  • 0f13162: chore: enable more Biome flags, apply linter fixes

0.10.10

Patch Changes

  • 0d8a24f: chore: remove Swagger 2.0 upgrade warning

0.10.9

Patch Changes

  • c10bbf5: chore: code style

0.10.8

Patch Changes

  • e350f23: chore: code style

0.10.7

Patch Changes

  • 1223c1f: chore: code style

0.10.6

Patch Changes

  • 4de3124: feat: make 'null' the second type in an array when upgrading
  • 34e6f52: feat: upgrade to stricter tsconfig

0.10.5

Patch Changes

  • a30e7cc: fix: package doesn’t work with moduleResolution: NodeNext

0.10.4

Patch Changes

  • 64df4fc: fix: example arrays are transformed to objects

0.10.3

Patch Changes

  • 8dce84f: Call onDereference after dereference process

0.10.2

Patch Changes

  • 3791738: fix(openapi-parser): correct schema upgrade for "format: binary"

0.10.1

Patch Changes

  • c263aaf: feat: better deal with empty OpenAPI documents

0.10.0

Minor Changes

  • fbef0c3: fix(openapi-parser): improve performance

Patch Changes

  • fbef0c3: fix: doesn’t validate files with external references

0.9.0

Minor Changes

  • 6fef2f3: feat(openapi-parser): support onDereference option on dereference

0.8.10

Patch Changes

  • 98e9cb2: feat: new sanitize utility to make documents OpenAPI-compliant

0.8.9

Patch Changes

  • 757fade: fix: when migrating example to example objects, the example should be inside the value attribute
  • a607115: feat: add openapi 3.0.4 and openapi 3.1.1

0.8.8

Patch Changes

  • 7323370: Allow relative URLs in v3.1 documents

0.8.7

Patch Changes

  • 6394a5d: chore: switch to @scalar/build-tooling

0.8.6

Patch Changes

  • d064a78: chore: make examples an array if it’s in a schema
  • 3db9355: feat: upgrade Swagger 2.0 securityDefinitions

0.8.5

Patch Changes

  • 983a5e4: feat: self reference the document
  • aee166c: fix: server URLs with variables are considered not valid

0.8.4

Patch Changes

  • 96c921c: feat: upgrade Swagger 2.0 formData parameters

0.8.3

Patch Changes

  • 674922f: chore: update fetch global tests

0.8.2

Patch Changes

  • 6bb85a5: feat: openapi() returns dynamic types based on the chained commands

0.8.1

Patch Changes

  • 5bd8337: feat: upgrade from Swagger 2.0 (experimental)

0.8.0

Minor Changes

  • b4f9f97: feat: new @scalar/openapi-types package

Patch Changes

  • b4f9f97: feat: add literal versions to OpenAPI.Document types
  • b4f9f97: feat: types: allow to type custom extensions
  • b4f9f97: feat: types: allow any attribute in schemas
  • b231e7d: fix: upgrade returns correct OpenAPI document version type
  • b4f9f97: feat: expose more types under the OpenAPI namespace

0.7.2

Patch Changes

  • 89dd0ef: feat: validate and dereference, throwOnError option

0.7.1

Patch Changes

  • 5e2c2d1: fix: read files export is wrong

0.7.0

Minor Changes

  • ec01324: refactor!: use dedicated entrypoints for the plugins

Patch Changes

  • c6944f2: fix: ajv import broken in CJS environments

0.6.0

Minor Changes

  • 61252ab: refactor!: most functions return an object now

Patch Changes

  • c9dd499: feat: intercept fetch requests
  • 61252ab: fix: max call stack exceeded error

0.5.0

Minor Changes

  • 10bd75c: chore: switch to rollup to make the library tree shakeable

0.4.1

Patch Changes

  • 1023e0a: chore: reduce bundle size

0.4.0

Minor Changes

  • 0b7d7be: refactor!: resolve is renamed to dereference
  • 63f72b4: refactor!: new OpenAPI types, removed the ResolvedOpenAPI types
  • 0b7d7be: refactor!: when using the pipeline syntax all tasks are queued and only executed when you add .get(), .toJson() or toYaml()
  • 56e7033: feat: file references
  • 0b7d7be: chore!: remove loadFiles utility, use load instead

Patch Changes

  • 03569c8: fix: existsSync is not a function
  • 6436ae1: refactor: resolve should resolve (and not validate)

0.3.2

Patch Changes

  • 02ea440: fix: make errors easier to consume

0.3.1

Patch Changes

  • 2498fc2: fix: make new parser behave like previous one on missing info.version

0.3.0

Minor Changes

  • c28d766: fix: circular references can not be resolved
  • c28d766: fix: references inside references are not resolved
  • c28d766: refactor: rewrote the whole parser (again)

Patch Changes

  • 0e98fdb: chore: add light-weight browser polyfill to join paths

0.2.0

Minor Changes

  • bf4568e: refactor: rewrite the whole package :)

0.1.0

Minor Changes

  • fb3b15f: init :)