Registry / serialization / api-ref-bundler

api-ref-bundler

JSON →
library0.5.1jsnpmunverified

api-ref-bundler is a JavaScript/TypeScript utility library designed to resolve and consolidate all external and internal `$ref` references within JSON-based API documents. It supports a wide range of specification formats including JsonSchema, Swagger 2.x, OpenAPI 3.x, AsyncAPI 2.x, and AsyncAPI 3.x. The current stable version is 0.5.1, with recent updates focusing on performance and new specification support, notably AsyncAPI v3.x. Key differentiators include its zero-dependency footprint, browser and Node.js compatibility, explicit handling of circular references, and a resolver-agnostic design, requiring users to provide their own logic for reading and parsing source paths. This approach offers flexibility but also shifts the responsibility for file I/O and deserialization to the developer. It ships with full TypeScript support.

npm install api-ref-bundler
INSTALL
IMPORT
SIG · API-REF-BUNDLER
A
api-ref-bundler
serializationjavascriptv0.5.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

bundle
import { bundle } from 'api-ref-bundler'
const { bundle } = require('api-ref-bundler')
Package is ESM-first. CommonJS `require` might lead to issues in newer Node.js environments or bundlers.
dereference
import { dereference } from 'api-ref-bundler'
import dereference from 'api-ref-bundler'
`bundle` and `dereference` are named exports, not default.
BundleOptions
import type { BundleOptions } from 'api-ref-bundler'
import { BundleOptions } from 'api-ref-bundler'
Use `import type` for type-only imports to prevent bundling issues and improve tree-shaking.
ApiRefBundler (Browser Global)
<!-- In browser HTML --> <script src="https://cdn.jsdelivr.net/npm/api-ref-bundler@latest"></script>
import { bundle } from 'api-ref-bundler' // In browser script without build step
For browser usage without a build step, the library exposes a global `ApiRefBundler` object after loading via CDN.

Demonstrates how to use `bundle` and `dereference` functions with a custom file system resolver for API documents, including handling of Markdown references and error hooks, using mock files for a runnable example.

