@apidevtools/json-schema-ref-parser 15.3.1 → 15.3.3

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/lib/ref.ts CHANGED
@@ -47,6 +47,11 @@ class $Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOpt
47
47
  */
48
48
  pathType: string | unknown;
49
49
 
50
+ /**
51
+ * Whether this document/resource should use JSON Schema 2019-09+ nested $id scope semantics.
52
+ */
53
+ dynamicIdScope = false;
54
+
50
55
  /**
51
56
  * List of all errors. Undefined if no errors.
52
57
  */
@@ -194,11 +199,18 @@ class $Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOpt
194
199
  * @param options
195
200
  * @returns
196
201
  */
197
- static isAllowed$Ref<S extends object = JSONSchema>(value: unknown, options?: ParserOptions<S>) {
202
+ static isAllowed$Ref<S extends object = JSONSchema>(
203
+ value: unknown,
204
+ options?: ParserOptions<S>,
205
+ allowPlainNameFragments = false,
206
+ ) {
198
207
  if (this.is$Ref(value)) {
199
208
  if (value.$ref.substring(0, 2) === "#/" || value.$ref === "#") {
200
209
  // It's a JSON Pointer reference, which is always allowed
201
210
  return true;
211
+ } else if (allowPlainNameFragments && value.$ref[0] === "#") {
212
+ // JSON Schema 2019-09+ allows plain-name fragments declared via $anchor/$dynamicAnchor
213
+ return true;
202
214
  } else if (value.$ref[0] !== "#" && (!options || options.resolve?.external)) {
203
215
  // It's an external reference, which is allowed by the options
204
216
  return true;
@@ -281,7 +293,12 @@ class $Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOpt
281
293
  $ref: $Ref<S, O>,
282
294
  resolvedValue: S,
283
295
  options?: O,
296
+ useSpecCompliantRefSiblings = false,
284
297
  ): S {
298
+ if ($Ref.isExtended$Ref($ref) && useSpecCompliantRefSiblings) {
299
+ return preserveRefSiblings($ref, resolvedValue) as S;
300
+ }
301
+
285
302
  if (resolvedValue && typeof resolvedValue === "object" && $Ref.isExtended$Ref($ref)) {
286
303
  const merged = {} as Partial<S>;
287
304
  for (const key of Object.keys($ref)) {
@@ -320,6 +337,27 @@ class $Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOpt
320
337
  }
321
338
  }
322
339
 
340
+ function preserveRefSiblings<T>(refValue: Record<string, any>, resolvedValue: T): T {
341
+ const preserved = {} as Record<string, any>;
342
+ const existingAllOf = "allOf" in refValue ? refValue.allOf : undefined;
343
+
344
+ for (const key of Object.keys(refValue)) {
345
+ if (key !== "$ref" && key !== "allOf") {
346
+ preserved[key] = refValue[key];
347
+ }
348
+ }
349
+
350
+ const allOf = [resolvedValue];
351
+ if (Array.isArray(existingAllOf)) {
352
+ allOf.push(...existingAllOf);
353
+ } else if (existingAllOf !== undefined) {
354
+ allOf.push(existingAllOf);
355
+ }
356
+
357
+ preserved.allOf = allOf;
358
+ return preserved as T;
359
+ }
360
+
323
361
  function deepMerge<T>(target: Partial<T>, source: Partial<T>): T {
324
362
  //return {...target, ...source};
325
363
 
package/lib/refs.ts CHANGED
@@ -95,11 +95,10 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
95
95
  */
96
96
  set(path: string, value: JSONSchema4Type | JSONSchema6Type | JSONSchema7Type) {
97
97
  const absPath = url.resolve(this._root$Ref.path!, path);
98
- const withoutHash = url.stripHash(absPath);
99
- const $ref = this._$refs[withoutHash];
98
+ const $ref = this._getRef(absPath);
100
99
 
101
100
  if (!$ref) {
102
- throw new Error(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
101
+ throw new Error(`Error resolving $ref pointer "${path}". \n"${url.stripHash(absPath)}" not found.`);
103
102
  }
104
103
 
105
104
  $ref.set(absPath, value);
@@ -113,8 +112,7 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
113
112
  */
114
113
  _get$Ref(path: string) {
115
114
  path = url.resolve(this._root$Ref.path!, path);
116
- const withoutHash = url.stripHash(path);
117
- return this._$refs[withoutHash];
115
+ return this._getRef(this._exactAliases[path] || path);
118
116
  }
119
117
 
120
118
  /**
@@ -134,6 +132,32 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
134
132
  return $ref;
135
133
  }
136
134
 
135
+ _addAlias(path: string, value: S, pathType?: string | unknown, dynamicIdScope = false) {
136
+ const withoutHash = url.stripHash(path);
137
+
138
+ if (!withoutHash || this._$refs[withoutHash] || this._aliases[withoutHash]) {
139
+ return this._$refs[withoutHash] || this._aliases[withoutHash];
140
+ }
141
+
142
+ const $ref = new $Ref<S, O>(this);
143
+ $ref.path = withoutHash;
144
+ $ref.pathType = pathType;
145
+ $ref.value = value;
146
+ $ref.dynamicIdScope = dynamicIdScope;
147
+
148
+ this._aliases[withoutHash] = $ref;
149
+ return $ref;
150
+ }
151
+
152
+ _addExactAlias(path: string, targetPath: string) {
153
+ if (!path || this._exactAliases[path]) {
154
+ return this._exactAliases[path];
155
+ }
156
+
157
+ this._exactAliases[path] = targetPath;
158
+ return targetPath;
159
+ }
160
+
137
161
  /**
138
162
  * Resolves the given JSON reference.
139
163
  *
@@ -145,14 +169,14 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
145
169
  */
146
170
  _resolve(path: string, pathFromRoot: string, options?: O) {
147
171
  const absPath = url.resolve(this._root$Ref.path!, path);
148
- const withoutHash = url.stripHash(absPath);
149
- const $ref = this._$refs[withoutHash];
172
+ const canonicalPath = this._exactAliases[absPath] || absPath;
173
+ const $ref = this._getRef(canonicalPath);
150
174
 
151
175
  if (!$ref) {
152
- throw new Error(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
176
+ throw new Error(`Error resolving $ref pointer "${path}". \n"${url.stripHash(absPath)}" not found.`);
153
177
  }
154
178
 
155
- return $ref.resolve(absPath, options, path, pathFromRoot);
179
+ return $ref.resolve(canonicalPath, options, path, pathFromRoot);
156
180
  }
157
181
 
158
182
  /**
@@ -163,6 +187,10 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
163
187
  */
164
188
  _$refs: $RefsMap<S, O> = {};
165
189
 
190
+ _aliases: $RefsMap<S, O> = {};
191
+
192
+ _exactAliases: Record<string, string> = {};
193
+
166
194
  /**
167
195
  * The {@link $Ref} object that is the root of the JSON schema.
168
196
  *
@@ -180,6 +208,8 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
180
208
  this.circular = false;
181
209
 
182
210
  this._$refs = {};
211
+ this._aliases = {};
212
+ this._exactAliases = {};
183
213
 
184
214
  // @ts-ignore
185
215
  this._root$Ref = null;
@@ -205,6 +235,11 @@ export default class $Refs<S extends object = JSONSchema, O extends ParserOption
205
235
  * @returns {object}
206
236
  */
207
237
  toJSON = this.values;
238
+
239
+ private _getRef(path: string) {
240
+ const withoutHash = url.stripHash(path);
241
+ return this._$refs[withoutHash] || this._aliases[withoutHash];
242
+ }
208
243
  }
209
244
 
210
245
  /**
@@ -3,6 +3,7 @@ import Pointer from "./pointer.js";
3
3
  import parse from "./parse.js";
4
4
  import * as url from "./util/url.js";
5
5
  import { isHandledError } from "./util/errors.js";
6
+ import { getSchemaBasePath } from "./util/schema-resources.js";
6
7
  import type $Refs from "./refs.js";
7
8
  import type { ParserOptions } from "./options.js";
8
9
  import type { JSONSchema } from "./types/index.js";
@@ -29,7 +30,14 @@ function resolveExternal<S extends object = JSONSchema, O extends ParserOptions<
29
30
 
30
31
  try {
31
32
  // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
32
- const promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
33
+ const promises = crawl(
34
+ parser.schema,
35
+ parser.$refs._root$Ref.path + "#",
36
+ parser.$refs._root$Ref.path!,
37
+ parser.$refs._root$Ref.dynamicIdScope,
38
+ parser.$refs,
39
+ options,
40
+ );
33
41
  return Promise.all(promises);
34
42
  } catch (e) {
35
43
  return Promise.reject(e);
@@ -55,6 +63,8 @@ function resolveExternal<S extends object = JSONSchema, O extends ParserOptions<
55
63
  function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
56
64
  obj: string | Buffer | S | undefined | null,
57
65
  path: string,
66
+ scopeBase: string,
67
+ dynamicIdScope: boolean,
58
68
  $refs: $Refs<S, O>,
59
69
  options: O,
60
70
  seen?: Set<any>,
@@ -65,15 +75,18 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
65
75
 
66
76
  if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
67
77
  seen.add(obj); // Track previously seen objects to avoid infinite recursion
78
+ const currentScopeBase = dynamicIdScope ? getSchemaBasePath(scopeBase, obj) : scopeBase;
68
79
  if ($Ref.isExternal$Ref(obj)) {
69
- promises.push(resolve$Ref<S, O>(obj, path, $refs, options));
80
+ promises.push(resolve$Ref<S, O>(obj, path, currentScopeBase, dynamicIdScope, $refs, options));
70
81
  }
71
82
 
72
83
  const keys = Object.keys(obj) as string[];
73
84
  for (const key of keys) {
74
85
  const keyPath = Pointer.join(path, key);
75
86
  const value = obj[key as keyof typeof obj] as string | JSONSchema | Buffer | undefined;
76
- promises = promises.concat(crawl(value, keyPath, $refs, options, seen, external));
87
+ const childScopeBase =
88
+ dynamicIdScope && $Ref.isExternal$Ref(value) ? getSchemaBasePath(currentScopeBase, value) : currentScopeBase;
89
+ promises = promises.concat(crawl(value, keyPath, childScopeBase, dynamicIdScope, $refs, options, seen, external));
77
90
  }
78
91
  }
79
92
 
@@ -95,17 +108,20 @@ function crawl<S extends object = JSONSchema, O extends ParserOptions<S> = Parse
95
108
  async function resolve$Ref<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
96
109
  $ref: S,
97
110
  path: string,
111
+ scopeBase: string,
112
+ dynamicIdScope: boolean,
98
113
  $refs: $Refs<S, O>,
99
114
  options: O,
100
115
  ) {
101
116
  const shouldResolveOnCwd = options.dereference?.externalReferenceResolution === "root";
102
- const resolvedPath = url.resolve(shouldResolveOnCwd ? url.cwd() : path, ($ref as JSONSchema).$ref!);
117
+ const resolutionBase = shouldResolveOnCwd ? url.cwd() : dynamicIdScope ? scopeBase : path;
118
+ const resolvedPath = url.resolve(resolutionBase, ($ref as JSONSchema).$ref!);
103
119
  const withoutHash = url.stripHash(resolvedPath);
104
120
 
105
121
  // $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);
106
122
 
107
123
  // Do we already have this $ref?
108
- const ref = $refs._$refs[withoutHash];
124
+ const ref = $refs._get$Ref(withoutHash);
109
125
  if (ref) {
110
126
  // We've already parsed this $ref, so use the existing value
111
127
  return Promise.resolve(ref.value);
@@ -113,11 +129,33 @@ async function resolve$Ref<S extends object = JSONSchema, O extends ParserOption
113
129
 
114
130
  // Parse the $referenced file/url
115
131
  try {
116
- const result = await parse(resolvedPath, $refs, options);
132
+ const reference = ($ref as JSONSchema).$ref;
133
+ const parseTarget: { url: string; baseUrl: string; reference?: string } = {
134
+ url: resolvedPath,
135
+ baseUrl: resolutionBase,
136
+ };
137
+ if (typeof reference === "string") {
138
+ parseTarget.reference = reference;
139
+ }
140
+ const result = await parse(
141
+ parseTarget,
142
+ $refs,
143
+ options,
144
+ );
117
145
 
118
146
  // Crawl the parsed value
119
147
  // console.log('Resolving $ref pointers in %s', withoutHash);
120
- const promises = crawl(result, withoutHash + "#", $refs, options, new Set(), true);
148
+ const parsedRef = $refs._get$Ref(withoutHash);
149
+ const promises = crawl(
150
+ result,
151
+ withoutHash + "#",
152
+ withoutHash,
153
+ parsedRef?.dynamicIdScope ?? false,
154
+ $refs,
155
+ options,
156
+ new Set(),
157
+ true,
158
+ );
121
159
 
122
160
  return Promise.all(promises);
123
161
  } catch (err) {
@@ -139,6 +139,19 @@ export interface FileInfo {
139
139
  */
140
140
  url: string;
141
141
 
142
+ /**
143
+ * The unresolved `$ref` value exactly as it appeared in the parent schema, without the hash.
144
+ * This is useful for custom resolvers that need to preserve relative reference semantics instead
145
+ * of relying on the already-resolved `url`.
146
+ */
147
+ reference?: string;
148
+
149
+ /**
150
+ * The URL that `reference` was resolved against to produce `url`.
151
+ * This may include a JSON Pointer fragment when the reference originated from a nested location.
152
+ */
153
+ baseUrl?: string;
154
+
142
155
  /**
143
156
  * The hash (URL fragment) of the file URL, including the # symbol. If the URL doesn't have a hash, then this will be an empty string.
144
157
  */
@@ -0,0 +1,109 @@
1
+ import * as url from "./url.js";
2
+ import type { ParserOptions } from "../options.js";
3
+ import type { JSONSchema } from "../index.js";
4
+ import type $Refs from "../refs.js";
5
+
6
+ export function getSchemaBasePath(basePath: string, value: unknown) {
7
+ const schemaId = getSchemaId(value);
8
+ return schemaId ? url.resolve(basePath, schemaId) : basePath;
9
+ }
10
+
11
+ export function usesDynamicIdScope(value: unknown) {
12
+ if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) {
13
+ return false;
14
+ }
15
+
16
+ const schema = (value as { $schema?: unknown }).$schema;
17
+ if (
18
+ typeof schema === "string" &&
19
+ (schema.includes("draft/2019-09/") || schema.includes("draft/2020-12/") || schema.includes("oas/3.1/"))
20
+ ) {
21
+ return true;
22
+ }
23
+
24
+ const openapi = (value as { openapi?: unknown }).openapi;
25
+ return typeof openapi === "string" && /^3\.1(?:\.|$)/.test(openapi);
26
+ }
27
+
28
+ export function registerSchemaResources<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
29
+ $refs: $Refs<S, O>,
30
+ basePath: string,
31
+ value: unknown,
32
+ pathType?: string | unknown,
33
+ dynamicIdScope = false,
34
+ ) {
35
+ if (!dynamicIdScope) {
36
+ return;
37
+ }
38
+
39
+ const seen = new Set<object>();
40
+
41
+ const visit = (node: unknown, scopeBase: string, pointerTokens: string[]) => {
42
+ if (!node || typeof node !== "object" || ArrayBuffer.isView(node) || seen.has(node)) {
43
+ return;
44
+ }
45
+
46
+ seen.add(node);
47
+
48
+ const nextScopeBase = getSchemaBasePath(scopeBase, node);
49
+ const resourcePointerTokens = nextScopeBase === scopeBase ? pointerTokens : [];
50
+ if (nextScopeBase !== scopeBase) {
51
+ $refs._addAlias(nextScopeBase, node as S, pathType, dynamicIdScope);
52
+ }
53
+ registerAnchorAliases($refs, nextScopeBase, resourcePointerTokens, node);
54
+
55
+ for (const key of Object.keys(node)) {
56
+ visit((node as Record<string, unknown>)[key], nextScopeBase, [...resourcePointerTokens, key]);
57
+ }
58
+ };
59
+
60
+ visit(value, basePath, []);
61
+ }
62
+
63
+ function getSchemaId(value: unknown): string | undefined {
64
+ if (
65
+ value &&
66
+ typeof value === "object" &&
67
+ "$id" in value &&
68
+ typeof (value as { $id?: unknown }).$id === "string" &&
69
+ (value as { $id: string }).$id.length > 0
70
+ ) {
71
+ return (value as { $id: string }).$id;
72
+ }
73
+
74
+ return undefined;
75
+ }
76
+
77
+ function registerAnchorAliases<S extends object = JSONSchema, O extends ParserOptions<S> = ParserOptions<S>>(
78
+ $refs: $Refs<S, O>,
79
+ scopeBase: string,
80
+ pointerTokens: string[],
81
+ value: unknown,
82
+ ) {
83
+ if (!value || typeof value !== "object" || ArrayBuffer.isView(value)) {
84
+ return;
85
+ }
86
+
87
+ const resourceBase = url.stripHash(scopeBase);
88
+ const targetPath = pointerTokens.length > 0 ? joinPointerPath(resourceBase, pointerTokens) : `${resourceBase}#`;
89
+ const anchors = [
90
+ (value as { $anchor?: unknown }).$anchor,
91
+ (value as { $dynamicAnchor?: unknown }).$dynamicAnchor,
92
+ ];
93
+
94
+ for (const anchor of anchors) {
95
+ if (typeof anchor === "string" && anchor.length > 0) {
96
+ $refs._addExactAlias(`${resourceBase}#${anchor}`, targetPath);
97
+ }
98
+ }
99
+ }
100
+
101
+ function joinPointerPath(basePath: string, tokens: string[]) {
102
+ let path = `${basePath}#`;
103
+
104
+ for (const token of tokens) {
105
+ path += `/${token.replace(/~/g, "~0").replace(/\//g, "~1")}`;
106
+ }
107
+
108
+ return path;
109
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apidevtools/json-schema-ref-parser",
3
- "version": "15.3.1",
3
+ "version": "15.3.3",
4
4
  "description": "Parse, Resolve, and Dereference JSON Schema $ref pointers",
5
5
  "type": "module",
6
6
  "types": "dist/lib/index.d.ts",
@@ -75,29 +75,29 @@
75
75
  "js-yaml": "^4.1.1"
76
76
  },
77
77
  "devDependencies": {
78
- "@eslint/compat": "^2.0.2",
78
+ "@eslint/compat": "^2.0.3",
79
79
  "@eslint/js": "^10.0.1",
80
80
  "@types/eslint": "^9.6.1",
81
81
  "@types/js-yaml": "^4.0.9",
82
82
  "@types/json-schema": "^7.0.15",
83
83
  "@types/node": "^25",
84
- "@typescript-eslint/eslint-plugin": "^8.56.1",
85
- "@typescript-eslint/parser": "^8.56.1",
86
- "@vitest/coverage-v8": "^4.0.18",
84
+ "@typescript-eslint/eslint-plugin": "^8.57.2",
85
+ "@typescript-eslint/parser": "^8.57.2",
86
+ "@vitest/coverage-v8": "^4.1.1",
87
87
  "cross-env": "^10.1.0",
88
- "eslint": "^10.0.2",
88
+ "eslint": "^10.1.0",
89
89
  "eslint-config-prettier": "^10.1.8",
90
90
  "eslint-plugin-import": "^2.32.0",
91
91
  "eslint-plugin-prettier": "^5.5.5",
92
92
  "eslint-plugin-promise": "^7.2.1",
93
93
  "eslint-plugin-unused-imports": "^4.4.1",
94
- "globals": "^17.3.0",
95
- "jsdom": "^28.1.0",
94
+ "globals": "^17.4.0",
95
+ "jsdom": "^29.0.1",
96
96
  "prettier": "^3.8.1",
97
97
  "rimraf": "^6.1.3",
98
- "typescript": "^5.9.3",
99
- "typescript-eslint": "^8.56.1",
100
- "vitest": "^4.0.18"
98
+ "typescript": "^6.0.2",
99
+ "typescript-eslint": "^8.57.2",
100
+ "vitest": "^4.1.1"
101
101
  },
102
102
  "release": {
103
103
  "branches": [
@@ -110,5 +110,5 @@
110
110
  "@semantic-release/github"
111
111
  ]
112
112
  },
113
- "packageManager": "yarn@4.12.0"
113
+ "packageManager": "yarn@4.13.0"
114
114
  }