@shipworthy/openapi-validator
v1.1.2
Published
Lint an OpenAPI document.
Readme
@shipworthy/openapi-validator
Lint an OpenAPI 3.x document with Spectral's
built-in spectral:oas ruleset, exposed as an Effect service.
Pass a JSON string, a YAML string, or an already-parsed object. The linter prints
each finding to the console. It fails with a typed LintError when the document has
blocking problems: a duplicate operationId, a duplicate tag name, or an unresolved
$ref. It reports other style findings as warnings and does not fail on them. Use it
to gate a spec in CI or before code generation. It powers the openapi lint command
in @shipworthy/openapi-cli. If you want a command-line linter, use that CLI instead
of calling this package.
Installation
bun add @shipworthy/openapi-validator [email protected]Requirements
- Effect 4. The package depends on
effect4.1.4. The public API is an EffectContext.Serviceand an EffectSchemaerror. Add a compatible version to your app so every package resolves to one Effect instance. - ESM only. The package is
"type": "module"and has no CommonJS build. - Node.js
>=22.19.0or Bun. The package ships compiled JavaScript and.d.tsdeclarations indist/. No TypeScript loader or bundler is needed. Its public API is exported from@shipworthy/openapi-validator. - These dependencies are installed with the package (you do not install them):
@stoplight/[email protected],@stoplight/[email protected],@stoplight/[email protected],@stoplight/[email protected].
Quick start
import { Effect } from "effect";
import { Linter } from "@shipworthy/openapi-validator";
const spec = `openapi: 3.1.0
info:
title: Pets
version: 1.0.0
paths:
/pets:
get:
operationId: listPets
responses:
"200":
description: ok
/pets/{id}:
get:
operationId: listPets
responses:
"200":
description: ok
`;
const program = Effect.gen(function* () {
const linter = yield* Linter;
yield* linter.lintDocument(spec, { sourceUrl: "file:///openapi.yaml" });
console.log("Spec is valid");
}).pipe(
Effect.catchTag("LintError", (error) =>
Effect.sync(() => {
for (const d of error.diagnostics) console.log(d.code, d.path.join("."));
}),
),
Effect.provide(Linter.layer),
);
await Effect.runPromise(program);Output (warnings go to console.warn, errors to console.error):
⚠ OpenAPI "servers" must be present and non-empty array.
⚠ Info object must have "contact" object. at #/info
...
⚠ Operation must define parameter "{id}" as expected by path "/pets/{id}". at #/paths//pets/{id}/get
✘ Every operation must have unique "operationId". at #/paths//pets/{id}/get/operationId
operation-operationId-unique paths./pets/{id}.get.operationIdOnly the duplicate operationId fails the run. The other findings are warnings.
API
The package exports two names: Linter and LintError.
Linter
class Linter extends Context.Service<
Linter,
{
readonly lintDocument: (
source: string | Record<string, unknown>,
options?: {
readonly sourceUrl?: string;
readonly silent?: boolean;
readonly strict?: boolean;
},
) => Effect.Effect<void, LintError>;
}
>()("@shipworthy/openapi-validator/Linter") {
static readonly layer: Layer.Layer<Linter>;
}Linter.layer: aLayerwith no requirements. It builds one configured Spectral instance per mode (default and strict), and you can reuse them for manylintDocumentcalls. Provide it withEffect.provide(Linter.layer).Linter.use(fn): the standardContext.Serviceaccessor. Use it for one-off calls:await Effect.runPromise( Linter.use((linter) => linter.lintDocument(source)).pipe(Effect.provide(Linter.layer)), );
lintDocument(source, options?)
| Parameter | Type | Default | Description |
| ------------------- | ----------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| source | string \| Record<string, unknown> | (required) | The document. A string whose first non-whitespace character is { is parsed as JSON. Any other string is parsed as YAML. An object is linted as-is. |
| options.sourceUrl | string | undefined | The document's URI (for example file:///abs/openapi.yaml or https://…/openapi.yaml). Spectral uses it to identify the document when it resolves $refs. |
| options.silent | boolean | false | Suppresses warning output. Errors are always printed. |
| options.strict | boolean | false | Keeps Spectral's original spectral:oas severities and fails on YAML/JSON syntax errors. See Strict mode. |
Returns: Effect<void, LintError>. The effect succeeds with undefined when no
blocking diagnostics are found, even if the linter printed warnings.
Fails with LintError when any of the following is true:
- The input is not an OpenAPI 3.x document: it is not a plain object with an
openapifield whose major version is3. Swagger 2.0, arrays, and{}are all rejected. The error hasmessage: "Expected an OpenAPI 3.x document"and one diagnostic,{ code: "unsupported-format", path: [] }. - At least one blocking diagnostic remains after filtering (see
Rules).
messageis every diagnostic message joined with"\n". - Building the document or running Spectral throws.
messageis the thrown error's message,diagnosticsis[], andcauseholds the original error.
Console output: the linter writes each finding through Effect's Console service.
Blocking diagnostics go to Console.error with the prefix ✘ . Non-blocking ones
go to Console.warn with the prefix ⚠ . A message ends with at #/<path> when it
has a location. Output is colored red or yellow only when process.stdout.isTTY is
true and NO_COLOR is unset. To capture or redirect output, provide your own
Console (for example TestConsole from effect/testing in tests).
LintError
class LintError extends Schema.TaggedError<LintError>()("LintError", {
message: Schema.String,
diagnostics: Schema.Array(
Schema.Struct({
code: Schema.Union([Schema.String, Schema.Finite]),
message: Schema.String,
path: Schema.Array(Schema.Union([Schema.String, Schema.Finite])),
}),
),
cause: Schema.optional(Schema.Defect()),
}) {}_tag:"LintError". Handle it withEffect.catchTag("LintError", …).diagnostics[].code: the Spectral rule ID (for example"operation-operationId-unique","openapi-tags-uniqueness", or"invalid-ref"), or"unsupported-format".diagnostics[].message: the rule message plusat #/<path>when a location exists.diagnostics[].path: JSON path segments into the document. Segments are strings, including array indexes and status codes:["tags", "1", "name"].
Example diagnostics for a duplicate tag and a missing schema reference:
[
{
"code": "openapi-tags-uniqueness",
"message": "\"tags\" object contains duplicate tag name \"a\". at #/tags/1/name",
"path": ["tags", "1", "name"]
},
{
"code": "invalid-ref",
"message": "'#/components/schemas/Missing' does not exist at #/paths//x/get/responses/200/content/application/json/schema/$ref",
"path": [
"paths",
"/x",
"get",
"responses",
"200",
"content",
"application/json",
"schema",
"$ref"
]
}
]Rules and severities
The linter extends Spectral's spectral:oas ruleset in its default ("recommended")
mode, restricted to the OpenAPI 3.x format. It changes Spectral's behavior in these
ways:
| Change | Effect |
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| oas3-schema is off | The linter does not validate the document's structure against the OpenAPI JSON Schema, so partial documents can be linted. |
| spectral:oas rules that default to error are downgraded to warn | This applies to path-params, array-items, no-$ref-siblings, oas3-server-variables, oas3-valid-media-example, and oas3-valid-schema-example. They are printed but do not fail. |
| operation-operationId-unique keeps error severity | A duplicate operationId fails the run. |
| Parser option incompatibleValues is off | YAML numeric keys such as 200: are accepted. |
Some findings are always reported as warnings, even when Spectral marks them as errors:
parserdiagnostics, such as YAML or JSON syntax errors. A malformed YAML string is printed as warnings and does not fail the run.invalid-refdiagnostics whose message starts withReadError:and whose path includesexamples. These are example payloads that use$refas data.
Diagnostics that fail the run: operation-operationId-unique,
openapi-tags-uniqueness, and invalid-ref for unresolved $refs. Any other
diagnostic that Spectral reports with error severity also fails, except the two cases
listed above.
Common warnings (non-blocking): oas3-api-servers, info-contact,
info-description, operation-description, operation-tags, operation-tag-defined,
operation-success-response, oas3-unused-component, duplicated-entry-in-enum,
path-params, and the other recommended spectral:oas rules.
Strict mode
Pass strict: true to turn off the lenient overrides:
- Every
spectral:oasrule keeps its original severity. Rules that default toerror(path-params,array-items,no-$ref-siblings, and the others listed above) fail the run. parserdiagnostics (YAML or JSON syntax errors, such as duplicate keys) fail the run.oas3-schemastays off, andinvalid-refdiagnostics for$refs insideexamplesare still warnings.
yield * linter.lintDocument(spec, { sourceUrl: "file:///openapi.yaml", strict: true });Apart from strict, you cannot change the rules. The package does not support a .spectral.yaml file,
custom rulesets, or per-rule overrides.
Supported OpenAPI versions
- Supported: OpenAPI 3.0.x, 3.1.x, and 3.2.x. The check is
parseInt(document.openapi) === 3. - Rejected: Swagger / OpenAPI 2.0 and any non-object input. Both fail with code
unsupported-format.
Caveats
- The linter does not validate the document's structure. Because
oas3-schemais off, a document with nopathsor a wrongly typedinfostill passes. Spectral only prints warnings for those problems. - YAML syntax errors do not fail by default. They appear only as
⚠warnings. Passstrict: trueto make them fail the run. - JSON detection relies on the first character. A string is treated as JSON only
if its first non-whitespace character is
{. Every other string is parsed as YAML. JSON is a subset of YAML, so most JSON still lints correctly through the YAML path. - The document is linted as given. The linter does not bundle or normalize it. Diagnostics point at paths in your original document.
- The linter writes to the console.
silent: truehides warnings only. To suppress everything, provide a no-opConsoleservice.
Troubleshooting
Expected an OpenAPI 3.x document: the root object has noopenapi: 3.xfield. This also happens with a Swagger 2.0 file or an empty object.- The run fails but you only see warnings above the error: only the
✘lines are blocking. Readerror.diagnosticsfor the exact set. - Unexpected
invalid-referrors: check that every local$reftarget exists under#/components/.... When you lint a file or URL, pass its location assourceUrl, as theopenapi lintCLI does. - Escape codes in logs: set
NO_COLOR=1, or run without a TTY.
Key facts (for AI agents)
- Exports:
Linter(an EffectContext.ServicewithLinter.layer) andLintError(an EffectSchema.TaggedError,_tag: "LintError"). There are no other exports. - Call pattern:
Linter.use((l) => l.lintDocument(source, { sourceUrl?, silent?, strict? })).pipe(Effect.provide(Linter.layer)). sourcecan be a JSON string, a YAML string, or a plain object. The call returnsEffect<void, LintError>.- Inputs that are not OpenAPI 3.x fail with diagnostic code
unsupported-format. - The ruleset is
spectral:oas(recommended) withoas3-schemaoff. Error-level oas rules are downgraded to warnings, exceptoperation-operationId-unique.openapi-tags-uniquenessandinvalid-refalso fail. Parser errors only warn. strict: truekeeps Spectral's originaloasseverities and makes parser (syntax) diagnostics fail.oas3-schemastays off in both modes. Nothing else is configurable.- Output goes through Effect
Console(errorfor blocking diagnostics,warnotherwise). Color is used only on a TTY withoutNO_COLOR. - Requirements: ESM only, compiled JavaScript and
.d.tsdeclarations indist/, Node.js>=22.19.0or Bun, and a dependency on[email protected]. - The CLI equivalent is
openapi lint [--strict] <file-or-url>from@shipworthy/openapi-cli.
License
MIT. See LICENSE.
