@amritk/resolve-refs 0.4.5 → 0.7.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.
@@ -1,10 +1,19 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFileSync } from "node:fs";
2
- import { dirname, resolve as resolvePath } from "node:path";
3
+ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "node:path";
4
+ import { assertPublicHost } from "./assert-public-host.js";
5
+ import { childRole } from "./child-role.js";
6
+ import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
7
+ import { pointerToPath } from "./get-by-pointer.js";
8
+ import { isContainedPath } from "./is-contained-path.js";
3
9
  import { isPrivateHost } from "./is-private-host.js";
10
+ import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
4
11
  import { readReference, resolveFragment } from "./reference.js";
5
12
  import { baseOfNode, buildResourceRegistry, resolveRefInScope, SYNTHETIC_BASE } from "./resource-registry.js";
13
+ import { roleAtPath } from "./role-at-path.js";
6
14
  import { assignKey } from "./safe-assign.js";
7
15
  const CYCLE = /* @__PURE__ */ Symbol("cycle");
16
+ const MISSING = /* @__PURE__ */ Symbol("missing");
8
17
  const ANNOTATION_ONLY_SIBLINGS = /* @__PURE__ */ new Set(["summary", "description"]);
9
18
  const isRemote = (location) => /^https?:\/\//i.test(location);
10
19
  const joinLocation = (base, ref) => {
@@ -21,10 +30,43 @@ const splitRef = (ref) => {
21
30
  fragment: hashIdx === -1 ? "" : ref.slice(hashIdx + 1)
22
31
  };
23
32
  };
33
+ const REMOTE_CACHE_TTL_MS = 10 * 6e4;
34
+ const REMOTE_CACHE_MAX_ENTRIES = 256;
24
35
  const remoteCache = /* @__PURE__ */ new Map();
25
36
  const inFlight = /* @__PURE__ */ new Map();
