@amritk/resolve-refs 0.2.0 → 0.2.1

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.
@@ -1,9 +1,12 @@
1
1
  import type { JsonPath } from './types.js';
2
2
  /**
3
3
  * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
4
- * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
5
- * and coerces all-digit segments to numbers so array indices and object keys read
6
- * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
4
+ * `/`, splits on `/`, decodes each segment, and coerces canonical array-index
5
+ * tokens to numbers so indices and object keys read back the way a path consumer
6
+ * expects. Only RFC 6901 array indices (`0` or a non-zero-leading run of digits)
7
+ * are coerced; a numeric *object* key with a leading zero such as `"01"` is kept
8
+ * as a string, since coercing it would alias to a different key (`obj["01"]` is
9
+ * not `obj[1]`). A bare `''` or `'/'` is the empty path.
7
10
  */
8
11
  export declare const pointerToPath: (pointer: string) => JsonPath;
9
12
  /**
@@ -13,4 +16,3 @@ export declare const pointerToPath: (pointer: string) => JsonPath;
13
16
  * the path is missing or traverses a non-object.
14
17
  */
15
18
  export declare const getByPointer: (root: unknown, pointer: string) => unknown;
16
- //# sourceMappingURL=get-by-pointer.d.ts.map
@@ -1,8 +1,25 @@
1
+ /**
2
+ * Decodes a single JSON Pointer segment (RFC 6901): percent-decodes it, then
3
+ * unescapes `~1` → `/` and `~0` → `~`. Invalid percent-escapes are left as-is.
4
+ */
5
+ const decodeSegment = (segment) => {
6
+ let decoded = segment;
7
+ try {
8
+ decoded = decodeURIComponent(segment);
9
+ }
10
+ catch {
11
+ // leave invalid percent-escapes as-is
12
+ }
13
+ return decoded.replace(/~1/g, '/').replace(/~0/g, '~');
14
+ };
1
15
  /**
2
16
  * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
3
- * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
4
- * and coerces all-digit segments to numbers so array indices and object keys read
5
- * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
17
+ * `/`, splits on `/`, decodes each segment, and coerces canonical array-index
18
+ * tokens to numbers so indices and object keys read back the way a path consumer
19
+ * expects. Only RFC 6901 array indices (`0` or a non-zero-leading run of digits)
20
+ * are coerced; a numeric *object* key with a leading zero such as `"01"` is kept
21
+ * as a string, since coercing it would alias to a different key (`obj["01"]` is
22
+ * not `obj[1]`). A bare `''` or `'/'` is the empty path.
6
23
  */
