Registry / serialization / webidl2

webidl2

JSON →
library24.5.0jsnpmunverified

webidl2.js is the official W3C-maintained parser for Web IDL (Interface Definition Language), which is used to specify web APIs in an interoperable manner. The library provides core functionalities to `parse` Web IDL strings into a structured Abstract Syntax Tree (AST), `write` an AST back into a Web IDL string, and `validate` the semantic correctness of an AST. This enables programmatic analysis, modification, and generation of Web IDL definitions. It supports both Node.js (requiring Node.js 18 or higher) and browser environments, with distinct usage patterns for each. The current stable version is 24.5.0, reflecting a mature and specification-compliant implementation. Its key differentiators include direct W3C backing, comprehensive support for the Web IDL specification, and tools for both parsing and re-serializing IDL, making it an authoritative choice for developers working with Web IDL definitions.

npm install webidl2
INSTALL
IMPORT
SIG · WEBIDL2
W
webidl2
serializationjavascriptv24.5.0
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.

parse
import { parse } from 'webidl2';
const { parse } = require('webidl2');
This is the recommended ESM import for Node.js environments. For older Node.js versions or CommonJS, use `require` syntax. In browsers supporting modules, path might be relative: `import { parse } from './webidl2/index.js';`
write
const { write } = require('webidl2');
import { write } from 'webidl2';
This is the correct CommonJS import for Node.js environments. If your project uses ESM, use the `import` statement. Browser usage typically involves the global `WebIDL2.write` or an ESM import with a relative path.
WebIDL2
const tree = WebIDL2.parse('interface Foo {}');
import * as WebIDL2 from 'webidl2';
The `WebIDL2` global object is available when the library is included via a `<script>` tag in a browser environment without module support. Do not attempt to `import` this global object in module contexts.
validate
import { validate } from 'webidl2';
import validate from 'webidl2/validate';
The `validate` function is a named export alongside `parse` and `write`. Always destructure it from the main package export, whether using CommonJS `require` or ES module `import`.

This quickstart demonstrates parsing a Web IDL string into an Abstract Syntax Tree (AST), re-serializing the AST back to a string, and validating its semantic correctness. It showcases the primary `parse`, `write`, and `validate` functions.

import { parse, write, validate } from 'webidl2'; const idlString = ` interface MyInterface { /** * A method that takes a string and returns a Promise. * @param input The input string. */ Promise<boolean> doSomething(DOMString input); attribute unsigned long value; [Reflect, URL] attribute USVString url; }; callback MyCallback = undefined (); `; try { // Parse the Web IDL string into an AST const ast = parse(idlString, { sourceName: 'MyIDL.webidl' }); console.log('Parsed AST:', JSON.stringify(ast, null, 2)); // Convert the AST back into an IDL string const reconstructedIdl = write(ast); console.log('\nReconstructed IDL:\n', reconstructedIdl); // Validate the AST for semantic correctness const errors = validate(ast); if (errors.length > 0) { console.error('\nValidation Errors:'); errors.forEach(err => console.error(`- [${err.level}] ${err.message} at ${err.sourceName}:${err.line}:${err.column}`)); } else { console.log('\nIDL is valid!'); } } catch (error) { console.error('Error processing IDL:', error.message); }
Debug
Known issues
breakingAs of version 24.x, webidl2.js officially requires Node.js version 18 or newer. Older Node.js environments (e.g., Node.js 16) are not supported and may encounter runtime errors or unexpected behavior.
fix
Upgrade your Node.js environment to version 18 or higher using `nvm install 18 && nvm use 18` or your preferred Node.js version manager.
affects: >=24.0.0
gotchaWhen migrating between CommonJS (`require`) and ES Modules (`import`), ensure you are using the correct syntax for named exports. Mixing `require` with `import` syntax (e.g., `const { parse } = require('webidl2');` in an ESM file) will lead to errors.
fix
For ESM files, use `import { parse, write, validate } from 'webidl2';`. For CommonJS files, use `const { parse, write, validate } = require('webidl2');`.
affects: >=1.0.0
gotchaThe `parse` function can generate a 'concrete' AST that includes EOF nodes and more trivia if the `concrete: true` option is passed. If you are inspecting the AST or performing transformations, be aware of whether you need the concrete or abstract representation, as it affects the structure.
fix
If your AST processing logic depends on a specific structure, explicitly set the `concrete` option in `parse(idlString, { concrete: true/false })` to ensure consistent output.
affects: >=1.0.0
gotchaThe `write` function accepts an optional `templates` object for advanced customization of the output IDL string. If the default serialization is not meeting your formatting needs, you'll need to provide custom template functions.
fix
Refer to the `webidl2.js` documentation on 'Custom productions' and 'templates' for `write` to implement custom serialization logic.
affects: >=1.0.0
gotchaAlways keep `webidl2` updated. As a W3C-maintained project, it tracks the Web IDL specification, and updates may include new syntax support or bug fixes. Also, its Snyk badge indicates vulnerability tracking, so staying current helps mitigate known security risks.
fix
Regularly run `npm update webidl2` and check the project's GitHub releases for important changes or security advisories.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'parse')
Attempting to use `WebIDL2.parse` in a Node.js or ESM environment where `WebIDL2` is not a global object, or improperly importing the library.
fix
Ensure you are using the correct import for your environment: `import { parse } from 'webidl2';` for Node.js ESM or `const { parse } = require('webidl2');` for Node.js CommonJS.
Error: Failed to parse Web IDL: unexpected token at line X, column Y
The input string provided to `parse()` contains malformed Web IDL syntax, which does not conform to the Web IDL specification.
fix
Review the Web IDL string around the indicated line and column for syntax errors (e.g., missing semicolons, incorrect keywords, mismatched brackets). Use the online checker (w3c.github.io/webidl2.js/checker/) to validate the IDL.
ERR_REQUIRE_ESM: require() of ES Module .../node_modules/webidl2/index.js from ... not supported.
You are attempting to use `require('webidl2')` in a CommonJS context, but `webidl2` is primarily an ES module, or your project's configuration is forcing it to be treated as such.
fix
Ensure your project is configured for ES modules (e.g., `"type": "module"` in `package.json` and `import` statements), or if you must use CommonJS, ensure your bundler/transpiler correctly handles the interop. For direct Node.js usage in CommonJS, sometimes an older version of the library might be needed if direct `require` is critical and ESM interop is not possible, but upgrading Node.js to a version that handles ESM better is usually the solution.
Upgrade
Version history
24.5.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources