@scalar/openapi-parser 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +134 -0
  3. package/dist/configuration/index.d.ts +2 -2
  4. package/dist/configuration/index.js +2 -2
  5. package/dist/configuration/index.js.map +1 -1
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +4 -0
  9. package/dist/index.js.map +2 -2
  10. package/dist/types/index.d.ts +1 -0
  11. package/dist/types/index.d.ts.map +1 -1
  12. package/dist/utils/bundle/bundle.d.ts +193 -0
  13. package/dist/utils/bundle/bundle.d.ts.map +1 -0
  14. package/dist/utils/bundle/bundle.js +197 -0
  15. package/dist/utils/bundle/bundle.js.map +7 -0
  16. package/dist/utils/bundle/create-limiter.d.ts +21 -0
  17. package/dist/utils/bundle/create-limiter.d.ts.map +1 -0
  18. package/dist/utils/bundle/create-limiter.js +31 -0
  19. package/dist/utils/bundle/create-limiter.js.map +7 -0
  20. package/dist/utils/bundle/index.d.ts +4 -0
  21. package/dist/utils/bundle/index.d.ts.map +1 -0
  22. package/dist/utils/bundle/index.js +9 -0
  23. package/dist/utils/bundle/index.js.map +7 -0
  24. package/dist/utils/bundle/plugins/fetch-urls.d.ts +38 -0
  25. package/dist/utils/bundle/plugins/fetch-urls.d.ts.map +1 -0
  26. package/dist/utils/bundle/plugins/fetch-urls.js +40 -0
  27. package/dist/utils/bundle/plugins/fetch-urls.js.map +7 -0
  28. package/dist/utils/bundle/plugins/read-files.d.ts +29 -0
  29. package/dist/utils/bundle/plugins/read-files.d.ts.map +1 -0
  30. package/dist/utils/bundle/plugins/read-files.js +30 -0
  31. package/dist/utils/bundle/plugins/read-files.js.map +7 -0
  32. package/dist/utils/details.d.ts +1 -2
  33. package/dist/utils/details.d.ts.map +1 -1
  34. package/dist/utils/details.js +12 -9
  35. package/dist/utils/details.js.map +2 -2
  36. package/dist/utils/normalize.d.ts +1 -1
  37. package/dist/utils/normalize.d.ts.map +1 -1
  38. package/dist/utils/normalize.js +16 -11
  39. package/dist/utils/normalize.js.map +2 -2
  40. package/dist/utils/resolve-references.d.ts.map +1 -1
  41. package/dist/utils/resolve-references.js +11 -0
  42. package/dist/utils/resolve-references.js.map +2 -2
  43. package/package.json +5 -5
  44. package/dist/lib/Validator/Validator.test.js +0 -8
  45. package/dist/lib/Validator/Validator.test.js.map +0 -7
  46. package/dist/plugins/fetch-urls/fetch-urls.test.js +0 -50
  47. package/dist/plugins/fetch-urls/fetch-urls.test.js.map +0 -7
  48. package/dist/plugins/read-files/read-files.test.js +0 -20
  49. package/dist/plugins/read-files/read-files.test.js.map +0 -7
  50. package/dist/utils/dereference.test.js +0 -300
  51. package/dist/utils/dereference.test.js.map +0 -7
  52. package/dist/utils/errors.test.js +0 -48
  53. package/dist/utils/errors.test.js.map +0 -7
  54. package/dist/utils/escape-json-pointer.test.js +0 -11
  55. package/dist/utils/escape-json-pointer.test.js.map +0 -7
  56. package/dist/utils/get-entrypoint.test.js +0 -18
  57. package/dist/utils/get-entrypoint.test.js.map +0 -7
  58. package/dist/utils/get-segments-from-path.test.js +0 -13
  59. package/dist/utils/get-segments-from-path.test.js.map +0 -7
  60. package/dist/utils/is-filesystem.test.js +0 -15
  61. package/dist/utils/is-filesystem.test.js.map +0 -7
  62. package/dist/utils/is-object.test.js +0 -23
  63. package/dist/utils/is-object.test.js.map +0 -7
  64. package/dist/utils/load/load.test.js +0 -361
  65. package/dist/utils/load/load.test.js.map +0 -7
  66. package/dist/utils/normalize.test.js +0 -88
  67. package/dist/utils/normalize.test.js.map +0 -7
  68. package/dist/utils/resolve-references.test.js +0 -567
  69. package/dist/utils/resolve-references.test.js.map +0 -7
  70. package/dist/utils/transform/sanitize.test.js +0 -148
  71. package/dist/utils/transform/sanitize.test.js.map +0 -7
  72. package/dist/utils/transform-errors.test.js +0 -17
  73. package/dist/utils/transform-errors.test.js.map +0 -7
  74. package/dist/utils/traverse.test.js +0 -68
  75. package/dist/utils/traverse.test.js.map +0 -7
  76. package/dist/utils/unescape-json-pointer.test.js +0 -19
  77. package/dist/utils/unescape-json-pointer.test.js.map +0 -7
  78. package/dist/utils/upgrade-from-three-to-three-one.test.js +0 -462
  79. package/dist/utils/upgrade-from-three-to-three-one.test.js.map +0 -7
  80. package/dist/utils/upgrade-from-two-to-three.test.js +0 -589
  81. package/dist/utils/upgrade-from-two-to-three.test.js.map +0 -7
  82. package/dist/utils/upgrade.test.js +0 -57
  83. package/dist/utils/upgrade.test.js.map +0 -7
  84. package/dist/utils/validate.test.js +0 -64
  85. package/dist/utils/validate.test.js.map +0 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @scalar/openapi-parser