7
24
  export const pointerToPath = (pointer) => {
8
25
  if (pointer === '' || pointer === '/')
@@ -11,15 +28,8 @@ export const pointerToPath = (pointer) => {
11
28
  .replace(/^\//, '')
12
29
  .split('/')
13
30
  .map((segment) => {
14
- let decoded = segment;
15
- try {
16
- decoded = decodeURIComponent(segment);
17
- }
18
- catch {
19
- // leave invalid percent-escapes as-is
20
- }
21
- decoded = decoded.replace(/~1/g, '/').replace(/~0/g, '~');
22
- return /^\d+$/.test(decoded) ? Number(decoded) : decoded;
31
+ const decoded = decodeSegment(segment);
32
+ return /^(0|[1-9]\d*)$/.test(decoded) ? Number(decoded) : decoded;
23
33
  });
24
34
  };
25
35
  /**
@@ -31,19 +41,7 @@ export const pointerToPath = (pointer) => {
31
41
  export const getByPointer = (root, pointer) => {
32
42
  if (pointer === '' || pointer === '/')
33
43
  return root;
34
- const segments = pointer
35
- .replace(/^\//, '')
36
- .split('/')
37
- .map((segment) => {
38
- let decoded = segment;
39
- try {
40
- decoded = decodeURIComponent(segment);
41
- }
42
- catch {
43
- // leave invalid percent-escapes as-is
44
- }
45
- return decoded.replace(/~1/g, '/').replace(/~0/g, '~');
46
- });
44
+ const segments = pointer.replace(/^\//, '').split('/').map(decodeSegment);
47
45
  let current = root;
48
46
  for (const segment of segments) {
49
47
  if (current === null || typeof current !== 'object')
package/dist/index.d.ts CHANGED
@@ -3,4 +3,3 @@ export { isPrivateHost } from './is-private-host.js';
3
3
  export { type ResolveRefsOptions, resolveRefs } from './resolve-refs.js';
4
4
  export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file.js';
5
5
  export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types.js';
6
- //# sourceMappingURL=index.d.ts.map
@@ -7,4 +7,3 @@
7
7
  * when resolving remote `$ref`s.
8
8
  */
9
9
  export declare const isPrivateHost: (hostname: string) => boolean;
10
- //# sourceMappingURL=is-private-host.d.ts.map
@@ -7,4 +7,3 @@ export declare const clearRemoteCache: () => void;
7
7
  * for the session; `options` governs whether/which remote hosts are allowed.
8
8
  */
9
9
  export declare const resolveRefsFromFile: (filename: string, options?: ResolveOptions) => Promise<ResolveResult>;
10
- //# sourceMappingURL=resolve-refs-from-file.d.ts.map
@@ -15,4 +15,3 @@ export type ResolveRefsOptions = {
15
15
  * an empty object so the result is always finite.
16
16
  */
17
17
  export declare const resolveRefs: (data: unknown, options?: ResolveRefsOptions) => ResolveResult;
18
- //# sourceMappingURL=resolve-refs.d.ts.map
package/dist/types.d.ts CHANGED
@@ -81,4 +81,3 @@ export type ResolveOptions = {
81
81
  */
82
82
  trackOrigins?: boolean;
83
83
  };
84
- //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Resolve and inline JSON Schema / OpenAPI $refs — internal, cross-file, and remote — with session caching and a default-deny SSRF guard.",
5
5
  "module": "./dist/index.js",
6
6
  "type": "module",
@@ -26,8 +26,7 @@
26
26
  "url": "https://github.com/amritk/mjst/issues"
27
27
  },
28
28
  "files": [
29
- "dist",
30
- "src"
29
+ "dist"
31
30
  ],
32
31
  "publishConfig": {
33
32
  "access": "public"
@@ -35,11 +34,11 @@
35
34
  "scripts": {
36
35
  "build": "tsgo -p tsconfig.build.json && tsc-alias -p tsconfig.build.json -f",
37
36
  "types:check": "tsgo -p . --noEmit",
38
- "test": "NODE_ENV=production vitest run --root ../.. resolve-refs"
37
+ "test": "NODE_ENV=production vitest run --root ../.. resolve-refs",
38
+ "bench": "bun run ./bench/run.ts"
39
39
  },
40
40
  "exports": {
41
41
  ".": {
42
- "development": "./src/index.ts",
43
42
  "default": "./dist/index.js",
44
43
  "types": "./dist/index.d.ts"
45
44
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"get-by-pointer.d.ts","sourceRoot":"","sources":["../src/get-by-pointer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAEvC;;;;;GAKG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,KAAG,QAe/C,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,SAAU,OAAO,WAAW,MAAM,KAAG,OAuB7D,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAC9D,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AACjD,OAAO,EAAE,KAAK,kBAAkB,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AACrE,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAChF,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"is-private-host.d.ts","sourceRoot":"","sources":["../src/is-private-host.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoDH,eAAO,MAAM,aAAa,aAAc,MAAM,KAAG,OA+BhD,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolve-refs-from-file.d.ts","sourceRoot":"","sources":["../src/resolve-refs-from-file.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAA2B,cAAc,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AA+CrF,iFAAiF;AACjF,eAAO,MAAM,gBAAgB,QAAO,IAEnC,CAAA;AAwND;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,aAAoB,MAAM,YAAW,cAAc,KAAQ,OAAO,CAAC,aAAa,CAY/G,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resolve-refs.d.ts","sourceRoot":"","sources":["../src/resolve-refs.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAa,aAAa,EAAE,MAAM,SAAS,CAAA;AAOvD,0CAA0C;AAC1C,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA;AA6CD;;;;GAIG;AACH,eAAO,MAAM,WAAW,SAAU,OAAO,YAAW,kBAAkB,KAAQ,aAI7E,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAAA;AAE1C,iFAAiF;AACjF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,QAAQ,CAAA;CACf,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG;IACnB,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,QAAQ,CAAA;CAClB,CAAA;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE3C,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG;IAC1B,kEAAkE;IAClE,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,YAAY,EAAE,CAAA;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,SAAS,CAAA;CACpB,CAAA;AAED,mEAAmE;AACnE,MAAM,MAAM,cAAc,GAAG;IAC3B;;OAEG;IACH,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAA;IACvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B;;;;;;;;;;;;;;;OAeG;IACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAA;IACtD;;;;;OAKG;IACH,YAAY,CAAC,EAAE,OAAO,CAAA;CACvB,CAAA"}
@@ -1,42 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
-
3
- import { getByPointer } from './get-by-pointer'
4
-
5
- describe('get-by-pointer', () => {
6
- const root = {
7
- info: { title: 'API' },
8
- paths: [{ get: { id: 1 } }, { post: { id: 2 } }],
9
- 'weird/key': true,
10
- 'tilde~key': false,
11
- }
12
-
13
- it('returns the root for an empty or bare-slash pointer', () => {
14
- expect(getByPointer(root, '')).toBe(root)
15
- expect(getByPointer(root, '/')).toBe(root)
16
- })
17
-
18
- it('navigates object keys', () => {
19
- expect(getByPointer(root, '/info/title')).toBe('API')
20
- })
21
-
22
- it('navigates array indices', () => {
23
- expect(getByPointer(root, '/paths/1/post/id')).toBe(2)
24
- })
25
-
26
- it('decodes ~1 and ~0 escapes', () => {
27
- expect(getByPointer(root, '/weird~1key')).toBe(true)
28
- expect(getByPointer(root, '/tilde~0key')).toBe(false)
29
- })
30
-
31
- it('percent-decodes URI-encoded segments', () => {
32
- const doc = { '{volume_id}': 'found', 'weird/key': true }
33
- expect(getByPointer(doc, '/%7Bvolume_id%7D')).toBe('found')
34
- // %2F in a segment must not be treated as a path separator
35
- expect(getByPointer(doc, '/weird%2Fkey')).toBe(true)
36
- })
37
-
38
- it('returns undefined when a segment is missing', () => {
39
- expect(getByPointer(root, '/info/nope')).toBeUndefined()
40
- expect(getByPointer(root, '/info/title/tooDeep')).toBeUndefined()
41
- })
42
- })
@@ -1,55 +0,0 @@
1
- import type { JsonPath } from './types'
2
-
3
- /**
4
- * Parses a JSON Pointer string (RFC 6901) into a path of keys: strips the leading
5
- * `/`, splits on `/`, decodes each segment (`%XX`, then `~1` → `/`, `~0` → `~`),
6
- * and coerces all-digit segments to numbers so array indices and object keys read
7
- * back the same way a path consumer expects. A bare `''` or `'/'` is the empty path.
8
- */
9
- export const pointerToPath = (pointer: string): JsonPath => {
10
- if (pointer === '' || pointer === '/') return []
11
- return pointer
12
- .replace(/^\//, '')
13
- .split('/')
14
- .map((segment) => {
15
- let decoded = segment
16
- try {
17
- decoded = decodeURIComponent(segment)
18
- } catch {
19
- // leave invalid percent-escapes as-is
20
- }
21
- decoded = decoded.replace(/~1/g, '/').replace(/~0/g, '~')
22
- return /^\d+$/.test(decoded) ? Number(decoded) : decoded
23
- })
24
- }
25
-
26
- /**
27
- * Walks a JSON Pointer string (RFC 6901) to the value it points to within
28
- * `root`. A bare `''` or `'/'` returns the root document. Segment escapes are
29
- * decoded (`~1` → `/`, `~0` → `~`). Returns `undefined` when any segment along
30
- * the path is missing or traverses a non-object.
31
- */
32
- export const getByPointer = (root: unknown, pointer: string): unknown => {
33
- if (pointer === '' || pointer === '/') return root
34
-
35
- const segments = pointer
36
- .replace(/^\//, '')
37
- .split('/')
38
- .map((segment) => {
39
- let decoded = segment
40
- try {
41
- decoded = decodeURIComponent(segment)
42
- } catch {
43
- // leave invalid percent-escapes as-is
44
- }
45
- return decoded.replace(/~1/g, '/').replace(/~0/g, '~')
46
- })
47
-
48
- let current: unknown = root
49
- for (const segment of segments) {
50
- if (current === null || typeof current !== 'object') return undefined
51
- const key = Array.isArray(current) ? Number(segment) : segment
52
- current = (current as Record<string, unknown>)[key]
53
- }
54
- return current
55
- }
package/src/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export { getByPointer, pointerToPath } from './get-by-pointer'
2
- export { isPrivateHost } from './is-private-host'
3
- export { type ResolveRefsOptions, resolveRefs } from './resolve-refs'
4
- export { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
5
- export type { JsonPath, Origin, OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types'
@@ -1,64 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
-
3
- import { isPrivateHost } from './is-private-host'
4
-
5
- describe('is-private-host', () => {
6
- it('treats localhost and its subdomains as private', () => {
7
- expect(isPrivateHost('localhost')).toBe(true)
8
- expect(isPrivateHost('api.localhost')).toBe(true)
9
- })
10
-
11
- it('flags loopback and RFC 1918 / CGNAT IPv4 ranges', () => {
12
- expect(isPrivateHost('127.0.0.1')).toBe(true)
13
- expect(isPrivateHost('10.1.2.3')).toBe(true)
14
- expect(isPrivateHost('172.16.0.1')).toBe(true)
15
- expect(isPrivateHost('172.31.255.255')).toBe(true)
16
- expect(isPrivateHost('192.168.0.1')).toBe(true)
17
- expect(isPrivateHost('100.64.0.1')).toBe(true)
18
- })
19
-
20
- it('flags the cloud-metadata link-local endpoint', () => {
21
- expect(isPrivateHost('169.254.169.254')).toBe(true)
22
- })
23
-
24
- it('flags private IPv6 (loopback, link-local, unique-local)', () => {
25
- expect(isPrivateHost('::1')).toBe(true)
26
- expect(isPrivateHost('[::1]')).toBe(true)
27
- expect(isPrivateHost('fe80::1')).toBe(true)
28
- expect(isPrivateHost('fd00::1')).toBe(true)
29
- })
30
-
31
- it('flags the full fe80::/10 link-local range, not just fe80', () => {
32
- expect(isPrivateHost('fe9a::1')).toBe(true)
33
- expect(isPrivateHost('feba::1')).toBe(true)
34
- expect(isPrivateHost('febf::1')).toBe(true)
35
- // fec0:: is outside fe80::/10 (third nibble c), so it is not link-local.
36
- expect(isPrivateHost('fec0::1')).toBe(false)
37
- })
38
-
39
- it('flags IPv4-mapped IPv6 loopback in both dotted and hex form', () => {
40
- expect(isPrivateHost('::ffff:127.0.0.1')).toBe(true)
41
- // The form `new URL()` produces for ::ffff:127.0.0.1.
42
- expect(isPrivateHost('::ffff:7f00:1')).toBe(true)
43
- // ::ffff:169.254.169.254 (cloud metadata) → hex a9fe:a9fe.
44
- expect(isPrivateHost('::ffff:a9fe:a9fe')).toBe(true)
45
- // A mapped public address stays public.
46
- expect(isPrivateHost('::ffff:8.8.8.8')).toBe(false)
47
- })
48
-
49
- it('flags decimal/octal/hex IPv4 encodings (defense-in-depth)', () => {
50
- expect(isPrivateHost('2130706433')).toBe(true) // 127.0.0.1
51
- expect(isPrivateHost('0177.0.0.1')).toBe(true)
52
- expect(isPrivateHost('0x7f000001')).toBe(true)
53
- expect(isPrivateHost('127.1')).toBe(true)
54
- })
55
-
56
- it('allows public hosts', () => {
57
- expect(isPrivateHost('example.com')).toBe(false)
58
- expect(isPrivateHost('8.8.8.8')).toBe(false)
59
- expect(isPrivateHost('172.32.0.1')).toBe(false)
60
- // Hostnames made only of hex letters must not be mistaken for IPs.
61
- expect(isPrivateHost('cafe')).toBe(false)
62
- expect(isPrivateHost('dead.beef')).toBe(false)
63
- })
64
- })
@@ -1,91 +0,0 @@
1
- /**
2
- * Best-effort check for a hostname that resolves to a non-public address —
3
- * loopback, private (RFC 1918 / ULA), link-local (incl. the `169.254.169.254`
4
- * cloud-metadata endpoint), or otherwise host-local. This is a syntactic guard
5
- * on the URL only; it does not perform DNS, so a public name that resolves to a
6
- * private IP is not caught here. It exists to stop the obvious SSRF footguns
7
- * when resolving remote `$ref`s.
8
- */
9
-
10
- /** True for an IPv4 address (given its first two octets) in a non-public range. */
11
- const isPrivateIpv4 = (a: number, b: number): boolean => {
12
- if (a === 10 || a === 127 || a === 0) return true
13
- if (a === 169 && b === 254) return true // link-local + cloud metadata
14
- if (a === 172 && b >= 16 && b <= 31) return true
15
- if (a === 192 && b === 168) return true
16
- if (a === 100 && b >= 64 && b <= 127) return true // CGNAT
17
- return false
18
- }
19
-
20
- /** Parses a single IPv4 part in decimal, octal (`0…`), or hex (`0x…`) form. */
21
- const parseIpv4Part = (s: string): number | null => {
22
- if (/^0x[0-9a-f]+$/i.test(s)) return Number.parseInt(s, 16)
23
- if (/^0[0-7]*$/.test(s)) return Number.parseInt(s, 8)
24
- if (/^[1-9][0-9]*$/.test(s)) return Number.parseInt(s, 10)
25
- return null
26
- }
27
-
28
- /**
29
- * Resolves the first two octets of an IPv4 host written in any inet_aton form
30
- * (dotted/decimal/octal/hex, 1–4 parts), or `null` if it is not an IPv4 literal.
31
- * The WHATWG URL parser normalizes these to dotted-decimal before they reach us,
32
- * but a direct caller (this is an exported guard) can pass the raw form.
33
- */
34
- const ipv4Octets = (host: string): [number, number] | null => {
35
- if (!/^[0-9a-fx.]+$/i.test(host)) return null
36
- const parts = host.split('.')
37
- if (parts.length === 0 || parts.length > 4) return null
38
- const nums: number[] = []
39
- for (const part of parts) {
40
- const n = parseIpv4Part(part)
41
- if (n === null) return null
42
- nums.push(n)
43
- }
44
- // inet_aton packing: every part but the last is one byte; the last fills the
45
- // remaining low bytes (so `127.1` is 127.0.0.1 and `2130706433` is too).
46
- let value = 0
47
- for (let i = 0; i < nums.length - 1; i++) {
48
- const byte = nums[i] as number
49
- if (byte > 0xff) return null
50
- value = value * 256 + byte
51
- }
52
- const remaining = 4 - (nums.length - 1)
53
- const last = nums[nums.length - 1] as number
54
- if (last > 256 ** remaining - 1) return null
55
- value = value * 256 ** remaining + last
56
- if (value > 0xffffffff) return null
57
- return [(value >>> 24) & 0xff, (value >>> 16) & 0xff]
58
- }
59
-
60
- export const isPrivateHost = (hostname: string): boolean => {
61
- const host = hostname.replace(/^\[|\]$/g, '').toLowerCase()
62
- if (host === 'localhost' || host.endsWith('.localhost')) return true
63
-
64
- if (host.includes(':')) {
65
- // --- IPv6 (and IPv4-mapped IPv6) ---
66
- if (host === '::1' || host === '::') return true
67
- // fe80::/10 link-local spans fe80–febf (third nibble 8–b).
68
- if (/^fe[89ab][0-9a-f]:/.test(host)) return true
69
- if (host.startsWith('fc') || host.startsWith('fd')) return true // fc00::/7 unique-local
70
-
71
- // IPv4-mapped/compatible, dotted (`::ffff:127.0.0.1`) — the URL parser
72
- // rewrites this to hex, but a direct caller may pass the dotted form.
73
- const dotted = /:((?:\d{1,3}\.){3}\d{1,3})$/.exec(host)
74
- if (dotted?.[1]) {
75
- const oct = ipv4Octets(dotted[1])
76
- if (oct) return isPrivateIpv4(oct[0], oct[1])
77
- }
78
- // IPv4-mapped, hex (`::ffff:7f00:1`) — what `new URL()` produces.
79
- const hex = /:ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(host)
80
- if (hex?.[1] && hex[2]) {
81
- const hi = Number.parseInt(hex[1], 16)
82
- return isPrivateIpv4((hi >> 8) & 0xff, hi & 0xff)
83
- }
84
- return false
85
- }
86
-
87
- // --- IPv4 (any inet_aton encoding) ---
88
- const oct = ipv4Octets(host)
89
- if (oct) return isPrivateIpv4(oct[0], oct[1])
90
- return false
91
- }
@@ -1,246 +0,0 @@
1
- import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
2
- import { tmpdir } from 'node:os'
3
- import { join } from 'node:path'
4
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
-
6
- import { clearRemoteCache, resolveRefsFromFile } from './resolve-refs-from-file'
7
-
8
- describe('resolve-refs-from-file', () => {
9
- let dir: string
10
-
11
- beforeEach(() => {
12
- dir = mkdtempSync(join(tmpdir(), 'resolve-refs-'))
13
- clearRemoteCache()
14
- })
15
-
16
- afterEach(() => {
17
- rmSync(dir, { recursive: true, force: true })
18
- vi.restoreAllMocks()
19
- })
20
-
21
- it('inlines a cross-file $ref between local documents', async () => {
22
- writeFileSync(
23
- join(dir, 'pet.json'),
24
- JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }),
25
- )
26
- writeFileSync(
27
- join(dir, 'api.json'),
28
- JSON.stringify({ components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } } }),
29
- )
30
-
31
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
32
-
33
- expect(errors).toEqual([])
34
- expect(resolved).toMatchObject({
35
- components: { schemas: { Pet: { type: 'object', properties: { name: { type: 'string' } } } } },
36
- })
37
- })
38
-
39
- it('inlines an internal $ref within a single document', async () => {
40
- writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
41
-
42
- const { resolved } = await resolveRefsFromFile(join(dir, 'root.json'))
43
-
44
- expect(resolved).toMatchObject({ a: { value: 1 }, b: { value: 1 } })
45
- })
46
-
47
- it('omits the origin map unless trackOrigins is set', async () => {
48
- writeFileSync(join(dir, 'root.json'), JSON.stringify({ a: { $ref: '#/b' }, b: { value: 1 } }))
49
-
50
- const result = await resolveRefsFromFile(join(dir, 'root.json'))
51
-
52
- expect(result.origins).toBeUndefined()
53
- })
54
-
55
- it('stamps inlined nodes with their origin document and in-file path', async () => {
56
- const petPath = join(dir, 'pet.json')
57
- const apiPath = join(dir, 'api.json')
58
- writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object', properties: { name: { type: 'string' } } } }))
59
- writeFileSync(
60
- apiPath,
61
- JSON.stringify({
62
- components: { schemas: { Pet: { $ref: './pet.json#/Pet' }, Pet2: { $ref: './pet.json#/Pet' } } },
63
- widget: { type: 'object' },
64
- useWidget: { $ref: '#/widget' },
65
- }),
66
- )
67
-
68
- const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
69
- expect(origins).toBeDefined()
70
- const tree = resolved as {
71
- components: { schemas: { Pet: object; Pet2: object } }
72
- useWidget: object
73
- }
74
-
75
- // The cross-file node is stamped with pet.json and its in-file path; both call
76
- // sites share the one inlined object, so the stamp identifies the definition.
77
- expect(tree.components.schemas.Pet).toBe(tree.components.schemas.Pet2)
78
- expect(origins?.get(tree.components.schemas.Pet)).toEqual({ location: petPath, pointer: ['Pet'] })
79
-
80
- // An internal ref is stamped against the root document at the target path.
81
- expect(origins?.get(tree.useWidget)).toEqual({ location: apiPath, pointer: ['widget'] })
82
- })
83
-
84
- it('keeps the definition origin when a node is reached through a chained ref (first-write-wins)', async () => {
85
- const petPath = join(dir, 'pet.json')
86
- const apiPath = join(dir, 'api.json')
87
- writeFileSync(petPath, JSON.stringify({ Pet: { type: 'object' } }))
88
- writeFileSync(
89
- apiPath,
90
- JSON.stringify({
91
- components: { schemas: { Pet: { $ref: './pet.json#/Pet' } } },
92
- // Resolves through the internal ref to the same pet.json object.
93
- alias: { $ref: '#/components/schemas/Pet' },
94
- }),
95
- )
96
-
97
- const { resolved, origins } = await resolveRefsFromFile(apiPath, { trackOrigins: true })
98
- const tree = resolved as { components: { schemas: { Pet: object } }; alias: object }
99
-
100
- // `alias` resolves through to the same object; its origin stays the pet.json
101
- // definition rather than the intermediate root-document pointer.
102
- expect(tree.alias).toBe(tree.components.schemas.Pet)
103
- expect(origins?.get(tree.alias)).toEqual({ location: petPath, pointer: ['Pet'] })
104
- })
105
-
106
- it('records an error and degrades to {} when a referenced file is missing', async () => {
107
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: './missing.json#/Nope' } }))
108
-
109
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
110
-
111
- // The missing document degrades to {}, so the pointer into it misses and the
112
- // ref resolves to undefined — the important part is that we recorded the
113
- // failure instead of throwing.
114
- expect((resolved as { x: unknown }).x).toBeUndefined()
115
- expect(errors.length).toBeGreaterThan(0)
116
- })
117
-
118
- it('refuses a remote $ref to a private host by default (SSRF guard)', async () => {
119
- const fetchSpy = vi.spyOn(globalThis, 'fetch')
120
- writeFileSync(
121
- join(dir, 'api.json'),
122
- JSON.stringify({ x: { $ref: 'http://169.254.169.254/latest/meta-data#/foo' } }),
123
- )
124
-
125
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'))
126
-
127
- // The refused document degrades to {}, so the pointer into it misses.
128
- expect((resolved as { x: unknown }).x).toBeUndefined()
129
- expect(errors[0]?.message).toMatch(/Refusing to resolve remote \$ref/)
130
- // The guard is syntactic — we never even attempt the request.
131
- expect(fetchSpy).not.toHaveBeenCalled()
132
- })
133
-
134
- it('refuses any remote $ref when remote resolution is disabled', async () => {
135
- const fetchSpy = vi.spyOn(globalThis, 'fetch')
136
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://example.com/s.json#/Foo' } }))
137
-
138
- const { errors } = await resolveRefsFromFile(join(dir, 'api.json'), { remote: false })
139
-
140
- expect(errors[0]?.message).toMatch(/remote \$ref resolution is disabled/)
141
- expect(fetchSpy).not.toHaveBeenCalled()
142
- })
143
-
144
- it('uses a custom parse callback to load non-JSON (e.g. YAML) documents', async () => {
145
- // Real YAML that JSON.parse would reject — a custom callback handles it.
146
- writeFileSync(join(dir, 'contact.yaml'), 'type: object\nproperties:\n name:\n type: string\n')
147
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ contact: { $ref: './contact.yaml' } }))
148
-
149
- const parse = (content: string, location: string): unknown => {
150
- if (/\.ya?ml$/i.test(location)) return { type: 'object', properties: { name: { type: 'string' } } }
151
- return JSON.parse(content) as unknown
152
- }
153
-
154
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), { parse })
155
-
156
- expect(errors).toEqual([])
157
- expect(resolved).toMatchObject({ contact: { type: 'object', properties: { name: { type: 'string' } } } })
158
- })
159
-
160
- it('fetches an allow-listed remote $ref and caches it for the session', async () => {
161
- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
162
- new Response(JSON.stringify({ Foo: { type: 'string' } }), {
163
- status: 200,
164
- headers: { 'content-type': 'application/json' },
165
- }),
166
- )
167
- writeFileSync(
168
- join(dir, 'api.json'),
169
- JSON.stringify({
170
- a: { $ref: 'https://api.example.com/s.json#/Foo' },
171
- b: { $ref: 'https://api.example.com/s.json#/Foo' },
172
- }),
173
- )
174
-
175
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
176
- allowedHosts: ['api.example.com'],
177
- })
178
-
179
- expect(errors).toEqual([])
180
- expect(resolved).toMatchObject({ a: { type: 'string' }, b: { type: 'string' } })
181
- // Both refs hit the same document, which is fetched and cached exactly once.
182
- expect(fetchSpy).toHaveBeenCalledTimes(1)
183
- })
184
-
185
- it('refuses a redirect that lands on a private host (SSRF via redirect)', async () => {
186
- const fetchSpy = vi
187
- .spyOn(globalThis, 'fetch')
188
- .mockResolvedValue(
189
- new Response(null, { status: 302, headers: { location: 'http://169.254.169.254/latest/meta-data' } }),
190
- )
191
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
192
-
193
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
194
- allowedHosts: ['api.example.com'],
195
- })
196
-
197
- expect((resolved as { x: unknown }).x).toBeUndefined()
198
- expect(errors[0]?.message).toMatch(/refusing to follow redirect/i)
199
- // The initial host was allowed, so the first request happened — but the
200
- // redirect target was re-checked and refused before any second request.
201
- expect(fetchSpy).toHaveBeenCalledTimes(1)
202
- expect(fetchSpy).toHaveBeenCalledWith('https://api.example.com/s.json', { redirect: 'manual' })
203
- })
204
-
205
- it('follows a redirect to another allowed host', async () => {
206
- const fetchSpy = vi
207
- .spyOn(globalThis, 'fetch')
208
- .mockResolvedValueOnce(
209
- new Response(null, { status: 301, headers: { location: 'https://cdn.example.com/s.json' } }),
210
- )
211
- .mockResolvedValueOnce(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
212
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
213
-
214
- const { resolved, errors } = await resolveRefsFromFile(join(dir, 'api.json'), {
215
- allowedHosts: ['api.example.com', 'cdn.example.com'],
216
- })
217
-
218
- expect(errors).toEqual([])
219
- expect(resolved).toMatchObject({ x: { type: 'string' } })
220
- expect(fetchSpy).toHaveBeenCalledTimes(2)
221
- })
222
-
223
- it('coalesces two concurrent resolves of the same remote URL into one fetch', async () => {
224
- let resolveFetch: ((r: Response) => void) | undefined
225
- const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(
226
- () =>
227
- new Promise<Response>((res) => {
228
- resolveFetch = res
229
- }),
230
- )
231
- writeFileSync(join(dir, 'api.json'), JSON.stringify({ x: { $ref: 'https://api.example.com/s.json#/Foo' } }))
232
-
233
- // Two passes start before either fetch settles — they must share one request.
234
- const pass1 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
235
- const pass2 = resolveRefsFromFile(join(dir, 'api.json'), { allowedHosts: ['api.example.com'] })
236
- await Promise.resolve()
237
- resolveFetch?.(new Response(JSON.stringify({ Foo: { type: 'string' } }), { status: 200 }))
238
-
239
- const [r1, r2] = await Promise.all([pass1, pass2])
240
- expect(r1.errors).toEqual([])
241
- expect(r2.errors).toEqual([])
242
- expect(r1.resolved).toMatchObject({ x: { type: 'string' } })
243
- expect(r2.resolved).toMatchObject({ x: { type: 'string' } })
244
- expect(fetchSpy).toHaveBeenCalledTimes(1)
245
- })
246
- })
@@ -1,289 +0,0 @@
1
- import { readFileSync } from 'node:fs'
2
- import { dirname, resolve as resolvePath } from 'node:path'
3
-
4
- import { getByPointer, pointerToPath } from './get-by-pointer'
5
- import { isPrivateHost } from './is-private-host'
6
- import type { OriginMap, ResolveError, ResolveOptions, ResolveResult } from './types'
7
-
8
- // A ref currently mid-resolution is marked with this sentinel; revisiting it
9
- // means a cycle, so we return `{}` instead of recursing forever.
10
- const CYCLE = Symbol('cycle')
11
- type CacheValue = unknown | typeof CYCLE
12
-
13
- // --- Document location helpers ---------------------------------------------
14
- //
15
- // A "location" is the absolute identity of a document: either an absolute file
16
- // path or an absolute http(s) URL. Refs are resolved relative to the location
17
- // of the document they appear in, so a relative ref inside a remote document
18
- // resolves to another remote URL, and one inside a local file to another path.
19
-
20
- const isRemote = (location: string): boolean => /^https?:\/\//i.test(location)
21
-
22
- /** Resolves the location of `ref` (its file/URL part) relative to `base`. */
23
- const joinLocation = (base: string, ref: string): string => {
24
- if (isRemote(ref)) return ref
25
- if (isRemote(base)) return new URL(ref, base).href
26
- return resolvePath(dirname(base), ref)
27
- }
28
-
29
- /** Splits a `$ref` into its document part and JSON-pointer part. */
30
- const splitRef = (ref: string): { filePart: string; pointer: string } => {
31
- const hashIdx = ref.indexOf('#')
32
- return {
33
- filePart: hashIdx === -1 ? ref : ref.slice(0, hashIdx),
34
- pointer: hashIdx === -1 ? '' : ref.slice(hashIdx + 1),
35
- }
36
- }
37
-
38
- // --- Remote document cache -------------------------------------------------
39
- //
40
- // Fetched remote documents are cached in memory for the lifetime of the
41
- // process ("the session"). Local files are intentionally NOT cached across
42
- // resolve passes — they can change on disk during a long-lived session (e.g.
43
- // an editor/LSP), so each pass re-reads them. Remote documents are assumed
44
- // stable for the session; call `clearRemoteCache()` to drop them.
45
-
46
- const remoteCache = new Map<string, unknown>()
47
-
48
- // In-flight remote loads, keyed by location. Two resolve passes that start at
49
- // the same time and reach the same URL share a single fetch instead of racing
50
- // two requests; whichever arrives first installs the promise, the rest await it.
51
- const inFlight = new Map<string, Promise<unknown>>()
52
-
53
- /** Drops every cached remote document. Mainly useful for tests/long sessions. */
54
- export const clearRemoteCache = (): void => {
55
- remoteCache.clear()
56
- }
57
-
58
- // Cap on redirect hops before we give up — generous enough for real services,
59
- // low enough to stop a redirect loop from spinning forever.
60
- const MAX_REDIRECTS = 5
61
-
62
- /**
63
- * Fetches and parses a remote document, following redirects manually so the
64
- * SSRF guard is re-applied to every hop. `fetch` follows redirects by default,
65
- * which would let an allow-listed public URL bounce to a private/loopback
66
- * address (e.g. the `169.254.169.254` metadata endpoint) — so we set
67
- * `redirect: 'manual'` and re-run {@link denialReason} on each `Location`.
68
- */
69
- const fetchRemote = async (location: string, options: ResolveOptions): Promise<unknown> => {
70
- let current = location
71
- for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
72
- const reason = denialReason(current, options)
73
- if (reason !== null) throw new Error(`refusing to follow redirect (${reason}): ${current}`)
74
-
75
- const response = await fetch(current, { redirect: 'manual' })
76
- if (response.status >= 300 && response.status < 400) {
77
- const next = response.headers.get('location')
78
- if (!next) throw new Error(`HTTP ${response.status} redirect with no Location header`)
79
- current = new URL(next, current).href
80
- continue
81
- }
82
- if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`)
83
-
84
- const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
85
- // Parse against the original request location so the caller's format sniffing
86
- // (e.g. `.yaml` vs `.json`) and any relative refs key off a stable identity.
87
- return parse(await response.text(), location)
88
- }
89
- throw new Error(`too many redirects (>${MAX_REDIRECTS}): ${location}`)
90
- }
91
-
92
- /** Returns why a remote location may not be fetched, or `null` if it is allowed. */
93
- const denialReason = (location: string, options: ResolveOptions): string | null => {
94
- if (options.remote === false) return 'remote $ref resolution is disabled'
95
-
96
- let url: URL
97
- try {
98
- url = new URL(location)
99
- } catch {
100
- return 'the URL is invalid'
101
- }
102
-
103
- const allow = options.allowedHosts
104
- // An explicit allow-list entry is an intentional opt-in and bypasses the
105
- // private-host guard; otherwise refuse non-public targets by default.
106
- if (allow && allow.length > 0) {
107
- return allow.includes(url.host) ? null : 'host is not in the allow-list'
108
- }
109
- if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
110
- return 'host resolves to a private or loopback address (set allowPrivateHosts to permit)'
111
- }
112
- return null
113
- }
114
-
115
- /**
116
- * Loads a document into `docCache`, fetching/reading it if needed. Remote
117
- * documents are additionally cached for the session in `remoteCache`. On
118
- * failure an error is recorded and the location is cached as `{}` so that
119
- * pointer lookups degrade gracefully instead of throwing. Returns whether the
120
- * document loaded successfully.
121
- */
122
- const loadDoc = async (
123
- location: string,
124
- docCache: Map<string, unknown>,
125
- options: ResolveOptions,
126
- errors: ResolveError[],
127
- ): Promise<boolean> => {
128
- if (docCache.has(location)) return true
129
-
130
- if (isRemote(location)) {
131
- if (remoteCache.has(location)) {
132
- docCache.set(location, remoteCache.get(location))
133
- return true
134
- }
135
- const reason = denialReason(location, options)
136
- if (reason !== null) {
137
- errors.push({ message: `Refusing to resolve remote $ref (${reason}): ${location}`, path: [] })
138
- docCache.set(location, {})
139
- return false
140
- }
141
- // Coalesce concurrent loads of the same URL onto one in-flight request; the
142
- // owner (first caller) clears the slot once it settles.
143
- let pending = inFlight.get(location)
144
- const owner = pending === undefined
145
- if (pending === undefined) {
146
- pending = fetchRemote(location, options)
147
- inFlight.set(location, pending)
148
- }
149
- try {
150
- const doc = await pending
151
- remoteCache.set(location, doc)
152
- docCache.set(location, doc)
153
- return true
154
- } catch (err) {
155
- errors.push({ message: `Failed to fetch ${location}: ${String(err)}`, path: [] })
156
- docCache.set(location, {})
157
- return false
158
- } finally {
159
- if (owner) inFlight.delete(location)
160
- }
161
- }
162
-
163
- try {
164
- const parse = options.parse ?? ((c: string) => JSON.parse(c) as unknown)
165
- docCache.set(location, parse(readFileSync(location, 'utf8'), location))
166
- return true
167
- } catch (err) {
168
- errors.push({ message: String(err), path: [] })
169
- docCache.set(location, {})
170
- return false
171
- }
172
- }
173
-
174
- /** Collects the distinct document parts of every `$ref` directly under `node`. */
175
- const collectRefTargets = (node: unknown, out: Set<string>): Set<string> => {
176
- if (node === null || typeof node !== 'object') return out
177
- if (Array.isArray(node)) {
178
- for (const item of node) collectRefTargets(item, out)
179
- return out
180
- }
181
- const obj = node as Record<string, unknown>
182
- if (typeof obj['$ref'] === 'string') {
183
- // A `$ref` object's siblings are ignored on resolution, so we do not recurse
184
- // into them — mirroring resolveAt's behaviour.
185
- const { filePart } = splitRef(obj['$ref'])
186
- if (filePart !== '') out.add(filePart)
187
- return out
188
- }
189
- for (const key of Object.keys(obj)) collectRefTargets(obj[key], out)
190
- return out
191
- }
192
-
193
- /**
194
- * Walks every reachable document starting from `rootLocation`, loading each one
195
- * so the synchronous resolve pass can look them up. This is the only async part
196
- * of resolution: remote documents are fetched here (in dependency order) and
197
- * cached for the session.
198
- */
199
- const prefetch = async (
200
- rootLocation: string,
201
- docCache: Map<string, unknown>,
202
- options: ResolveOptions,
203
- errors: ResolveError[],
204
- ): Promise<void> => {
205
- const seen = new Set<string>([rootLocation])
206
- const queue: string[] = [rootLocation]
207
- while (queue.length > 0) {
208
- const location = queue.shift() as string
209
- for (const filePart of collectRefTargets(docCache.get(location), new Set())) {
210
- const target = joinLocation(location, filePart)
211
- if (seen.has(target)) continue
212
- seen.add(target)
213
- await loadDoc(target, docCache, options, errors)
214
- queue.push(target)
215
- }
216
- }
217
- }
218
-
219
- /**
220
- * Single-pass resolver that inlines internal and external (`$ref` to other
221
- * file/URL) references. Every reachable document has already been loaded into
222
- * `docCache` by `prefetch`, so this stays synchronous. Refs are resolved once
223
- * (`refCache`); the CYCLE sentinel short-circuits re-entrant resolution.
224
- *
225
- * `baseLocation` is the location of the document `node` belongs to, used to
226
- * resolve relative refs and `#/...` pointers within it.
227
- */
228
- const resolveAt = (
229
- node: unknown,
230
- baseLocation: string,
231
- docCache: Map<string, unknown>,
232
- refCache: Map<string, CacheValue>,
233
- origins: OriginMap | undefined,
234
- ): unknown => {
235
- if (node === null || typeof node !== 'object') return node
236
- if (Array.isArray(node)) {
237
- return node.map((item) => resolveAt(item, baseLocation, docCache, refCache, origins))
238
- }
239
- const obj = node as Record<string, unknown>
240
- if (typeof obj['$ref'] === 'string') {
241
- const { filePart, pointer } = splitRef(obj['$ref'])
242
- const targetLocation = filePart === '' ? baseLocation : joinLocation(baseLocation, filePart)
243
- const targetRoot = docCache.get(targetLocation) ?? {}
244
-
245
- const cacheKey = `${targetLocation}#${pointer}`
246
- if (refCache.has(cacheKey)) {
247
- const cached = refCache.get(cacheKey)
248
- return cached === CYCLE ? {} : cached
249
- }
250
- refCache.set(cacheKey, CYCLE)
251
- const target = pointer ? getByPointer(targetRoot, pointer) : targetRoot
252
- const resolved = resolveAt(target, targetLocation, docCache, refCache, origins)
253
- refCache.set(cacheKey, resolved)
254
- // Stamp the inlined node with where it was defined so a consumer can map a
255
- // resolved-tree node back to its source document/path. Only objects/arrays are
256
- // stamped (primitives can't key the map). First-write-wins: resolution recurses
257
- // to the deepest `$ref` before returning, so the *definition* site stamps first;
258
- // an outer ref that merely points (transitively) at the same object must not
259
- // overwrite it with an intermediate location.
260
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
261
- origins.set(resolved, { location: targetLocation, pointer: pointerToPath(pointer) })
262
- }
263
- return resolved
264
- }
265
- const result: Record<string, unknown> = {}
266
- for (const key of Object.keys(obj)) {
267
- result[key] = resolveAt(obj[key], baseLocation, docCache, refCache, origins)
268
- }
269
- return result
270
- }
271
-
272
- /**
273
- * Resolves `$ref`s in a document on disk (or at a URL), including cross-file
274
- * and remote refs. Remote documents are fetched on the fly and cached in memory
275
- * for the session; `options` governs whether/which remote hosts are allowed.
276
- */
277
- export const resolveRefsFromFile = async (filename: string, options: ResolveOptions = {}): Promise<ResolveResult> => {
278
- const rootLocation = isRemote(filename) ? filename : resolvePath(filename)
279
- const errors: ResolveError[] = []
280
- const docCache = new Map<string, unknown>()
281
-
282
- if (!(await loadDoc(rootLocation, docCache, options, errors))) {
283
- return { resolved: {}, errors }
284
- }
285
- await prefetch(rootLocation, docCache, options, errors)
286
- const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
287
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, docCache, new Map(), origins)
288
- return origins ? { resolved, errors, origins } : { resolved, errors }
289
- }
@@ -1,78 +0,0 @@
1
- import { describe, expect, it } from 'vitest'
2
-
3
- import { resolveRefs } from './resolve-refs'
4
-
5
- describe('resolve-refs', () => {
6
- it('inlines an internal $ref', () => {
7
- const { resolved, errors } = resolveRefs({
8
- type: 'object',
9
- properties: { contact: { $ref: '#/$defs/contact' } },
10
- $defs: { contact: { type: 'string' } },
11
- })
12
-
13
- expect(errors).toEqual([])
14
- expect(resolved).toMatchObject({ properties: { contact: { type: 'string' } } })
15
- })
16
-
17
- it('breaks a self-referential cycle with an empty object', () => {
18
- const { resolved } = resolveRefs({
19
- $defs: { node: { type: 'object', properties: { next: { $ref: '#/$defs/node' } } } },
20
- properties: { head: { $ref: '#/$defs/node' } },
21
- })
22
-
23
- const head = (resolved as { properties: { head: { properties: { next: unknown } } } }).properties.head
24
- // The first level resolves; the recursive self-reference terminates at `{}`.
25
- expect(head.properties.next).toEqual({})
26
- })
27
-
28
- it('breaks a mutual cycle (A → B → A) without infinite recursion', () => {
29
- const { resolved } = resolveRefs({
30
- $defs: {
31
- a: { type: 'object', properties: { b: { $ref: '#/$defs/b' } } },
32
- b: { type: 'object', properties: { a: { $ref: '#/$defs/a' } } },
33
- },
34
- properties: { root: { $ref: '#/$defs/a' } },
35
- })
36
-
37
- // Resolution terminates; `a` is in the cache by the time `properties.root` is
38
- // processed, so we get the partially-resolved shape where the back-reference
39
- // leg terminated at `{}` rather than looping forever.
40
- const root = (resolved as { properties: { root: { type: string; properties: { b: unknown } } } }).properties.root
41
- expect(root.type).toBe('object')
42
- expect(root.properties.b).toEqual({})
43
- })
44
-
45
- it('leaves external (non-#) refs untouched', () => {
46
- const { resolved } = resolveRefs({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
47
-
48
- expect(resolved).toEqual({ properties: { pet: { $ref: 'pet.json#/Pet' } } })
49
- })
50
-
51
- it('omits the origin map unless trackOrigins is set', () => {
52
- const result = resolveRefs({ a: { $ref: '#/$defs/x' }, $defs: { x: { type: 'string' } } })
53
- expect(result.origins).toBeUndefined()
54
- })
55
-
56
- it('stamps each inlined node with its in-document origin path', () => {
57
- const { resolved, origins } = resolveRefs(
58
- {
59
- properties: { a: { $ref: '#/$defs/x' }, b: { $ref: '#/$defs/x' } },
60
- $defs: { x: { type: 'object', properties: { id: { type: 'string' } } } },
61
- },
62
- { trackOrigins: true },
63
- )
64
- const tree = resolved as { properties: { a: object; b: object } }
65
- // Repeated refs share one object, stamped once with the definition path.
66
- expect(tree.properties.a).toBe(tree.properties.b)
67
- expect(origins?.get(tree.properties.a)).toEqual({ location: '', pointer: ['$defs', 'x'] })
68
- })
69
-
70
- it('decodes pointer escapes and array indices in origin paths', () => {
71
- const { resolved, origins } = resolveRefs(
72
- { ref: { $ref: '#/a~1b/c~0d/0' }, 'a/b': { 'c~d': [{ type: 'number' }] } },
73
- { trackOrigins: true },
74
- )
75
- const node = (resolved as { ref: object }).ref
76
- expect(origins?.get(node)).toEqual({ location: '', pointer: ['a/b', 'c~d', 0] })
77
- })
78
- })
@@ -1,72 +0,0 @@
1
- import { getByPointer, pointerToPath } from './get-by-pointer'
2
- import type { OriginMap, ResolveResult } from './types'
3
-
4
- // A ref currently mid-resolution is marked with this sentinel; revisiting it
5
- // means we have looped, so we return `{}` instead of recursing forever.
6
- const CYCLE = Symbol('cycle')
7
- type CacheValue = unknown | typeof CYCLE
8
-
9
- /** Options for the in-memory resolver. */
10
- export type ResolveRefsOptions = {
11
- /**
12
- * Record a per-node origin map on the result (`origins`). For every object or
13
- * array inlined in place of a `$ref`, the map records the in-document path it
14
- * was defined at (the `location` is `''`, the single in-memory document).
15
- * Defaults to `false`.
16
- */
17
- trackOrigins?: boolean
18
- }
19
-
20
- /**
21
- * Single-pass internal-only `$ref` resolver. Each unique ref string is resolved
22
- * exactly once (the `cache`); revisiting a ref that is still mid-resolution
23
- * means a cycle, so we return `{}` (the CYCLE sentinel). Non-`#` refs (external
24
- * files, HTTP) are left untouched — callers that need those should use
25
- * `resolveRefsFromFile`.
26
- */
27
- const resolveInternal = (
28
- node: unknown,
29
- root: unknown,
30
- cache: Map<string, CacheValue>,
31
- origins: OriginMap | undefined,
32
- ): unknown => {
33
- if (node === null || typeof node !== 'object') return node
34
- if (Array.isArray(node)) return node.map((item) => resolveInternal(item, root, cache, origins))
35
-
36
- const obj = node as Record<string, unknown>
37
- if (typeof obj['$ref'] === 'string') {
38
- const ref = obj['$ref']
39
- if (!ref.startsWith('#')) return obj // external ref — leave as-is
40
- if (cache.has(ref)) {
41
- const cached = cache.get(ref)
42
- return cached === CYCLE ? {} : cached
43
- }
44
- cache.set(ref, CYCLE)
45
- const resolved = resolveInternal(getByPointer(root, ref.slice(1)), root, cache, origins)
46
- cache.set(ref, resolved)
47
- // Stamp the inlined node with the path it was defined at (see resolveAt).
48
- // First-write-wins so the deepest definition stamps before any outer ref that
49
- // transitively points at the same object. Primitives can't key the map.
50
- if (origins && resolved !== null && typeof resolved === 'object' && !origins.has(resolved)) {
51
- origins.set(resolved, { location: '', pointer: pointerToPath(ref.slice(1)) })
52
- }
53
- return resolved
54
- }
55
-
56
- const result: Record<string, unknown> = {}
57
- for (const key of Object.keys(obj)) {
58
- result[key] = resolveInternal(obj[key], root, cache, origins)
59
- }
60
- return result
61
- }
62
-
63
- /**
64
- * Resolves all internal (`#/...`) `$ref`s in an in-memory document, inlining
65
- * each target. External and remote refs are left as-is. Cycles are broken with
66
- * an empty object so the result is always finite.
67
- */
68
- export const resolveRefs = (data: unknown, options: ResolveRefsOptions = {}): ResolveResult => {
69
- const origins: OriginMap | undefined = options.trackOrigins ? new Map() : undefined
70
- const resolved = resolveInternal(data, data, new Map(), origins)
71
- return origins ? { resolved, errors: [], origins } : { resolved, errors: [] }
72
- }
package/src/types.ts DELETED
@@ -1,88 +0,0 @@
1
- /**
2
- * A path into a JSON document: object keys and array indices, in order. Errors
3
- * report the location of the offending `$ref` with one of these.
4
- */
5
- export type JsonPath = (string | number)[]
6
-
7
- /** A single `$ref` resolution failure (a missing file, a bad URL, a refusal). */
8
- export type ResolveError = {
9
- message: string
10
- path: JsonPath
11
- }
12
-
13
- /**
14
- * Where an inlined node came from: the absolute location (file path or URL, or
15
- * `''` for the single in-memory document) of the document it was defined in, and
16
- * the path to it within that document.
17
- */
18
- export type Origin = {
19
- location: string
20
- pointer: JsonPath
21
- }
22
-
23
- /**
24
- * Per-node origin map produced when `trackOrigins` is set: maps each object/array
25
- * that was inlined in place of a `$ref` to where it was defined. A consumer can
26
- * then attribute a node in the resolved tree back to its source document and path
27
- * with a single lookup instead of re-deriving the `$ref` traversal. Keyed by node
28
- * identity, so it relies on the resolver sharing one object per repeated `$ref`
29
- * target (which it does).
30
- */
31
- export type OriginMap = Map<object, Origin>
32
-
33
- /** The outcome of a resolve pass: the dereferenced document plus any errors. */
34
- export type ResolveResult = {
35
- /** The dereferenced document (all resolvable `$ref`s inlined). */
36
- resolved: unknown
37
- errors: ResolveError[]
38
- /**
39
- * Per-node origin map. Present only when `trackOrigins` was requested; each
40
- * entry maps an inlined object/array to the document and path it came from.
41
- */
42
- origins?: OriginMap
43
- }
44
-
45
- /** Controls how external `$ref`s to other documents are loaded. */
46
- export type ResolveOptions = {
47
- /**
48
- * Whether http(s) `$ref`s may be fetched. Defaults to `true`.
49
- */
50
- remote?: boolean
51
- /**
52
- * If non-empty, only these hosts (e.g. `api.example.com`) may be fetched for
53
- * remote `$ref`s. An empty/undefined list allows any host (subject to
54
- * `remote`). An explicit entry here always bypasses the private-host guard.
55
- */
56
- allowedHosts?: string[]
57
- /**
58
- * Allow remote `$ref`s to loopback, private, link-local, and other
59
- * non-public addresses. Defaults to `false`: such hosts are refused as a
60
- * best-effort SSRF guard (notably the `169.254.169.254` cloud-metadata
61
- * endpoint). An explicit `allowedHosts` entry always bypasses this guard.
62
- */
63
- allowPrivateHosts?: boolean
64
- /**
65
- * Custom content parser. Receives the raw text of every loaded document and
66
- * its absolute location (file path or URL). Defaults to `JSON.parse`.
67
- *
68
- * Pass a YAML-aware function to support `.yaml`/`.yml` documents without
69
- * adding a dependency to this package:
70
- *
71
- * ```ts
72
- * import { parse as parseYaml } from 'yaml'
73
- *
74
- * resolveRefsFromFile(path, {
75
- * parse: (content, location) =>
76
- * /\.ya?ml$/i.test(location) ? parseYaml(content) : JSON.parse(content),
77
- * })
78
- * ```
79
- */
80
- parse?: (content: string, location: string) => unknown
81
- /**
82
- * Record a per-node origin map on the result (`origins`). For every object or
83
- * array inlined in place of a `$ref`, the map records the document and in-file
84
- * path it was defined at, so a consumer can attribute resolved-tree nodes back
85
- * to their source without re-walking the `$ref` chain. Defaults to `false`.
86
- */
87
- trackOrigins?: boolean
88
- }