@usearazzo/cli 0.0.0-stage → 1.0.1-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,20 @@
1
+ Arazzo Toolkit
2
+ Copyright (c) 2026 UseArazzo
3
+ Arazzo Toolkit is licensed under Apache 2.0 license.
4
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
5
+
6
+ jentic/jentic-arazzo-tools
7
+ Copyright (c) 2026 Jentic
8
+ Jentic Arazzo Tools is licensed under Apache 2.0 license.
9
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
10
+ Arazzo Tookit project was founded on Jentic Arazzo Tools from commit c696c9.
11
+ Arazzo Toolkit includes modifications by members of UseArazzo GitHub organization.
12
+ All such modifications are licensed under the Apache License, Version 2.0.
13
+
14
+ swagger-js/swagger-client
15
+ Copyright 2020-2021 SmartBear Software Inc.
16
+ swagger-client is being pre-processed by our build process
17
+ and swagger-client build artifact is included in npm distribution.
18
+ It's not dynamically linked via npm dependency management.
19
+ swagger-client is licensed under Apache 2.0 license.
20
+ Copy of the Apache 2.0 license can be found in `LICENSE` file.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">@usearazzo/cli</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ Command-line interface for <a href="https://spec.openapis.org/arazzo/latest.html">Arazzo</a> documents:
5
+ validate and lint from your terminal or CI/CD pipeline.
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/@usearazzo/cli"><img src="https://img.shields.io/npm/v/@usearazzo/cli.svg" alt="npm version"></a>
10
+ <a href="https://github.com/usearazzo/arazzo-toolkit/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg" alt="License: Apache 2.0"></a>
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://usearazzo.com"><img alt="UseArazzo" width="96" src="https://usearazzo.com/assets/images/logos/usearazzo-logo.svg"></a>
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Get started
20
+
21
+ Validate an Arazzo document. Nothing to install:
22
+
23
+ ```sh
24
+ npx @usearazzo/cli validate adopt-a-pet.arazzo.yaml
25
+ ```
26
+
27
+ <a href="https://usearazzo.com/cli/"><img alt="usearazzo validate reporting two duplicate stepId errors in one Arazzo document and a missing step description warning in another, each with its line range and rule code" src="https://raw.githubusercontent.com/usearazzo/arazzo-toolkit/main/packages/cli/assets/validate-demo.svg"></a>
28
+
29
+ The argument is a path, a `file:` URI, or an HTTP(S) URL. Every problem comes with the line range that caused it and the code of the rule it broke.
30
+
31
+ Prefer a global install?
32
+
33
+ ```sh
34
+ npm install --global @usearazzo/cli
35
+ usearazzo --help
36
+ ```
37
+
38
+ Requires Node.js 20.10 or newer.
39
+
40
+ ## Commands
41
+
42
+ | Command | What it does |
43
+ | :------ | :----------- |
44
+ | [`validate`](https://usearazzo.com/docs/cli/#validate) | Validate and lint an Arazzo 1.0.x or 1.1.0 document, from a file or a URL. Wraps [@usearazzo/validator](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/validator#readme). |
45
+
46
+ Built for CI: the exit code gates on a severity you choose (`--fail-severity`), and problems are available as JSON (`--format json`). Settings can live in a `.usearazzo.yaml` or `.usearazzo.json` file in the working directory.
47
+
48
+ A command to run workflows, wrapping [@usearazzo/runner](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/runner#readme), comes next.
49
+
50
+ ## Documentation
51
+
52
+ Every option is documented on [usearazzo.com](https://usearazzo.com/) and in `usearazzo <command> --help`:
53
+
54
+ - **[UseArazzo CLI](https://usearazzo.com/cli/)** introduces the CLI: what it does in a terminal and in CI, and the commands that come next. Start here when you are deciding whether it fits.
55
+ - **[CLI Reference](https://usearazzo.com/docs/cli/)** covers every command and option, both output formats, the exit codes, the configuration file, and running in CI. Start here when you know what you want to run.
56
+
57
+ ## Supported versions
58
+
59
+ - [Arazzo 1.0.0](https://spec.openapis.org/arazzo/v1.0.0)
60
+ - [Arazzo 1.0.1](https://spec.openapis.org/arazzo/v1.0.1)
61
+ - [Arazzo 1.1.0](https://spec.openapis.org/arazzo/v1.1.0)
62
+
63
+ ## Part of the Arazzo Toolkit
64
+
65
+ `@usearazzo/cli` is the command-line layer of the [arazzo-toolkit](https://github.com/usearazzo/arazzo-toolkit) monorepo, beside [@usearazzo/parser](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/parser#readme), [@usearazzo/resolver](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/resolver#readme), [@usearazzo/validator](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/validator#readme), and [@usearazzo/runner](https://github.com/usearazzo/arazzo-toolkit/tree/main/packages/runner#readme). Questions and ideas go to [GitHub Discussions](https://github.com/orgs/usearazzo/discussions).
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from '../src/cli.mjs';
4
+
5
+ program.parse();
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@usearazzo/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1-alpha.11",
4
+ "description": "Command-line interface for Arazzo documents: validate and lint from your terminal or CI/CD pipeline.",
5
+ "keywords": [
6
+ "arazzo",
7
+ "arazzo-specification",
8
+ "cli",
9
+ "validator",
10
+ "validation",
11
+ "linter",
12
+ "linting",
13
+ "workflow",
14
+ "workflows"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "registry": "https://registry.npmjs.org",
19
+ "provenance": true,
20
+ "tag": "latest",
21
+ "timeout": 60000
22
+ },
23
+ "type": "module",
24
+ "sideEffects": false,
25
+ "bin": {
26
+ "usearazzo": "./bin/usearazzo.mjs"
27
+ },
28
+ "engines": {
29
+ "node": ">=20.10.0"
30
+ },
31
+ "scripts": {
32
+ "build": "npm run clean && npm run build:es",
33
+ "build:es": "cross-env BABEL_ENV=es babel src --out-dir src --extensions '.ts' --out-file-extension '.mjs' --root-mode 'upward'",
34
+ "lint": "eslint ./",
35
+ "lint:fix": "eslint ./ --fix",
36
+ "clean": "rimraf --glob 'src/**/*.mjs' 'src/**/*.cjs' 'test/**/*.mjs'",
37
+ "typescript:check-types": "tsc --noEmit",
38
+ "test": "npm run build:es && cross-env BABEL_ENV=es babel test --out-dir test --extensions '.ts' --out-file-extension '.mjs' --root-mode 'upward' && cross-env NODE_ENV=test mocha",
39
+ "prepack": "copyfiles -u 2 ../../LICENSE . && copyfiles -u 2 ../../NOTICE .",
40
+ "postpack": "rimraf NOTICE LICENSE"
41
+ },
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/usearazzo/arazzo-toolkit.git"
45
+ },
46
+ "homepage": "https://usearazzo.com/cli/",
47
+ "author": "Vladimir Gorej <vladimir.gorej@gmail.com>",
48
+ "license": "Apache-2.0",
49
+ "dependencies": {
50
+ "@babel/runtime-corejs3": "^8.0.6",
51
+ "@usearazzo/validator": "1.0.1-alpha.11",
52
+ "chalk": "^5.6.2",
53
+ "commander": "^14.0.3",
54
+ "ramda-adjunct": "^6.1.0",
55
+ "vscode-languageserver-types": "=3.18.3",
56
+ "yaml": "^2.9.1"
57
+ },
58
+ "files": [
59
+ "bin/",
60
+ "src/**/*.mjs",
61
+ "LICENSE",
62
+ "NOTICE",
63
+ "README.md"
64
+ ],
65
+ "gitHead": "3cfffaf0045eff162d73df30f840c35cc593af77"
66
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,10 @@
1
+ import { createRequire } from 'node:module';
2
+ import { Command } from 'commander';
3
+ import validate from "./commands/validate/index.mjs";
4
+ const require = createRequire(import.meta.url);
5
+ const {
6
+ version
7
+ } = require('../package.json');
8
+ export const program = new Command();
9
+ program.name('usearazzo').description('UseArazzo CLI for Arazzo documents').version(version);
10
+ program.addCommand(validate);
@@ -0,0 +1,110 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { DiagnosticSeverity } from 'vscode-languageserver-types';
4
+ import { loadConfig } from "../../config.mjs";
5
+ import { formatters, defaultFormat } from "./formatters/index.mjs";
6
+ import writeReport, { wouldOverwriteInput } from "./output.mjs";
7
+ // --fail-severity choices, mapped to their LSP severity. Error is the most
8
+ // severe (smallest numeric value).
9
+ const failSeverities = {
10
+ error: DiagnosticSeverity.Error,
11
+ warning: DiagnosticSeverity.Warning,
12
+ info: DiagnosticSeverity.Information,
13
+ hint: DiagnosticSeverity.Hint
14
+ };
15
+ export const failSeverityChoices = Object.keys(failSeverities);
16
+ export const defaultFailSeverity = 'error';
17
+
18
+ // a diagnostic fails the run when its severity is at least as severe as the
19
+ // --fail-severity threshold (Error is most severe = smallest numeric value)
20
+ const isFailure = (diagnostic, threshold) => diagnostic.severity !== undefined && diagnostic.severity <= threshold;
21
+
22
+ // LSP leaves an absent severity to the client; treat it as an error everywhere
23
+ // (exit code, sort order, formatters) rather than in some places only
24
+ const withSeverity = diagnostic => diagnostic.severity === undefined ? {
25
+ ...diagnostic,
26
+ severity: DiagnosticSeverity.Error
27
+ } : diagnostic;
28
+
29
+ // the local filesystem path of the input, or undefined for an http(s) URL
30
+ const toInputPath = source => {
31
+ if (/^https?:/i.test(source)) {
32
+ return undefined;
33
+ }
34
+ return /^file:/i.test(source) ? fileURLToPath(source) : path.resolve(source);
35
+ };
36
+
37
+ // the root reason of a read failure (ENOENT, HTTP 404, ...) sits several `cause`
38
+ // levels below ValidateError, so the whole chain is walked; a message already
39
+ // contained in the text so far is skipped
40
+ const errorMessage = error => {
41
+ let message = error instanceof Error ? error.message : String(error);
42
+ let cause = error instanceof Error ? error.cause : undefined;
43
+ while (cause instanceof Error) {
44
+ if (!message.includes(cause.message)) {
45
+ message = `${message}: ${cause.message}`;
46
+ }
47
+ cause = cause.cause;
48
+ }
49
+ return message;
50
+ };
51
+ const action = async (source, opts) => {
52
+ try {
53
+ // refuse to overwrite the input document with the diagnostics report - that
54
+ // would silently destroy the user's Arazzo document. wouldOverwriteInput
55
+ // compares filesystem identity to catch symlink/hardlink/case-insensitive
56
+ // aliases, not only equal path strings.
57
+ const inputPath = toInputPath(source);
58
+ if (opts.output && inputPath !== undefined && wouldOverwriteInput(opts.output, inputPath)) {
59
+ process.stderr.write('Error: --output path must differ from the input file\n');
60
+ process.exitCode = 1;
61
+ return;
62
+ }
63
+
64
+ // precedence: validator defaults < configuration file < command-line flags. A flag
65
+ // only overrides when given, so an absent --json-schema-validation keeps the
66
+ // configuration file's choice.
67
+ const languageService = loadConfig(opts.config).languageService ?? {};
68
+ const context = opts.jsonSchemaValidation ? {
69
+ ...languageService,
70
+ validationContext: {
71
+ ...languageService.validationContext,
72
+ jsonSchemaValidation: true
73
+ }
74
+ } : languageService;
75
+
76
+ // the validator pulls in the language service, a heavy (~seconds) import, so it
77
+ // is loaded lazily rather than at module top level - otherwise `--help` and
78
+ // `--version` would pay the cost too
79
+ const {
80
+ validateURI
81
+ } = await import('@usearazzo/validator');
82
+ const diagnostics = (await validateURI(source, context)).map(withSeverity);
83
+ const threshold = failSeverities[opts.failSeverity ?? defaultFailSeverity];
84
+ const failed = diagnostics.some(diagnostic => isFailure(diagnostic, threshold));
85
+
86
+ // sort once, then cap once, so the JSON and human outputs report the same
87
+ // diagnostics in the same (line:column:severity) order. The exit code above
88
+ // is computed from the full set, so --max-problems never masks a failure.
89
+ const sorted = [...diagnostics].sort((a, b) => a.range.start.line - b.range.start.line || a.range.start.character - b.range.start.character || (a.severity ?? DiagnosticSeverity.Error) - (b.severity ?? DiagnosticSeverity.Error));
90
+ const reported = typeof opts.maxProblems === 'number' && opts.maxProblems > 0 ? sorted.slice(0, opts.maxProblems) : sorted;
91
+
92
+ // --json is shorthand for --format json and wins if both are given
93
+ const format = opts.json ? 'json' : opts.format ?? defaultFormat;
94
+ const formatter = formatters[format] ?? formatters[defaultFormat];
95
+ const rendered = `${formatter(reported, {
96
+ path: source,
97
+ total: diagnostics.length
98
+ })}\n`;
99
+ writeReport(rendered, format, opts.output);
100
+
101
+ // set the exit code and let the process exit naturally. Calling process.exit()
102
+ // here would terminate before an async (piped) stdout write drains, truncating
103
+ // large output at the ~64KB pipe buffer.
104
+ process.exitCode = failed ? 1 : 0;
105
+ } catch (error) {
106
+ process.stderr.write(`Error: ${errorMessage(error)}\n`);
107
+ process.exitCode = 1;
108
+ }
109
+ };
110
+ export default action;
@@ -0,0 +1,10 @@
1
+ import stylish from "./stylish.mjs";
2
+ import json from "./json.mjs";
3
+ // diagnostic renderers keyed by the `--format` choice. `stylish` is the default;
4
+ // `json` is the machine-readable form.
5
+ export const formatters = {
6
+ stylish,
7
+ json
8
+ };
9
+ export const defaultFormat = 'stylish';
10
+ export const formatChoices = Object.keys(formatters);
@@ -0,0 +1,4 @@
1
+ // machine-readable output: the raw diagnostics array as pretty-printed JSON.
2
+ // An empty diagnostics set renders as `[]`.
3
+ const json = diagnostics => JSON.stringify(diagnostics, null, 2);
4
+ export default json;
@@ -0,0 +1,74 @@
1
+ import chalk from 'chalk';
2
+ import { DiagnosticSeverity } from 'vscode-languageserver-types';
3
+ const severityLabels = {
4
+ [DiagnosticSeverity.Error]: 'error',
5
+ [DiagnosticSeverity.Warning]: 'warning',
6
+ [DiagnosticSeverity.Information]: 'info',
7
+ [DiagnosticSeverity.Hint]: 'hint'
8
+ };
9
+ const severityColors = {
10
+ [DiagnosticSeverity.Error]: chalk.red,
11
+ [DiagnosticSeverity.Warning]: chalk.yellow,
12
+ [DiagnosticSeverity.Information]: chalk.blue,
13
+ [DiagnosticSeverity.Hint]: chalk.cyan
14
+ };
15
+ const severityToString = severity => severity !== undefined && severityLabels[severity] || 'unknown';
16
+
17
+ // a single `line:column` position, or `line:col-line:col` when the diagnostic
18
+ // spans a range.
19
+ const formatLocation = diagnostic => {
20
+ const startLine = diagnostic.range.start.line + 1;
21
+ const startCol = diagnostic.range.start.character + 1;
22
+ const endLine = diagnostic.range.end.line + 1;
23
+ const endCol = diagnostic.range.end.character + 1;
24
+ if (startLine === endLine && startCol === endCol) {
25
+ return `${startLine}:${startCol}`;
26
+ }
27
+ return `${startLine}:${startCol}-${endLine}:${endCol}`;
28
+ };
29
+ const pluralize = (word, count) => `${count} ${word}${count === 1 ? '' : 's'}`;
30
+
31
+ // eslint-style "stylish" output: a file header, one aligned row per
32
+ // diagnostic (`location severity code message`), and a severity-count
33
+ // summary. Colors are applied via chalk, which auto-disables on non-TTY output.
34
+ const stylish = (diagnostics, context) => {
35
+ if (diagnostics.length === 0) {
36
+ return 'No problems found';
37
+ }
38
+
39
+ // column widths for alignment (measured on the uncolored strings)
40
+ const maxLocationLength = Math.max(...diagnostics.map(d => formatLocation(d).length));
41
+ const maxSeverityLength = Math.max(...diagnostics.map(d => severityToString(d.severity).length));
42
+ const maxCodeLength = Math.max(...diagnostics.map(d => d.code ? String(d.code).length : 0));
43
+ const lines = [chalk.bold(context.path)];
44
+ for (const diagnostic of diagnostics) {
45
+ const location = chalk.dim(formatLocation(diagnostic).padEnd(maxLocationLength));
46
+ const colorize = diagnostic.severity !== undefined && severityColors[diagnostic.severity] || String;
47
+ const severity = colorize(severityToString(diagnostic.severity).padEnd(maxSeverityLength));
48
+ const codeStr = diagnostic.code ? String(diagnostic.code) : '';
49
+ const code = codeStr ? chalk.cyan(codeStr.padEnd(maxCodeLength)) : ' '.repeat(maxCodeLength);
50
+ lines.push(` ${location} ${severity} ${code} ${diagnostic.message}`);
51
+ }
52
+ const counts = {
53
+ error: diagnostics.filter(d => d.severity === DiagnosticSeverity.Error).length,
54
+ warning: diagnostics.filter(d => d.severity === DiagnosticSeverity.Warning).length,
55
+ info: diagnostics.filter(d => d.severity === DiagnosticSeverity.Information).length,
56
+ hint: diagnostics.filter(d => d.severity === DiagnosticSeverity.Hint).length
57
+ };
58
+ const parts = [];
59
+ if (counts.error > 0) parts.push(pluralize('error', counts.error));
60
+ if (counts.warning > 0) parts.push(pluralize('warning', counts.warning));
61
+ if (counts.info > 0) parts.push(pluralize('info', counts.info));
62
+ if (counts.hint > 0) parts.push(pluralize('hint', counts.hint));
63
+ const symbol = counts.error > 0 ? chalk.red('✖') : chalk.yellow('⚠');
64
+ const breakdown = parts.length > 0 ? ` (${parts.join(', ')})` : '';
65
+ lines.push('');
66
+ lines.push(`${symbol} ${pluralize('problem', diagnostics.length)}${breakdown}`);
67
+
68
+ // the action caps diagnostics before formatting; note when a cap is in effect
69
+ if (context.total > diagnostics.length) {
70
+ lines.push(chalk.dim(`(showing ${diagnostics.length} of ${context.total} problems)`));
71
+ }
72
+ return lines.join('\n');
73
+ };
74
+ export default stylish;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import { Command, Option, InvalidArgumentError } from 'commander';
2
+ import action, { defaultFailSeverity, failSeverityChoices } from "./action.mjs";
3
+ import { defaultFormat, formatChoices } from "./formatters/index.mjs";
4
+ const parseMaxProblems = value => {
5
+ const parsed = Number.parseInt(value, 10);
6
+ if (!/^\d+$/.test(value) || parsed < 1) {
7
+ throw new InvalidArgumentError('must be a positive integer.');
8
+ }
9
+ return parsed;
10
+ };
11
+ const command = new Command('validate');
12
+ command.description('Validate and lint an Arazzo document').argument('<uri>', 'path or URL to the Arazzo document (JSON or YAML)').addOption(new Option('-f, --format <format>', 'output format for diagnostics').choices(formatChoices).default(defaultFormat)).option('--json', 'shorthand for --format json').option('-o, --output <file>', 'write diagnostics to file instead of stdout').option('-c, --config <file>', 'configuration file (default: first of .usearazzo.{yaml,yml,json} or usearazzo.{yaml,yml,json} in the cwd)').option('--json-schema-validation', 'enable JSON Schema (AJV) validation').option('--max-problems <n>', 'maximum number of problems to report', parseMaxProblems).addOption(new Option('--fail-severity <severity>', 'minimum diagnostic severity that fails the run').choices(failSeverityChoices).default(defaultFailSeverity)).action(action);
13
+ export default command;
@@ -0,0 +1,55 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import stripAnsi from "./strip-ansi.mjs"; // true when writing to outputPath would clobber the file at inputPath. Resolved
4
+ // path strings are compared first; when the output already exists, filesystem
5
+ // identity (device + inode) is compared too, so a symlink, hard link, or
6
+ // case-insensitive-filesystem alias (Arazzo.yaml vs arazzo.yaml) to the input
7
+ // is caught even though the path strings differ. statSync follows symlinks, so
8
+ // an output symlink pointing at the input resolves to the input's inode. When
9
+ // the output does not exist there is nothing on disk to alias, so the string
10
+ // compare is authoritative. ino is only trusted when non-zero (it can be 0 on
11
+ // some Windows/network filesystems, which would otherwise alias every file).
12
+ //
13
+ // not covered: an output path matching a source description rather than the
14
+ // entry document — the resolved source descriptions are not tracked here.
15
+ export const wouldOverwriteInput = (outputPath, inputPath) => {
16
+ const resolvedOutput = path.resolve(outputPath);
17
+ const resolvedInput = path.resolve(inputPath);
18
+ if (resolvedOutput === resolvedInput) {
19
+ return true;
20
+ }
21
+ try {
22
+ const outputStat = fs.statSync(resolvedOutput);
23
+ const inputStat = fs.statSync(resolvedInput);
24
+ return outputStat.ino !== 0 && outputStat.dev === inputStat.dev && outputStat.ino === inputStat.ino;
25
+ } catch {
26
+ // output (or input) is absent or not statable — no on-disk alias possible
27
+ return false;
28
+ }
29
+ };
30
+
31
+ // write the formatted diagnostics report to its destination. stdout is the
32
+ // default (stderr stays reserved for hard errors); a path from -o/--output
33
+ // redirects it to a file instead.
34
+ //
35
+ // Only the stylish formatter emits chalk colors, and it keys them on
36
+ // process.stdout's TTY state — unaware the bytes are being written to a file.
37
+ // So ANSI is stripped for file output only; the json formatter emits none and
38
+ // is written exactly as rendered, and stdout keeps its colors for the terminal.
39
+ const writeReport = (rendered, format, outputPath) => {
40
+ if (!outputPath) {
41
+ process.stdout.write(rendered);
42
+ return;
43
+ }
44
+ const absPath = path.resolve(outputPath);
45
+ const payload = format === 'json' ? rendered : stripAnsi(rendered);
46
+ try {
47
+ fs.writeFileSync(absPath, payload, 'utf-8');
48
+ } catch (error) {
49
+ const message = error instanceof Error ? error.message : String(error);
50
+ throw new Error(`failed to write ${absPath}: ${message}`, {
51
+ cause: error
52
+ });
53
+ }
54
+ };
55
+ export default writeReport;
@@ -0,0 +1,6 @@
1
+ // remove ANSI SGR escape sequences (e.g. chalk colors) so file output is plain
2
+ // text. Matches ESC[…m — the only sequences the stylish formatter emits. ESC is
3
+ // built from its code point to keep a raw control byte out of the source.
4
+ const ansiSgrPattern = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g');
5
+ const stripAnsi = text => text.replace(ansiSgrPattern, '');
6
+ export default stripAnsi;
package/src/config.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parse } from 'yaml';
4
+ import { isPlainObject } from 'ramda-adjunct';
5
+ /**
6
+ * Configuration file names discovered in the current working directory, in
7
+ * priority order. Like Spectral's `.?spectral.(ya?ml|json)`, the leading dot is
8
+ * optional and the file may be YAML or JSON (the YAML parser reads both).
9
+ */
10
+ export const CONFIG_FILENAMES = ['.usearazzo.yaml', '.usearazzo.yml', '.usearazzo.json', 'usearazzo.yaml', 'usearazzo.yml', 'usearazzo.json'];
11
+ /**
12
+ * Loads the CLI configuration. An explicit `configPath` (relative to the current
13
+ * working directory) must exist; without one, the first of `CONFIG_FILENAMES`
14
+ * present in the current working directory is used, and an empty configuration
15
+ * otherwise. Parent directories are not searched.
16
+ *
17
+ * @throws Error - When the file cannot be read, is not valid YAML or JSON, or has the wrong shape
18
+ */
19
+ export const loadConfig = configPath => {
20
+ const absPath = configPath !== undefined ? path.resolve(configPath) : CONFIG_FILENAMES.map(filename => path.resolve(filename)).find(candidate => fs.existsSync(candidate));
21
+ if (absPath === undefined) {
22
+ return {};
23
+ }
24
+ let config;
25
+ try {
26
+ config = parse(fs.readFileSync(absPath, 'utf-8'));
27
+ } catch (error) {
28
+ const message = error instanceof Error ? error.message : String(error);
29
+ throw new Error(`failed to load configuration file ${absPath}: ${message}`, {
30
+ cause: error
31
+ });
32
+ }
33
+
34
+ // an empty file parses to null and means "no configuration"
35
+ if (config === null || config === undefined) {
36
+ return {};
37
+ }
38
+ if (!isPlainObject(config)) {
39
+ throw new Error(`invalid configuration file ${absPath}: expected a mapping`);
40
+ }
41
+ const {
42
+ languageService
43
+ } = config;
44
+ if (languageService !== undefined && !isPlainObject(languageService)) {
45
+ throw new Error(`invalid configuration file ${absPath}: 'languageService' must be a mapping`);
46
+ }
47
+ return config;
48
+ };