@scalar/openapi-parser 0.16.0 → 0.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.
- package/CHANGELOG.md +18 -0
- package/README.md +44 -1
- package/dist/plugins-browser.d.ts +2 -0
- package/dist/plugins-browser.d.ts.map +1 -1
- package/dist/plugins-browser.js +5 -1
- package/dist/plugins-browser.js.map +2 -2
- package/dist/plugins.d.ts +2 -0
- package/dist/plugins.d.ts.map +1 -1
- package/dist/plugins.js +4 -0
- package/dist/plugins.js.map +2 -2
- package/dist/utils/bundle/bundle.d.ts +25 -18
- package/dist/utils/bundle/bundle.d.ts.map +1 -1
- package/dist/utils/bundle/bundle.js +64 -28
- package/dist/utils/bundle/bundle.js.map +2 -2
- package/dist/utils/bundle/plugins/fetch-urls/index.js +1 -1
- package/dist/utils/bundle/plugins/fetch-urls/index.js.map +2 -2
- package/dist/utils/bundle/plugins/parse-json/index.d.ts +13 -0
- package/dist/utils/bundle/plugins/parse-json/index.d.ts.map +1 -0
- package/dist/utils/bundle/plugins/parse-json/index.js +22 -0
- package/dist/utils/bundle/plugins/parse-json/index.js.map +7 -0
- package/dist/utils/bundle/plugins/parse-yaml/index.d.ts +13 -0
- package/dist/utils/bundle/plugins/parse-yaml/index.d.ts.map +1 -0
- package/dist/utils/bundle/plugins/parse-yaml/index.js +23 -0
- package/dist/utils/bundle/plugins/parse-yaml/index.js.map +7 -0
- package/dist/utils/bundle/plugins/read-files/index.d.ts.map +1 -1
- package/dist/utils/bundle/plugins/read-files/index.js +3 -3
- package/dist/utils/bundle/plugins/read-files/index.js.map +2 -2
- package/dist/utils/bundle/value-generator.d.ts +79 -0
- package/dist/utils/bundle/value-generator.d.ts.map +1 -0
- package/dist/utils/bundle/value-generator.js +55 -0
- package/dist/utils/bundle/value-generator.js.map +7 -0
- package/dist/utils/load/load.d.ts +6 -0
- package/dist/utils/load/load.d.ts.map +1 -1
- package/dist/utils/load/load.js.map +2 -2
- package/dist/utils/upgrade-from-three-to-three-one.js +4 -0
- package/dist/utils/upgrade-from-three-to-three-one.js.map +2 -2
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @scalar/openapi-parser
|
|
2
2
|
|
|
3
|
+
## 0.18.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 291f09d: feat(openapi-parser): ensure unique hashes and support custom compression
|
|
8
|
+
|
|
9
|
+
## 0.17.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- f823d45: feat(openapi-parser): introduce parseJson and parseYaml plugins for bundler
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- 166e298: feat(openapi-parser): correctly set the base origin for string inputs for the bundler
|
|
18
|
+
- 4156f1d: Expand workspace store integration
|
|
19
|
+
- 37c90b8: feat: add x-webhooks upgrade to the upgrader
|
|
20
|
+
|
|
3
21
|
## 0.16.0
|
|
4
22
|
|
|
5
23
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -174,7 +174,8 @@ console.log(result)
|
|
|
174
174
|
This plugins handles local files. Only works on node.js environment
|
|
175
175
|
|
|
176
176
|
```ts
|
|
177
|
-
import { bundle
|
|
177
|
+
import { bundle } from '@scalar/openapi-parser'
|
|
178
|
+
import { readFiles } from '@scalar/openapi-parser/plugins-browser'
|
|
178
179
|
|
|
179
180
|
const document = {
|
|
180
181
|
openapi: '3.1.0',
|
|
@@ -214,6 +215,48 @@ const result = await bundle(
|
|
|
214
215
|
console.log(result)
|
|
215
216
|
```
|
|
216
217
|
|
|
218
|
+
##### parseJson
|
|
219
|
+
|
|
220
|
+
You can pass raw json string as input
|
|
221
|
+
```ts
|
|
222
|
+
import { bundle } from '@scalar/openapi-parser'
|
|
223
|
+
import { parseJson } from '@scalar/openapi-parser/plugins-browser'
|
|
224
|
+
|
|
225
|
+
const result = await bundle(
|
|
226
|
+
'{ "openapi": "3.1.1" }',
|
|
227
|
+
{
|
|
228
|
+
plugins: [
|
|
229
|
+
parseJson(),
|
|
230
|
+
],
|
|
231
|
+
treeShake: false
|
|
232
|
+
},
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
// Bundled document
|
|
236
|
+
console.log(result)
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
##### parseYaml
|
|
240
|
+
|
|
241
|
+
You can pass raw yaml string as input
|
|
242
|
+
```ts
|
|
243
|
+
import { bundle } from '@scalar/openapi-parser'
|
|
244
|
+
import { parseYaml } from '@scalar/openapi-parser/plugins-browser'
|
|
245
|
+
|
|
246
|
+
const result = await bundle(
|
|
247
|
+
'openapi: "3.1.1"\n',
|
|
248
|
+
{
|
|
249
|
+
plugins: [
|
|
250
|
+
parseYaml(),
|
|
251
|
+
],
|
|
252
|
+
treeShake: false
|
|
253
|
+
},
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
// Bundled document
|
|
257
|
+
console.log(result)
|
|
258
|
+
```
|
|
259
|
+
|
|
217
260
|
### Track references
|
|
218
261
|
|
|
219
262
|
The `dereference` function accepts an `onDereference` callback option that gets called whenever a reference is resolved. This can be useful for tracking which schemas are being dereferenced:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins-browser.d.ts","sourceRoot":"","sources":["../src/plugins-browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA"}
|
|
1
|
+
{"version":3,"file":"plugins-browser.d.ts","sourceRoot":"","sources":["../src/plugins-browser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA"}
|
package/dist/plugins-browser.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { fetchUrls } from "./utils/bundle/plugins/fetch-urls/index.js";
|
|
2
|
+
import { parseJson } from "./utils/bundle/plugins/parse-json/index.js";
|
|
3
|
+
import { parseYaml } from "./utils/bundle/plugins/parse-yaml/index.js";
|
|
2
4
|
export {
|
|
3
|
-
fetchUrls
|
|
5
|
+
fetchUrls,
|
|
6
|
+
parseJson,
|
|
7
|
+
parseYaml
|
|
4
8
|
};
|
|
5
9
|
//# sourceMappingURL=plugins-browser.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plugins-browser.ts"],
|
|
4
|
-
"sourcesContent": ["export { fetchUrls } from './utils/bundle/plugins/fetch-urls'\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;",
|
|
4
|
+
"sourcesContent": ["export { fetchUrls } from './utils/bundle/plugins/fetch-urls'\nexport { parseJson } from './utils/bundle/plugins/parse-json'\nexport { parseYaml } from './utils/bundle/plugins/parse-yaml'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/plugins.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { fetchUrls } from './utils/bundle/plugins/fetch-urls/index.js';
|
|
2
2
|
export { readFiles } from './utils/bundle/plugins/read-files/index.js';
|
|
3
|
+
export { parseJson } from './utils/bundle/plugins/parse-json/index.js';
|
|
4
|
+
export { parseYaml } from './utils/bundle/plugins/parse-yaml/index.js';
|
|
3
5
|
//# sourceMappingURL=plugins.d.ts.map
|
package/dist/plugins.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA"}
|
|
1
|
+
{"version":3,"file":"plugins.d.ts","sourceRoot":"","sources":["../src/plugins.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA;AAC7D,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAA"}
|
package/dist/plugins.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { fetchUrls } from "./utils/bundle/plugins/fetch-urls/index.js";
|
|
2
2
|
import { readFiles } from "./utils/bundle/plugins/read-files/index.js";
|
|
3
|
+
import { parseJson } from "./utils/bundle/plugins/parse-json/index.js";
|
|
4
|
+
import { parseYaml } from "./utils/bundle/plugins/parse-yaml/index.js";
|
|
3
5
|
export {
|
|
4
6
|
fetchUrls,
|
|
7
|
+
parseJson,
|
|
8
|
+
parseYaml,
|
|
5
9
|
readFiles
|
|
6
10
|
};
|
|
7
11
|
//# sourceMappingURL=plugins.js.map
|
package/dist/plugins.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/plugins.ts"],
|
|
4
|
-
"sourcesContent": ["export { fetchUrls } from './utils/bundle/plugins/fetch-urls'\nexport { readFiles } from './utils/bundle/plugins/read-files'\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;",
|
|
4
|
+
"sourcesContent": ["export { fetchUrls } from './utils/bundle/plugins/fetch-urls'\nexport { readFiles } from './utils/bundle/plugins/read-files'\nexport { parseJson } from './utils/bundle/plugins/parse-json'\nexport { parseYaml } from './utils/bundle/plugins/parse-yaml'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;AAC1B,SAAS,iBAAiB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -12,6 +12,21 @@ import type { UnknownObject } from '../../types/index.js';
|
|
|
12
12
|
* ```
|
|
13
13
|
*/
|
|
14
14
|
export declare function isRemoteUrl(value: string): boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Checks if a string represents a file path by ensuring it's not a remote URL,
|
|
17
|
+
* YAML content, or JSON content.
|
|
18
|
+
*
|
|
19
|
+
* @param value - The string to check
|
|
20
|
+
* @returns true if the string appears to be a file path, false otherwise
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* isFilePath('./schemas/user.json') // true
|
|
24
|
+
* isFilePath('https://example.com/schema.json') // false
|
|
25
|
+
* isFilePath('{"type": "object"}') // false
|
|
26
|
+
* isFilePath('type: object') // false
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function isFilePath(value: string): boolean;
|
|
15
30
|
/**
|
|
16
31
|
* Checks if a string is a local reference (starts with #)
|
|
17
32
|
* @param value - The reference string to check
|
|
@@ -128,20 +143,6 @@ export declare function prefixInternalRef(input: string, prefix: string[]): stri
|
|
|
128
143
|
* ```
|
|
129
144
|
*/
|
|
130
145
|
export declare function prefixInternalRefRecursive(input: unknown, prefix: string[]): string;
|
|
131
|
-
/**
|
|
132
|
-
* Generates a short SHA-1 hash from a string value.
|
|
133
|
-
* This function is used to create unique identifiers for external references
|
|
134
|
-
* while keeping the hash length manageable. It uses the Web Crypto API to
|
|
135
|
-
* generate a SHA-1 hash and returns the first 7 characters of the hex string.
|
|
136
|
-
* If the hash would be all numbers, it ensures at least one letter is included.
|
|
137
|
-
*
|
|
138
|
-
* @param value - The string to hash
|
|
139
|
-
* @returns A 7-character hexadecimal hash with at least one letter
|
|
140
|
-
* @example
|
|
141
|
-
* // Returns "2ae91d7"
|
|
142
|
-
* await getHash("https://example.com/schema.json")
|
|
143
|
-
*/
|
|
144
|
-
export declare function getHash(value: string): Promise<string>;
|
|
145
146
|
/**
|
|
146
147
|
* Represents a plugin that handles resolving references from external sources.
|
|
147
148
|
* Plugins are responsible for fetching and processing data from different sources
|
|
@@ -197,6 +198,11 @@ type Config = {
|
|
|
197
198
|
* in an x-ext-urls section for reference mapping.
|
|
198
199
|
*/
|
|
199
200
|
urlMap?: boolean;
|
|
201
|
+
/**
|
|
202
|
+
* Optional function to compress input URLs or file paths before bundling.
|
|
203
|
+
* Returns either a Promise resolving to the compressed string or the compressed string directly.
|
|
204
|
+
*/
|
|
205
|
+
compress?: (value: string) => Promise<string> | string;
|
|
200
206
|
/**
|
|
201
207
|
* Optional hooks to monitor the bundler's lifecycle.
|
|
202
208
|
* Allows tracking the progress and status of reference resolution.
|
|
@@ -218,9 +224,10 @@ type Config = {
|
|
|
218
224
|
* If the input is an object, it will be modified in place by adding an x-ext
|
|
219
225
|
* property to store resolved external references.
|
|
220
226
|
*
|
|
221
|
-
* @param input - The OpenAPI specification
|
|
222
|
-
*
|
|
223
|
-
*
|
|
227
|
+
* @param input - The OpenAPI specification to bundle. Can be either an object or string.
|
|
228
|
+
* If a string is provided, it will be resolved using the provided plugins.
|
|
229
|
+
* If no plugin can process the input, the onReferenceError hook will be invoked
|
|
230
|
+
* and an error will be emitted to the console.
|
|
224
231
|
* @param config - Configuration object containing plugins and options for bundling OpenAPI specifications
|
|
225
232
|
* @returns A promise that resolves to the bundled specification with all references embedded
|
|
226
233
|
* @example
|
|
@@ -274,6 +281,6 @@ type Config = {
|
|
|
274
281
|
* // The function will first fetch the OpenAPI spec from the URL,
|
|
275
282
|
* // then bundle all its external references into the x-ext section
|
|
276
283
|
*/
|
|
277
|
-
export declare function bundle(input: UnknownObject | string, config: Config): Promise<
|
|
284
|
+
export declare function bundle(input: UnknownObject | string, config: Config): Promise<object>;
|
|
278
285
|
export {};
|
|
279
286
|
//# sourceMappingURL=bundle.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../../src/utils/bundle/bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../../src/utils/bundle/bundle.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAS5C;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,WAOxC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,WAEvC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAA;CAAE,CAAA;AA2BvE;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,OAO7E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI,CAyBvE;AAiCD;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAMhE;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,UAgB1E;AAqFD;;;;;;;;;GASG;AACH,MAAM,MAAM,MAAM,GAAG;IAEnB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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,mBA6MzE"}
|
|
@@ -2,8 +2,19 @@ import { escapeJsonPointer } from "../../utils/escape-json-pointer.js";
|
|
|
2
2
|
import path from "../../polyfills/path.js";
|
|
3
3
|
import { getSegmentsFromPath } from "../../utils/get-segments-from-path.js";
|
|
4
4
|
import { isObject } from "../../utils/is-object.js";
|
|
5
|
+
import { isYaml } from "../../utils/is-yaml.js";
|
|
6
|
+
import { isJson } from "../../utils/is-json.js";
|
|
7
|
+
import { getHash, uniqueValueGeneratorFactory } from "../../utils/bundle/value-generator.js";
|
|
5
8
|
function isRemoteUrl(value) {
|
|
6
|
-
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(value);
|
|
11
|
+
return url.protocol === "http:" || url.protocol === "https:";
|
|
12
|
+
} catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function isFilePath(value) {
|
|
17
|
+
return !isRemoteUrl(value) && !isYaml(value) && !isJson(value);
|
|
7
18
|
}
|
|
8
19
|
function isLocalRef(value) {
|
|
9
20
|
return value.startsWith("#");
|
|
@@ -105,15 +116,21 @@ const resolveAndCopyReferences = (targetDocument, sourceDocument, referencePath,
|
|
|
105
116
|
};
|
|
106
117
|
traverse(referencedValue);
|
|
107
118
|
};
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
119
|
+
const extensions = {
|
|
120
|
+
/**
|
|
121
|
+
* Custom OpenAPI extension key used to store external references.
|
|
122
|
+
* This key will contain all bundled external documents.
|
|
123
|
+
* The x-ext key is used to maintain a clean separation between the main
|
|
124
|
+
* OpenAPI document and its bundled external references.
|
|
125
|
+
*/
|
|
126
|
+
externalDocuments: "x-ext",
|
|
127
|
+
/**
|
|
128
|
+
* Custom OpenAPI extension key used to maintain a mapping between
|
|
129
|
+
* hashed keys and their original URLs in x-ext.
|
|
130
|
+
* This mapping is essential for tracking the source of bundled references
|
|
131
|
+
*/
|
|
132
|
+
externalDocumentsMappings: "x-ext-urls"
|
|
133
|
+
};
|
|
117
134
|
async function bundle(input, config) {
|
|
118
135
|
const cache = config.cache ?? /* @__PURE__ */ new Map();
|
|
119
136
|
const resolveInput = async () => {
|
|
@@ -121,7 +138,7 @@ async function bundle(input, config) {
|
|
|
121
138
|
return input;
|
|
122
139
|
}
|
|
123
140
|
const result = await resolveContents(input, config.plugins);
|
|
124
|
-
if (result.ok) {
|
|
141
|
+
if (result.ok && typeof result.data === "object") {
|
|
125
142
|
return result.data;
|
|
126
143
|
}
|
|
127
144
|
throw new Error(
|
|
@@ -130,11 +147,25 @@ async function bundle(input, config) {
|
|
|
130
147
|
};
|
|
131
148
|
const rawSpecification = await resolveInput();
|
|
132
149
|
const documentRoot = config.root ?? rawSpecification;
|
|
133
|
-
const EXTERNAL_KEY = "x-ext";
|
|
134
|
-
const EXTERNAL_URL_MAPPING = "x-ext-urls";
|
|
135
150
|
const isPartialBundling = config.root !== void 0 && config.root !== rawSpecification;
|
|
136
151
|
const processedNodes = config.visitedNodes ?? /* @__PURE__ */ new Set();
|
|
137
|
-
const
|
|
152
|
+
const defaultOrigin = () => {
|
|
153
|
+
if (typeof input !== "string") {
|
|
154
|
+
return "";
|
|
155
|
+
}
|
|
156
|
+
if (isRemoteUrl(input) || isFilePath(input)) {
|
|
157
|
+
return input;
|
|
158
|
+
}
|
|
159
|
+
return "";
|
|
160
|
+
};
|
|
161
|
+
if (documentRoot[extensions.externalDocumentsMappings] === void 0) {
|
|
162
|
+
documentRoot[extensions.externalDocumentsMappings] = {};
|
|
163
|
+
}
|
|
164
|
+
const { generate } = uniqueValueGeneratorFactory(
|
|
165
|
+
config.compress ?? getHash,
|
|
166
|
+
documentRoot[extensions.externalDocumentsMappings]
|
|
167
|
+
);
|
|
168
|
+
const bundler = async (root, origin = defaultOrigin(), isChunkParent = false) => {
|
|
138
169
|
if (!isObject(root) && !Array.isArray(root)) {
|
|
139
170
|
return;
|
|
140
171
|
}
|
|
@@ -153,7 +184,7 @@ async function bundle(input, config) {
|
|
|
153
184
|
}
|
|
154
185
|
const [prefix, path2 = ""] = ref.split("#", 2);
|
|
155
186
|
const resolvedPath = resolveReferencePath(origin, prefix);
|
|
156
|
-
const
|
|
187
|
+
const compressedPath = await generate(resolvedPath);
|
|
157
188
|
const seen = cache.has(resolvedPath);
|
|
158
189
|
if (!seen) {
|
|
159
190
|
cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins));
|
|
@@ -163,36 +194,38 @@ async function bundle(input, config) {
|
|
|
163
194
|
if (result.ok) {
|
|
164
195
|
if (!seen) {
|
|
165
196
|
if (!isChunk) {
|
|
166
|
-
prefixInternalRefRecursive(result.data, [
|
|
197
|
+
prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath]);
|
|
167
198
|
}
|
|
168
199
|
await bundler(result.data, isChunk ? origin : resolvedPath, isChunk);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
200
|
+
setValueAtPath(
|
|
201
|
+
documentRoot,
|
|
202
|
+
`/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,
|
|
203
|
+
resolvedPath
|
|
204
|
+
);
|
|
172
205
|
}
|
|
173
206
|
if (config.treeShake === true) {
|
|
174
207
|
resolveAndCopyReferences(
|
|
175
208
|
documentRoot,
|
|
176
|
-
{ [
|
|
177
|
-
prefixInternalRef(`#${path2}`, [
|
|
178
|
-
|
|
179
|
-
|
|
209
|
+
{ [extensions.externalDocuments]: { [compressedPath]: result.data } },
|
|
210
|
+
prefixInternalRef(`#${path2}`, [extensions.externalDocuments, compressedPath]).substring(1),
|
|
211
|
+
extensions.externalDocuments,
|
|
212
|
+
compressedPath
|
|
180
213
|
);
|
|
181
214
|
} else if (!seen) {
|
|
182
|
-
setValueAtPath(documentRoot, `/${
|
|
215
|
+
setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data);
|
|
183
216
|
}
|
|
184
|
-
root.$ref = prefixInternalRef(`#${path2}`, [
|
|
217
|
+
root.$ref = prefixInternalRef(`#${path2}`, [extensions.externalDocuments, compressedPath]);
|
|
185
218
|
config?.hooks?.onResolveSuccess?.(root);
|
|
186
219
|
return;
|
|
187
220
|
}
|
|
188
221
|
config?.hooks?.onResolveError?.(root);
|
|
189
222
|
return console.warn(
|
|
190
|
-
`Failed to resolve external reference "${
|
|
223
|
+
`Failed to resolve external reference "${resolvedPath}". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`
|
|
191
224
|
);
|
|
192
225
|
}
|
|
193
226
|
await Promise.all(
|
|
194
227
|
Object.entries(root).map(async ([key, value]) => {
|
|
195
|
-
if (key ===
|
|
228
|
+
if (key === extensions.externalDocuments) {
|
|
196
229
|
return;
|
|
197
230
|
}
|
|
198
231
|
await bundler(value, origin, isChunkParent);
|
|
@@ -200,12 +233,15 @@ async function bundle(input, config) {
|
|
|
200
233
|
);
|
|
201
234
|
};
|
|
202
235
|
await bundler(rawSpecification);
|
|
236
|
+
if (!config.urlMap && !isPartialBundling) {
|
|
237
|
+
delete documentRoot[extensions.externalDocumentsMappings];
|
|
238
|
+
}
|
|
203
239
|
return rawSpecification;
|
|
204
240
|
}
|
|
205
241
|
export {
|
|
206
242
|
bundle,
|
|
207
|
-
getHash,
|
|
208
243
|
getNestedValue,
|
|
244
|
+
isFilePath,
|
|
209
245
|
isLocalRef,
|
|
210
246
|
isRemoteUrl,
|
|
211
247
|
prefixInternalRef,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/utils/bundle/bundle.ts"],
|
|
4
|
-
"sourcesContent": ["import type { UnknownObject } from '@/types'\nimport { escapeJsonPointer } from '@/utils/escape-json-pointer'\nimport path from '@/polyfills/path'\nimport { getSegmentsFromPath } from '@/utils/get-segments-from-path'\nimport { isObject } from '@/utils/is-object'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string): boolean {\n return value.startsWith('http://') || value.startsWith('https://')\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: Plugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Retrieves a nested value from an object using an array of property segments.\n * @param target - The target object to traverse\n * @param segments - Array of property names representing the path to the desired value\n * @returns The value at the specified path, or undefined if the path doesn't exist\n * @example\n * const obj = { foo: { bar: { baz: 42 } } };\n * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42\n */\nexport function getNestedValue(target: Record<string, any>, segments: string[]) {\n return segments.reduce<any>((acc, key) => {\n if (acc === undefined) {\n return undefined\n }\n return acc[key]\n }, target)\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n return (input['$ref'] = prefixInternalRef(ref, prefix))\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nconst resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n processedNodes = new Set(),\n) => {\n const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath))\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n documentKey,\n externalRefsKey,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * Generates a short SHA-1 hash from a string value.\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses the Web Crypto API to\n * generate a SHA-1 hash and returns the first 7 characters of the hex string.\n * If the hash would be all numbers, it ensures at least one letter is included.\n *\n * @param value - The string to hash\n * @returns A 7-character hexadecimal hash with at least one letter\n * @example\n * // Returns \"2ae91d7\"\n * await getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string) {\n // Convert string to ArrayBuffer\n const encoder = new TextEncoder()\n const data = encoder.encode(value)\n\n // Hash the data\n const hashBuffer = await crypto.subtle.digest('SHA-1', data)\n\n // Convert buffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n\n // Return first 7 characters of the hash, ensuring at least one letter\n const hash = hashHex.substring(0, 7)\n return hash.match(/^\\d+$/) ? 'a' + hash.substring(1) : hash\n}\n\n/**\n * Represents a plugin that handles resolving references from external sources.\n * Plugins are responsible for fetching and processing data from different sources\n * like URLs or the filesystem. Each plugin must implement validation to determine\n * if it can handle a specific reference, and an execution function to perform\n * the actual resolution.\n *\n * @property validate - Determines if this plugin can handle the given reference\n * @property exec - Fetches and processes the reference, returning the resolved data\n */\nexport type Plugin = {\n // Determines if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Fetches and processes the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /** Called when starting to resolve a reference */\n onResolveStart: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference resolution fails */\n onResolveError: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference is successfully resolved */\n onResolveSuccess: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n }>\n}\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification object or string to bundle. If a string is provided,\n * it should be a URL or file path that points to an OpenAPI specification.\n * The string will be resolved using the provided plugins before bundling.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, config.plugins)\n\n if (result.ok) {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Custom OpenAPI extension key used to store external references\n // This key will contain all bundled external documents\n const EXTERNAL_KEY = 'x-ext'\n\n // Custom OpenAPI extension key used to maintain a mapping between\n // original URLs and their corresponding hashed keys in x-ext\n const EXTERNAL_URL_MAPPING = 'x-ext-urls'\n\n // Indicates whether we're performing a partial bundle operation, which occurs when\n // a root document is provided that differs from the raw specification being bundled\n const isPartialBundling = config.root !== undefined && config.root !== rawSpecification\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n const bundler = async (\n root: unknown,\n origin: string = typeof input === 'string' ? input : '',\n isChunkParent = false,\n ) => {\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n if (isLocalRef(ref)) {\n if (isPartialBundling) {\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))), origin, isChunkParent)\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(origin, prefix)\n const hashPath = await getHash(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk)\n\n // Store the mapping between original URLs and their hashed keys in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n if (config.urlMap) {\n setValueAtPath(documentRoot, `/${EXTERNAL_URL_MAPPING}/${escapeJsonPointer(resolvedPath)}`, hashPath)\n }\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [EXTERNAL_KEY]: { [hashPath]: result.data } },\n prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath]).substring(1),\n EXTERNAL_KEY,\n hashPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${EXTERNAL_KEY}/${hashPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [EXTERNAL_KEY, hashPath])\n config?.hooks?.onResolveSuccess?.(root)\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n return console.warn(\n `Failed to resolve external reference \"${prefix}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively process all child objects to handle nested references\n // This ensures we catch and resolve any $refs that exist deeper in the object tree\n // We skip EXTERNAL_KEY to avoid processing already bundled content\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === EXTERNAL_KEY) {\n return\n }\n\n await bundler(value, origin, isChunkParent)\n }),\n )\n }\n\n await bundler(rawSpecification)\n return rawSpecification\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,yBAAyB;AAClC,OAAO,UAAU;AACjB,SAAS,2BAA2B;AACpC,SAAS,gBAAgB;
|
|
4
|
+
"sourcesContent": ["import type { UnknownObject } from '@/types'\nimport { escapeJsonPointer } from '@/utils/escape-json-pointer'\nimport path from '@/polyfills/path'\nimport { getSegmentsFromPath } from '@/utils/get-segments-from-path'\nimport { isObject } from '@/utils/is-object'\nimport { isYaml } from '@/utils/is-yaml'\nimport { isJson } from '@/utils/is-json'\nimport { getHash, uniqueValueGeneratorFactory } from '@/utils/bundle/value-generator'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string) {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * Checks if a string represents a file path by ensuring it's not a remote URL,\n * YAML content, or JSON content.\n *\n * @param value - The string to check\n * @returns true if the string appears to be a file path, false otherwise\n * @example\n * ```ts\n * isFilePath('./schemas/user.json') // true\n * isFilePath('https://example.com/schema.json') // false\n * isFilePath('{\"type\": \"object\"}') // false\n * isFilePath('type: object') // false\n * ```\n */\nexport function isFilePath(value: string) {\n return !isRemoteUrl(value) && !isYaml(value) && !isJson(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: Plugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Retrieves a nested value from an object using an array of property segments.\n * @param target - The target object to traverse\n * @param segments - Array of property names representing the path to the desired value\n * @returns The value at the specified path, or undefined if the path doesn't exist\n * @example\n * const obj = { foo: { bar: { baz: 42 } } };\n * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42\n */\nexport function getNestedValue(target: Record<string, any>, segments: string[]) {\n return segments.reduce<any>((acc, key) => {\n if (acc === undefined) {\n return undefined\n }\n return acc[key]\n }, target)\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n return (input['$ref'] = prefixInternalRef(ref, prefix))\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nconst resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n processedNodes = new Set(),\n) => {\n const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath))\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n documentKey,\n externalRefsKey,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * Represents a plugin that handles resolving references from external sources.\n * Plugins are responsible for fetching and processing data from different sources\n * like URLs or the filesystem. Each plugin must implement validation to determine\n * if it can handle a specific reference, and an execution function to perform\n * the actual resolution.\n *\n * @property validate - Determines if this plugin can handle the given reference\n * @property exec - Fetches and processes the reference, returning the resolved data\n */\nexport type Plugin = {\n // Determines if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Fetches and processes the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional function to compress input URLs or file paths before bundling.\n * Returns either a Promise resolving to the compressed string or the compressed string directly.\n */\n compress?: (value: string) => Promise<string> | string\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /** Called when starting to resolve a reference */\n onResolveStart: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference resolution fails */\n onResolveError: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n /** Called when a reference is successfully resolved */\n onResolveSuccess: (node: Record<string, unknown> & Record<'$ref', unknown>) => void\n }>\n}\n\n/**\n * Extension keys used for bundling external references in OpenAPI documents.\n * These custom extensions help maintain the structure and traceability of bundled documents.\n */\nconst extensions = {\n /**\n * Custom OpenAPI extension key used to store external references.\n * This key will contain all bundled external documents.\n * The x-ext key is used to maintain a clean separation between the main\n * OpenAPI document and its bundled external references.\n */\n externalDocuments: 'x-ext',\n\n /**\n * Custom OpenAPI extension key used to maintain a mapping between\n * hashed keys and their original URLs in x-ext.\n * This mapping is essential for tracking the source of bundled references\n */\n externalDocumentsMappings: 'x-ext-urls',\n} as const\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification to bundle. Can be either an object or string.\n * If a string is provided, it will be resolved using the provided plugins.\n * If no plugin can process the input, the onReferenceError hook will be invoked\n * and an error will be emitted to the console.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, config.plugins)\n\n if (result.ok && typeof result.data === 'object') {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Indicates whether we're performing a partial bundle operation, which occurs when\n // a root document is provided that differs from the raw specification being bundled\n const isPartialBundling = config.root !== undefined && config.root !== rawSpecification\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n // Determines the initial origin path for the bundler based on the input type.\n // For string inputs that are URLs or file paths, uses the input as the origin.\n // For non-string inputs or other string types, returns an empty string.\n const defaultOrigin = () => {\n if (typeof input !== 'string') {\n return ''\n }\n\n if (isRemoteUrl(input) || isFilePath(input)) {\n return input\n }\n\n return ''\n }\n\n // Create the cache to store the compressed values to their map values\n if (documentRoot[extensions.externalDocumentsMappings] === undefined) {\n documentRoot[extensions.externalDocumentsMappings] = {}\n }\n const { generate } = uniqueValueGeneratorFactory(\n config.compress ?? getHash,\n documentRoot[extensions.externalDocumentsMappings],\n )\n\n const bundler = async (root: unknown, origin: string = defaultOrigin(), isChunkParent = false) => {\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n if (isLocalRef(ref)) {\n if (isPartialBundling) {\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(getNestedValue(documentRoot, getSegmentsFromPath(ref.substring(1))), origin, isChunkParent)\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(origin, prefix)\n\n // Generate a unique compressed path for the external document\n // This is used as a key to store and reference the bundled external document\n // The compression helps reduce the overall file size of the bundled document\n const compressedPath = await generate(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk)\n\n // Store the mapping between hashed keys and original URLs in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n setValueAtPath(\n documentRoot,\n `/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,\n resolvedPath,\n )\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [extensions.externalDocuments]: { [compressedPath]: result.data } },\n prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath]).substring(1),\n extensions.externalDocuments,\n compressedPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath])\n config?.hooks?.onResolveSuccess?.(root)\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n return console.warn(\n `Failed to resolve external reference \"${resolvedPath}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively process all child objects to handle nested references\n // This ensures we catch and resolve any $refs that exist deeper in the object tree\n // We skip EXTERNAL_KEY to avoid processing already bundled content\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === extensions.externalDocuments) {\n return\n }\n\n await bundler(value, origin, isChunkParent)\n }),\n )\n }\n\n await bundler(rawSpecification)\n\n // Keep urlMappings when doing partial bundling to track hash values and handle collisions\n // For full bundling without urlMap config, remove the mappings to clean up the output\n if (!config.urlMap && !isPartialBundling) {\n // Remove the external document mappings from the output when doing a full bundle without urlMap config\n delete documentRoot[extensions.externalDocumentsMappings]\n }\n\n return rawSpecification\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,yB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AA,MAC5C,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,QAAQ,gBAAgB;AAI9B,MAAI,CAAC,OAAO,UAAU,CAAC,mBAAmB;AAExC,WAAO,aAAa,WAAW,yBAAyB;AAAA,EAC1D;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": ["path"]
|
|
7
7
|
}
|
|
@@ -30,7 +30,7 @@ async function fetchUrl(url, limiter, config) {
|
|
|
30
30
|
function fetchUrls(config) {
|
|
31
31
|
const limiter = config?.limit ? createLimiter(config.limit) : (fn) => fn();
|
|
32
32
|
return {
|
|
33
|
-
validate:
|
|
33
|
+
validate: isRemoteUrl,
|
|
34
34
|
exec: (value) => fetchUrl(value, limiter, config)
|
|
35
35
|
};
|
|
36
36
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/utils/bundle/plugins/fetch-urls/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport { isRemoteUrl, type Plugin, type ResolveResult } from '@/utils/bundle/bundle'\nimport { createLimiter } from '@/utils/bundle/create-limiter'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const domain = new URL(url).host\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === domain) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n }\n }\n\n return {\n ok: false,\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): Plugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n validate:
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,mBAAoD;AAC7D,SAAS,qBAAqB;AAqB9B,eAAsB,SACpB,KACA,SACA,QACwB;AACxB,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,GAAG,EAAE;AAG5B,UAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,MAAM,MAAM,MAAM,MAAS,GAAG;AAEjG,UAAM,OAAO,QAAQ,SAAS;AAE9B,UAAM,SAAS,MAAM;AAAA,MAAQ,MAC3B,KAAK,KAAK;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,IAAI;AACb,YAAM,OAAO,MAAM,OAAO,KAAK;AAE/B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,UAAU,IAAI;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,UAAU,QAAkE;AAE1F,QAAM,UAAU,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAI,OAAyB,GAAG;AAE9F,SAAO;AAAA,IACL,UAAU
|
|
4
|
+
"sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport { isRemoteUrl, type Plugin, type ResolveResult } from '@/utils/bundle/bundle'\nimport { createLimiter } from '@/utils/bundle/create-limiter'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const domain = new URL(url).host\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === domain) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n }\n }\n\n return {\n ok: false,\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): Plugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n validate: isRemoteUrl,\n exec: (value) => fetchUrl(value, limiter, config),\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,mBAAoD;AAC7D,SAAS,qBAAqB;AAqB9B,eAAsB,SACpB,KACA,SACA,QACwB;AACxB,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,GAAG,EAAE;AAG5B,UAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,MAAM,MAAM,MAAM,MAAS,GAAG;AAEjG,UAAM,OAAO,QAAQ,SAAS;AAE9B,UAAM,SAAS,MAAM;AAAA,MAAQ,MAC3B,KAAK,KAAK;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,IAAI;AACb,YAAM,OAAO,MAAM,OAAO,KAAK;AAE/B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,UAAU,IAAI;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,UAAU,QAAkE;AAE1F,QAAM,UAAU,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAI,OAAyB,GAAG;AAE9F,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM,CAAC,UAAU,SAAS,OAAO,SAAS,MAAM;AAAA,EAClD;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Plugin } from '../../../../utils/bundle/bundle.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a plugin that parses JSON strings into JavaScript objects.
|
|
4
|
+
* @returns A plugin object with validate and exec functions
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* const jsonPlugin = parseJson()
|
|
8
|
+
* const result = jsonPlugin.exec('{"name": "John", "age": 30}')
|
|
9
|
+
* // result = { name: 'John', age: 30 }
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseJson(): Plugin;
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/parse-json/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,uBAAuB,CAAA;AAGlE;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAgBlC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { isJson } from "../../../../utils/is-json.js";
|
|
2
|
+
function parseJson() {
|
|
3
|
+
return {
|
|
4
|
+
validate: isJson,
|
|
5
|
+
exec: async (value) => {
|
|
6
|
+
try {
|
|
7
|
+
return {
|
|
8
|
+
ok: true,
|
|
9
|
+
data: JSON.parse(value)
|
|
10
|
+
};
|
|
11
|
+
} catch {
|
|
12
|
+
return {
|
|
13
|
+
ok: false
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export {
|
|
20
|
+
parseJson
|
|
21
|
+
};
|
|
22
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/utils/bundle/plugins/parse-json/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Plugin, ResolveResult } from '@/utils/bundle/bundle'\nimport { isJson } from '@/utils/is-json'\n\n/**\n * Creates a plugin that parses JSON strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const jsonPlugin = parseJson()\n * const result = jsonPlugin.exec('{\"name\": \"John\", \"age\": 30}')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseJson(): Plugin {\n return {\n validate: isJson,\n exec: async (value): Promise<ResolveResult> => {\n try {\n return {\n ok: true,\n data: JSON.parse(value),\n }\n } catch {\n return {\n ok: false,\n }\n }\n },\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,cAAc;AAYhB,SAAS,YAAoB;AAClC,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM,OAAO,UAAkC;AAC7C,UAAI;AACF,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,KAAK;AAAA,QACxB;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,UACL,IAAI;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Plugin } from '../../../../utils/bundle/bundle.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a plugin that parses YAML strings into JavaScript objects.
|
|
4
|
+
* @returns A plugin object with validate and exec functions
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* const yamlPlugin = parseYaml()
|
|
8
|
+
* const result = yamlPlugin.exec('name: John\nage: 30')
|
|
9
|
+
* // result = { name: 'John', age: 30 }
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare function parseYaml(): Plugin;
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/parse-yaml/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAiB,MAAM,uBAAuB,CAAA;AAIlE;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAgBlC"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { isYaml } from "../../../../utils/is-yaml.js";
|
|
2
|
+
import YAML from "yaml";
|
|
3
|
+
function parseYaml() {
|
|
4
|
+
return {
|
|
5
|
+
validate: isYaml,
|
|
6
|
+
exec: async (value) => {
|
|
7
|
+
try {
|
|
8
|
+
return {
|
|
9
|
+
ok: true,
|
|
10
|
+
data: YAML.parse(value)
|
|
11
|
+
};
|
|
12
|
+
} catch {
|
|
13
|
+
return {
|
|
14
|
+
ok: false
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export {
|
|
21
|
+
parseYaml
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../../src/utils/bundle/plugins/parse-yaml/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Plugin, ResolveResult } from '@/utils/bundle/bundle'\nimport { isYaml } from '@/utils/is-yaml'\nimport YAML from 'yaml'\n\n/**\n * Creates a plugin that parses YAML strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const yamlPlugin = parseYaml()\n * const result = yamlPlugin.exec('name: John\\nage: 30')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseYaml(): Plugin {\n return {\n validate: isYaml,\n exec: async (value): Promise<ResolveResult> => {\n try {\n return {\n ok: true,\n data: YAML.parse(value),\n }\n } catch {\n return {\n ok: false,\n }\n }\n },\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,cAAc;AACvB,OAAO,UAAU;AAYV,SAAS,YAAoB;AAClC,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM,OAAO,UAAkC;AAC7C,UAAI;AACF,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,KAAK;AAAA,QACxB;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,UACL,IAAI;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/read-files/index.ts"],"names":[],"mappings":"AACA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/utils/bundle/plugins/read-files/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAEnF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAmBnE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,IAAI,MAAM,CAKlC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { normalize } from "../../../../utils/normalize.js";
|
|
2
|
-
import {
|
|
2
|
+
import { isFilePath } from "../../../../utils/bundle/bundle.js";
|
|
3
3
|
async function readFile(path) {
|
|
4
4
|
const fs = typeof window === "undefined" ? await import("node:fs/promises") : void 0;
|
|
5
5
|
if (fs === void 0) {
|
|
@@ -19,8 +19,8 @@ async function readFile(path) {
|
|
|
19
19
|
}
|
|
20
20
|
function readFiles() {
|
|
21
21
|
return {
|
|
22
|
-
validate:
|
|
23
|
-
exec:
|
|
22
|
+
validate: isFilePath,
|
|
23
|
+
exec: readFile
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
26
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/utils/bundle/plugins/read-files/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport {
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,
|
|
4
|
+
"sourcesContent": ["import { normalize } from '@/utils/normalize'\nimport { isFilePath, type Plugin, type ResolveResult } from '@/utils/bundle/bundle'\n\n/**\n * Reads and normalizes data from a local file\n * @param path - The file path to read from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await readFile('./schemas/user.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to read file')\n * }\n * ```\n */\nexport async function readFile(path: string): Promise<ResolveResult> {\n const fs = typeof window === 'undefined' ? await import('node:fs/promises') : undefined\n\n if (fs === undefined) {\n throw 'Can not use readFiles plugin outside of a node environment'\n }\n\n try {\n const fileContents = await fs.readFile(path, { encoding: 'utf-8' })\n\n return {\n ok: true,\n data: normalize(fileContents),\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling local file references.\n * This plugin validates and reads data from local filesystem paths.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const filePlugin = readFiles()\n * if (filePlugin.validate('./local-schema.json')) {\n * const result = await filePlugin.exec('./local-schema.json')\n * }\n */\nexport function readFiles(): Plugin {\n return {\n validate: isFilePath,\n exec: readFile,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,kBAAmD;AAgB5D,eAAsB,SAAS,MAAsC;AACnE,QAAM,KAAK,OAAO,WAAW,cAAc,MAAM,OAAO,kBAAkB,IAAI;AAE9E,MAAI,OAAO,QAAW;AACpB,UAAM;AAAA,EACR;AAEA,MAAI;AACF,UAAM,eAAe,MAAM,GAAG,SAAS,MAAM,EAAE,UAAU,QAAQ,CAAC;AAElE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,MAAM,UAAU,YAAY;AAAA,IAC9B;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,YAAoB;AAClC,SAAO;AAAA,IACL,UAAU;AAAA,IACV,MAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates a short SHA-1 hash from a string value.
|
|
3
|
+
* This function is used to create unique identifiers for external references
|
|
4
|
+
* while keeping the hash length manageable. It uses the Web Crypto API to
|
|
5
|
+
* generate a SHA-1 hash and returns the first 7 characters of the hex string.
|
|
6
|
+
* If the hash would be all numbers, it ensures at least one letter is included.
|
|
7
|
+
*
|
|
8
|
+
* @param value - The string to hash
|
|
9
|
+
* @returns A 7-character hexadecimal hash with at least one letter
|
|
10
|
+
* @example
|
|
11
|
+
* // Returns "2ae91d7"
|
|
12
|
+
* await getHash("https://example.com/schema.json")
|
|
13
|
+
*/
|
|
14
|
+
export declare function getHash(value: string): Promise<string>;
|
|
15
|
+
/**
|
|
16
|
+
* Generates a unique compressed value for a string, handling collisions by recursively compressing
|
|
17
|
+
* until a unique value is found. This is used to create unique identifiers for external
|
|
18
|
+
* references in the bundled OpenAPI document.
|
|
19
|
+
*
|
|
20
|
+
* @param compress - Function that generates a compressed value from a string
|
|
21
|
+
* @param value - The original string value to compress
|
|
22
|
+
* @param compressedToValue - Object mapping compressed values to their original values
|
|
23
|
+
* @param prevCompressedValue - Optional previous compressed value to use as input for generating a new value
|
|
24
|
+
* @param depth - Current recursion depth to prevent infinite loops
|
|
25
|
+
* @returns A unique compressed value that doesn't conflict with existing values
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* const valueMap = {}
|
|
29
|
+
* // First call generates compressed value for "example.com/schema.json"
|
|
30
|
+
* const value1 = await generateUniqueValue(compress, "example.com/schema.json", valueMap)
|
|
31
|
+
* // Returns something like "2ae91d7"
|
|
32
|
+
*
|
|
33
|
+
* // Second call with same value returns same compressed value
|
|
34
|
+
* const value2 = await generateUniqueValue(compress, "example.com/schema.json", valueMap)
|
|
35
|
+
* // Returns same value as value1
|
|
36
|
+
*
|
|
37
|
+
* // Call with different value generates new unique compressed value
|
|
38
|
+
* const value3 = await generateUniqueValue(compress, "example.com/other.json", valueMap)
|
|
39
|
+
* // Returns different value like "3bf82e9"
|
|
40
|
+
*/
|
|
41
|
+
export declare function generateUniqueValue(compress: (value: string) => Promise<string> | string, value: string, compressedToValue: Record<string, string>, prevCompressedValue?: string, depth?: number): Promise<string>;
|
|
42
|
+
/**
|
|
43
|
+
* Factory function that creates a value generator with caching capabilities.
|
|
44
|
+
* The generator maintains a bidirectional mapping between original values and their compressed forms.
|
|
45
|
+
*
|
|
46
|
+
* @param compress - Function that generates a compressed value from a string
|
|
47
|
+
* @param compressedToValue - Initial mapping of compressed values to their original values
|
|
48
|
+
* @returns An object with a generate method that produces unique compressed values
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const compress = (value) => value.substring(0, 6) // Simple compression example
|
|
52
|
+
* const initialMap = { 'abc123': 'example.com/schema.json' }
|
|
53
|
+
* const generator = uniqueValueGeneratorFactory(compress, initialMap)
|
|
54
|
+
*
|
|
55
|
+
* // Generate compressed value for new string
|
|
56
|
+
* const compressed = await generator.generate('example.com/other.json')
|
|
57
|
+
* // Returns something like 'example'
|
|
58
|
+
*
|
|
59
|
+
* // Generate compressed value for existing string
|
|
60
|
+
* const cached = await generator.generate('example.com/schema.json')
|
|
61
|
+
* // Returns 'abc123' from cache
|
|
62
|
+
*/
|
|
63
|
+
export declare const uniqueValueGeneratorFactory: (compress: (value: string) => Promise<string> | string, compressedToValue: Record<string, string>) => {
|
|
64
|
+
/**
|
|
65
|
+
* Generates a unique compressed value for the given input string.
|
|
66
|
+
* First checks if a compressed value already exists in the cache.
|
|
67
|
+
* If not, generates a new unique compressed value and stores it in the cache.
|
|
68
|
+
*
|
|
69
|
+
* @param value - The original string value to compress
|
|
70
|
+
* @returns A Promise that resolves to the compressed string value
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* const generator = uniqueValueGeneratorFactory(compress, {})
|
|
74
|
+
* const compressed = await generator.generate('example.com/schema.json')
|
|
75
|
+
* // Returns a unique compressed value like 'example'
|
|
76
|
+
*/
|
|
77
|
+
generate: (value: string) => Promise<string>;
|
|
78
|
+
};
|
|
79
|
+
//# sourceMappingURL=value-generator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"value-generator.d.ts","sourceRoot":"","sources":["../../../src/utils/bundle/value-generator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAAC,KAAK,EAAE,MAAM,mBAe1C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,EACrD,KAAK,EAAE,MAAM,EACb,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACzC,mBAAmB,CAAC,EAAE,MAAM,EAC5B,KAAK,SAAI,mBAoBV;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,2BAA2B,aAC5B,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,qBAClC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAMvC;;;;;;;;;;;;OAYG;sBACqB,MAAM;CAqBjC,CAAA"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
async function getHash(value) {
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
const data = encoder.encode(value);
|
|
4
|
+
const hashBuffer = await crypto.subtle.digest("SHA-1", data);
|
|
5
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
6
|
+
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
7
|
+
const hash = hashHex.substring(0, 7);
|
|
8
|
+
return hash.match(/^\d+$/) ? "a" + hash.substring(1) : hash;
|
|
9
|
+
}
|
|
10
|
+
async function generateUniqueValue(compress, value, compressedToValue, prevCompressedValue, depth = 0) {
|
|
11
|
+
const MAX_DEPTH = 100;
|
|
12
|
+
if (depth >= MAX_DEPTH) {
|
|
13
|
+
throw "Can not generate unique compressed values";
|
|
14
|
+
}
|
|
15
|
+
const compressedValue = await compress(prevCompressedValue ?? value);
|
|
16
|
+
if (compressedToValue[compressedValue] !== void 0 && compressedToValue[compressedValue] !== value) {
|
|
17
|
+
return generateUniqueValue(compress, value, compressedToValue, compressedValue, depth + 1);
|
|
18
|
+
}
|
|
19
|
+
compressedToValue[compressedValue] = value;
|
|
20
|
+
return compressedValue;
|
|
21
|
+
}
|
|
22
|
+
const uniqueValueGeneratorFactory = (compress, compressedToValue) => {
|
|
23
|
+
const valueToCompressed = Object.fromEntries(Object.entries(compressedToValue).map(([key, value]) => [value, key]));
|
|
24
|
+
return {
|
|
25
|
+
/**
|
|
26
|
+
* Generates a unique compressed value for the given input string.
|
|
27
|
+
* First checks if a compressed value already exists in the cache.
|
|
28
|
+
* If not, generates a new unique compressed value and stores it in the cache.
|
|
29
|
+
*
|
|
30
|
+
* @param value - The original string value to compress
|
|
31
|
+
* @returns A Promise that resolves to the compressed string value
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const generator = uniqueValueGeneratorFactory(compress, {})
|
|
35
|
+
* const compressed = await generator.generate('example.com/schema.json')
|
|
36
|
+
* // Returns a unique compressed value like 'example'
|
|
37
|
+
*/
|
|
38
|
+
generate: async (value) => {
|
|
39
|
+
const cache = valueToCompressed[value];
|
|
40
|
+
if (cache) {
|
|
41
|
+
return cache;
|
|
42
|
+
}
|
|
43
|
+
const generatedValue = await generateUniqueValue(compress, value, compressedToValue);
|
|
44
|
+
const compressedValue = generatedValue.match(/^\d+$/) ? `a${generatedValue}` : generatedValue;
|
|
45
|
+
valueToCompressed[value] = compressedValue;
|
|
46
|
+
return compressedValue;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
export {
|
|
51
|
+
generateUniqueValue,
|
|
52
|
+
getHash,
|
|
53
|
+
uniqueValueGeneratorFactory
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=value-generator.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/utils/bundle/value-generator.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Generates a short SHA-1 hash from a string value.\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses the Web Crypto API to\n * generate a SHA-1 hash and returns the first 7 characters of the hex string.\n * If the hash would be all numbers, it ensures at least one letter is included.\n *\n * @param value - The string to hash\n * @returns A 7-character hexadecimal hash with at least one letter\n * @example\n * // Returns \"2ae91d7\"\n * await getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string) {\n // Convert string to ArrayBuffer\n const encoder = new TextEncoder()\n const data = encoder.encode(value)\n\n // Hash the data\n const hashBuffer = await crypto.subtle.digest('SHA-1', data)\n\n // Convert buffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n\n // Return first 7 characters of the hash, ensuring at least one letter\n const hash = hashHex.substring(0, 7)\n return hash.match(/^\\d+$/) ? 'a' + hash.substring(1) : hash\n}\n\n/**\n * Generates a unique compressed value for a string, handling collisions by recursively compressing\n * until a unique value is found. This is used to create unique identifiers for external\n * references in the bundled OpenAPI document.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param value - The original string value to compress\n * @param compressedToValue - Object mapping compressed values to their original values\n * @param prevCompressedValue - Optional previous compressed value to use as input for generating a new value\n * @param depth - Current recursion depth to prevent infinite loops\n * @returns A unique compressed value that doesn't conflict with existing values\n *\n * @example\n * const valueMap = {}\n * // First call generates compressed value for \"example.com/schema.json\"\n * const value1 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns something like \"2ae91d7\"\n *\n * // Second call with same value returns same compressed value\n * const value2 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns same value as value1\n *\n * // Call with different value generates new unique compressed value\n * const value3 = await generateUniqueValue(compress, \"example.com/other.json\", valueMap)\n * // Returns different value like \"3bf82e9\"\n */\nexport async function generateUniqueValue(\n compress: (value: string) => Promise<string> | string,\n value: string,\n compressedToValue: Record<string, string>,\n prevCompressedValue?: string,\n depth = 0,\n) {\n // Prevent infinite recursion by limiting depth\n const MAX_DEPTH = 100\n\n if (depth >= MAX_DEPTH) {\n throw 'Can not generate unique compressed values'\n }\n\n // Compress the value, using previous compressed value if provided\n const compressedValue = await compress(prevCompressedValue ?? value)\n\n // Handle collision by recursively trying with compressed value as input\n if (compressedToValue[compressedValue] !== undefined && compressedToValue[compressedValue] !== value) {\n return generateUniqueValue(compress, value, compressedToValue, compressedValue, depth + 1)\n }\n\n // Store mapping and return unique compressed value\n compressedToValue[compressedValue] = value\n return compressedValue\n}\n\n/**\n * Factory function that creates a value generator with caching capabilities.\n * The generator maintains a bidirectional mapping between original values and their compressed forms.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param compressedToValue - Initial mapping of compressed values to their original values\n * @returns An object with a generate method that produces unique compressed values\n *\n * @example\n * const compress = (value) => value.substring(0, 6) // Simple compression example\n * const initialMap = { 'abc123': 'example.com/schema.json' }\n * const generator = uniqueValueGeneratorFactory(compress, initialMap)\n *\n * // Generate compressed value for new string\n * const compressed = await generator.generate('example.com/other.json')\n * // Returns something like 'example'\n *\n * // Generate compressed value for existing string\n * const cached = await generator.generate('example.com/schema.json')\n * // Returns 'abc123' from cache\n */\nexport const uniqueValueGeneratorFactory = (\n compress: (value: string) => Promise<string> | string,\n compressedToValue: Record<string, string>,\n) => {\n // Create a reverse mapping from original values to their compressed forms\n const valueToCompressed = Object.fromEntries(Object.entries(compressedToValue).map(([key, value]) => [value, key]))\n\n return {\n /**\n * Generates a unique compressed value for the given input string.\n * First checks if a compressed value already exists in the cache.\n * If not, generates a new unique compressed value and stores it in the cache.\n *\n * @param value - The original string value to compress\n * @returns A Promise that resolves to the compressed string value\n *\n * @example\n * const generator = uniqueValueGeneratorFactory(compress, {})\n * const compressed = await generator.generate('example.com/schema.json')\n * // Returns a unique compressed value like 'example'\n */\n generate: async (value: string) => {\n // Check if we already have a compressed value for this input\n const cache = valueToCompressed[value]\n if (cache) {\n return cache\n }\n\n // Generate a new unique compressed value\n const generatedValue = await generateUniqueValue(compress, value, compressedToValue)\n\n // Ensure the generated string contains at least one non-numeric character\n // This prevents the `setValueAtPath` function from interpreting the value as an array index\n // by forcing it to be treated as an object property name\n const compressedValue = generatedValue.match(/^\\d+$/) ? `a${generatedValue}` : generatedValue\n\n // Store the new mapping in our cache\n valueToCompressed[value] = compressedValue\n\n return compressedValue\n },\n }\n}\n"],
|
|
5
|
+
"mappings": "AAaA,eAAsB,QAAQ,OAAe;AAE3C,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,OAAO,QAAQ,OAAO,KAAK;AAGjC,QAAM,aAAa,MAAM,OAAO,OAAO,OAAO,SAAS,IAAI;AAG3D,QAAM,YAAY,MAAM,KAAK,IAAI,WAAW,UAAU,CAAC;AACvD,QAAM,UAAU,UAAU,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAG7E,QAAM,OAAO,QAAQ,UAAU,GAAG,CAAC;AACnC,SAAO,KAAK,MAAM,OAAO,IAAI,MAAM,KAAK,UAAU,CAAC,IAAI;AACzD;AA4BA,eAAsB,oBACpB,UACA,OACA,mBACA,qBACA,QAAQ,GACR;AAEA,QAAM,YAAY;AAElB,MAAI,SAAS,WAAW;AACtB,UAAM;AAAA,EACR;AAGA,QAAM,kBAAkB,MAAM,SAAS,uBAAuB,KAAK;AAGnE,MAAI,kBAAkB,eAAe,MAAM,UAAa,kBAAkB,eAAe,MAAM,OAAO;AACpG,WAAO,oBAAoB,UAAU,OAAO,mBAAmB,iBAAiB,QAAQ,CAAC;AAAA,EAC3F;AAGA,oBAAkB,eAAe,IAAI;AACrC,SAAO;AACT;AAuBO,MAAM,8BAA8B,CACzC,UACA,sBACG;AAEH,QAAM,oBAAoB,OAAO,YAAY,OAAO,QAAQ,iBAAiB,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,OAAO,GAAG,CAAC,CAAC;AAElH,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcL,UAAU,OAAO,UAAkB;AAEjC,YAAM,QAAQ,kBAAkB,KAAK;AACrC,UAAI,OAAO;AACT,eAAO;AAAA,MACT;AAGA,YAAM,iBAAiB,MAAM,oBAAoB,UAAU,OAAO,iBAAiB;AAKnF,YAAM,kBAAkB,eAAe,MAAM,OAAO,IAAI,IAAI,cAAc,KAAK;AAG/E,wBAAkB,KAAK,IAAI;AAE3B,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -12,6 +12,12 @@ export type LoadOptions = {
|
|
|
12
12
|
filesystem?: Filesystem;
|
|
13
13
|
} & ThrowOnErrorOption;
|
|
14
14
|
/**
|
|
15
|
+
* @deprecated This function is deprecated and will be removed in a future version.
|
|
16
|
+
* Please use the new bundler utility instead:
|
|
17
|
+
* ```ts
|
|
18
|
+
* import { bundle } from "@scalar/openapi-parser"
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
15
21
|
* Loads an OpenAPI document, including any external references.
|
|
16
22
|
*
|
|
17
23
|
* This function handles loading content from various sources, normalizes the content,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../../../src/utils/load/load.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,sBAAsB,EAGtB,UAAU,EACV,UAAU,EACV,kBAAkB,EACnB,MAAM,eAAe,CAAA;AAMtB,MAAM,MAAM,UAAU,GAAG;IACvB,KAAK,EAAE,CAAC,KAAK,CAAC,EAAE,GAAG,KAAK,OAAO,CAAA;IAC/B,GAAG,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,GAAG,CAAA;IACxB,WAAW,CAAC,EAAE,C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AAG,OAAO,CAAC,UAAU,CAAC,CAyHpG"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/utils/load/load.ts"],
|
|
4
|
-
"sourcesContent": ["import { ERRORS } from '@/configuration'\nimport type {\n AnyApiDefinitionFormat,\n AnyObject,\n ErrorObject,\n Filesystem,\n LoadResult,\n ThrowOnErrorOption,\n} from '@/types/index'\nimport { getEntrypoint } from '@/utils/get-entrypoint'\nimport { getListOfReferences } from '@/utils/get-list-of-references'\nimport { makeFilesystem } from '@/utils/make-filesystem'\nimport { normalize } from '@/utils/normalize'\n\nexport type LoadPlugin = {\n check: (value?: any) => boolean\n get: (value: any) => any\n resolvePath?: (value: any, reference: string) => string\n getDir?: (value: any) => string\n getFilename?: (value: any) => string\n}\n\nexport type LoadOptions = {\n plugins?: LoadPlugin[]\n filename?: string\n filesystem?: Filesystem\n} & ThrowOnErrorOption\n\n/**\n * Loads an OpenAPI document, including any external references.\n *\n * This function handles loading content from various sources, normalizes the content,\n * and recursively loads any external references found within the definition.\n *\n * It builds a filesystem representation of all loaded content and collects any errors\n * encountered during the process.\n */\nexport async function load(value: AnyApiDefinitionFormat, options?: LoadOptions): Promise<LoadResult> {\n const errors: ErrorObject[] = []\n\n // Don\u2019t load a reference twice, check the filesystem before fetching something\n if (options?.filesystem?.find((entry) => entry.filename === value)) {\n return {\n specification: getEntrypoint(options.filesystem)?.specification,\n filesystem: options.filesystem,\n errors,\n }\n }\n\n // Check whether the value is an URL or file path\n const plugin = options?.plugins?.find((thisPlugin) => thisPlugin.check(value))\n\n let content: AnyObject\n\n if (plugin) {\n try {\n content = normalize(await plugin.get(value))\n } catch (_error) {\n if (options?.throwOnError) {\n throw new Error(ERRORS.EXTERNAL_REFERENCE_NOT_FOUND.replace('%s', value as string))\n }\n\n errors.push({\n code: 'EXTERNAL_REFERENCE_NOT_FOUND',\n message: ERRORS.EXTERNAL_REFERENCE_NOT_FOUND.replace('%s', value as string),\n })\n\n return {\n specification: null,\n filesystem: [],\n errors,\n }\n }\n } else {\n content = normalize(value)\n }\n\n // No content\n if (content === undefined) {\n if (options?.throwOnError) {\n throw new Error('No content to load')\n }\n\n errors.push({\n code: 'NO_CONTENT',\n message: ERRORS.NO_CONTENT,\n })\n\n return {\n specification: null,\n filesystem: [],\n errors,\n }\n }\n\n let filesystem = makeFilesystem(content, {\n filename: options?.filename ?? null,\n })\n\n // Get references from file system entry, or from the content\n const newEntry = options?.filename\n ? filesystem.find((entry) => entry.filename === options?.filename)\n : getEntrypoint(filesystem)\n\n const listOfReferences = newEntry.references ?? getListOfReferences(content)\n\n // No other references\n if (listOfReferences.length === 0) {\n return {\n specification: getEntrypoint(filesystem)?.specification,\n filesystem,\n errors,\n }\n }\n\n // Load other external references\n for (const reference of listOfReferences) {\n // Find a matching plugin\n const otherPlugin = options?.plugins?.find((thisPlugin) => thisPlugin.check(reference))\n\n // Skip if no plugin is found (internal references don\u2019t need a plugin for example)\n if (!otherPlugin) {\n continue\n }\n\n const target =\n otherPlugin.check(reference) && otherPlugin.resolvePath ? otherPlugin.resolvePath(value, reference) : reference\n\n // Don\u2019t load a reference twice, check the filesystem before fetching something\n if (filesystem.find((entry) => entry.filename === reference)) {\n continue\n }\n\n const { filesystem: referencedFiles, errors: newErrors } = await load(target, {\n ...options,\n // Make the filename the exact same value as the $ref\n // TODO: This leads to problems, if there are multiple references with the same file name but in different folders\n filename: reference,\n })\n\n errors.push(...newErrors)\n\n filesystem = [\n ...filesystem,\n ...referencedFiles.map((file) => {\n return {\n ...file,\n isEntrypoint: false,\n }\n }),\n ]\n }\n\n return {\n specification: getEntrypoint(filesystem)?.specification,\n filesystem,\n errors,\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,cAAc;AASvB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;
|
|
4
|
+
"sourcesContent": ["import { ERRORS } from '@/configuration'\nimport type {\n AnyApiDefinitionFormat,\n AnyObject,\n ErrorObject,\n Filesystem,\n LoadResult,\n ThrowOnErrorOption,\n} from '@/types/index'\nimport { getEntrypoint } from '@/utils/get-entrypoint'\nimport { getListOfReferences } from '@/utils/get-list-of-references'\nimport { makeFilesystem } from '@/utils/make-filesystem'\nimport { normalize } from '@/utils/normalize'\n\nexport type LoadPlugin = {\n check: (value?: any) => boolean\n get: (value: any) => any\n resolvePath?: (value: any, reference: string) => string\n getDir?: (value: any) => string\n getFilename?: (value: any) => string\n}\n\nexport type LoadOptions = {\n plugins?: LoadPlugin[]\n filename?: string\n filesystem?: Filesystem\n} & ThrowOnErrorOption\n\n/**\n * @deprecated This function is deprecated and will be removed in a future version.\n * Please use the new bundler utility instead:\n * ```ts\n * import { bundle } from \"@scalar/openapi-parser\"\n * ```\n *\n * Loads an OpenAPI document, including any external references.\n *\n * This function handles loading content from various sources, normalizes the content,\n * and recursively loads any external references found within the definition.\n *\n * It builds a filesystem representation of all loaded content and collects any errors\n * encountered during the process.\n */\nexport async function load(value: AnyApiDefinitionFormat, options?: LoadOptions): Promise<LoadResult> {\n const errors: ErrorObject[] = []\n\n // Don\u2019t load a reference twice, check the filesystem before fetching something\n if (options?.filesystem?.find((entry) => entry.filename === value)) {\n return {\n specification: getEntrypoint(options.filesystem)?.specification,\n filesystem: options.filesystem,\n errors,\n }\n }\n\n // Check whether the value is an URL or file path\n const plugin = options?.plugins?.find((thisPlugin) => thisPlugin.check(value))\n\n let content: AnyObject\n\n if (plugin) {\n try {\n content = normalize(await plugin.get(value))\n } catch (_error) {\n if (options?.throwOnError) {\n throw new Error(ERRORS.EXTERNAL_REFERENCE_NOT_FOUND.replace('%s', value as string))\n }\n\n errors.push({\n code: 'EXTERNAL_REFERENCE_NOT_FOUND',\n message: ERRORS.EXTERNAL_REFERENCE_NOT_FOUND.replace('%s', value as string),\n })\n\n return {\n specification: null,\n filesystem: [],\n errors,\n }\n }\n } else {\n content = normalize(value)\n }\n\n // No content\n if (content === undefined) {\n if (options?.throwOnError) {\n throw new Error('No content to load')\n }\n\n errors.push({\n code: 'NO_CONTENT',\n message: ERRORS.NO_CONTENT,\n })\n\n return {\n specification: null,\n filesystem: [],\n errors,\n }\n }\n\n let filesystem = makeFilesystem(content, {\n filename: options?.filename ?? null,\n })\n\n // Get references from file system entry, or from the content\n const newEntry = options?.filename\n ? filesystem.find((entry) => entry.filename === options?.filename)\n : getEntrypoint(filesystem)\n\n const listOfReferences = newEntry.references ?? getListOfReferences(content)\n\n // No other references\n if (listOfReferences.length === 0) {\n return {\n specification: getEntrypoint(filesystem)?.specification,\n filesystem,\n errors,\n }\n }\n\n // Load other external references\n for (const reference of listOfReferences) {\n // Find a matching plugin\n const otherPlugin = options?.plugins?.find((thisPlugin) => thisPlugin.check(reference))\n\n // Skip if no plugin is found (internal references don\u2019t need a plugin for example)\n if (!otherPlugin) {\n continue\n }\n\n const target =\n otherPlugin.check(reference) && otherPlugin.resolvePath ? otherPlugin.resolvePath(value, reference) : reference\n\n // Don\u2019t load a reference twice, check the filesystem before fetching something\n if (filesystem.find((entry) => entry.filename === reference)) {\n continue\n }\n\n const { filesystem: referencedFiles, errors: newErrors } = await load(target, {\n ...options,\n // Make the filename the exact same value as the $ref\n // TODO: This leads to problems, if there are multiple references with the same file name but in different folders\n filename: reference,\n })\n\n errors.push(...newErrors)\n\n filesystem = [\n ...filesystem,\n ...referencedFiles.map((file) => {\n return {\n ...file,\n isEntrypoint: false,\n }\n }),\n ]\n }\n\n return {\n specification: getEntrypoint(filesystem)?.specification,\n filesystem,\n errors,\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,cAAc;AASvB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,sBAAsB;AAC/B,SAAS,iBAAiB;AA+B1B,eAAsB,KAAK,OAA+B,SAA4C;AACpG,QAAM,SAAwB,CAAC;AAG/B,MAAI,SAAS,YAAY,KAAK,CAAC,UAAU,MAAM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;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAGA,aAAW,aAAa,kBAAkB;AAExC,UAAM,cAAc,SAAS,SAAS,KAAK,CAAC,eAAe,WAAW,MAAM,SAAS,CAAC;AAGtF,QAAI,CAAC,aAAa;AAChB;AAAA,IACF;AAEA,UAAM,SACJ,YAAY,MAAM,SAAS,KAAK,YAAY,cAAc,YAAY,YAAY,OAAO,SAAS,IAAI;AAGxG,QAAI,WAAW,KAAK,CAAC,UAAU,MAAM,aAAa,SAAS,GAAG;AAC5D;AAAA,IACF;AAEA,UAAM,EAAE,YAAY,iBAAiB,QAAQ,UAAU,IAAI,MAAM,KAAK,QAAQ;AAAA,MAC5E,GAAG;AAAA;AAAA;AAAA,MAGH,UAAU;AAAA,IACZ,CAAC;AAED,WAAO,KAAK,GAAG,SAAS;AAExB,iBAAa;AAAA,MACX,GAAG;AAAA,MACH,GAAG,gBAAgB,IAAI,CAAC,SAAS;AAC/B,eAAO;AAAA,UACL,GAAG;AAAA,UACH,cAAc;AAAA,QAChB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,eAAe,cAAc,UAAU,GAAG;AAAA,IAC1C;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/upgrade-from-three-to-three-one.ts"],
|
|
4
|
-
"sourcesContent": ["import type { OpenAPIV3_1 } from '@scalar/openapi-types'\nimport type { UnknownObject } from '@scalar/types/utils'\n\nimport { traverse } from './traverse'\n\n// Create Sets for faster schema path lookups\nconst SCHEMA_SEGMENTS = new Set([\n 'properties',\n 'items',\n 'allOf',\n 'anyOf',\n 'oneOf',\n 'not',\n 'additionalProperties',\n 'schema',\n])\n\n/** Determine if the current path is within a schema - optimized version */\nexport function isSchemaPath(path: string[]): boolean {\n // Check for schema segments first (most common case)\n if (path.some((segment) => SCHEMA_SEGMENTS.has(segment))) {\n return true\n }\n\n // Check for schema suffix\n if (path.some((segment) => segment.endsWith('Schema'))) {\n return true\n }\n\n // Check for components/schemas path\n if (path.length >= 2 && path[0] === 'components' && path[1] === 'schemas') {\n return true\n }\n\n return false\n}\n\n/**\n * Upgrade from OpenAPI 3.0.x to 3.1.1\n *\n * https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0\n */\nexport function upgradeFromThreeToThreeOne(originalContent: UnknownObject) {\n let content = originalContent\n\n // Version check - early return if not 3.0.x\n if (content === null || typeof content.openapi !== 'string' || !content.openapi.startsWith('3.0')) {\n return content\n }\n\n content.openapi = '3.1.1'\n\n // Single traversal that handles all transformations\n content = traverse(content, applyChangesToDocument)\n\n return content as OpenAPIV3_1.Document\n}\n\nconst applyChangesToDocument = (schema: UnknownObject, path: string[]) => {\n // 1. Handle nullable types\n if (schema.type !== 'undefined' && schema.nullable === true) {\n schema.type = [schema.type, 'null']\n delete schema.nullable\n }\n\n // 2. Handle exclusiveMinimum and exclusiveMaximum\n if (schema.exclusiveMinimum === true) {\n schema.exclusiveMinimum = schema.minimum\n delete schema.minimum\n } else if (schema.exclusiveMinimum === false) {\n delete schema.exclusiveMinimum\n }\n\n if (schema.exclusiveMaximum === true) {\n schema.exclusiveMaximum = schema.maximum\n delete schema.maximum\n } else if (schema.exclusiveMaximum === false) {\n delete schema.exclusiveMaximum\n }\n\n // 3. Handle examples\n if (schema.example !== undefined) {\n if (isSchemaPath(path)) {\n schema.examples = [schema.example]\n } else {\n schema.examples = {\n default: {\n value: schema.example,\n },\n }\n }\n delete schema.example\n }\n\n // 4. Handle multipart file uploads\n if (schema.type === 'object' && schema.properties !== undefined) {\n const parentPath = path.slice(0, -1)\n const isMultipart = parentPath.some((segment, index) => {\n return segment === 'content' && path[index + 1] === 'multipart/form-data'\n })\n\n if (isMultipart) {\n for (const value of Object.values(schema.properties)) {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n 'format' in value &&\n value.type === 'string' &&\n value.format === 'binary'\n ) {\n ;(value as any).contentMediaType = 'application/octet-stream'\n delete (value as any).format\n }\n }\n }\n }\n\n // 5. Handle binary file uploads\n if (path.includes('content') && path.includes('application/octet-stream')) {\n return {}\n }\n\n if (schema.type === 'string') {\n if (schema.format === 'binary') {\n return {\n type: 'string',\n contentMediaType: 'application/octet-stream',\n }\n }\n\n if (schema.format === 'base64') {\n return {\n type: 'string',\n contentEncoding: 'base64',\n }\n }\n\n if (schema.format === 'byte') {\n const parentPath = path.slice(0, -1)\n const contentMediaType = parentPath.find((_, index) => path[index - 1] === 'content')\n return {\n type: 'string',\n contentEncoding: 'base64',\n contentMediaType,\n }\n }\n }\n\n return schema\n}\n"],
|
|
5
|
-
"mappings": "AAGA,SAAS,gBAAgB;AAGzB,MAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,SAAS,aAAa,MAAyB;AAEpD,MAAI,KAAK,KAAK,CAAC,YAAY,gBAAgB,IAAI,OAAO,CAAC,GAAG;AACxD,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,KAAK,CAAC,YAAY,QAAQ,SAAS,QAAQ,CAAC,GAAG;AACtD,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,UAAU,KAAK,KAAK,CAAC,MAAM,gBAAgB,KAAK,CAAC,MAAM,WAAW;AACzE,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAOO,SAAS,2BAA2B,iBAAgC;AACzE,MAAI,UAAU;AAGd,MAAI,YAAY,QAAQ,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,QAAQ,WAAW,KAAK,GAAG;AACjG,WAAO;AAAA,EACT;AAEA,UAAQ,UAAU;AAGlB,YAAU,SAAS,SAAS,sBAAsB;AAElD,SAAO;AACT;AAEA,MAAM,yBAAyB,CAAC,QAAu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O,SAAS,UAAU;AAC5B,QAAI,OAAO,WAAW,UAAU;AAC9B,aAAO;AAAA,QACL,MAAM;AAAA,QACN,kBAAkB;AAAA,MACpB;AAAA,IACF;AAEA,QAAI,OAAO,WAAW,UAAU;AAC9B,aAAO;AAAA,QACL,MAAM;AAAA,QACN,iBAAiB;AAAA,MACnB;AAAA,IACF;AAEA,QAAI,OAAO,WAAW,QAAQ;AAC5B,YAAM,aAAa,KAAK,MAAM,GAAG,EAAE;AACnC,YAAM,mBAAmB,WAAW,KAAK,CAAC,GAAG,UAAU,KAAK,QAAQ,CAAC,MAAM,SAAS;AACpF,aAAO;AAAA,QACL,MAAM;AAAA,QACN,iBAAiB;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
4
|
+
"sourcesContent": ["import type { OpenAPIV3_1 } from '@scalar/openapi-types'\nimport type { UnknownObject } from '@scalar/types/utils'\n\nimport { traverse } from './traverse'\n\n// Create Sets for faster schema path lookups\nconst SCHEMA_SEGMENTS = new Set([\n 'properties',\n 'items',\n 'allOf',\n 'anyOf',\n 'oneOf',\n 'not',\n 'additionalProperties',\n 'schema',\n])\n\n/** Determine if the current path is within a schema - optimized version */\nexport function isSchemaPath(path: string[]): boolean {\n // Check for schema segments first (most common case)\n if (path.some((segment) => SCHEMA_SEGMENTS.has(segment))) {\n return true\n }\n\n // Check for schema suffix\n if (path.some((segment) => segment.endsWith('Schema'))) {\n return true\n }\n\n // Check for components/schemas path\n if (path.length >= 2 && path[0] === 'components' && path[1] === 'schemas') {\n return true\n }\n\n return false\n}\n\n/**\n * Upgrade from OpenAPI 3.0.x to 3.1.1\n *\n * https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0\n */\nexport function upgradeFromThreeToThreeOne(originalContent: UnknownObject) {\n let content = originalContent\n\n // Version check - early return if not 3.0.x\n if (content === null || typeof content.openapi !== 'string' || !content.openapi.startsWith('3.0')) {\n return content\n }\n\n content.openapi = '3.1.1'\n\n // Single traversal that handles all transformations\n content = traverse(content, applyChangesToDocument)\n\n return content as OpenAPIV3_1.Document\n}\n\nconst applyChangesToDocument = (schema: UnknownObject, path: string[]) => {\n // 1. Handle nullable types\n if (schema.type !== 'undefined' && schema.nullable === true) {\n schema.type = [schema.type, 'null']\n delete schema.nullable\n }\n\n // 2. Handle exclusiveMinimum and exclusiveMaximum\n if (schema.exclusiveMinimum === true) {\n schema.exclusiveMinimum = schema.minimum\n delete schema.minimum\n } else if (schema.exclusiveMinimum === false) {\n delete schema.exclusiveMinimum\n }\n\n if (schema.exclusiveMaximum === true) {\n schema.exclusiveMaximum = schema.maximum\n delete schema.maximum\n } else if (schema.exclusiveMaximum === false) {\n delete schema.exclusiveMaximum\n }\n\n // 3. Handle examples\n if (schema.example !== undefined) {\n if (isSchemaPath(path)) {\n schema.examples = [schema.example]\n } else {\n schema.examples = {\n default: {\n value: schema.example,\n },\n }\n }\n delete schema.example\n }\n\n // 4. Handle multipart file uploads\n if (schema.type === 'object' && schema.properties !== undefined) {\n const parentPath = path.slice(0, -1)\n const isMultipart = parentPath.some((segment, index) => {\n return segment === 'content' && path[index + 1] === 'multipart/form-data'\n })\n\n if (isMultipart) {\n for (const value of Object.values(schema.properties)) {\n if (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n 'format' in value &&\n value.type === 'string' &&\n value.format === 'binary'\n ) {\n ;(value as any).contentMediaType = 'application/octet-stream'\n delete (value as any).format\n }\n }\n }\n }\n\n // 5. Handle binary file uploads\n if (path.includes('content') && path.includes('application/octet-stream')) {\n return {}\n }\n\n if (schema.type === 'string') {\n if (schema.format === 'binary') {\n return {\n type: 'string',\n contentMediaType: 'application/octet-stream',\n }\n }\n\n if (schema.format === 'base64') {\n return {\n type: 'string',\n contentEncoding: 'base64',\n }\n }\n\n if (schema.format === 'byte') {\n const parentPath = path.slice(0, -1)\n const contentMediaType = parentPath.find((_, index) => path[index - 1] === 'content')\n return {\n type: 'string',\n contentEncoding: 'base64',\n contentMediaType,\n }\n }\n }\n\n // 6. Handle x-webhooks\n if (schema['x-webhooks'] !== undefined) {\n schema.webhooks = schema['x-webhooks']\n delete schema['x-webhooks']\n }\n\n return schema\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,gBAAgB;AAGzB,MAAM,kBAAkB,oBAAI,IAAI;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,SAAS,aAAa,MAAyB;AAEpD,MAAI,KAAK,KAAK,CAAC,YAAY,gBAAgB,IAAI,OAAO,CAAC,GAAG;AACxD,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,KAAK,CAAC,YAAY,QAAQ,SAAS,QAAQ,CAAC,GAAG;AACtD,WAAO;AAAA,EACT;AAGA,MAAI,KAAK,UAAU,KAAK,KAAK,CAAC,MAAM,gBAAgB,KAAK,CAAC,MAAM,WAAW;AACzE,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAOO,SAAS,2BAA2B,iBAAgC;AACzE,MAAI,UAAU;AAGd,MAAI,YAAY,QAAQ,OAAO,QAAQ,YAAY,YAAY,CAAC,QAAQ,QAAQ,WAAW,KAAK,GAAG;AACjG,WAAO;AAAA,EACT;AAEA,UAAQ,UAAU;AAGlB,YAAU,SAAS,SAAS,sBAAsB;AAElD,SAAO;AACT;AAEA,MAAM,yBAAyB,CAAC,QAAuB,SAAmB;AAExE,MAAI,OAAO,SAAS,eAAe,OAAO,aAAa,MAAM;AAC3D,WAAO,OAAO,CAAC,OAAO,MAAM,MAAM;AAClC,WAAO,OAAO;AAAA,EAChB;AAGA,MAAI,OAAO,qBAAqB,MAAM;AACpC,WAAO,mBAAmB,OAAO;AACjC,WAAO,OAAO;AAAA,EAChB,WAAW,OAAO,qBAAqB,OAAO;AAC5C,WAAO,OAAO;AAAA,EAChB;AAEA,MAAI,OAAO,qBAAqB,MAAM;AACpC,WAAO,mBAAmB,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C,GAAG,UAAU,KAAK,QAAQ,CAAC,MAAM,SAAS;AACpF,aAAO;AAAA,QACL,MAAM;AAAA,QACN,iBAAiB;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAGA,MAAI,OAAO,YAAY,MAAM,QAAW;AACtC,WAAO,WAAW,OAAO,YAAY;AACrC,WAAO,OAAO,YAAY;AAAA,EAC5B;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"parser",
|
|
18
18
|
"typescript"
|
|
19
19
|
],
|
|
20
|
-
"version": "0.
|
|
20
|
+
"version": "0.18.0",
|
|
21
21
|
"engines": {
|
|
22
22
|
"node": ">=20"
|
|
23
23
|
},
|
|
@@ -73,9 +73,9 @@
|
|
|
73
73
|
"just-diff": "^6.0.2",
|
|
74
74
|
"tinybench": "^2.8.0",
|
|
75
75
|
"vite": "5.4.19",
|
|
76
|
-
"@scalar/
|
|
77
|
-
"@scalar/
|
|
78
|
-
"@scalar/
|
|
76
|
+
"@scalar/build-tooling": "0.2.3",
|
|
77
|
+
"@scalar/openapi-types": "0.3.3",
|
|
78
|
+
"@scalar/types": "0.2.3"
|
|
79
79
|
},
|
|
80
80
|
"scripts": {
|
|
81
81
|
"build": "scalar-build-esbuild",
|