@scalar/cli 2.15.0 → 2.18.0

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.
Files changed (112) hide show
  1. package/README.md +121 -25
  2. package/chunks/{action-3W4IC7QL.js → action-2WVJ2WEW.js} +26 -27
  3. package/chunks/{action-HOCCP353.js → action-4BDZ2CXP.js} +12 -13
  4. package/chunks/{action-3QQSKGM3.js → action-5AXDB5VN.js} +21 -23
  5. package/chunks/{action-LD5B5QQ4.js → action-6I3TJLRO.js} +34 -33
  6. package/chunks/{action-T7SD3ETN.js → action-6WZN63LT.js} +299 -75
  7. package/chunks/{action-IUAYC2SC.js → action-7GZGVTYI.js} +1071 -775
  8. package/chunks/{action-2BGAMGXU.js → action-7ZCJAWI2.js} +9 -9
  9. package/chunks/{action-6HFH7DAW.js → action-A6YOY24G.js} +14 -10
  10. package/chunks/{action-IU2AVNOW.js → action-AGGHY4N2.js} +26 -26
  11. package/chunks/{action-B2WWTOF6.js → action-BVZOA2G5.js} +15 -16
  12. package/chunks/{action-2UZWKMSJ.js → action-BYDJ4R4F.js} +18 -19
  13. package/chunks/{action-HDT7EO7W.js → action-CBAL5CYB.js} +19 -21
  14. package/chunks/action-COFGCCYS.js +89 -0
  15. package/chunks/action-CYU5Q5LT.js +254 -0
  16. package/chunks/{action-MJHLG7AE.js → action-DTQH6CKR.js} +33 -33
  17. package/chunks/{action-P2RPH5R2.js → action-ED5WLLIE.js} +11 -12
  18. package/chunks/action-F4CQ4DW3.js +654 -0
  19. package/chunks/{action-SRFBOLDL.js → action-GQDQU2WE.js} +1 -1
  20. package/chunks/{action-PDSSIW2A.js → action-GVW5PSPT.js} +26 -28
  21. package/chunks/{action-WOLNPEUQ.js → action-H5VRLFCY.js} +16 -12
  22. package/chunks/{action-G2WBTXOK.js → action-IWEAWDT3.js} +19 -19
  23. package/chunks/{action-NZJ4Z64U.js → action-JN6JVQUV.js} +16 -18
  24. package/chunks/{action-PNSWHIHC.js → action-KVM76ZKQ.js} +20 -20
  25. package/chunks/{action-JNH4DCZX.js → action-LLMFEBHH.js} +3 -4
  26. package/chunks/{action-QJMRAFOF.js → action-PEG7AUA6.js} +20 -19
  27. package/chunks/{action-2HPMP473.js → action-QC72LLYE.js} +13 -11
  28. package/chunks/{action-ZTLOQZTT.js → action-QP6MRSQW.js} +16 -15
  29. package/chunks/{action-4HXB3YQR.js → action-R53K22GE.js} +230 -52
  30. package/chunks/{action-U2RJ3ZAU.js → action-SJPWL723.js} +6 -5
  31. package/chunks/{action-57SV3ZBM.js → action-T3R4SDAI.js} +9 -9
  32. package/chunks/{action-777R7LOG.js → action-TT7ZJNST.js} +25 -25
  33. package/chunks/{action-TY4BZEMN.js → action-UPVVJE26.js} +18 -19
  34. package/chunks/{action-MBAAYXKK.js → action-V35W4MRK.js} +18 -19
  35. package/chunks/{action-TR2T2UYB.js → action-W4KGRBRV.js} +9 -9
  36. package/chunks/{action-ENDUKGWS.js → action-ZIVYJCC2.js} +16 -18
  37. package/chunks/{action-7LK4RUDP.js → action-ZU5X2KQX.js} +52 -49
  38. package/chunks/{actions-D5OHPBWC.js → actions-CERT7BL4.js} +25 -26
  39. package/chunks/{actions-RI42JY6H.js → actions-RCIS37Y6.js} +22 -24
  40. package/chunks/{agent-NA3QFKJX.js → agent-CT3RRYPJ.js} +7 -7
  41. package/chunks/{asyncapi-YBTWMTW6.js → asyncapi-DVBS23QW.js} +17 -18
  42. package/chunks/{build.action-4YDNDBXC.js → build.action-7MKMMV6V.js} +38 -32
  43. package/chunks/{chunk-MGGMCT77.js → chunk-36UI2W7I.js} +1 -1
  44. package/chunks/chunk-4BMOCIYO.js +536 -0
  45. package/chunks/{chunk-ADQ6B6QI.js → chunk-5DRLDTTU.js} +1 -1
  46. package/chunks/{chunk-G5WWW7VD.js → chunk-5EO2CVAR.js} +6 -6
  47. package/chunks/{chunk-Q26DFKTY.js → chunk-5GZAGHKL.js} +1 -1
  48. package/chunks/{chunk-DWJMPHLY.js → chunk-7LUXRNKV.js} +27 -2
  49. package/chunks/{chunk-BY4NGQ5D.js → chunk-A2MPF6GE.js} +7 -3
  50. package/chunks/{chunk-5D3T63G4.js → chunk-BIQFYZP6.js} +1 -1
  51. package/chunks/chunk-CNJ4TLU7.js +83 -0
  52. package/chunks/{chunk-UM3WZUGF.js → chunk-CWCRBWA6.js} +7 -3
  53. package/chunks/{chunk-Z6HOHGUJ.js → chunk-CYIGEQOJ.js} +2 -2
  54. package/chunks/{chunk-4S3DGMMZ.js → chunk-DUIMDHQQ.js} +1 -1
  55. package/chunks/{chunk-W7P6VTCG.js → chunk-DVA4NCCY.js} +6 -4
  56. package/chunks/chunk-DWWY3LPC.js +85 -0
  57. package/chunks/{chunk-USVU6AC2.js → chunk-F6E7FJEC.js} +18 -12
  58. package/chunks/{chunk-E24BNP6E.js → chunk-FDW4LC45.js} +1 -1
  59. package/chunks/{chunk-TW2UASEW.js → chunk-FMPJSW6A.js} +4 -4
  60. package/chunks/{chunk-IPWJEGPD.js → chunk-GCVB22TG.js} +2 -2
  61. package/chunks/{chunk-6BQHLHBE.js → chunk-GXKNYM54.js} +3 -3
  62. package/chunks/chunk-I25ZCHBJ.js +22 -0
  63. package/chunks/{chunk-I57ID5K7.js → chunk-JBMHCTZD.js} +8 -1
  64. package/chunks/{chunk-KOLEQNLG.js → chunk-JEOQ7LSA.js} +1 -1
  65. package/chunks/{chunk-QMERQSPM.js → chunk-KI2AVDKM.js} +8 -6
  66. package/chunks/{chunk-2KSOARE4.js → chunk-KSY2GH53.js} +3 -3
  67. package/chunks/{chunk-SHRUJFQI.js → chunk-KWQVA66H.js} +105 -18
  68. package/chunks/{chunk-DLYMDGFW.js → chunk-LPWRG2MS.js} +4 -4
  69. package/chunks/{chunk-Y6GKZ2FM.js → chunk-LVUMNGVA.js} +1 -1
  70. package/chunks/{chunk-PIDLENYN.js → chunk-M34HMQMV.js} +42 -83
  71. package/chunks/{chunk-7FS7BAUX.js → chunk-MRZ5A7LB.js} +133 -19
  72. package/chunks/chunk-O3I3LTTJ.js +24 -0
  73. package/chunks/{chunk-VBHPHAGS.js → chunk-O4DJIA6Y.js} +2 -18
  74. package/chunks/chunk-OKLL5422.js +263 -0
  75. package/chunks/{chunk-HIDIW2FN.js → chunk-OQE3WKI3.js} +1 -1
  76. package/chunks/{chunk-ERZ3HYB5.js → chunk-PMDHYIB4.js} +9 -21
  77. package/chunks/{chunk-IDGT5RAQ.js → chunk-RELSIFIL.js} +2 -2
  78. package/chunks/{chunk-BOCMOHQA.js → chunk-RGJPENX7.js} +1 -1
  79. package/chunks/{chunk-7FGJIUDN.js → chunk-RHAQ4XBA.js} +3 -3
  80. package/chunks/chunk-RQ7QBRJT.js +93 -0
  81. package/chunks/chunk-S3LY7RKP.js +54 -0
  82. package/chunks/{chunk-T76K7QNX.js → chunk-S5OGPH2P.js} +3 -3
  83. package/chunks/{chunk-ANP5XF26.js → chunk-U36HEOGO.js} +12625 -1369
  84. package/chunks/{chunk-IPUJEBMI.js → chunk-UWRJCJVG.js} +1 -1
  85. package/chunks/chunk-V7DBDXSJ.js +24 -0
  86. package/chunks/{chunk-RRYUCZYO.js → chunk-WGTZEX4Y.js} +7 -3
  87. package/chunks/{chunk-7PNOYE6B.js → chunk-Y3CXAIAG.js} +30 -3
  88. package/chunks/{chunk-GOKHFNB2.js → chunk-Z7EH7CJC.js} +3 -3
  89. package/chunks/{chunk-42MIV6WF.js → chunk-ZMJW5UWU.js} +6 -5
  90. package/chunks/chunk-ZQDAPKWX.js +111 -0
  91. package/chunks/{create.action-52K3XAYN.js → create.action-VA2ISPIM.js} +27 -29
  92. package/chunks/{delete.action-47LPLTOX.js → delete.action-AIWMDGXV.js} +26 -28
  93. package/chunks/{delete.action-3NMOQPIR.js → delete.action-GEN6OD7A.js} +26 -28
  94. package/chunks/{diff.action-5TLC2EHT.js → diff.action-LBK656RN.js} +32 -27
  95. package/chunks/{get.action-BCMLG7C7.js → get.action-5SWRNQ3D.js} +20 -19
  96. package/chunks/{get.action-TOZ474GO.js → get.action-UPPPGGI4.js} +29 -23
  97. package/chunks/{list.action-6ZWEENT6.js → list.action-YJZBC25S.js} +26 -28
  98. package/chunks/{list.action-CMAA5KTY.js → list.action-YOWWC4I4.js} +54 -25
  99. package/chunks/{publish.action-U3VIU5LZ.js → publish.action-QMVDHDJZ.js} +52 -49
  100. package/chunks/{update.action-UQHZYVTP.js → update.action-GFDZIGEP.js} +27 -29
  101. package/chunks/{update.action-QZOP25ME.js → update.action-SNGKPS7A.js} +26 -28
  102. package/index.js +688 -212
  103. package/package.json +11 -11
  104. package/skills/scalar-cli/SKILL.md +4 -3
  105. package/template.md +120 -24
  106. package/chunks/action-3KP3WVPZ.js +0 -112
  107. package/chunks/action-APBLB3IU.js +0 -235
  108. package/chunks/chunk-BLY2CF4S.js +0 -58
  109. package/chunks/chunk-BMQFEKHA.js +0 -3534
  110. package/chunks/chunk-EOTD7HAV.js +0 -318
  111. package/chunks/chunk-QXOUDBFK.js +0 -92
  112. package/chunks/chunk-TR5U7G7T.js +0 -32