2
2
 
3
+ ## 0.14.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ee3eb77: feat(openapi-parser): bundle openapi documents
8
+
9
+ ## 0.13.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 1e87feb: fix: normalize doesn’t handle empty documents well
14
+
3
15
  ## 0.12.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -55,6 +55,140 @@ const specification = `{
55
55
  const { schema, errors } = await dereference(specification)
56
56
  ```
57
57
 
58
+ ### Bundle external references
59
+
60
+ The OpenAPI specification allows to point to external files (URLs or files). But sometimes, you just want to combine all files into one.
61
+
62
+ #### Plugins
63
+
64
+ ##### fetchUrls
65
+ This plugins handles all external urls. It works for both node.js and browser environment
66
+
67
+ ```ts
68
+ import { bundle, fetchUrls } from '@scalar/openapi-parser'
69
+
70
+ const document = {
71
+ openapi: '3.1.0',
72
+ info: { title: 'Bundled API', version: '1.0.0' },
73
+ paths: {},
74
+ components: {
75
+ schemas: {
76
+ User: { $ref: 'https://example.com/user-schema.json#' }
77
+ }
78
+ }
79
+ }
80
+
81
+ // This will bundle all external documents and turn all references from external into internal
82
+ await bundle(document, {
83
+ plugins: [fetchUrls()],
84
+ treeShake: true // <------ This flag will try to remove any unused part of the external document
85
+ })
86
+
87
+ console.log(document)
88
+ ```
89
+
90
+ ###### Limiting the number of concurrent requests
91
+
92
+ ```ts
93
+ await bundle(document, {
94
+ plugins: [
95
+ fetchUrls({
96
+ limit: 10, // it should run at most 10 requests at the same time
97
+ }),
98
+ ],
99
+ treeShake: false
100
+ })
101
+
102
+ ```
103
+
104
+ ###### Custom headers
105
+ To pass custom headers to requests for specific domains you can configure the fetch plugin like the example
106
+
107
+ ```ts
108
+ await bundle(
109
+ document,
110
+ {
111
+ plugins: [
112
+ fetchUrls({
113
+ // Pass custom headers
114
+ // The header will only be attached to the list of domains
115
+ headers: [
116
+ {
117
+ domains: ['example.com'],
118
+ headers: {
119
+ 'Authorization': 'Bearer <TOKEN>'
120
+ }
121
+ }
122
+ ]
123
+ }),
124
+ readFiles(),
125
+ ],
126
+ treeShake: false
127
+ },
128
+ )
129
+ ```
130
+
131
+ ###### Bundle from remote url
132
+
133
+ ```ts
134
+ const result = await bundle(
135
+ 'https://example.com/openapi.json',
136
+ {
137
+ plugins: [
138
+ fetchUrls(),
139
+ ],
140
+ treeShake: false
141
+ },
142
+ )
143
+
144
+ // Bundled document
145
+ console.log(result)
146
+ ```
147
+
148
+ ##### readFiles
149
+ This plugins handles local files. Only works on node.js environment
150
+
151
+ ```ts
152
+ import { bundle, readFiles } from '@scalar/openapi-parser'
153
+
154
+ const document = {
155
+ openapi: '3.1.0',
156
+ info: { title: 'Bundled API', version: '1.0.0' },
157
+ paths: {},
158
+ components: {
159
+ schemas: {
160
+ User: { $ref: './user-schema.json#' }
161
+ }
162
+ }
163
+ }
164
+
165
+ // This will bundle all external documents and turn all references from external into internal
166
+ await bundle(document, {
167
+ plugins: [readFiles()],
168
+ treeShake: false
169
+ })
170
+
171
+ console.log(document)
172
+ ```
173
+
174
+ ###### Bundle from local file
175
+ You can pass the file path directly but make sure to have the correct plugins to handle reading from the local files
176
+
177
+ ```ts
178
+ const result = await bundle(
179
+ './input.json',
180
+ {
181
+ plugins: [
182
+ readFiles(),
183
+ ],
184
+ treeShake: false
185
+ },
186
+ )
187
+
188
+ // Bundled document
189
+ console.log(result)
190
+ ```
191
+
58
192
  ### Track references
59
193
 
60
194
  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:
@@ -3897,8 +3897,8 @@ export declare const OpenApiVersions: OpenApiVersion[];
3897
3897
  * List of error messages used in the Validator
3898
3898
  */
3899
3899
  export declare const ERRORS: {
3900
- readonly EMPTY_OR_INVALID: "Can’t find JSON, YAML or filename in data";
3901
- readonly OPENAPI_VERSION_NOT_SUPPORTED: "Can’t find supported Swagger/OpenAPI version in specification, version must be a string.";
3900
+ readonly EMPTY_OR_INVALID: "Can’t find JSON, YAML or filename in data.";
3901
+ readonly OPENAPI_VERSION_NOT_SUPPORTED: "Can’t find supported Swagger/OpenAPI version in the provided document, version must be a string.";
3902
3902
  readonly INVALID_REFERENCE: "Can’t resolve reference: %s";
3903
3903
  readonly EXTERNAL_REFERENCE_NOT_FOUND: "Can’t resolve external reference: %s";
3904
3904
  readonly FILE_DOES_NOT_EXIST: "File does not exist: %s";
@@ -8,9 +8,9 @@ const OpenApiSpecifications = {
8
8
  };
9
9
  const OpenApiVersions = Object.keys(OpenApiSpecifications);
10
10
  const ERRORS = {
11
- EMPTY_OR_INVALID: "Can\u2019t find JSON, YAML or filename in data",
11
+ EMPTY_OR_INVALID: "Can\u2019t find JSON, YAML or filename in data.",
12
12
  // URI_MUST_BE_STRING: 'uri parameter or $id attribute must be a string',
13
- OPENAPI_VERSION_NOT_SUPPORTED: "Can\u2019t find supported Swagger/OpenAPI version in specification, version must be a string.",
13
+ OPENAPI_VERSION_NOT_SUPPORTED: "Can\u2019t find supported Swagger/OpenAPI version in the provided document, version must be a string.",
14
14
  INVALID_REFERENCE: "Can\u2019t resolve reference: %s",
15
15
  EXTERNAL_REFERENCE_NOT_FOUND: "Can\u2019t resolve external reference: %s",
16
16
  FILE_DOES_NOT_EXIST: "File does not exist: %s",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/configuration/index.ts"],
4
- "sourcesContent": ["import Swagger20 from '@/schemas/v2.0/schema'\nimport OpenApi30 from '@/schemas/v3.0/schema'\nimport OpenApi31 from '@/schemas/v3.1/schema'\n\n/**\n * A list of the supported OpenAPI specifications\n */\nexport const OpenApiSpecifications = {\n '2.0': Swagger20,\n '3.0': OpenApi30,\n '3.1': OpenApi31,\n}\n\nexport type OpenApiVersion = keyof typeof OpenApiSpecifications\n\nexport const OpenApiVersions = Object.keys(OpenApiSpecifications) as OpenApiVersion[]\n\n/**\n * List of error messages used in the Validator\n */\nexport const ERRORS = {\n EMPTY_OR_INVALID: 'Can\u2019t find JSON, YAML or filename in data',\n // URI_MUST_BE_STRING: 'uri parameter or $id attribute must be a string',\n OPENAPI_VERSION_NOT_SUPPORTED:\n 'Can\u2019t find supported Swagger/OpenAPI version in specification, version must be a string.',\n INVALID_REFERENCE: 'Can\u2019t resolve reference: %s',\n EXTERNAL_REFERENCE_NOT_FOUND: 'Can\u2019t resolve external reference: %s',\n FILE_DOES_NOT_EXIST: 'File does not exist: %s',\n NO_CONTENT: 'No content found',\n} as const\n\nexport type ValidationError = keyof typeof ERRORS\n"],
4
+ "sourcesContent": ["import Swagger20 from '@/schemas/v2.0/schema'\nimport OpenApi30 from '@/schemas/v3.0/schema'\nimport OpenApi31 from '@/schemas/v3.1/schema'\n\n/**\n * A list of the supported OpenAPI specifications\n */\nexport const OpenApiSpecifications = {\n '2.0': Swagger20,\n '3.0': OpenApi30,\n '3.1': OpenApi31,\n}\n\nexport type OpenApiVersion = keyof typeof OpenApiSpecifications\n\nexport const OpenApiVersions = Object.keys(OpenApiSpecifications) as OpenApiVersion[]\n\n/**\n * List of error messages used in the Validator\n */\nexport const ERRORS = {\n EMPTY_OR_INVALID: 'Can\u2019t find JSON, YAML or filename in data.',\n // URI_MUST_BE_STRING: 'uri parameter or $id attribute must be a string',\n OPENAPI_VERSION_NOT_SUPPORTED:\n 'Can\u2019t find supported Swagger/OpenAPI version in the provided document, version must be a string.',\n INVALID_REFERENCE: 'Can\u2019t resolve reference: %s',\n EXTERNAL_REFERENCE_NOT_FOUND: 'Can\u2019t resolve external reference: %s',\n FILE_DOES_NOT_EXIST: 'File does not exist: %s',\n NO_CONTENT: 'No content found',\n} as const\n\nexport type ValidationError = keyof typeof ERRORS\n"],
5
5
  "mappings": "AAAA,OAAO,eAAe;AACtB,OAAO,eAAe;AACtB,OAAO,eAAe;AAKf,MAAM,wBAAwB;AAAA,EACnC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACT;AAIO,MAAM,kBAAkB,OAAO,KAAK,qBAAqB;AAKzD,MAAM,SAAS;AAAA,EACpB,kBAAkB;AAAA;AAAA,EAElB,+BACE;AAAA,EACF,mBAAmB;AAAA,EACnB,8BAA8B;AAAA,EAC9B,qBAAqB;AAAA,EACrB,YAAY;AACd;",
6
6
  "names": []
7
7
  }
package/dist/index.d.ts CHANGED
@@ -14,5 +14,6 @@ export { upgrade } from './utils/upgrade.js';
14
14
  export { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one.js';
15
15
  export { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three.js';
16
16
  export { validate } from './utils/validate.js';
17
+ export { bundle, fetchUrls, readFiles } from './utils/bundle/index.js';
17
18
  export type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types/index.js';
18
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAA;AAC/D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,MAAM,EAAE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AM,iBAAiB,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAA;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAA;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAA;AACzE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAC3C,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC7D,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -14,14 +14,18 @@ import { upgrade } from "./utils/upgrade.js";
14
14
  import { upgradeFromThreeToThreeOne } from "./utils/upgrade-from-three-to-three-one.js";
15
15
  import { upgradeFromTwoToThree } from "./utils/upgrade-from-two-to-three.js";
16
16
  import { validate } from "./utils/validate.js";
17
+ import { bundle, fetchUrls, readFiles } from "./utils/bundle/index.js";
17
18
  export {
19
+ bundle,
18
20
  dereference,
19
21
  escapeJsonPointer,
22
+ fetchUrls,
20
23
  filter,
21
24
  isJson,
22
25
  isYaml,
23
26
  load,
24
27
  normalize,
28
+ readFiles,
25
29
  sanitize,
26
30
  toJson,
27
31
  toYaml,
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["export { dereference } from './utils/dereference'\nexport { escapeJsonPointer } from './utils/escape-json-pointer'\nexport { filter } from './utils/filter'\nexport { isJson } from './utils/is-json'\nexport { isYaml } from './utils/is-yaml'\nexport { load } from './utils/load'\nexport { normalize } from './utils/normalize'\nexport { sanitize } from './utils/transform/sanitize'\nexport { toJson } from './utils/to-json'\nexport { toYaml } from './utils/to-yaml'\nexport { traverse } from './utils/traverse'\nexport { unescapeJsonPointer } from './utils/unescape-json-pointer'\nexport { upgrade } from './utils/upgrade'\nexport { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one'\nexport { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three'\nexport { validate } from './utils/validate'\nexport type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types'\n"],
5
- "mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gBAAgB;",
4
+ "sourcesContent": ["export { dereference } from './utils/dereference'\nexport { escapeJsonPointer } from './utils/escape-json-pointer'\nexport { filter } from './utils/filter'\nexport { isJson } from './utils/is-json'\nexport { isYaml } from './utils/is-yaml'\nexport { load } from './utils/load'\nexport { normalize } from './utils/normalize'\nexport { sanitize } from './utils/transform/sanitize'\nexport { toJson } from './utils/to-json'\nexport { toYaml } from './utils/to-yaml'\nexport { traverse } from './utils/traverse'\nexport { unescapeJsonPointer } from './utils/unescape-json-pointer'\nexport { upgrade } from './utils/upgrade'\nexport { upgradeFromThreeToThreeOne } from './utils/upgrade-from-three-to-three-one'\nexport { upgradeFromTwoToThree } from './utils/upgrade-from-two-to-three'\nexport { validate } from './utils/validate'\nexport { bundle, fetchUrls, readFiles } from './utils/bundle'\nexport type { LoadResult, Filesystem, AnyObject, ErrorObject } from './types'\n"],
5
+ "mappings": "AAAA,SAAS,mBAAmB;AAC5B,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,cAAc;AACvB,SAAS,gBAAgB;AACzB,SAAS,2BAA2B;AACpC,SAAS,eAAe;AACxB,SAAS,kCAAkC;AAC3C,SAAS,6BAA6B;AACtC,SAAS,gBAAgB;AACzB,SAAS,QAAQ,WAAW,iBAAiB;",
6
6
  "names": []
7
7
  }
@@ -5,6 +5,7 @@ import type { ERRORS, OpenApiVersion } from '../configuration/index.js';
5
5
  */
6
6
  export type Merge<A, B> = A & Omit<B, keyof A>;
7
7
  export type AnyObject = Record<string, any>;
8
+ export type UnknownObject = Record<string, unknown>;
8
9
  /**
9
10
  * JSON, YAML or object representation of an OpenAPI API definition
10
11
  */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAA;AAEpD,OAAO,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAG7D;;GAEG;AACH,MAAM,MAAM,KAAK,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAAA;AAE9C,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;AAE3C;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAAG,MAAM,GAAG,SAAS,CAAA;AAEvD,MAAM,MAAM,UAAU,GAAG;IACvB,UAAU,EAAE,UAAU,CAAA;IACtB,aAAa,EAAE,SAAS,CAAA;IACxB,MAAM,CAAC,EAAE,WAAW,EAAE,CAAA;CACvB,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,KAAK,EAAE,OAAO,CAAA;IACd,aAAa,CAAC,EAAE,OAA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,GAAG,QAAQ,CAAC,MAAM,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAA;AAEnD,MAAM,MAAM,uBAAuB,GAAG;IACpC,UAAU,EAAE,UAAU,CAAA;IACtB,aAAa,EAAE,SAAS,CAAA;CACzB,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,MAAM,YAAY,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,KAAK,EAAE,GAAG,MAAM,IAAI,CAAC,GAC/E,KAAK,SAAS,IAAI,GAChB,IAAI,SAAS,IAAI,EAAE,GACjB,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC,GAC5D,KAAK,GACP,KAAK,GACP,uBAAuB,CAAA"}
@@ -0,0 +1,193 @@
1
+ import type { UnknownObject } from '../../types/index.js';
2
+ /**
3
+ * Checks if a string is a remote URL (starts with http:// or https://)
4
+ * @param value - The URL string to check
5
+ * @returns true if the string is a remote URL, false otherwise
6
+ * @example
7
+ * ```ts
8
+ * isRemoteUrl('https://example.com/schema.json') // true
9
+ * isRemoteUrl('http://api.example.com/schemas/user.json') // true
10
+ * isRemoteUrl('#/components/schemas/User') // false
11
+ * isRemoteUrl('./local-schema.json') // false
12
+ * ```
13
+ */
14
+ export declare function isRemoteUrl(value: string): boolean;
15
+ /**
16
+ * Checks if a string is a local reference (starts with #)
17
+ * @param value - The reference string to check
18
+ * @returns true if the string is a local reference, false otherwise
19
+ * @example
20
+ * ```ts
21
+ * isLocalRef('#/components/schemas/User') // true
22
+ * isLocalRef('https://example.com/schema.json') // false
23
+ * isLocalRef('./local-schema.json') // false
24
+ * ```
25
+ */
26
+ export declare function isLocalRef(value: string): boolean;
27
+ export type ResolveResult = {
28
+ ok: true;
29
+ data: unknown;
30
+ } | {
31
+ ok: false;
32
+ };
33
+ /**
34
+ * Retrieves a nested value from an object using an array of property segments.
35
+ * @param target - The target object to traverse
36
+ * @param segments - Array of property names representing the path to the desired value
37
+ * @returns The value at the specified path, or undefined if the path doesn't exist
38
+ * @example
39
+ * const obj = { foo: { bar: { baz: 42 } } };
40
+ * getNestedValue(obj, ['foo', 'bar', 'baz']); // returns 42
41
+ */
42
+ export declare function getNestedValue(target: Record<string, any>, segments: string[]): any;
43
+ /**
44
+ * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.
45
+ * This function traverses the object structure and creates any missing intermediate objects
46
+ * or arrays based on the path segments. If the next segment is a numeric string, it creates
47
+ * an array instead of an object.
48
+ *
49
+ * @param obj - The target object to set the value in
50
+ * @param path - The JSON pointer path where the value should be set
51
+ * @param value - The value to set at the specified path
52
+ * @throws {Error} If attempting to set a value at the root path ('')
53
+ *
54
+ * @example
55
+ * const obj = {}
56
+ * setValueAtPath(obj, '/foo/bar/0', 'value')
57
+ * // Result:
58
+ * // {
59
+ * // foo: {
60
+ * // bar: ['value']
61
+ * // }
62
+ * // }
63
+ *
64
+ * @example
65
+ * const obj = { existing: { path: 'old' } }
66
+ * setValueAtPath(obj, '/existing/path', 'new')
67
+ * // Result:
68
+ * // {
69
+ * // existing: {
70
+ * // path: 'new'
71
+ * // }
72
+ * // }
73
+ */
74
+ export declare function setValueAtPath(obj: any, path: string, value: any): void;
75
+ /**
76
+ * Prefixes an internal JSON reference with a given path prefix.
77
+ * Takes a local reference (starting with #) and prepends the provided prefix segments.
78
+ *
79
+ * @param input - The internal reference string to prefix (must start with #)
80
+ * @param prefix - Array of path segments to prepend to the reference
81
+ * @returns The prefixed reference string
82
+ * @throws Error if input is not a local reference
83
+ * @example
84
+ * prefixInternalRef('#/components/schemas/User', ['definitions'])
85
+ * // Returns: '#/definitions/components/schemas/User'
86
+ */
87
+ export declare function prefixInternalRef(input: string, prefix: string[]): string;
88
+ /**
89
+ * Updates internal references in an object by adding a prefix to their paths.
90
+ * Recursively traverses the input object and modifies any local $ref references
91
+ * by prepending the given prefix to their paths. This is used when embedding external
92
+ * documents to maintain correct reference paths relative to the main document.
93
+ *
94
+ * @param input - The object to update references in
95
+ * @param prefix - Array of path segments to prepend to internal reference paths
96
+ * @returns void
97
+ * @example
98
+ * ```ts
99
+ * const input = {
100
+ * foo: {
101
+ * $ref: '#/components/schemas/User'
102
+ * }
103
+ * }
104
+ * prefixInternalRefRecursive(input, ['definitions'])
105
+ * // Result:
106
+ * // {
107
+ * // foo: {
108
+ * // $ref: '#/definitions/components/schemas/User'
109
+ * // }
110
+ * // }
111
+ * ```
112
+ */
113
+ export declare function prefixInternalRefRecursive(input: unknown, prefix: string[]): string;
114
+ /**
115
+ * Generates a short SHA-1 hash from a string value.
116
+ * This function is used to create unique identifiers for external references
117
+ * while keeping the hash length manageable. It uses the Web Crypto API to
118
+ * generate a SHA-1 hash and returns the first 7 characters of the hex string.
119
+ *
120
+ * @param value - The string to hash
121
+ * @returns A 7-character hexadecimal hash
122
+ * @example
123
+ * // Returns "a1b2c3d"
124
+ * getHash("https://example.com/schema.json")
125
+ */
126
+ export declare function getHash(value: string): Promise<string>;
127
+ /**
128
+ * Represents a plugin that handles resolving references from external sources.
129
+ * Plugins are responsible for fetching and processing data from different sources
130
+ * like URLs or the filesystem. Each plugin must implement validation to determine
131
+ * if it can handle a specific reference, and an execution function to perform
132
+ * the actual resolution.
133
+ *
134
+ * @property validate - Determines if this plugin can handle the given reference
135
+ * @property exec - Fetches and processes the reference, returning the resolved data
136
+ */
137
+ export type Plugin = {
138
+ validate: (value: string) => boolean;
139
+ exec: (value: string) => Promise<ResolveResult>;
140
+ };
141
+ type Config = {
142
+ plugins: Plugin[];
143
+ root?: UnknownObject;
144
+ cache?: Map<string, Promise<ResolveResult>>;
145
+ treeShake: boolean;
146
+ urlMap?: boolean;
147
+ };
148
+ /**
149
+ * Bundles an OpenAPI specification by resolving all external references.
150
+ * This function traverses the input object recursively and embeds external $ref
151
+ * references into an x-ext section. External references can be URLs or local files.
152
+ * The original $refs are updated to point to their embedded content in the x-ext section.
153
+ * If the input is an object, it will be modified in place by adding an x-ext
154
+ * property to store resolved external references.
155
+ *
156
+ * @param input - The OpenAPI specification object or string to bundle. If a string is provided,
157
+ * it should be a URL or file path that points to an OpenAPI specification.
158
+ * The string will be resolved using the provided plugins before bundling.
159
+ * @param config - Configuration object containing plugins for resolving references
160
+ * @returns A promise that resolves to the bundled specification with all references embedded
161
+ * @example
162
+ * // Example with object input
163
+ * const spec = {
164
+ * paths: {
165
+ * '/users': {
166
+ * $ref: 'https://example.com/schemas/users.yaml'
167
+ * }
168
+ * }
169
+ * }
170
+ *
171
+ * const bundled = await bundle(spec, { plugins: [fetchUrls()] })
172
+ * // Result:
173
+ * // {
174
+ * // paths: {
175
+ * // '/users': {
176
+ * // $ref: '#/x-ext/https~1~1example.com~1schemas~1users.yaml'
177
+ * // }
178
+ * // },
179
+ * // 'x-ext': {
180
+ * // 'https~1~1example.com~1schemas~1users.yaml': {
181
+ * // // Resolved content from users.yaml
182
+ * // }
183
+ * // }
184
+ * // }
185
+ *
186
+ * // Example with URL input
187
+ * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', { plugins: [fetchUrls()] })
188
+ * // The function will first fetch the OpenAPI spec from the URL,
189
+ * // then bundle all its external references into the x-ext section
190
+ */
191
+ export declare function bundle(input: UnknownObject | string, config: Config): Promise<unknown>;
192
+ export {};
193
+ //# sourceMappingURL=bundle.d.ts.map
@@ -0,0 +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;AAM5C;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE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AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,oBA2IzE"}
@@ -0,0 +1,197 @@
1
+ import { escapeJsonPointer } from "../../utils/escape-json-pointer.js";
2
+ import path from "../../polyfills/path.js";
3
+ import { getSegmentsFromPath } from "../../utils/get-segments-from-path.js";
4
+ import { isObject } from "../../utils/is-object.js";
5
+ function isRemoteUrl(value) {
6
+ return value.startsWith("http://") || value.startsWith("https://");
7
+ }
8
+ function isLocalRef(value) {
9
+ return value.startsWith("#");
10
+ }
11
+ async function resolveContents(value, plugins) {
12
+ const plugin = plugins.find((p) => p.validate(value));
13
+ if (plugin) {
14
+ return plugin.exec(value);
15
+ }
16
+ return {
17
+ ok: false
18
+ };
19
+ }
20
+ function getNestedValue(target, segments) {
21
+ return segments.reduce((acc, key) => {
22
+ if (acc === void 0) {
23
+ return void 0;
24
+ }
25
+ return acc[key];
26
+ }, target);
27
+ }
28
+ function setValueAtPath(obj, path2, value) {
29
+ if (path2 === "") {
30
+ throw new Error("Cannot set value at root ('') pointer");
31
+ }
32
+ const parts = getSegmentsFromPath(path2);
33
+ let current = obj;
34
+ for (let i = 0; i < parts.length; i++) {
35
+ const key = parts[i];
36
+ const isLast = i === parts.length - 1;
37
+ const nextKey = parts[i + 1];
38
+ const shouldBeArray = /^\d+$/.test(nextKey ?? "");
39
+ if (isLast) {
40
+ current[key] = value;
41
+ } else {
42
+ if (!(key in current) || typeof current[key] !== "object") {
43
+ current[key] = shouldBeArray ? [] : {};
44
+ }
45
+ current = current[key];
46
+ }
47
+ }
48
+ }
49
+ function resolveReferencePath(base, relativePath) {
50
+ if (isRemoteUrl(relativePath)) {
51
+ return relativePath;
52
+ }
53
+ if (isRemoteUrl(base)) {
54
+ const url = new URL(base);
55
+ const mergedPath = path.join(path.dirname(url.pathname), relativePath);
56
+ return new URL(mergedPath, base).toString();
57
+ }
58
+ return path.join(path.dirname(base), relativePath);
59
+ }
60
+ function prefixInternalRef(input, prefix) {
61
+ if (!isLocalRef(input)) {
62
+ throw "Please provide an internal ref";
63
+ }
64
+ return `#/${prefix.map(escapeJsonPointer).join("/")}${input.substring(1)}`;
65
+ }
66
+ function prefixInternalRefRecursive(input, prefix) {
67
+ if (!isObject(input)) {
68
+ return;
69
+ }
70
+ Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix));
71
+ if (typeof input === "object" && "$ref" in input && typeof input["$ref"] === "string") {
72
+ const ref = input["$ref"];
73
+ if (!isLocalRef(ref)) {
74
+ return;
75
+ }
76
+ return input["$ref"] = prefixInternalRef(ref, prefix);
77
+ }
78
+ }
79
+ const resolveAndCopyReferences = (targetDocument, sourceDocument, referencePath, externalRefsKey, documentKey, processedNodes = /* @__PURE__ */ new Set()) => {
80
+ const referencedValue = getNestedValue(sourceDocument, getSegmentsFromPath(referencePath));
81
+ if (processedNodes.has(referencedValue)) {
82
+ return;
83
+ }
84
+ processedNodes.add(referencedValue);
85
+ setValueAtPath(targetDocument, referencePath, referencedValue);
86
+ const traverse = (node) => {
87
+ if (!node || typeof node !== "object") {
88
+ return;
89
+ }
90
+ if ("$ref" in node && typeof node["$ref"] === "string") {
91
+ if (node["$ref"].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {
92
+ resolveAndCopyReferences(
93
+ targetDocument,
94
+ sourceDocument,
95
+ node["$ref"].substring(1),
96
+ documentKey,
97
+ externalRefsKey,
98
+ processedNodes
99
+ );
100
+ }
101
+ }
102
+ for (const value of Object.values(node)) {
103
+ traverse(value);
104
+ }
105
+ };
106
+ traverse(referencedValue);
107
+ };
108
+ async function getHash(value) {
109
+ const encoder = new TextEncoder();
110
+ const data = encoder.encode(value);
111
+ const hashBuffer = await crypto.subtle.digest("SHA-1", data);
112
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
113
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
114
+ return hashHex.slice(0, 7);
115
+ }
116
+ async function bundle(input, config) {
117
+ const cache = config.cache ?? /* @__PURE__ */ new Map();
118
+ const resolveInput = async () => {
119
+ if (typeof input !== "string") {
120
+ return input;
121
+ }
122
+ const result = await resolveContents(input, config.plugins);
123
+ if (result.ok) {
124
+ return result.data;
125
+ }
126
+ throw "Please provide a valid string value or pass a loader to process the input";
127
+ };
128
+ const rawSpecification = await resolveInput();
129
+ const documentRoot = config.root ?? rawSpecification;
130
+ const EXTERNAL_KEY = "x-ext";
131
+ const EXTERNAL_URL_MAPPING = "x-ext-urls";
132
+ const bundler = async (root, origin = typeof input === "string" ? input : "") => {
133
+ if (!isObject(root) && !Array.isArray(root)) {
134
+ return;
135
+ }
136
+ if (typeof root === "object" && "$ref" in root && typeof root["$ref"] === "string") {
137
+ const ref = root["$ref"];
138
+ if (isLocalRef(ref)) {
139
+ return;
140
+ }
141
+ const [prefix, path2 = ""] = ref.split("#", 2);
142
+ const resolvedPath = resolveReferencePath(origin, prefix);
143
+ const hashPath = await getHash(resolvedPath);
144
+ const seen = cache.has(resolvedPath);
145
+ if (!seen) {
146
+ cache.set(resolvedPath, resolveContents(resolvedPath, config.plugins));
147
+ }
148
+ const result = await cache.get(resolvedPath);
149
+ if (result.ok) {
150
+ if (!seen) {
151
+ prefixInternalRefRecursive(result.data, [EXTERNAL_KEY, hashPath]);
152
+ await bundler(result.data, resolvedPath);
153
+ if (config.urlMap) {
154
+ setValueAtPath(documentRoot, `/${EXTERNAL_URL_MAPPING}/${escapeJsonPointer(resolvedPath)}`, hashPath);
155
+ }
156
+ }
157
+ if (config.treeShake === true) {
158
+ resolveAndCopyReferences(
159
+ documentRoot,
160
+ { [EXTERNAL_KEY]: { [hashPath]: result.data } },
161
+ prefixInternalRef(`#${path2}`, [EXTERNAL_KEY, hashPath]).substring(1),
162
+ EXTERNAL_KEY,
163
+ hashPath
164
+ );
165
+ } else if (!seen) {
166
+ setValueAtPath(documentRoot, `/${EXTERNAL_KEY}/${hashPath}`, result.data);
167
+ }
168
+ root.$ref = prefixInternalRef(`#${path2}`, [EXTERNAL_KEY, hashPath]);
169
+ return;
170
+ }
171
+ return console.warn(
172
+ `Failed to resolve external reference "${prefix}". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`
173
+ );
174
+ }
175
+ await Promise.all(
176
+ Object.entries(root).map(async ([key, value]) => {
177
+ if (key === EXTERNAL_KEY) {
178
+ return;
179
+ }
180
+ await bundler(value, origin);
181
+ })
182
+ );
183
+ };
184
+ await bundler(rawSpecification);
185
+ return rawSpecification;
186
+ }
187
+ export {
188
+ bundle,
189
+ getHash,
190
+ getNestedValue,
191
+ isLocalRef,
192
+ isRemoteUrl,
193
+ prefixInternalRef,
194
+ prefixInternalRefRecursive,
195
+ setValueAtPath
196
+ };
197
+ //# sourceMappingURL=bundle.js.map