26
- const clearRemoteCache = () => {
27
- remoteCache.clear();
37
+ const SCOPE_SEPARATOR = "\0";
38
+ const clearRemoteCache = (location) => {
39
+ if (location === void 0) {
40
+ remoteCache.clear();
41
+ return;
42
+ }
43
+ const suffix = `${SCOPE_SEPARATOR}${location}`;
44
+ for (const key of remoteCache.keys()) {
45
+ if (key.endsWith(suffix))
46
+ remoteCache.delete(key);
47
+ }
48
+ };
49
+ const readRemoteCache = (key) => {
50
+ const entry = remoteCache.get(key);
51
+ if (entry === void 0)
52
+ return void 0;
53
+ if (Date.now() >= entry.expiresAt) {
54
+ remoteCache.delete(key);
55
+ return void 0;
56
+ }
57
+ remoteCache.delete(key);
58
+ remoteCache.set(key, entry);
59
+ return entry;
60
+ };
61
+ const writeRemoteCache = (key, value) => {
62
+ remoteCache.delete(key);
63
+ remoteCache.set(key, { value, expiresAt: Date.now() + REMOTE_CACHE_TTL_MS });
64
+ while (remoteCache.size > REMOTE_CACHE_MAX_ENTRIES) {
65
+ const oldest = remoteCache.keys().next();
66
+ if (oldest.done)
67
+ break;
68
+ remoteCache.delete(oldest.value);
69
+ }
28
70
  };
29
71
  const MAX_REDIRECTS = 5;
30
72
  const FETCH_TIMEOUT_MS = 3e4;
@@ -53,7 +95,41 @@ const headersFor = (url, options) => {
53
95
  return void 0;
54
96
  return typeof options.headers === "function" ? options.headers(url) : options.headers;
55
97
  };
56
- const fetchRemote = async (location, options) => {
98
+ const callableIds = /* @__PURE__ */ new WeakMap();
99
+ let nextCallableId = 0;
100
+ const callableId = (fn) => {
101
+ if (typeof fn !== "function")
102
+ return "default";
103
+ let id = callableIds.get(fn);
104
+ if (id === void 0) {
105
+ id = `fn${++nextCallableId}`;
106
+ callableIds.set(fn, id);
107
+ }
108
+ return id;
109
+ };
110
+ const headersFingerprint = (headers) => {
111
+ if (headers === void 0)
112
+ return "none";
113
+ const entries = Object.entries(headers).map(([name, value]) => `${name.toLowerCase()}:${value}`).sort();
114
+ if (entries.length === 0)
115
+ return "none";
116
+ return createHash("sha256").update(entries.join("\n")).digest("hex").slice(0, 32);
117
+ };
118
+ const fetchScope = (location, options) => [
119
+ headersFingerprint(headersFor(location, options)),
120
+ callableId(options.fetch),
121
+ callableId(options.parse),
122
+ String(options.timeoutMs ?? FETCH_TIMEOUT_MS),
123
+ String(options.maxRedirects ?? MAX_REDIRECTS),
124
+ String(options.maxBytes ?? MAX_REMOTE_BYTES),
125
+ options.verifyDns === false ? "nodns" : "dns",
126
+ options.allowPrivateHosts === true ? "private" : "public",
127
+ // Sorted so two callers spelling the same allowlist in a different order
128
+ // still share a document.
129
+ [...options.allowedHosts ?? []].sort().join(",")
130
+ ].join("|");
131
+ const cacheKeyFor = (location, options) => `${fetchScope(location, options)}${SCOPE_SEPARATOR}${location}`;
132
+ const fetchRemote = async (location, options, deadline) => {
57
133
  const maxRedirects = options.maxRedirects ?? MAX_REDIRECTS;
58
134
  const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
59
135
  const maxBytes = options.maxBytes ?? MAX_REMOTE_BYTES;
@@ -64,11 +140,15 @@ const fetchRemote = async (location, options) => {
64
140
  const reason = denialReason(current, options);
65
141
  if (reason !== null)
66
142
  throw new Error(`refusing to follow redirect (${reason}): ${current}`);
143
+ if (needsDnsVerification(options))
144
+ await assertPublicHost(new URL(current).hostname);
67
145
  const headers = new URL(current).origin === origin ? headersFor(location, options) : void 0;
68
146
  const response = await doFetch(current, {
69
147
  redirect: "manual",
70
- // Cap the wait for a response so a stalling host can't hang resolution forever.
71
- signal: AbortSignal.timeout(timeoutMs),
148
+ // Cap the wait for a response so a stalling host can't hang resolution
149
+ // forever — and never past the whole resolve's deadline, so a chain of
150
+ // slow hops cannot outlive the caller's total budget.
151
+ signal: AbortSignal.timeout(Math.max(0, Math.min(timeoutMs, deadline - Date.now()))),
72
152
  ...headers !== void 0 ? { headers } : {}
73
153
  });
74
154
  if (response.status >= 300 && response.status < 400) {
@@ -85,6 +165,15 @@ const fetchRemote = async (location, options) => {
85
165
  }
86
166
  throw new Error(`too many redirects (>${maxRedirects}): ${location}`);
87
167
  };
168
+ const isAllowedHost = (url, allow) => {
169
+ const hostname = url.hostname.toLowerCase();
170
+ const port = url.port === "" ? url.protocol === "https:" ? "443" : "80" : url.port;
171
+ const withPort = `${hostname}:${port}`;
172
+ return allow.some((entry) => {
173
+ const candidate = entry.trim().toLowerCase();
174
+ return candidate === hostname || candidate === withPort;
175
+ });
176
+ };
88
177
  const denialReason = (location, options) => {
89
178
  if (options.remote === false)
90
179
  return "remote $ref resolution is disabled";
@@ -99,14 +188,23 @@ const denialReason = (location, options) => {
99
188
  }
100
189
  const allow = options.allowedHosts;
101
190
  if (allow && allow.length > 0) {
102
- return allow.includes(url.host) ? null : "host is not in the allow-list";
191
+ return isAllowedHost(url, allow) ? null : "host is not in the allow-list";
103
192
  }
104
193
  if (!options.allowPrivateHosts && isPrivateHost(url.hostname)) {
105
194
  return "host resolves to a private or loopback address (set allowPrivateHosts to permit)";
106
195
  }
107
196
  return null;
108
197
  };
109
- const loadDoc = async (location, docCache, options, errors) => {
198
+ const needsDnsVerification = (options) => {
199
+ if (options.verifyDns === false)
200
+ return false;
201
+ if (options.allowPrivateHosts)
202
+ return false;
203
+ if (options.allowedHosts && options.allowedHosts.length > 0)
204
+ return false;
205
+ return true;
206
+ };
207
+ const loadDoc = async (location, docCache, options, errors, deadline) => {
110
208
  if (docCache.has(location))
111
209
  return true;
112
210
  if (isRemote(location)) {
@@ -117,13 +215,17 @@ const loadDoc = async (location, docCache, options, errors) => {
117
215
  return false;
118
216
  }
119
217
  const useSessionCache = options.cache !== false;
120
- if (useSessionCache && remoteCache.has(location)) {
121
- docCache.set(location, remoteCache.get(location));
122
- return true;
218
+ const key = cacheKeyFor(location, options);
219
+ if (useSessionCache) {
220
+ const entry = readRemoteCache(key);
221
+ if (entry !== void 0) {
222
+ docCache.set(location, entry.value);
223
+ return true;
224
+ }
123
225
  }
124
226
  if (!useSessionCache) {
125
227
  try {
126
- const doc = await fetchRemote(location, options);
228
+ const doc = await fetchRemote(location, options, deadline);
127
229
  docCache.set(location, doc);
128
230
  return true;
129
231
  } catch (err) {
@@ -132,15 +234,15 @@ const loadDoc = async (location, docCache, options, errors) => {
132
234
  return false;
133
235
  }
134
236
  }
135
- let pending = inFlight.get(location);
237
+ let pending = inFlight.get(key);
136
238
  const owner = pending === void 0;
137
239
  if (pending === void 0) {
138
- pending = fetchRemote(location, options);
139
- inFlight.set(location, pending);
240
+ pending = fetchRemote(location, options, deadline);
241
+ inFlight.set(key, pending);
140
242
  }
141
243
  try {
142
244
  const doc = await pending;
143
- remoteCache.set(location, doc);
245
+ writeRemoteCache(key, doc);
144
246
  docCache.set(location, doc);
145
247
  return true;
146
248
  } catch (err) {
@@ -149,7 +251,7 @@ const loadDoc = async (location, docCache, options, errors) => {
149
251
  return false;
150
252
  } finally {
151
253
  if (owner)
152
- inFlight.delete(location);
254
+ inFlight.delete(key);
153
255
  }
154
256
  }
155
257
  try {
@@ -162,7 +264,126 @@ const loadDoc = async (location, docCache, options, errors) => {
162
264
  return false;
163
265
  }
164
266
  };
165
- const escapeSegment = (segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1");
267
+ const escapeSegment = (segment) => segment.replace(/~/g, "~0").replace(/\//g, "~1").replace(/%/g, "%25");
268
+ const detach = (node) => {
269
+ if (node === null || typeof node !== "object")
270
+ return node;
271
+ const seen = /* @__PURE__ */ new Map();
272
+ const out = { value: void 0 };
273
+ const stack = [
274
+ {
275
+ src: node,
276
+ set: (value) => {
277
+ out.value = value;
278
+ }
279
+ }
280
+ ];
281
+ while (stack.length > 0) {
282
+ const frame = stack.pop();
283
+ if (frame === void 0)
284
+ break;
285
+ const { src, set } = frame;
286
+ if (src === null || typeof src !== "object") {
287
+ set(src);
288
+ continue;
289
+ }
290
+ const already = seen.get(src);
291
+ if (already !== void 0) {
292
+ set(already);
293
+ continue;
294
+ }
295
+ if (Array.isArray(src)) {
296
+ const copy2 = new Array(src.length);
297
+ seen.set(src, copy2);
298
+ set(copy2);
299
+ for (let index = src.length - 1; index >= 0; index--) {
300
+ const at = index;
301
+ stack.push({
302
+ src: src[at],
303
+ set: (value) => {
304
+ copy2[at] = value;
305
+ }
306
+ });
307
+ }
308
+ continue;
309
+ }
310
+ const prototype = Object.getPrototypeOf(src);
311
+ if (prototype !== Object.prototype && prototype !== null) {
312
+ const kept = src instanceof Date ? new Date(src.getTime()) : src;
313
+ seen.set(src, kept);
314
+ set(kept);
315
+ continue;
316
+ }
317
+ const copy = {};
318
+ seen.set(src, copy);
319
+ set(copy);
320
+ const keys = Object.keys(src);
321
+ for (let index = keys.length - 1; index >= 0; index--) {
322
+ const key = keys[index];
323
+ stack.push({
324
+ src: src[key],
325
+ set: (value) => assignKey(copy, key, value)
326
+ });
327
+ }
328
+ }
329
+ return out.value;
330
+ };
331
+ const rebaseKeptRef = (value, from, root) => {
332
+ if (from === root)
333
+ return value;
334
+ const { filePart, fragment } = splitRef(value);
335
+ if (filePart === "")
336
+ return `${renderLocation(from, root)}${value}`;
337
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]+:/.test(filePart))
338
+ return value;
339
+ const target = joinLocation(from, filePart);
340
+ const suffix = value.includes("#") ? `#${fragment}` : "";
341
+ return `${renderLocation(target, root)}${suffix}`;
342
+ };
343
+ const renderLocation = (target, root) => {
344
+ if (isRemote(target) || isRemote(root))
345
+ return target;
346
+ const relative = relativePath(dirname(root), target).split(sep).join("/");
347
+ return relative.startsWith(".") ? relative : `./${relative}`;
348
+ };
349
+ const rebaseKeptRefs = (node, from, root, role) => {
350
+ if (from === root || node === null || typeof node !== "object")
351
+ return node;
352
+ const seen = /* @__PURE__ */ new Set();
353
+ const stack = [{ value: node, role }];
354
+ while (stack.length > 0) {
355
+ const current = stack.pop();
356
+ if (current === void 0)
357
+ break;
358
+ const { value: current_, role: currentRole } = current;
359
+ if (current_ === null || typeof current_ !== "object")
360
+ continue;
361
+ if (currentRole === "value")
362
+ continue;
363
+ if (seen.has(current_))
364
+ continue;
365
+ seen.add(current_);
366
+ if (Array.isArray(current_)) {
367
+ for (let index = 0; index < current_.length; index++) {
368
+ stack.push({ value: current_[index], role: childRole(currentRole, index) });
369
+ }
370
+ continue;
371
+ }
372
+ const prototype = Object.getPrototypeOf(current_);
373
+ if (prototype !== Object.prototype && prototype !== null)
374
+ continue;
375
+ const obj = current_;
376
+ const isSchema = currentRole !== "schemaMap";
377
+ for (const [key, value] of Object.entries(obj)) {
378
+ if (isSchema && key === "$ref" && typeof value === "string") {
379
+ assignKey(obj, key, rebaseKeptRef(value, from, root));
380
+ } else {
381
+ stack.push({ value, role: childRole(currentRole, key) });
382
+ }
383
+ }
384
+ }
385
+ return node;
386
+ };
166
387
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
167
388
  const hoistName = (targetLocation, fragment, taken) => {
168
389
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
@@ -175,34 +396,64 @@ const hoistName = (targetLocation, fragment, taken) => {
175
396
  taken.add(name);
176
397
  return name;
177
398
  };
399
+ const MAX_DOCUMENTS = 500;
400
+ const TOTAL_TIMEOUT_MS = 6e4;
178
401
  const resolveRefsFromFile = async (filename, options = {}) => {
179
402
  const rootLocation = isRemote(filename) ? filename : resolvePath(filename);
180
403
  const errors = [];
181
404
  const docCache = /* @__PURE__ */ new Map();
182
- if (!await loadDoc(rootLocation, docCache, options, errors)) {
405
+ const unloadable = /* @__PURE__ */ new Set();
406
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
407
+ const maxDocuments = options.maxDocuments ?? MAX_DOCUMENTS;
408
+ const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS);
409
+ const localRoots = (options.allowedRoots ?? (isRemote(rootLocation) ? [] : [dirname(rootLocation)])).map((root) => resolvePath(root));
410
+ const localDenialReason = (location) => {
411
+ if (options.localRefs === false)
412
+ return "local $ref resolution is disabled";
413
+ if (localRoots.length === 0) {
414
+ return "no local directory is allowed for this document (set allowedRoots to permit one)";
415
+ }
416
+ if (localRoots.some((root) => isContainedPath(root, location)))
417
+ return null;
418
+ return `it resolves outside the allowed roots [${localRoots.join(", ")}] (set allowedRoots to permit it)`;
419
+ };
420
+ if (!await loadDoc(rootLocation, docCache, options, errors, deadline)) {
183
421
  return { resolved: {}, errors };
184
422
  }
185
423
  const registries = /* @__PURE__ */ new Map();
186
424
  const registryFor = (location) => {
187
425
  let registry = registries.get(location);
188
426
  if (registry === void 0) {
189
- registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE);
427
+ registry = buildResourceRegistry(docCache.get(location), isRemote(location) ? location : SYNTHETIC_BASE, maxDepth);
190
428
  registries.set(location, registry);
191
429
  }
192
430
  return registry;
193
431
  };
194
- const collectRefTargets = (node, location, base, out) => {
195
- if (node === null || typeof node !== "object")
432
+ let depthLimitReported = false;
433
+ const reportDepthLimit = () => {
434
+ if (depthLimitReported)
435
+ return;
436
+ depthLimitReported = true;
437
+ errors.push(depthLimitError(maxDepth));
438
+ };
439
+ const collectRefTargets = (node, location, base, out, depth, role) => {
440
+ if (node === null || typeof node !== "object" || role === "value")
196
441
  return;
442
+ if (depth > maxDepth) {
443
+ reportDepthLimit();
444
+ return;
445
+ }
197
446
  if (Array.isArray(node)) {
198
- for (const item of node)
199
- collectRefTargets(item, location, base, out);
447
+ node.forEach((item, index) => {
448
+ collectRefTargets(item, location, base, out, depth + 1, childRole(role, index));
449
+ });
200
450
  return;
201
451
  }
202
452
  const obj = node;
203
453
  const registry = registryFor(location);
204
- const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
205
- const reference = readReference(obj);
454
+ const isSchema = role !== "schemaMap";
455
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
456
+ const reference = isSchema ? readReference(obj) : void 0;
206
457
  if (reference && reference.keyword !== "$recursiveRef") {
207
458
  const scoped = resolveRefInScope(registry, reference.keyword, reference.value, nodeBase);
208
459
  if (scoped === "external") {
@@ -214,22 +465,48 @@ const resolveRefsFromFile = async (filename, options = {}) => {
214
465
  for (const key of Object.keys(obj)) {
215
466
  if (reference && key === reference.keyword)
216
467
  continue;
217
- collectRefTargets(obj[key], location, nodeBase, out);
468
+ collectRefTargets(obj[key], location, nodeBase, out, depth + 1, childRole(role, key));
218
469
  }
219
470
  };
220
471
  const prefetch = async () => {
221
472
  const seen = /* @__PURE__ */ new Set([rootLocation]);
222
473
  const queue = [rootLocation];
474
+ let loaded = 1;
223
475
  while (queue.length > 0) {
224
476
  const location = queue.shift();
225
477
  const out = /* @__PURE__ */ new Set();
226
- collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out);
478
+ collectRefTargets(docCache.get(location), location, registryFor(location).rootBase, out, 0, "schema");
227
479
  for (const filePart of out) {
228
480
  const target = joinLocation(location, filePart);
229
481
  if (seen.has(target))
230
482
  continue;
231
483
  seen.add(target);
232
- await loadDoc(target, docCache, options, errors);
484
+ if (loaded >= maxDocuments) {
485
+ errors.push({
486
+ message: `Refusing to load more than ${maxDocuments} documents; the rest of the $ref graph was left unresolved (raise maxDocuments to allow more)`,
487
+ path: []
488
+ });
489
+ return;
490
+ }
491
+ if (Date.now() >= deadline) {
492
+ errors.push({
493
+ message: `Resolve deadline of ${options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS}ms elapsed; the rest of the $ref graph was left unresolved (raise totalTimeoutMs to allow more)`,
494
+ path: []
495
+ });
496
+ return;
497
+ }
498
+ if (!isRemote(target)) {
499
+ const reason = localDenialReason(target);
500
+ if (reason !== null) {
501
+ errors.push({ message: `Refusing to read local $ref (${reason}): ${target}`, path: [] });
502
+ docCache.set(target, {});
503
+ unloadable.add(target);
504
+ continue;
505
+ }
506
+ }
507
+ loaded++;
508
+ if (!await loadDoc(target, docCache, options, errors, deadline))
509
+ unloadable.add(target);
233
510
  queue.push(target);
234
511
  }
235
512
  }
@@ -237,20 +514,48 @@ const resolveRefsFromFile = async (filename, options = {}) => {
237
514
  await prefetch();
238
515
  const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
239
516
  const refCache = /* @__PURE__ */ new Map();
517
+ const sensitive = /* @__PURE__ */ new WeakSet();
518
+ const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
240
519
  const hoists = /* @__PURE__ */ new Map();
241
- const hoistTaken = /* @__PURE__ */ new Set();
242
- const resolveAt = (node, baseLocation, base) => {
520
+ const rootDoc = docCache.get(rootLocation);
521
+ const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
522
+ const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
523
+ const hoistRefSites = /* @__PURE__ */ new Map();
524
+ const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
525
+ const kept = {};
526
+ for (const key of Object.keys(obj)) {
527
+ const value = obj[key];
528
+ assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
529
+ }
530
+ return kept;
531
+ };
532
+ const resolveAt = (node, baseLocation, base, depth, role) => {
243
533
  if (node === null || typeof node !== "object")
244
534
  return node;
535
+ if (role === "value")
536
+ return detach(node);
537
+ if (depth > maxDepth) {
538
+ reportDepthLimit();
539
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
540
+ }
245
541
  if (Array.isArray(node)) {
246
- return node.map((item) => resolveAt(item, baseLocation, base));
542
+ const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
543
+ if (items.some((item) => isScopeSensitive(sensitive, item)))
544
+ sensitive.add(items);
545
+ return items;
247
546
  }
248
547
  const obj = node;
249
548
  const registry = registryFor(baseLocation);
250
- const nodeBase = typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
251
- const reference = readReference(obj);
549
+ const isSchema = role !== "schemaMap";
550
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
551
+ const reference = isSchema ? readReference(obj) : void 0;
252
552
  if (reference) {
253
553
  const { keyword, value } = reference;
554
+ if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
555
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
556
+ sensitive.add(kept);
557
+ return kept;
558
+ }
254
559
  let scoped;
255
560
  let targetLocation = baseLocation;
256
561
  let fragment = "";
@@ -271,9 +576,11 @@ const resolveRefsFromFile = async (filename, options = {}) => {
271
576
  const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
272
577
  let resolved2;
273
578
  let pointer;
579
+ let targetBase = nodeBase;
274
580
  const cached = refCache.get(cacheKey);
275
581
  if (cached === CYCLE) {
276
582
  let keptRef;
583
+ let hoisted = false;
277
584
  if (scoped !== void 0 && baseLocation === rootLocation) {
278
585
  keptRef = pathToRef(scoped.pointer);
279
586
  } else if (scoped === void 0 && targetLocation === rootLocation) {
@@ -284,24 +591,39 @@ const resolveRefsFromFile = async (filename, options = {}) => {
284
591
  name = hoistName(targetLocation, fragment, hoistTaken);
285
592
  hoists.set(cacheKey, name);
286
593
  }
594
+ hoisted = true;
287
595
  keptRef = `#/$defs/${name}`;
288
596
  }
289
597
  const kept = {};
290
598
  for (const key of Object.keys(obj)) {
291
599
  if (key === keyword)
292
600
  continue;
293
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase));
601
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
294
602
  }
295
603
  assignKey(kept, "$ref", keptRef);
604
+ if (hoisted)
605
+ hoistRefSites.set(kept, cacheKey);
296
606
  return kept;
297
607
  }
608
+ const keepUnresolved = () => {
609
+ const kept = {};
610
+ for (const key of Object.keys(obj)) {
611
+ if (key === keyword)
612
+ continue;
613
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
614
+ }
615
+ assignKey(kept, keyword, keyword === "$ref" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
616
+ return kept;
617
+ };
618
+ if (cached === MISSING)
619
+ return keepUnresolved();
298
620
  if (cached !== void 0) {
299
621
  resolved2 = cached.value;
300
622
  pointer = cached.pointer;
623
+ targetBase = cached.base;
301
624
  } else {
302
625
  refCache.set(cacheKey, CYCLE);
303
626
  let found;
304
- let targetBase;
305
627
  if (scoped !== void 0) {
306
628
  found = scoped;
307
629
  targetBase = scoped.base;
@@ -322,19 +644,41 @@ const resolveRefsFromFile = async (filename, options = {}) => {
322
644
  }
323
645
  }
324
646
  }
647
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
648
+ if (found === void 0 || !targetLoaded) {
649
+ if (targetLoaded) {
650
+ errors.push({
651
+ message: `Cannot resolve ${keyword} "${value}"`,
652
+ path: fragment === "" || fragment.startsWith("/") ? pointerToPath(fragment) : []
653
+ });
654
+ }
655
+ refCache.set(cacheKey, MISSING);
656
+ return keepUnresolved();
657
+ }
325
658
  pointer = found?.pointer ?? [];
326
- resolved2 = resolveAt(found?.value, targetLocation, targetBase);
327
- refCache.set(cacheKey, { value: resolved2, pointer });
659
+ resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
660
+ refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
328
661
  if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
329
662
  origins.set(resolved2, { location: targetLocation, pointer });
330
663
  }
331
664
  }
665
+ if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
666
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
667
+ sensitive.add(kept);
668
+ return kept;
669
+ }
332
670
  const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
333
671
  if (siblingKeys.length === 0)
334
672
  return resolved2;
335
673
  const siblings = {};
336
- for (const key of siblingKeys)
337
- assignKey(siblings, key, resolveAt(obj[key], baseLocation, nodeBase));
674
+ let siblingIsSensitive = false;
675
+ for (const key of siblingKeys) {
676
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
677
+ assignKey(siblings, key, child);
678
+ if (isScopeSensitive(sensitive, child))
679
+ siblingIsSensitive = true;
680
+ }
681
+ const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
338
682
  if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
339
683
  if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
340
684
  const overridden = {};
@@ -343,8 +687,13 @@ const resolveRefsFromFile = async (filename, options = {}) => {
343
687
  }
344
688
  for (const key of Object.keys(siblings))
345
689
  assignKey(overridden, key, siblings[key]);
690
+ const hoistOf = hoistRefSites.get(resolved2);
691
+ if (hoistOf !== void 0)
692
+ hoistRefSites.set(overridden, hoistOf);
346
693
  if (origins && !origins.has(overridden))
347
694
  origins.set(overridden, { location: targetLocation, pointer });
695
+ if (inlineIsSensitive)
696
+ sensitive.add(overridden);
348
697
  return overridden;
349
698
  }
350
699
  return resolved2;
@@ -353,23 +702,45 @@ const resolveRefsFromFile = async (filename, options = {}) => {
353
702
  const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
354
703
  if (origins && !origins.has(merged))
355
704
  origins.set(merged, { location: targetLocation, pointer });
705
+ if (inlineIsSensitive)
706
+ sensitive.add(merged);
356
707
  return merged;
357
708
  }
358
709
  const result = {};
359
710
  for (const key of Object.keys(obj)) {
360
- assignKey(result, key, resolveAt(obj[key], baseLocation, nodeBase));
711
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
712
+ assignKey(result, key, child);
713
+ if (isScopeSensitive(sensitive, child))
714
+ sensitive.add(result);
361
715
  }
716
+ if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
717
+ sensitive.add(result);
362
718
  return result;
363
719
  };
364
720
  const rootRegistry = registryFor(rootLocation);
365
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase);
721
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
366
722
  if (hoists.size > 0) {
367
723
  if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
368
724
  const container = resolved;
369
725
  const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
726
+ const taken = new Set(Object.keys(defs));
727
+ const finalNames = /* @__PURE__ */ new Map();
370
728
  for (const [cacheKey, name] of hoists) {
729
+ let unique = name;
730
+ for (let n = 2; taken.has(unique); n++)
731
+ unique = `${name}-${n}`;
732
+ taken.add(unique);
733
+ finalNames.set(cacheKey, unique);
734
+ }
735
+ for (const [node, cacheKey] of hoistRefSites) {
736
+ const name = finalNames.get(cacheKey);
737
+ if (name !== void 0)
738
+ assignKey(node, "$ref", `#/$defs/${name}`);
739
+ }
740
+ for (const [cacheKey] of hoists) {
371
741
  const cached = refCache.get(cacheKey);
372
- assignKey(defs, name, cached !== void 0 && cached !== CYCLE ? cached.value ?? {} : {});
742
+ const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
743
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
373
744
  }
374
745
  assignKey(container, "$defs", defs);
375
746
  } else {