@@ -0,0 +1,654 @@
1
+ import { createRequire as $$cR } from "node:module"; const require = $$cR(import.meta.url);
2
+ import {
3
+ resolveForValidation
4
+ } from "./chunk-RQ7QBRJT.js";
5
+ import {
6
+ bundleDocument,
7
+ inspectReferences
8
+ } from "./chunk-OKLL5422.js";
9
+ import {
10
+ childReferenceContext
11
+ } from "./chunk-DWWY3LPC.js";
12
+ import {
13
+ writeFileAtomic
14
+ } from "./chunk-CNJ4TLU7.js";
15
+ import {
16
+ isDocument
17
+ } from "./chunk-WGTZEX4Y.js";
18
+ import "./chunk-CWCRBWA6.js";
19
+ import "./chunk-A2MPF6GE.js";
20
+ import "./chunk-FDW4LC45.js";
21
+ import {
22
+ isUrl
23
+ } from "./chunk-4ORL4MST.js";
24
+ import "./chunk-KSY2GH53.js";
25
+ import "./chunk-T5HJUAWB.js";
26
+ import {
27
+ err,
28
+ ok
29
+ } from "./chunk-DUIMDHQQ.js";
30
+ import "./chunk-Y3CXAIAG.js";
31
+ import "./chunk-5GZAGHKL.js";
32
+ import {
33
+ external_exports
34
+ } from "./chunk-JBMHCTZD.js";
35
+ import "./chunk-3MZYUBJ6.js";
36
+
37
+ // src/domains/document/transform/action.ts
38
+ import fs2 from "node:fs/promises";
39
+ import path2 from "node:path";
40
+ import YAML from "yaml";
41
+ import { fetchUrls, readFiles } from "@scalar/json-magic/bundle/plugins/node";
42
+
43
+ // src/domains/document/transform/config.ts
44
+ var pointer = external_exports.string().regex(
45
+ /^\/(?:[^~]|~[01])*$/,
46
+ "Use a non-root JSON Pointer with valid ~0 and ~1 escapes"
47
+ );
48
+ var configSchema = external_exports.strictObject({
49
+ version: external_exports.literal(1),
50
+ steps: external_exports.array(
51
+ external_exports.discriminatedUnion("type", [
52
+ external_exports.strictObject({ type: external_exports.literal("remove-internal-operations") }),
53
+ external_exports.strictObject({ type: external_exports.literal("remove"), pointer }),
54
+ external_exports.strictObject({ type: external_exports.literal("set"), pointer, value: external_exports.json() })
55
+ ])
56
+ ),
57
+ removeUnusedComponents: external_exports.boolean().default(false)
58
+ });
59
+ var parseTransformConfig = (value) => {
60
+ try {
61
+ const result = configSchema.safeParse(value);
62
+ return result.success ? ok(result.data) : err(
63
+ result.error.issues.map(
64
+ (issue) => `${issue.path.join(".") || "config"}: ${issue.message}`
65
+ ).join("\n")
66
+ );
67
+ } catch {
68
+ return err("Configuration must contain finite JSON-compatible values.");
69
+ }
70
+ };
71
+
72
+ // src/domains/document/transform/transform.ts
73
+ import { validate as validateAsyncApi } from "@scalar/asyncapi-validator";
74
+ import { apply } from "@scalar/json-magic/diff";
75
+ import { validate as validateOpenApi } from "@scalar/openapi-validator";
76
+
77
+ // src/domains/document/transform/graph.ts
78
+ import { resolveReferencePath } from "@scalar/json-magic/bundle";
79
+ import { escapeJsonPointer } from "@scalar/json-magic/helpers/escape-json-pointer";
80
+
81
+ // src/domains/document/transform/pointer.ts
82
+ var pointerSegments = (pointer2) => pointer2.slice(1).split("/").map((key) => key.replace(/~1/g, "/").replace(/~0/g, "~"));
83
+ var pointerValue = (value, segments) => {
84
+ if (!segments.length) return value;
85
+ const [key, ...rest] = segments;
86
+ if (key === void 0 || value === null || typeof value !== "object" || !Object.hasOwn(value, key))
87
+ return void 0;
88
+ return pointerValue(value[key], rest);
89
+ };
90
+ var editPath = (document, pointer2, remove) => {
91
+ const segments = pointerSegments(pointer2);
92
+ if (segments.some(
93
+ (key2) => ["__proto__", "constructor", "prototype"].includes(key2)
94
+ ))
95
+ return err("Prototype paths cannot be edited.");
96
+ const parent = pointerValue(document, segments.slice(0, -1));
97
+ const key = segments.at(-1) ?? "";
98
+ if (parent === null || typeof parent !== "object")
99
+ return err(`Parent does not exist: ${pointer2}`);
100
+ if (Array.isArray(parent) && (!/^(0|[1-9]\d*)$/.test(key) || Number(key) >= parent.length))
101
+ return err(`Array index does not exist: ${pointer2}`);
102
+ if (remove && !Object.hasOwn(parent, key))
103
+ return err(`Target does not exist: ${pointer2}`);
104
+ return ok(segments);
105
+ };
106
+
107
+ // src/domains/document/transform/graph.ts
108
+ var maps = /* @__PURE__ */ new Set([
109
+ "objects",
110
+ "schemas",
111
+ "responses",
112
+ "links",
113
+ "path-items",
114
+ "callbacks",
115
+ "messages"
116
+ ]);
117
+ var operationMethods = [
118
+ "get",
119
+ "put",
120
+ "post",
121
+ "delete",
122
+ "options",
123
+ "head",
124
+ "patch",
125
+ "trace",
126
+ "query"
127
+ ];
128
+ var childPath = (parent, key) => `${parent}/${escapeJsonPointer(key)}`;
129
+ var traversalContext = (value, context, key, swagger) => {
130
+ if (!Array.isArray(value))
131
+ return childReferenceContext(context, key, swagger, "bundle");
132
+ if (context === "messages") return "message";
133
+ if (context === "schemas") return "schema";
134
+ return context === "objects" ? "object" : context;
135
+ };
136
+ var createGraph = (document, origin) => {
137
+ const entries = /* @__PURE__ */ new Map();
138
+ const resources = /* @__PURE__ */ new Map([[origin, ""]]);
139
+ const anchors = /* @__PURE__ */ new Map();
140
+ const swagger = document.swagger === "2.0";
141
+ const index = (value, path3, base, context, ancestors) => {
142
+ const currentOrigin = isDocument(value) && typeof value.$id === "string" ? resolveReferencePath(base, value.$id) : base;
143
+ entries.set(path3, { value, path: path3, origin: currentOrigin, context });
144
+ if (value === null || typeof value !== "object" || context === "data" || ancestors.has(value))
145
+ return;
146
+ const next = new Set(ancestors).add(value);
147
+ if (isDocument(value)) {
148
+ if (typeof value.$id === "string") resources.set(currentOrigin, path3);
149
+ for (const anchor of [value.$anchor, value.$dynamicAnchor]) {
150
+ if (typeof anchor === "string")
151
+ anchors.set(`${currentOrigin}#${anchor}`, path3);
152
+ }
153
+ }
154
+ for (const [key, child] of Object.entries(value)) {
155
+ const childContext = traversalContext(value, context, key, swagger);
156
+ index(child, childPath(path3, key), currentOrigin, childContext, next);
157
+ }
158
+ };
159
+ index(document, "", origin, "object", /* @__PURE__ */ new Set());
160
+ const resolve = (reference, from = "") => {
161
+ const base = entries.get(from)?.origin ?? origin;
162
+ const [prefix, fragment = ""] = reference.split("#", 2);
163
+ const source = prefix ? resolveReferencePath(base, prefix) : base;
164
+ if (fragment && !fragment.startsWith("/"))
165
+ return anchors.get(`${source}#${fragment}`);
166
+ const resource = resources.get(source);
167
+ if (resource === void 0) return void 0;
168
+ try {
169
+ const pointer2 = fragment ? decodeURIComponent(fragment) : "";
170
+ const target = resource + pointer2;
171
+ if (entries.has(target)) return target;
172
+ if (!prefix && entries.has(pointer2)) return pointer2;
173
+ return void 0;
174
+ } catch {
175
+ return void 0;
176
+ }
177
+ };
178
+ const dereference = (value, path3, seen = /* @__PURE__ */ new Set()) => {
179
+ if (!isDocument(value) || typeof value.$ref !== "string") return value;
180
+ const target = resolve(value.$ref, path3);
181
+ if (target === void 0 || seen.has(target)) return value;
182
+ const resolved = dereference(
183
+ entries.get(target)?.value,
184
+ target,
185
+ new Set(seen).add(target)
186
+ );
187
+ return isDocument(resolved) ? {
188
+ ...resolved,
189
+ ...Object.fromEntries(
190
+ Object.entries(value).filter(([key]) => key !== "$ref")
191
+ )
192
+ } : resolved;
193
+ };
194
+ return { entries, resolve, dereference };
195
+ };
196
+ var checkAndPrune = (document, origin, prune) => {
197
+ const graph = createGraph(document, origin);
198
+ const async = typeof document.asyncapi === "string";
199
+ const async3 = async && String(document.asyncapi).startsWith("3.");
200
+ const swagger = document.swagger === "2.0";
201
+ const errors = /* @__PURE__ */ new Set();
202
+ const live = /* @__PURE__ */ new Set();
203
+ const visited = /* @__PURE__ */ new Set();
204
+ const candidates = /* @__PURE__ */ new Set();
205
+ const operationIds = /* @__PURE__ */ new Map();
206
+ const operationLinks = [];
207
+ for (const entry of graph.entries.values()) {
208
+ const segments = pointerSegments(entry.path);
209
+ const parent = graph.entries.get(
210
+ entry.path.slice(0, entry.path.lastIndexOf("/"))
211
+ );
212
+ if (segments.length === 3 && segments[0] === "components" || segments.length === 2 && [
213
+ "definitions",
214
+ "parameters",
215
+ "responses",
216
+ "securityDefinitions",
217
+ "x-ext"
218
+ ].includes(segments[0] ?? "") || async3 && segments.length === 2 && segments[0] === "channels")
219
+ candidates.add(entry.path);
220
+ if (isDocument(entry.value) && typeof entry.value.operationId === "string" && (parent?.context === "path-item" && operationMethods.includes(segments.at(-1) ?? "") || segments.at(-2) === "additionalOperations" && graph.entries.get(
221
+ entry.path.slice(
222
+ 0,
223
+ entry.path.lastIndexOf("/additionalOperations/")
224
+ )
225
+ )?.context === "path-item" || async && ["publish", "subscribe"].includes(segments.at(-1) ?? "") || async3 && segments[0] === "operations" && segments.length === 2)) {
226
+ const paths = operationIds.get(entry.value.operationId) ?? /* @__PURE__ */ new Set();
227
+ paths.add(entry.path);
228
+ operationIds.set(entry.value.operationId, paths);
229
+ }
230
+ }
231
+ const mark = (path3) => {
232
+ live.add(path3);
233
+ if (path3) mark(path3.slice(0, path3.lastIndexOf("/")));
234
+ };
235
+ const follow = (reference, from, context) => {
236
+ const target = graph.resolve(reference, from);
237
+ if (target === void 0)
238
+ errors.add(
239
+ `${from || "/"}: Reference target does not exist: ${reference}`
240
+ );
241
+ else visit(target, context);
242
+ };
243
+ const security = (value, path3) => {
244
+ if (async3 || !Array.isArray(value)) return;
245
+ for (const requirement of value) {
246
+ if (!isDocument(requirement) || "$ref" in requirement) continue;
247
+ for (const name of Object.keys(requirement))
248
+ follow(
249
+ `${swagger ? "#/securityDefinitions" : "#/components/securitySchemes"}/${escapeJsonPointer(name)}`,
250
+ path3
251
+ );
252
+ }
253
+ };
254
+ const visit = (path3, override) => {
255
+ const entry = graph.entries.get(path3);
256
+ if (!entry) return;
257
+ const context = override ?? entry.context;
258
+ mark(path3);
259
+ const visitKey = `${context}:${path3}`;
260
+ if (visited.has(visitKey)) return;
261
+ visited.add(visitKey);
262
+ const value = entry.value;
263
+ if (value === null || typeof value !== "object" || context === "data")
264
+ return;
265
+ if (isDocument(value) && !maps.has(context)) {
266
+ if (typeof value.$ref === "string") follow(value.$ref, path3, context);
267
+ if (context === "schema" && typeof value.$dynamicRef === "string") {
268
+ follow(value.$dynamicRef, path3, "schema");
269
+ const target = graph.resolve(value.$dynamicRef, path3);
270
+ const targetValue = target === void 0 ? void 0 : graph.entries.get(target)?.value;
271
+ if (isDocument(targetValue) && typeof targetValue.$dynamicAnchor === "string") {
272
+ for (const candidate of graph.entries.values()) {
273
+ if (isDocument(candidate.value) && candidate.value.$dynamicAnchor === targetValue.$dynamicAnchor)
274
+ visit(candidate.path, "schema");
275
+ }
276
+ }
277
+ }
278
+ if (context === "schema" && "$recursiveRef" in value)
279
+ errors.add(
280
+ `${path3}: $recursiveRef is not supported; use a supported $ref or $dynamicRef before transforming.`
281
+ );
282
+ if (context === "schema" && isDocument(value.discriminator) && isDocument(value.discriminator.mapping)) {
283
+ for (const target of Object.values(value.discriminator.mapping))
284
+ if (typeof target === "string")
285
+ follow(
286
+ target.includes("/") || target.includes("#") ? target : `#/components/schemas/${escapeJsonPointer(target)}`,
287
+ path3,
288
+ "schema"
289
+ );
290
+ }
291
+ if (context === "link") {
292
+ if (typeof value.operationRef === "string")
293
+ follow(value.operationRef, path3, "object");
294
+ if (typeof value.operationId === "string")
295
+ operationLinks.push({ id: value.operationId, path: path3 });
296
+ }
297
+ if (context === "object" || context === "path-item")
298
+ security(value.security, path3);
299
+ if (async && Array.isArray(value.servers)) {
300
+ for (const server of value.servers)
301
+ if (typeof server === "string")
302
+ follow(`#/servers/${escapeJsonPointer(server)}`, path3);
303
+ }
304
+ }
305
+ for (const [key, child] of Object.entries(value)) {
306
+ const nextPath = childPath(path3, key);
307
+ if (prune && candidates.has(nextPath)) continue;
308
+ if (prune && path3 === "" && ([
309
+ "components",
310
+ "x-ext",
311
+ "definitions",
312
+ "parameters",
313
+ "responses",
314
+ "securityDefinitions"
315
+ ].includes(key) || async3 && key === "channels"))
316
+ continue;
317
+ const childContext = traversalContext(value, context, key, swagger);
318
+ if (child !== void 0) visit(nextPath, childContext);
319
+ }
320
+ };
321
+ visit("");
322
+ for (const link of operationLinks) {
323
+ const targets = operationIds.get(link.id);
324
+ if (!targets || prune && ![...targets].some((target) => live.has(target)))
325
+ errors.add(`${link.path}: Operation does not exist: ${link.id}`);
326
+ }
327
+ if (errors.size) return err([...errors].join("\n"));
328
+ if (prune) {
329
+ for (const path3 of [...candidates].sort((a, b) => b.length - a.length)) {
330
+ if (live.has(path3)) continue;
331
+ const segments = pointerSegments(path3);
332
+ const parent = pointerValue(document, segments.slice(0, -1));
333
+ if (isDocument(parent)) delete parent[segments.at(-1) ?? ""];
334
+ }
335
+ const sweepExternal = (value, path3) => {
336
+ if (!isDocument(value) || graph.entries.get(path3)?.context === "data")
337
+ return;
338
+ for (const [key, child] of Object.entries(value)) {
339
+ const location = childPath(path3, key);
340
+ if (["$id", "$anchor", "$dynamicAnchor", "$schema", "$global"].includes(
341
+ key
342
+ ))
343
+ continue;
344
+ if (!live.has(location)) delete value[key];
345
+ else sweepExternal(child, location);
346
+ }
347
+ };
348
+ if (isDocument(document["x-ext"])) {
349
+ for (const [key, value] of Object.entries(document["x-ext"]))
350
+ sweepExternal(value, childPath("/x-ext", key));
351
+ }
352
+ }
353
+ return ok(document);
354
+ };
355
+
356
+ // src/domains/document/transform/filter.ts
357
+ var removeInternalOperations = (document, origin) => {
358
+ const graph = createGraph(document, origin);
359
+ const filteredCallbacks = /* @__PURE__ */ new Set();
360
+ const pathItems = (items, path3, ancestors = /* @__PURE__ */ new Set()) => {
361
+ if (!isDocument(items)) return;
362
+ for (const [name, raw] of Object.entries(items)) {
363
+ if (name.startsWith("x-")) continue;
364
+ const location = childPath(path3, name);
365
+ const value = graph.dereference(raw, location);
366
+ if (!isDocument(value)) continue;
367
+ if (value["x-internal"] === true) {
368
+ delete items[name];
369
+ continue;
370
+ }
371
+ const item = structuredClone(value);
372
+ const containers = [
373
+ { container: item, path: location, methods: operationMethods },
374
+ ...isDocument(item.additionalOperations) ? [
375
+ {
376
+ container: item.additionalOperations,
377
+ path: childPath(location, "additionalOperations"),
378
+ methods: Object.keys(item.additionalOperations)
379
+ }
380
+ ] : []
381
+ ];
382
+ const operations = containers.flatMap(
383
+ ({ container, path: path4, methods }) => methods.filter((method) => method in container).map((method) => ({
384
+ container,
385
+ method,
386
+ path: childPath(path4, method)
387
+ }))
388
+ );
389
+ items[name] = item;
390
+ for (const { container, method, path: operationPath } of operations) {
391
+ const operation = structuredClone(
392
+ graph.dereference(container[method], operationPath)
393
+ );
394
+ if (!isDocument(operation)) continue;
395
+ if (operation["x-internal"] === true) {
396
+ delete container[method];
397
+ continue;
398
+ }
399
+ container[method] = operation;
400
+ if (!isDocument(operation.callbacks)) continue;
401
+ for (const [name2, callback] of Object.entries(operation.callbacks)) {
402
+ const callbackPath = childPath(
403
+ childPath(operationPath, "callbacks"),
404
+ name2
405
+ );
406
+ const target = isDocument(callback) && typeof callback.$ref === "string" ? graph.resolve(callback.$ref, callbackPath) : callbackPath;
407
+ if (target !== void 0 && isDocument(callback) && typeof callback.$ref === "string" && !filteredCallbacks.has(target)) {
408
+ filteredCallbacks.add(target);
409
+ pathItems(
410
+ graph.entries.get(target)?.value,
411
+ target,
412
+ /* @__PURE__ */ new Set([target])
413
+ );
414
+ }
415
+ if (target === void 0 || ancestors.has(target)) continue;
416
+ const resolved = structuredClone(
417
+ graph.dereference(callback, callbackPath)
418
+ );
419
+ operation.callbacks[name2] = resolved;
420
+ pathItems(resolved, target, new Set(ancestors).add(target));
421
+ }
422
+ }
423
+ if (operations.length > 0 && !operations.some(({ container, method }) => method in container) && !("$ref" in item))
424
+ delete items[name];
425
+ }
426
+ };
427
+ if (typeof document.asyncapi !== "string") {
428
+ pathItems(document.paths, "/paths");
429
+ pathItems(document.webhooks, "/webhooks");
430
+ if (isDocument(document.components))
431
+ pathItems(document.components.pathItems, "/components/pathItems");
432
+ return;
433
+ }
434
+ if (document.asyncapi.startsWith("3.")) {
435
+ if (isDocument(document.operations))
436
+ for (const [name, raw] of Object.entries(document.operations)) {
437
+ const location = childPath("/operations", name);
438
+ const operation = graph.dereference(raw, location);
439
+ if (!isDocument(operation)) continue;
440
+ const channel = graph.dereference(
441
+ operation.channel,
442
+ childPath(location, "channel")
443
+ );
444
+ if (operation["x-internal"] === true || isDocument(channel) && channel["x-internal"] === true)
445
+ delete document.operations[name];
446
+ }
447
+ if (isDocument(document.channels))
448
+ for (const [name, raw] of Object.entries(document.channels)) {
449
+ const channel = graph.dereference(raw, childPath("/channels", name));
450
+ if (isDocument(channel) && channel["x-internal"] === true)
451
+ delete document.channels[name];
452
+ }
453
+ return;
454
+ }
455
+ if (!isDocument(document.channels)) return;
456
+ for (const [name, raw] of Object.entries(document.channels)) {
457
+ const location = childPath("/channels", name);
458
+ const channel = graph.dereference(raw, location);
459
+ if (!isDocument(channel)) continue;
460
+ if (channel["x-internal"] === true) {
461
+ delete document.channels[name];
462
+ continue;
463
+ }
464
+ const copy = structuredClone(channel);
465
+ const hadOperations = "publish" in copy || "subscribe" in copy;
466
+ document.channels[name] = copy;
467
+ for (const method of ["publish", "subscribe"]) {
468
+ const operation = graph.dereference(
469
+ copy[method],
470
+ childPath(location, method)
471
+ );
472
+ if (isDocument(operation) && operation["x-internal"] === true)
473
+ delete copy[method];
474
+ }
475
+ if (hadOperations && !("publish" in copy) && !("subscribe" in copy))
476
+ delete document.channels[name];
477
+ }
478
+ };
479
+
480
+ // src/domains/document/transform/transform.ts
481
+ var transformDocument = (input, config, origin) => {
482
+ try {
483
+ const document = structuredClone(input);
484
+ const versionKey = typeof input.asyncapi === "string" ? "asyncapi" : typeof input.openapi === "string" ? "openapi" : "swagger";
485
+ if (!(versionKey in input))
486
+ return err(
487
+ "Provide an OpenAPI or AsyncAPI description with a supported version."
488
+ );
489
+ const version = input[versionKey];
490
+ if (typeof version !== "string" || !(versionKey === "swagger" ? version === "2.0" : versionKey === "asyncapi" ? /^[23]\.\d+\.\d+$/.test(version) : /^3\.[012]\.\d+$/.test(version)))
491
+ return err(`Unsupported ${versionKey} version: ${String(version)}`);
492
+ for (const [index, step] of config.steps.entries()) {
493
+ if (step.type === "remove-internal-operations") {
494
+ removeInternalOperations(document, origin);
495
+ continue;
496
+ }
497
+ const path3 = editPath(document, step.pointer, step.type === "remove");
498
+ if (!path3.ok) return err(`steps.${index}: ${path3.error}`);
499
+ apply(document, [
500
+ {
501
+ path: path3.data,
502
+ type: step.type === "remove" ? "delete" : "add",
503
+ changes: step.type === "set" ? structuredClone(step.value) : void 0
504
+ }
505
+ ]);
506
+ }
507
+ if (document[versionKey] !== input[versionKey] || ["openapi", "asyncapi", "swagger"].some(
508
+ (key) => key !== versionKey && key in document
509
+ ))
510
+ return err(
511
+ "Transformations cannot change the document format or version."
512
+ );
513
+ const checked = checkAndPrune(
514
+ document,
515
+ origin,
516
+ config.removeUnusedComponents
517
+ );
518
+ if (!checked.ok) return checked;
519
+ const retained = checkAndPrune(document, origin, false);
520
+ if (!retained.ok) return retained;
521
+ const resolved = resolveForValidation(document);
522
+ if (!resolved.ok) return resolved;
523
+ const result = versionKey === "asyncapi" ? validateAsyncApi(document) : validateOpenApi(document);
524
+ if (!result.valid)
525
+ return err(
526
+ `Transformed description is invalid: ${JSON.stringify(result.errors)}`
527
+ );
528
+ if (versionKey !== "asyncapi") {
529
+ const resolvedResult = validateOpenApi(resolved.data, {
530
+ checkPathParameters: true
531
+ });
532
+ if (!resolvedResult.valid)
533
+ return err(
534
+ `Transformed description is invalid: ${JSON.stringify(resolvedResult.errors)}`
535
+ );
536
+ }
537
+ return ok(document);
538
+ } catch (error) {
539
+ return err(
540
+ `Could not transform API description: ${error instanceof Error ? error.message : String(error)}`
541
+ );
542
+ }
543
+ };
544
+
545
+ // src/domains/document/transform/write.ts
546
+ import fs from "node:fs/promises";
547
+ import path from "node:path";
548
+ var writeTransformed = async (destination, content, sources) => {
549
+ try {
550
+ const resolved = path.resolve(destination);
551
+ const existing = await fs.stat(resolved).catch(() => void 0);
552
+ const real = await fs.realpath(resolved).catch(() => resolved);
553
+ for (const source of sources) {
554
+ const sourcePath = path.resolve(source);
555
+ const sourceReal = await fs.realpath(sourcePath).catch(() => sourcePath);
556
+ const sourceStat = await fs.stat(sourcePath).catch(() => void 0);
557
+ if (resolved === sourcePath || real === sourceReal || existing && sourceStat && existing.dev === sourceStat.dev && existing.ino === sourceStat.ino)
558
+ return err(`Output cannot overwrite a source file: ${source}`);
559
+ }
560
+ const entry = await fs.lstat(resolved).catch(() => void 0);
561
+ if (entry && !entry.isFile())
562
+ return err(`Output must be a regular file: ${destination}`);
563
+ const result = await writeFileAtomic(resolved, content);
564
+ return result.ok ? result : err(`Could not write ${destination}: ${result.error}`);
565
+ } catch (error) {
566
+ return err(
567
+ `Could not write ${destination}: ${error instanceof Error ? error.message : String(error)}`
568
+ );
569
+ }
570
+ };
571
+
572
+ // src/domains/document/transform/action.ts
573
+ var parseConfigFile = async (filename) => {
574
+ try {
575
+ return ok(YAML.parse(await fs2.readFile(filename, "utf8")));
576
+ } catch (error) {
577
+ return err(`Could not read configuration ${filename}: ${String(error)}`);
578
+ }
579
+ };
580
+ var transformAction = async (input, options) => {
581
+ const fail = (message) => {
582
+ process.stderr.write(`${message}
583
+ `);
584
+ process.exitCode = 1;
585
+ };
586
+ const stdout = options.output === "-";
587
+ if (!stdout && !/\.(json|ya?ml)$/i.test(options.output))
588
+ return fail(
589
+ "Use a .json, .yaml, or .yml output file, or --output - for stdout."
590
+ );
591
+ const parsed = await parseConfigFile(options.config);
592
+ if (!parsed.ok) return fail(parsed.error);
593
+ const config = parseTransformConfig(parsed.data);
594
+ if (!config.ok) return fail(`${options.config}: ${config.error}`);
595
+ const origin = isUrl(input) ? input : path2.resolve(input);
596
+ const sources = /* @__PURE__ */ new Set([path2.resolve(options.config)]);
597
+ const files = readFiles();
598
+ const trackedFiles = {
599
+ ...files,
600
+ exec: async (source) => {
601
+ sources.add(source);
602
+ return files.exec(source);
603
+ }
604
+ };
605
+ const inspected = await inspectReferences(origin, [
606
+ trackedFiles,
607
+ fetchUrls({ limit: 5 })
608
+ ]);
609
+ if (!inspected.ok) return fail(inspected.error);
610
+ if (inspected.data.diagnostics.length)
611
+ return fail(
612
+ inspected.data.diagnostics.map(
613
+ (diagnostic) => `${diagnostic.source}${diagnostic.pointer}: ${diagnostic.message} ${diagnostic.reference}`
614
+ ).join("\n")
615
+ );
616
+ const root = await inspected.data.loader.exec(origin);
617
+ const yaml = stdout ? root.ok && !root.raw.trimStart().startsWith("{") : /\.ya?ml$/i.test(options.output);
618
+ const bundled = await bundleDocument(inspected.data, origin, {
619
+ treeShake: false,
620
+ urlMap: false
621
+ });
622
+ if (!bundled.ok) return fail(bundled.error);
623
+ if (!isDocument(bundled.data))
624
+ return fail("Provide an OpenAPI or AsyncAPI description.");
625
+ const result = transformDocument(bundled.data, config.data, origin);
626
+ if (!result.ok) return fail(result.error);
627
+ const serialized = serialize(result.data, yaml);
628
+ if (!serialized.ok) return fail(serialized.error);
629
+ if (stdout) {
630
+ process.stdout.write(serialized.data);
631
+ return;
632
+ }
633
+ const written = await writeTransformed(options.output, serialized.data, [
634
+ ...sources
635
+ ]);
636
+ if (!written.ok) return fail(written.error);
637
+ process.stderr.write(
638
+ `API description transformed. Written to ${options.output}
639
+ `
640
+ );
641
+ };
642
+ var serialize = (document, yaml) => {
643
+ try {
644
+ return ok(
645
+ yaml ? YAML.stringify(document) : `${JSON.stringify(document, null, 2)}
646
+ `
647
+ );
648
+ } catch (error) {
649
+ return err(`Could not serialize transformed description: ${String(error)}`);
650
+ }
651
+ };
652
+ export {
653
+ transformAction
654
+ };
@@ -1,7 +1,7 @@
1
1
  import { createRequire as $$cR } from "node:module"; const require = $$cR(import.meta.url);
2
2
  import {
3
3
  buildCliContext
4
- } from "./chunk-ADQ6B6QI.js";
4
+ } from "./chunk-5DRLDTTU.js";
5
5
  import "./chunk-3MZYUBJ6.js";
6
6
 
7
7
  // src/domains/context/action.ts