Web IDL Type Conversions
webidl-conversions is a JavaScript library that rigorously implements the Web IDL specification's algorithms for converting JavaScript values to and from Web IDL types. It ensures strict adherence to the Web IDL type conversion rules, including handling edge cases, type coercion, and error conditions, to provide consistent behavior as if the operations were natively defined in Web IDL. The current stable version is 8.0.1, with major version updates typically occurring annually to align with Node.js version requirements and Web IDL specification changes. Key differentiators include its meticulous adherence to the spec, support for multiple JavaScript realms, and options for customizing conversion behavior like clamping integers or allowing shared/resizable buffers, making it a critical component for libraries implementing Web APIs in JavaScript.
Common errors
-
TypeError: Argument X of Y is not a finite floating-point value.
cause Attempting to convert a non-finite number (like `NaN` or `Infinity`) using `conversions.float` or `conversions['unrestricted float']`, which, according to Web IDL, must be finite.fixBefore converting to `float`, ensure the value is finite using `Number.isFinite(value)`. If it's not finite, handle the condition gracefully or provide a finite default. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require('webidl-conversions')` inside an ES module (e.g., in a `.mjs` file or when `type: 'module'` is set in `package.json`).fixUse the ES module import syntax: `import conversions from 'webidl-conversions';`. -
TypeError: conversions.Function is not a function
cause Calling `conversions.Function` or `conversions.VoidFunction` after upgrading to version 7.0.0 or later, where these exports were removed.fixRemove usage of `conversions.Function` and `conversions.VoidFunction`. These are no longer part of the library and typically handled by `webidl2js` for interface binding. -
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for .../node_modules/webidl-conversions/index.ts
cause This package is not published as TypeScript source files that need transpilation by the consumer, but rather compiled JavaScript. This error might indicate a misconfiguration in a build system or an incorrect environment.fixEnsure your Node.js environment meets the minimum version requirement (>=20 for v8.x) and that your module resolution is correctly configured. `webidl-conversions` is distributed as plain JavaScript; this error typically suggests a problem external to the library itself, possibly with how your project is trying to import or transpile modules. -
SyntaxError: The requested module 'webidl-conversions' does not provide an export named 'boolean'
cause Attempting to destructure individual conversion functions like `boolean` or `unsignedLong` directly from the `webidl-conversions` package in an ES module import statement.fixThe library's default export is an object containing all conversion functions as properties. Import the entire object and then access the functions: `import conversions from 'webidl-conversions'; const booleanValue = conversions.boolean(input);`
Warnings
- breaking Version 8.0.0 and newer require Node.js version 20 or greater. Attempting to use it with older Node.js versions will result in errors.
- breaking In v8.0.0, support for environments without SharedArrayBuffer was removed. The `allowShared` option was removed from the `ArrayBuffer` export, and a new `SharedArrayBuffer` export was added, aligning with Web IDL spec updates.
- breaking Version 7.0.0 removed the `Function` and `VoidFunction` exports. These types are now recommended to be handled by `webidl2js`.
- breaking In version 7.0.0, the `void` export was renamed to `undefined` to reflect updates in the Web IDL specification.
- breaking Version 5.0.0 removed the `Error` export, as the `Error` type was removed from the Web IDL specification.
- breaking Version 4.0.0 removed the `Date` and `RegExp` exports because these types were also removed from the Web IDL specification.
- gotcha Conversions for `float` and `unrestricted float` will throw a `TypeError` if the input value is `NaN`, as per the Web IDL specification (float values must be finite).
Install
-
npm install webidl-conversions -
yarn add webidl-conversions -
pnpm add webidl-conversions
Imports
- conversions
const conversions = require('webidl-conversions'); - conversions
import { boolean, unsignedLong } from 'webidl-conversions';import conversions from 'webidl-conversions';
- booleanConversion
import { boolean } from 'webidl-conversions';const booleanConversion = conversions.boolean;
Quickstart
import conversions from 'webidl-conversions';
// Example: Implementing a function that mirrors a Web IDL operation
function doWebIDLStuff(name, count) {
try {
// Convert 'name' to DOMString, treating null as empty string
const domName = conversions.DOMString(name, { treatNullAsEmptyString: true });
// Convert 'count' to unsigned long, clamping if out of range
const ulCount = conversions['unsigned long'](count, { enforceRange: true, clamp: true });
console.log(`Processing item: "${domName}" with count: ${ulCount}`);
// Demonstrate another conversion: float
const floatValue = conversions.float(Math.PI / 2);
console.log(`Float value of PI/2: ${floatValue}`);
// Demonstrate object conversion
const obj = conversions.object({ a: 1, b: 'hello' });
console.log('Object conversion successful:', obj);
return `Processed ${domName} ${ulCount} times.`;
} catch (error) {
if (error instanceof TypeError) {
console.error(`Web IDL Conversion Error: ${error.message}`);
return `Failed to process: ${error.message}`;
} else {
throw error;
}
}
}
// Run some examples
console.log(doWebIDLStuff('Widget A', 10));
console.log(doWebIDLStuff(null, -5)); // treatNullAsEmptyString and clamp will handle this
console.log(doWebIDLStuff('Item C', '100')); // String '100' converts to number 100
console.log(doWebIDLStuff('Invalid Float', NaN)); // float(NaN) will throw a TypeError
console.log(doWebIDLStuff('Large Number', 999999999999));
// To run this: save as .mjs and run with Node.js >= 20