import { promises as fs } from 'fs' import * as path from 'path' import { bundle, dereference } from 'api-ref-bundler' // A custom resolver function is required to load the document content. // It must handle both JSON and potential Markdown references. const resolver = async (sourcePath: string) => { try { const filePath = path.join(process.cwd(), './', sourcePath); const data = await fs.readFile(filePath, 'utf8'); // Assume .md files are plain text, others are JSON. return sourcePath.slice(-3) === '.md' ? data : JSON.parse(data); } catch (error) { console.error(`Error resolving ${sourcePath}:`, error); throw error; } } // Example: Bundling all external references into a single document async function runBundling() { console.log('--- Bundling Example ---'); try { const bundledSchema = await bundle('my-api-spec.json', resolver, { ignoreSibling: true }); console.log('Bundled Schema (first 500 chars):', JSON.stringify(bundledSchema, null, 2).substring(0, 500) + '...'); } catch (errors) { console.error('Bundling errors:', errors); } } // Example: Full dereference (removing all references) async function runFullDereference() { console.log('\n--- Full Dereference Example ---'); const onErrorHook = (msg: string) => { console.error(`Dereference Error: ${msg}`); throw new Error(msg); } try { const fullyDereferencedSchema = await dereference('my-api-spec.json', resolver, { hooks: { onError: onErrorHook } }); console.log('Fully Dereferenced Schema (first 500 chars):', JSON.stringify(fullyDereferencedSchema, null, 2).substring(0, 500) + '...'); } catch (errors) { console.error('Full dereference errors:', errors); } } // Example: Partial dereference (removing references only in a specific path) async function runPartialDereference() { console.log('\n--- Partial Dereference Example ---'); try { // Assuming 'my-api-spec.json' has a path like '#/components/schemas/User' const partialDereferencedPart = await dereference('my-api-spec.json#/components/schemas/User', resolver); console.log('Partially Dereferenced Segment (first 200 chars):', JSON.stringify(partialDereferencedPart, null, 2).substring(0, 200) + '...'); } catch (errors) { console.error('Partial dereference errors:', errors); } } // In a real scenario, you'd create 'my-api-spec.json' and any referenced files. // For demonstration, let's mock a simple schema. async function setupMockFiles() { await fs.writeFile('my-api-spec.json', JSON.stringify({ "openapi": "3.0.0", "info": { "title": "Mock API", "version": "1.0.0" }, "paths": {}, "components": { "schemas": { "User": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "$ref": "#/components/schemas/Name" } } }, "Name": { "type": "string" }, "Address": { "$ref": "./address.json" } } } }), 'utf8'); await fs.writeFile('address.json', JSON.stringify({ "type": "object", "properties": { "street": { "type": "string" } } }), 'utf8'); } async function main() { await setupMockFiles(); await runBundling(); await runFullDereference(); await runPartialDereference(); } main();
Debug
Known issues
breakingVersion 0.5.0 introduced full support for AsyncAPI v3.x. While designed for compatibility, users with complex AsyncAPI 2.x documents might experience changes in how references are resolved or processed, especially concerning the restructured architecture (top-level operations, channel-scoped messages) of AsyncAPI v3. Review your AsyncAPI documents and resolution logic if upgrading from versions prior to 0.5.0 and using AsyncAPI.
fix
Thoroughly test existing AsyncAPI 2.x documents after upgrading. If encountering issues, refer to the AsyncAPI v3 specification for structural changes and adjust your input documents or custom resolver logic accordingly.
affects: >=0.5.0
gotchaThe library explicitly states 'no parser included - bring your own!' and 'no concept of resolvers - you are in charge of the whole reading & path parsing process'. This means you *must* provide a custom `resolver` function that handles reading file content (e.g., from disk, network, or memory) and parsing it (e.g., `JSON.parse` for JSON, or returning raw string for Markdown). Failure to provide a correct resolver will result in errors.
fix
Implement a robust `resolver` function that takes a `sourcePath` string and returns the parsed content (object for JSON, string for Markdown/text). Ensure it handles file system lookups, network requests, or any other data source your application uses.
affects: >=0.1.0
gotchaWhen using `dereference`, be aware of circular references. While the library supports them, you might need to enable the `enableCircular` option in `DereferenceOptions` if you want circular `$refs` to be converted into actual nodes rather than potentially causing errors or infinite loops in your subsequent processing.
fix
If your documents contain circular references and you want them to be resolved into their respective nodes during dereferencing, set `enableCircular: true` in the `DereferenceOptions`. Otherwise, implement `onCycle` hook to handle them gracefully.
affects: >=0.1.0
gotchaThe `ignoreSibling` option, available for both `bundle` and `dereference`, controls whether content adjacent to a `$ref` is preserved or ignored. If set to `true`, any sibling properties next to a `$ref` will be discarded, which is common in OpenAPI/Swagger specifications where `$ref` should be the sole property. Incorrect usage can lead to unexpected loss of data.
fix
Carefully consider the `ignoreSibling` option based on your specification's requirements. For OpenAPI/Swagger documents where `$ref` typically stands alone, `ignoreSibling: true` is usually appropriate. For other JSON Schema use cases where `$ref` can co-exist with other properties, ensure this option is set correctly (e.g., `false` or omitted if you want to merge).
affects: >=0.1.0
Errors
Common errors & fixes
TypeError: (0 , api_ref_bundler__WEBPACK_IMPORTED_MODULE_2__.bundle) is not a function
This error typically occurs in a CommonJS environment or certain bundler configurations when trying to import an ESM-first package using named exports directly, or when the bundler fails to correctly transpile ESM `import` statements.
fix
Ensure your project is configured for ESM. If using Node.js, add `"type": "module"` to your `package.json` or use `.mjs` file extension. If using a bundler (e.g., Webpack, Rollup), verify its configuration for handling ESM imports. As a workaround for CommonJS, you might try `const { bundle } = await import('api-ref-bundler');` for dynamic ESM import.
Error: ENOENT: no such file or directory, open 'path/to/missing-file.json'
The custom `resolver` function failed to find or read the specified file. This often happens due to incorrect file paths, insufficient permissions, or the file not existing at the expected location relative to the script or `process.cwd()`.
fix
Double-check the `sourcePath` being passed to the `resolver` and ensure the file exists. Verify that `path.join` (if used in your resolver) constructs the correct absolute or relative path. Ensure your application has read permissions for the file system location.
SyntaxError: Unexpected token '...' in JSON at position X
Your `resolver` function attempted to `JSON.parse` content that was not valid JSON. This commonly happens if a `.md` (Markdown) or other non-JSON file is incorrectly identified and passed to `JSON.parse`.
fix
Refine the logic within your `resolver` to correctly identify the content type based on file extension, MIME type, or content sniffing. Only apply `JSON.parse` to content confirmed to be JSON. For non-JSON content like Markdown, return it as a raw string as intended by the library.
Error: Cyclic $ref detected for 'some/path/to/ref'
The dereferencing process encountered a circular reference, and the `enableCircular` option was not set to `true` or the `onCycle` hook was not implemented to handle it.
fix
If you want circular references to be converted into their respective nodes during dereferencing, set `enableCircular: true` in your `DereferenceOptions`. Alternatively, implement the `onCycle` hook within `DereferenceOptions` to provide custom logic for handling or reporting cyclic references without throwing an error.
Upgrade
Version history
0.5.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
20 hits · last 30 days
node
17
OpenAI (training)
1
Resources