kogosoftwarellc / open-api

A Monorepo of various packages to power OpenAPI in node
MIT License
895 stars 237 forks source link

[enhancement] openapi-response-validator: native ESM node modules default export not working as intended #874

Open webketje opened 1 year ago

webketje commented 1 year ago

Context

Bug

import OpenAPIResponseValidator from 'openapi-response-validator'
const validator = new OpenAPIResponseValidator({ responses: { }, components: {}})
// throws "OpenAPIResponseValidator is not a constructor"
// because OpenAPIResponseValidator === { __esModule: true, default: function OpenAPIResponseValidator () {}}

Temp fixes

(clunky, TS types intellisense no longer working in VS Code)

import OpenAPIResponseValidator from 'openapi-response-validator'
const validator = new OpenAPIResponseValidator.default({ responses: { }, components: {}})

or (in generated code, not clean but working) Replace following statements

exports.__esModule = true
exports["default"] = OpenAPIResponseValidator

with

OpenAPIResponseValidator.default = OpenAPIResponseValidator
OpenAPIResponseValidator.__esModule = true
module.exports = OpenAPIResponseValidator

Solution

Provide different entrypoints in dist and expose them to the relevant environments using package.json main, module and exports fields. Alternatively, manually wrap output in a UMD wrapper

jsdevel commented 1 year ago

plz submit a PR

renkei commented 1 year ago

The same issue also exists for OpenAPIRequestValidator and OpenAPIRequestCoercer. As mentioned by the reporter, using

new OpenAPIRequestValidator.default(...)
new OpenAPIResponseValidator.default(...)
new OpenAPIRequestCoercer.default(...)

instead of

new OpenAPIRequestValidator(...)
new OpenAPIResponseValidator(...)
new OpenAPIRequestCoercer(...)

is a workaround for ESM projects. For CommonJS projects, the workaround is not necessary.

jtlindsey commented 1 year ago

same issue with import OpenAPISchemaValidator from 'openapi-schema-validator', workarounds not working. Property 'default' does not exist on type 'typeof OpenAPISchemaValidator'