@amritk/resolve-refs 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -26,8 +26,8 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
26
26
  ## Gotchas — where agents fail
27
27
 
28
28
  1. **`resolveRefs` is in-memory only.** It does NOT load other files/URLs —
29
- external refs stay in place and are pushed to `errors` (the ref becomes `{}`).
30
- Use `resolveRefsFromFile` for cross-file/remote.
29
+ external refs stay in place and are pushed to `errors` (the `{ $ref }` node is
30
+ kept as written, not inlined). Use `resolveRefsFromFile` for cross-file/remote.
31
31
  2. **Errors are collected, never thrown.** A missing file, refused host, or bad
32
32
  URL lands on `result.errors` while the rest still resolves. Always check it.
33
33
  Each error's `path` is where the offending reference was written in the
package/README.md CHANGED
@@ -72,6 +72,7 @@ const remote = await resolveRefsFromFile('https://api.example.com/schema.json',
72
72
  | `parse` | `JSON.parse` | Custom content parser (e.g. YAML-aware). |
73
73
  | `rootDocument` | — | The root's already-parsed value. The named file is then neither read nor parsed; its location still anchors relative refs, `allowedRoots`, and `origins`. The value is only read, never written or aliased into the result. |
74
74
  | `trackOrigins` | `false` | Record a per-node origin map on the result. |
75
+ | `bundle` | `false` | Bundle instead of inlining: hoist each target from another document into the root's `$defs` once and point its refs there, keeping refs into the root as written. The output is one document with only internal refs — what a code generator wants, since a shared schema stays one definition instead of a copy at every use. A document with an absolute `$id` is embedded whole with its `$id`, and refs to anything in an embedded resource name it by that URI; a document with a relative `$id` is inlined. |
75
76
 
76
77
  Errors (a missing file, a refused host, a refused path, a bad URL, a document too
77
78
  deeply nested) are collected on `result.errors` rather than thrown; the
@@ -101,7 +102,8 @@ The remote path has always been default-deny; the local path now matches it.
101
102
  planted in the tree cannot be used to escape it. The root document itself is
102
103
  exempt: it is the file you explicitly named.
103
104
  - **The session cache is credential-scoped.** Its key covers the request headers,
104
- the `fetch`/`parse` callbacks, and the transfer limits, so a document fetched
105
+ the `fetch`/`parse` callbacks, the transfer limits, and the host guards
106
+ (`allowPrivateHosts`, `allowedHosts`, `verifyDns`), so a document fetched
105
107
  with one tenant's token is invisible to a call carrying different (or no)
106
108
  credentials — and no caller inherits another's `fetch`. In-flight coalescing
107
109
  uses the same key.
@@ -192,20 +194,12 @@ recursive cycles intact, and records a diagnostic for every external ref. The
192
194
  registry, no scoping, no diagnostics — and re-resolves each ref on every
193
195
  encounter, so the gap is the production resolver's *total* per-call cost against
194
196
  the cheapest thing that produces the same inlined shape. Both are asserted to
195
- produce byte-identical output before either is timed. Medians of three runs on each runtime, one machine (Linux x64, a 4-vCPU cloud
196
- box, Bun 1.4.0 and Node 26.8.1 — your hardware will differ, run `bun run bench`
197
- or `bun run bench:node` yourself):
198
-
199
- | schema | Bun: cached | Bun: naive | Bun speedup | Node: cached | Node: naive | Node speedup |
200
- |:---|---:|---:|---:|---:|---:|---:|
201
- | chain (40 `$ref` → `$ref` links) | ~4.6k ops/s | ~1.1k ops/s | **~4.1×** | ~4.7k ops/s | ~1.1k ops/s | **~4.1×** |
202
- | reuse-heavy (50 refs → 1 def) | ~6.9k ops/s | ~11k ops/s | ~0.62× | ~6.6k ops/s | ~10k ops/s | ~0.66× |
203
- | cyclic tree | ~50k ops/s | ~183k ops/s | ~0.27× | ~58k ops/s | ~184k ops/s | ~0.31× |
204
- | wide-distinct (60 defs, each used once) | ~3.7k ops/s | ~9.5k ops/s | ~0.39× | ~3.4k ops/s | ~9.0k ops/s | ~0.38× |
205
-
206
- The two engines agree on every row to within a few percent, which is what you
207
- would expect from a resolver whose cost is one document walk rather than a hot
208
- inner loop.
197
+ produce byte-identical output before either is timed. Run it with `bun run bench`
198
+ (Bun) or `bun run bench:node` (Node); the shapes are a long `$ref` → `$ref`
199
+ chain, many refs reusing one definition, a cyclic tree, and many distinct
200
+ definitions each used once. Bun and Node land close together on every shape,
201
+ which is what you would expect from a resolver whose cost is one document walk
202
+ rather than a hot inner loop.
209
203
 
210
204
  Memoization overtakes the naive walk only on the **chain** shape, where a long
211
205
  indirection path is expensive to re-resolve and the cache collapses it to one
@@ -215,10 +209,9 @@ the bare inliner is faster — these are small schemas where that one document w
215
209
  dominates. The takeaway is practical: the resolver's per-call floor is a full
216
210
  document traversal, so in a hot loop resolve a document **once** and reuse the
217
211
  result rather than re-resolving. The `reuse-heavy`, `cyclic`, and `wide-distinct`
218
- rows are kept in the table precisely to show that trade honestly rather than
212
+ shapes are kept in the bench precisely to show that trade honestly rather than
219
213
  cherry-picking the one shape the cache wins.
220
214
 
221
215
  Opting into `trackOrigins` (which records where each inlined value came from)
222
- costs nothing measurable on these small schemas, on either runtime: the four
223
- rows land between −9% and +7% on Bun and between −3% and +1% on Node, straddling
224
- zero in both cases, which is run-to-run noise rather than a price.
216
+ costs nothing measurable on these small schemas, on either runtime: the
217
+ differences straddle zero, which is run-to-run noise rather than a price.
@@ -4,6 +4,7 @@ import { dirname, relative as relativePath, resolve as resolvePath, sep } from "
4
4
  import { assertPublicHost } from "./assert-public-host.js";
5
5
  import { childRole } from "./child-role.js";
6
6
  import { bindsAtEvaluationTime, declaresAmbiguousAnchor, inliningKeepsScope, isScopeSensitive } from "./dynamic-scope.js";
7
+ import { getByPointer } from "./get-by-pointer.js";
7
8
  import { isContainedPath } from "./is-contained-path.js";
8
9
  import { isPrivateHost } from "./is-private-host.js";
9
10
  import { DEFAULT_MAX_DEPTH, depthLimitError } from "./max-depth.js";
@@ -387,15 +388,72 @@ const rebaseKeptRefs = (node, from, root, role) => {
387
388
  return node;
388
389
  };
389
390
  const pathToRef = (path) => path.length === 0 ? "#" : `#/${path.map((segment) => escapeSegment(String(segment))).join("/")}`;
390
- const hoistName = (targetLocation, fragment, taken) => {
391
+ const DEFINITION_CONTAINERS = [["$defs"], ["definitions"], ["components", "schemas"]];
392
+ const enclosingDefinitionLength = (pointer) => {
393
+ for (const container of DEFINITION_CONTAINERS) {
394
+ const length = container.length + 1;
395
+ if (pointer.length > length && container.every((key, index) => pointer[index] === key))
396
+ return length;
397
+ }
398
+ return 0;
399
+ };
400
+ const asWritten = (name) => name;
401
+ const asFilename = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
402
+ const NAME_CONTAINERS = ["$defs", "definitions"];
403
+ const POINTER_NAME_CONTAINERS = /* @__PURE__ */ new Set(["$defs", "definitions", "properties"]);
404
+ const generatedName = (pointer) => {
405
+ const segments = pointer.split("/").filter((segment) => segment !== "");
406
+ const named = segments.map((segment, index) => ({
407
+ segment,
408
+ nested: index > 0 && POINTER_NAME_CONTAINERS.has(segments[index - 1])
409
+ })).filter(({ segment }) => !POINTER_NAME_CONTAINERS.has(segment));
410
+ return named.filter((part, index) => part.nested || index === named.length - 1).map(({ segment }) => segment).join("-");
411
+ };
412
+ const internalPointers = (root) => {
413
+ const pointers = /* @__PURE__ */ new Set();
414
+ const seen = /* @__PURE__ */ new WeakSet();
415
+ const stack = [{ value: root, depth: 0 }];
416
+ while (stack.length > 0) {
417
+ const { value, depth } = stack.pop();
418
+ if (value === null || typeof value !== "object" || seen.has(value) || depth > DEFAULT_MAX_DEPTH)
419
+ continue;
420
+ seen.add(value);
421
+ const ref = value.$ref;
422
+ if (typeof ref === "string" && ref.startsWith("#/"))
423
+ pointers.add(ref.slice(1));
424
+ for (const member of Object.values(value))
425
+ stack.push({ value: member, depth: depth + 1 });
426
+ }
427
+ return pointers;
428
+ };
429
+ const nestedDefinitionNames = (map) => {
430
+ const names = [];
431
+ const seen = /* @__PURE__ */ new WeakSet();
432
+ const stack = [{ prefix: "", map, depth: 0 }];
433
+ while (stack.length > 0) {
434
+ const { prefix: parent, map: current, depth } = stack.pop();
435
+ if (seen.has(current) || depth > DEFAULT_MAX_DEPTH)
436
+ continue;
437
+ seen.add(current);
438
+ for (const [key, value] of Object.entries(current)) {
439
+ const name = parent === "" ? key : `${parent}-${key}`;
440
+ names.push(name);
441
+ for (const nested of containedNameMaps(value))
442
+ stack.push({ prefix: name, map: nested, depth: depth + 1 });
443
+ }
444
+ }
445
+ return names;
446
+ };
447
+ const containedNameMaps = (schema) => schema === null || typeof schema !== "object" || Array.isArray(schema) ? [] : NAME_CONTAINERS.map((container) => schema[container]).filter((map) => map !== null && typeof map === "object" && !Array.isArray(map));
448
+ const hoistName = (targetLocation, fragment, taken, keyOf = asWritten) => {
391
449
  const fragmentTail = fragment.split("/").filter(Boolean).pop();
392
450
  const locationTail = targetLocation.split("/").filter(Boolean).pop()?.replace(/\.[a-z0-9]+$/i, "");
393
451
  const raw = fragmentTail || locationTail || "cycle";
394
452
  const sanitized = raw.replace(/[^A-Za-z0-9_.-]/g, "-") || "cycle";
395
453
  let name = sanitized;
396
- for (let n = 2; taken.has(name); n++)
454
+ for (let n = 2; taken.has(keyOf(name)); n++)
397
455
  name = `${sanitized}-${n}`;
398
- taken.add(name);
456
+ taken.add(keyOf(name));
399
457
  return name;
400
458
  };
401
459
  const MAX_DOCUMENTS = 500;
@@ -525,245 +583,452 @@ const resolveRefsFromFile = async (filename, options = {}) => {
525
583
  }
526
584
  };
527
585
  await prefetch();
528
- const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
529
- const refCache = /* @__PURE__ */ new Map();
530
- const sensitive = /* @__PURE__ */ new WeakSet();
531
- const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
532
- const hoists = /* @__PURE__ */ new Map();
533
- const rootDoc = docCache.get(rootLocation);
534
- const rootDefs = rootDoc !== null && typeof rootDoc === "object" && !Array.isArray(rootDoc) ? rootDoc["$defs"] : void 0;
535
- const hoistTaken = new Set(rootDefs !== null && typeof rootDefs === "object" && !Array.isArray(rootDefs) ? Object.keys(rootDefs) : []);
536
- const hoistRefSites = /* @__PURE__ */ new Map();
537
- const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
538
- const kept = {};
539
- for (const key of Object.keys(obj)) {
540
- const value = obj[key];
541
- assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
542
- }
543
- return kept;
544
- };
545
- const resolveAt = (node, baseLocation, base, depth, role) => {
546
- if (node === null || typeof node !== "object")
547
- return node;
548
- if (role === "value")
549
- return detach(node);
550
- if (depth > maxDepth) {
551
- reportDepthLimit();
552
- return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
553
- }
554
- if (Array.isArray(node)) {
555
- const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
556
- if (items.some((item) => isScopeSensitive(sensitive, item)))
557
- sensitive.add(items);
558
- return items;
559
- }
560
- const obj = node;
561
- const registry = registryFor(baseLocation);
562
- const isSchema = role !== "schemaMap";
563
- const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
564
- const reference = isSchema ? readReference(obj) : void 0;
565
- if (reference) {
566
- const { keyword, value } = reference;
567
- if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
568
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
569
- sensitive.add(kept);
570
- return kept;
586
+ const errorsBeforeResolve = errors.length;
587
+ const depthReportedBeforeResolve = depthLimitReported;
588
+ const resolvePass = (inlineOnly) => {
589
+ const unplaceable = /* @__PURE__ */ new Set();
590
+ const origins = options.trackOrigins ? /* @__PURE__ */ new Map() : void 0;
591
+ const refCache = /* @__PURE__ */ new Map();
592
+ const sensitive = /* @__PURE__ */ new WeakSet();
593
+ const ambiguousDynamicAnchors = docCache.size === 1 ? registryFor(rootLocation).ambiguousDynamicAnchors : /* @__PURE__ */ new Set();
594
+ const hoists = /* @__PURE__ */ new Map();
595
+ const rootDoc = docCache.get(rootLocation);
596
+ const nameKey = options.bundle === true ? asFilename : asWritten;
597
+ const definitionNames = (root) => (options.bundle === true ? DEFINITION_CONTAINERS : [["$defs"]]).flatMap((container) => {
598
+ const map = getByPointer(root, `/${container.join("/")}`);
599
+ if (map === null || typeof map !== "object" || Array.isArray(map))
600
+ return [];
601
+ return options.bundle === true ? nestedDefinitionNames(map) : Object.keys(map);
602
+ });
603
+ const rootRefNames = (root) => options.bundle === true ? [...internalPointers(root)].map(generatedName) : [];
604
+ const rootNames = [...definitionNames(rootDoc), ...rootRefNames(rootDoc)];
605
+ const hoistTaken = new Set(rootNames.map(nameKey));
606
+ const hoistRefSites = /* @__PURE__ */ new Map();
607
+ const hoistRefSuffixes = /* @__PURE__ */ new Map();
608
+ const keepScopedReference = (obj, keyword, baseLocation, nodeBase, depth, role) => {
609
+ const kept = {};
610
+ for (const key of Object.keys(obj)) {
611
+ const value = obj[key];
612
+ assignKey(kept, key, key !== keyword ? resolveAt(value, baseLocation, nodeBase, depth + 1, childRole(role, key)) : keyword === "$ref" && typeof value === "string" ? rebaseKeptRef(value, baseLocation, rootLocation) : value);
571
613
  }
572
- let scoped;
573
- let targetLocation = baseLocation;
574
- let fragment = "";
614
+ return kept;
615
+ };
616
+ const lookupTarget = (scoped, keyword, targetLocation, fragment) => {
617
+ if (scoped !== void 0)
618
+ return { found: scoped, base: scoped.base };
619
+ const targetRegistry = registryFor(targetLocation);
620
+ const targetRoot = docCache.get(targetLocation) ?? {};
575
621
  if (keyword === "$recursiveRef") {
576
- fragment = value.startsWith("#") ? value.slice(1) : value;
577
- } else {
578
- const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
579
- if (inScope === "external" || inScope === void 0) {
580
- const parts = splitRef(value);
581
- fragment = parts.fragment;
582
- if (inScope === "external" && parts.uriPart !== "") {
583
- const target = joinLocation(baseLocation, parts.uriPart);
584
- if (target === void 0)
585
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
586
- targetLocation = target;
587
- }
588
- } else {
589
- scoped = inScope;
622
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
623
+ }
624
+ const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
625
+ if (scopedFragment !== "external" && scopedFragment !== void 0) {
626
+ return { found: scopedFragment, base: scopedFragment.base };
627
+ }
628
+ return { found: resolveFragment(targetRoot, keyword, fragment), base: targetRegistry.rootBase };
629
+ };
630
+ const placements = [];
631
+ const embeddedIds = /* @__PURE__ */ new Map();
632
+ const contestedIds = /* @__PURE__ */ new Set();
633
+ const uriRefSites = /* @__PURE__ */ new Map();
634
+ const hoistTargets = /* @__PURE__ */ new Map();
635
+ const declaresRootId = (location) => {
636
+ const root = docCache.get(location);
637
+ return root !== null && typeof root === "object" && !Array.isArray(root) && typeof root.$id === "string";
638
+ };
639
+ const absoluteRootId = (location) => {
640
+ const root = docCache.get(location);
641
+ if (root === null || typeof root !== "object" || Array.isArray(root))
642
+ return void 0;
643
+ const id = root["$id"];
644
+ if (typeof id !== "string" || !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(id))
645
+ return void 0;
646
+ return registryFor(location).rootBase;
647
+ };
648
+ const uriFor = (location, base, pointer) => {
649
+ if (base.startsWith(SYNTHETIC_BASE))
650
+ return void 0;
651
+ const registry = registryFor(location);
652
+ const declared = base === registry.rootBase ? absoluteRootId(location) === base : registry.resources.has(base);
653
+ if (!declared)
654
+ return void 0;
655
+ const resourcePointer = base === registry.rootBase ? [] : registry.resources.get(base)?.pointer;
656
+ if (resourcePointer === void 0 || resourcePointer.some((segment, index) => pointer[index] !== segment)) {
657
+ return void 0;
658
+ }
659
+ const inner = pointer.slice(resourcePointer.length);
660
+ return inner.length === 0 ? base : `${base}${pathToRef(inner)}`;
661
+ };
662
+ const cycleTargetUri = (scoped, keyword, targetLocation, fragment) => {
663
+ const { found, base } = lookupTarget(scoped, keyword, targetLocation, fragment);
664
+ return found === void 0 ? void 0 : uriFor(targetLocation, base, found.pointer);
665
+ };
666
+ const hoistFor = (targetLocation, found, targetBase, plain, depth) => {
667
+ const wholeHoisted = plain && hoists.has(`$ref ${targetLocation}#`);
668
+ const split = plain && !wholeHoisted ? enclosingDefinitionLength(found.pointer) : 0;
669
+ const pointer = plain && !wholeHoisted ? split > 0 ? found.pointer.slice(0, split) : found.pointer : [];
670
+ const key = `$ref ${targetLocation}${pathToRef(pointer)}`;
671
+ const name = hoists.get(key) ?? hoistName(targetLocation, pathToRef(pointer).slice(1), hoistTaken, nameKey);
672
+ hoists.set(key, name);
673
+ hoistTargets.set(key, { location: targetLocation, pointer });
674
+ if (!refCache.has(key)) {
675
+ refCache.set(key, CYCLE);
676
+ const whole = pointer.length === found.pointer.length;
677
+ const value = whole ? found.value : getByPointer(docCache.get(targetLocation), pathToRef(pointer).slice(1));
678
+ const base = whole ? targetBase : registryFor(targetLocation).rootBase;
679
+ const resolved2 = resolveAt(value, targetLocation, base, depth + 1, roleAtPath(pointer));
680
+ refCache.set(key, { value: resolved2, pointer, base });
681
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
682
+ origins.set(resolved2, { location: targetLocation, pointer });
590
683
  }
591
684
  }
592
- const cacheKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
593
- let resolved2;
594
- let pointer;
595
- let targetBase = nodeBase;
596
- const cached = refCache.get(cacheKey);
597
- if (cached === CYCLE) {
598
- let keptRef;
599
- let hoisted = false;
600
- if (scoped !== void 0 && baseLocation === rootLocation) {
601
- keptRef = pathToRef(scoped.pointer);
602
- } else if (scoped === void 0 && targetLocation === rootLocation) {
603
- keptRef = `#${fragment}`;
604
- } else {
605
- let name = hoists.get(cacheKey);
606
- if (name === void 0) {
607
- name = hoistName(targetLocation, fragment, hoistTaken);
608
- hoists.set(cacheKey, name);
609
- }
610
- hoisted = true;
611
- keptRef = `#/$defs/${name}`;
685
+ return { key, name, pointer };
686
+ };
687
+ const bundleReference = (obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role) => {
688
+ const placedIn = placements.at(-1);
689
+ const siteInRoot = placedIn === void 0 && nodeBase === registryFor(baseLocation).rootBase;
690
+ const intoRoot = scoped !== void 0 ? baseLocation === rootLocation : targetLocation === rootLocation;
691
+ const plain = !intoRoot && registryFor(targetLocation).bases.size === 0 && !declaresRootId(targetLocation);
692
+ const embeddedId = intoRoot || plain ? void 0 : absoluteRootId(targetLocation);
693
+ if (!intoRoot && !plain) {
694
+ if (embeddedId === void 0 || inlineOnly.has(targetLocation))
695
+ return void 0;
696
+ const claimedBy = embeddedIds.get(embeddedId);
697
+ if (registryFor(rootLocation).resources.has(embeddedId) || (claimedBy ?? targetLocation) !== targetLocation) {
698
+ if (claimedBy !== void 0 && claimedBy !== targetLocation)
699
+ contestedIds.add(embeddedId);
700
+ return void 0;
612
701
  }
613
- const kept = {};
614
- for (const key of Object.keys(obj)) {
615
- if (key === keyword)
616
- continue;
617
- assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
702
+ }
703
+ if (plain && !siteInRoot)
704
+ return void 0;
705
+ if (refCache.get(cacheKey) === MISSING || refCache.get(refKey) === MISSING)
706
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
707
+ const { found, base: targetBase } = lookupTarget(scoped, "$ref", targetLocation, fragment);
708
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
709
+ if (found === void 0 || !targetLoaded) {
710
+ if (targetLoaded) {
711
+ errors.push({
712
+ message: `Cannot resolve $ref "${value}"`,
713
+ path: baseLocation === rootLocation ? refPathAt("$ref", value) : []
714
+ });
618
715
  }
619
- assignKey(kept, "$ref", keptRef);
620
- if (hoisted)
621
- hoistRefSites.set(kept, cacheKey);
622
- return kept;
716
+ refCache.set(cacheKey, MISSING);
717
+ refCache.set(refKey, MISSING);
718
+ return keepScopedReference(obj, "$ref", baseLocation, nodeBase, depth, role);
623
719
  }
624
- if (cached === MISSING)
625
- return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
626
- if (cached !== void 0) {
627
- resolved2 = cached.value;
628
- pointer = cached.pointer;
629
- targetBase = cached.base;
630
- } else {
631
- refCache.set(cacheKey, CYCLE);
632
- let found;
633
- if (scoped !== void 0) {
634
- found = scoped;
635
- targetBase = scoped.base;
720
+ const sameResource = placedIn !== void 0 && placedIn === nodeBase && nodeBase === targetBase && baseLocation === targetLocation && (scoped !== void 0 || splitRef(value).uriPart === "");
721
+ const byUri = !sameResource && (!siteInRoot || embeddedId !== void 0);
722
+ const uri = byUri ? uriFor(targetLocation, targetBase, found.pointer) : void 0;
723
+ if (byUri && uri === void 0)
724
+ return void 0;
725
+ if (embeddedId !== void 0)
726
+ embeddedIds.set(embeddedId, targetLocation);
727
+ const hoist = intoRoot ? void 0 : hoistFor(targetLocation, found, targetBase, plain, depth);
728
+ const named = hoist !== void 0 && plain && siteInRoot;
729
+ const suffix = named ? pathToRef(found.pointer.slice(hoist.pointer.length)).slice(1) : "";
730
+ const target = uri ?? (sameResource ? value : named ? `#/$defs/${hoist.name}${suffix}` : scoped !== void 0 || value.startsWith("#") ? value : pathToRef(found.pointer));
731
+ const kept = {};
732
+ for (const key of Object.keys(obj)) {
733
+ assignKey(kept, key, key === "$ref" ? target : resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
734
+ }
735
+ if (named) {
736
+ hoistRefSites.set(kept, hoist.key);
737
+ if (suffix !== "")
738
+ hoistRefSuffixes.set(kept, suffix);
739
+ }
740
+ if (siteInRoot && hoist !== void 0 && embeddedId !== void 0) {
741
+ uriRefSites.set(kept, { key: hoist.key, id: embeddedId, suffix: pathToRef(found.pointer).slice(1) });
742
+ }
743
+ if (Object.values(kept).some((child) => isScopeSensitive(sensitive, child)) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors)) {
744
+ sensitive.add(kept);
745
+ }
746
+ return kept;
747
+ };
748
+ const resolveAt = (node, baseLocation, base, depth, role) => {
749
+ const entersResource = options.bundle === true && role !== "value" && role !== "schemaMap" && node !== null && typeof node === "object" && !Array.isArray(node) && typeof node["$id"] === "string" && // Draft-07's `#Foo` names a location, not a resource, wherever it lands.
750
+ splitRef(node["$id"]).uriPart !== "" && !(depth === 0 && baseLocation === rootLocation);
751
+ const nodeBase = entersResource ? baseOfNode(registryFor(baseLocation), node, base) : base;
752
+ if (!entersResource || nodeBase === (placements.at(-1) ?? registryFor(rootLocation).rootBase)) {
753
+ return resolveNode(node, baseLocation, base, depth, role);
754
+ }
755
+ placements.push(nodeBase);
756
+ try {
757
+ return resolveNode(node, baseLocation, base, depth, role);
758
+ } finally {
759
+ placements.pop();
760
+ }
761
+ };
762
+ const resolveNode = (node, baseLocation, base, depth, role) => {
763
+ if (node === null || typeof node !== "object")
764
+ return node;
765
+ if (role === "value")
766
+ return detach(node);
767
+ if (depth > maxDepth) {
768
+ reportDepthLimit();
769
+ return rebaseKeptRefs(detach(node), baseLocation, rootLocation, role);
770
+ }
771
+ if (Array.isArray(node)) {
772
+ const items = node.map((item, index) => resolveAt(item, baseLocation, base, depth + 1, childRole(role, index)));
773
+ if (items.some((item) => isScopeSensitive(sensitive, item)))
774
+ sensitive.add(items);
775
+ return items;
776
+ }
777
+ const obj = node;
778
+ const registry = registryFor(baseLocation);
779
+ const isSchema = role !== "schemaMap";
780
+ const nodeBase = isSchema && typeof obj["$id"] === "string" ? baseOfNode(registry, obj, base) : base;
781
+ const reference = isSchema ? readReference(obj) : void 0;
782
+ if (reference) {
783
+ const { keyword, value } = reference;
784
+ if (bindsAtEvaluationTime(keyword, value, ambiguousDynamicAnchors)) {
785
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
786
+ sensitive.add(kept);
787
+ return kept;
788
+ }
789
+ let scoped;
790
+ let targetLocation = baseLocation;
791
+ let fragment = "";
792
+ if (keyword === "$recursiveRef") {
793
+ fragment = value.startsWith("#") ? value.slice(1) : value;
636
794
  } else {
637
- const targetRegistry = registryFor(targetLocation);
638
- const targetRoot = docCache.get(targetLocation) ?? {};
639
- if (keyword === "$recursiveRef") {
640
- found = resolveFragment(targetRoot, keyword, fragment);
641
- targetBase = targetRegistry.rootBase;
642
- } else {
643
- const scopedFragment = resolveRefInScope(targetRegistry, keyword, `#${fragment}`, targetRegistry.rootBase);
644
- if (scopedFragment !== "external" && scopedFragment !== void 0) {
645
- found = scopedFragment;
646
- targetBase = scopedFragment.base;
647
- } else {
648
- found = resolveFragment(targetRoot, keyword, fragment);
649
- targetBase = targetRegistry.rootBase;
795
+ const inScope = resolveRefInScope(registry, keyword, value, nodeBase);
796
+ if (inScope === "external" || inScope === void 0) {
797
+ const parts = splitRef(value);
798
+ fragment = parts.fragment;
799
+ if (inScope === "external" && parts.uriPart !== "") {
800
+ const target = joinLocation(baseLocation, parts.uriPart);
801
+ if (target === void 0)
802
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
803
+ targetLocation = target;
650
804
  }
805
+ } else {
806
+ scoped = inScope;
651
807
  }
652
808
  }
653
- const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
654
- if (found === void 0 || !targetLoaded) {
655
- if (targetLoaded) {
656
- errors.push({
657
- message: `Cannot resolve ${keyword} "${value}"`,
658
- // `refPathAt` indexes the *root* document only, so it can only
659
- // speak for a ref that lives there. Called unguarded it answered
660
- // for a ref in a sub-document by handing back the position of an
661
- // identical ref in the root — pointing a diagnostic at a line
662
- // that is not the offending one. The prefetch loop above already
663
- // guards this the same way; an empty path means "no position to
664
- // give", which is honest.
665
- path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
666
- });
809
+ const refKey = scoped !== void 0 ? `${keyword} ${baseLocation} ${nodeBase} ${value}` : `${keyword} ${targetLocation}#${fragment}`;
810
+ const placedIn = options.bundle === true ? placements.at(-1) : void 0;
811
+ const cacheKey = placedIn === void 0 ? refKey : `${refKey} (in ${placedIn})`;
812
+ if (options.bundle === true && keyword === "$ref") {
813
+ const bundled = bundleReference(obj, value, scoped, targetLocation, fragment, cacheKey, refKey, baseLocation, nodeBase, depth, role);
814
+ if (bundled !== void 0)
815
+ return bundled;
816
+ }
817
+ let resolved2;
818
+ let pointer;
819
+ let targetBase = nodeBase;
820
+ const cached = refCache.get(cacheKey) ?? (refCache.get(refKey) === MISSING ? MISSING : void 0);
821
+ if (cached === CYCLE) {
822
+ const cycleUri = placedIn === void 0 ? void 0 : cycleTargetUri(scoped, keyword, targetLocation, fragment);
823
+ if (placedIn !== void 0 && cycleUri === void 0) {
824
+ const innermost = placements.findLast((base2) => embeddedIds.has(base2));
825
+ if (innermost !== void 0)
826
+ unplaceable.add(embeddedIds.get(innermost));
827
+ }
828
+ let keptRef;
829
+ let hoisted = false;
830
+ if (cycleUri !== void 0) {
831
+ keptRef = cycleUri;
832
+ } else if (scoped !== void 0 && baseLocation === rootLocation) {
833
+ keptRef = pathToRef(scoped.pointer);
834
+ } else if (scoped === void 0 && targetLocation === rootLocation) {
835
+ keptRef = `#${fragment}`;
836
+ } else {
837
+ let name = hoists.get(cacheKey);
838
+ if (name === void 0) {
839
+ name = hoistName(targetLocation, fragment, hoistTaken, nameKey);
840
+ hoists.set(cacheKey, name);
841
+ }
842
+ hoisted = true;
843
+ keptRef = `#/$defs/${name}`;
844
+ }
845
+ const kept = {};
846
+ for (const key of Object.keys(obj)) {
847
+ if (key === keyword)
848
+ continue;
849
+ assignKey(kept, key, resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key)));
667
850
  }
668
- refCache.set(cacheKey, MISSING);
851
+ assignKey(kept, "$ref", keptRef);
852
+ if (hoisted)
853
+ hoistRefSites.set(kept, cacheKey);
854
+ return kept;
855
+ }
856
+ if (cached === MISSING)
669
857
  return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
858
+ if (cached !== void 0) {
859
+ resolved2 = cached.value;
860
+ pointer = cached.pointer;
861
+ targetBase = cached.base;
862
+ } else {
863
+ refCache.set(cacheKey, CYCLE);
864
+ const lookup = lookupTarget(scoped, keyword, targetLocation, fragment);
865
+ const found = lookup.found;
866
+ targetBase = lookup.base;
867
+ const targetLoaded = docCache.has(targetLocation) && !unloadable.has(targetLocation);
868
+ if (found === void 0 || !targetLoaded) {
869
+ if (targetLoaded) {
870
+ errors.push({
871
+ message: `Cannot resolve ${keyword} "${value}"`,
872
+ // `refPathAt` indexes the *root* document only, so it can only
873
+ // speak for a ref that lives there. Called unguarded it answered
874
+ // for a ref in a sub-document by handing back the position of an
875
+ // identical ref in the root — pointing a diagnostic at a line
876
+ // that is not the offending one. The prefetch loop above already
877
+ // guards this the same way; an empty path means "no position to
878
+ // give", which is honest.
879
+ path: baseLocation === rootLocation ? refPathAt(keyword, value) : []
880
+ });
881
+ }
882
+ refCache.set(cacheKey, MISSING);
883
+ refCache.set(refKey, MISSING);
884
+ return keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
885
+ }
886
+ pointer = found?.pointer ?? [];
887
+ resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
888
+ refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
889
+ if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
890
+ origins.set(resolved2, { location: targetLocation, pointer });
891
+ }
670
892
  }
671
- pointer = found?.pointer ?? [];
672
- resolved2 = resolveAt(found?.value, targetLocation, targetBase, depth + 1, roleAtPath(pointer));
673
- refCache.set(cacheKey, { value: resolved2, pointer, base: targetBase });
674
- if (origins && resolved2 !== null && typeof resolved2 === "object" && !origins.has(resolved2)) {
675
- origins.set(resolved2, { location: targetLocation, pointer });
893
+ if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
894
+ const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
895
+ sensitive.add(kept);
896
+ return kept;
676
897
  }
898
+ const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
899
+ if (siblingKeys.length === 0)
900
+ return resolved2;
901
+ const siblings = {};
902
+ let siblingIsSensitive = false;
903
+ for (const key of siblingKeys) {
904
+ const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
905
+ assignKey(siblings, key, child);
906
+ if (isScopeSensitive(sensitive, child))
907
+ siblingIsSensitive = true;
908
+ }
909
+ const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
910
+ if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
911
+ if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
912
+ const overridden = {};
913
+ for (const key of Object.keys(resolved2)) {
914
+ assignKey(overridden, key, resolved2[key]);
915
+ }
916
+ for (const key of Object.keys(siblings))
917
+ assignKey(overridden, key, siblings[key]);
918
+ const hoistOf = hoistRefSites.get(resolved2);
919
+ if (hoistOf !== void 0)
920
+ hoistRefSites.set(overridden, hoistOf);
921
+ const suffixOf = hoistRefSuffixes.get(resolved2);
922
+ if (suffixOf !== void 0)
923
+ hoistRefSuffixes.set(overridden, suffixOf);
924
+ const uriSite = uriRefSites.get(resolved2);
925
+ if (uriSite !== void 0)
926
+ uriRefSites.set(overridden, uriSite);
927
+ if (origins && !origins.has(overridden))
928
+ origins.set(overridden, { location: targetLocation, pointer });
929
+ if (inlineIsSensitive)
930
+ sensitive.add(overridden);
931
+ return overridden;
932
+ }
933
+ return resolved2;
934
+ }
935
+ const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
936
+ const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
937
+ if (origins && !origins.has(merged))
938
+ origins.set(merged, { location: targetLocation, pointer });
939
+ if (inlineIsSensitive)
940
+ sensitive.add(merged);
941
+ return merged;
677
942
  }
678
- if (isScopeSensitive(sensitive, resolved2) && !inliningKeepsScope(resolved2, nodeBase, targetBase)) {
679
- const kept = keepScopedReference(obj, keyword, baseLocation, nodeBase, depth, role);
680
- sensitive.add(kept);
681
- return kept;
682
- }
683
- const siblingKeys = Object.keys(obj).filter((key) => key !== keyword);
684
- if (siblingKeys.length === 0)
685
- return resolved2;
686
- const siblings = {};
687
- let siblingIsSensitive = false;
688
- for (const key of siblingKeys) {
943
+ const result = {};
944
+ for (const key of Object.keys(obj)) {
689
945
  const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
690
- assignKey(siblings, key, child);
946
+ assignKey(result, key, child);
691
947
  if (isScopeSensitive(sensitive, child))
692
- siblingIsSensitive = true;
948
+ sensitive.add(result);
693
949
  }
694
- const inlineIsSensitive = siblingIsSensitive || isScopeSensitive(sensitive, resolved2) || declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors);
695
- if (siblingKeys.every((key) => ANNOTATION_ONLY_SIBLINGS.has(key))) {
696
- if (resolved2 !== null && typeof resolved2 === "object" && !Array.isArray(resolved2)) {
697
- const overridden = {};
698
- for (const key of Object.keys(resolved2)) {
699
- assignKey(overridden, key, resolved2[key]);
700
- }
701
- for (const key of Object.keys(siblings))
702
- assignKey(overridden, key, siblings[key]);
703
- const hoistOf = hoistRefSites.get(resolved2);
704
- if (hoistOf !== void 0)
705
- hoistRefSites.set(overridden, hoistOf);
706
- if (origins && !origins.has(overridden))
707
- origins.set(overridden, { location: targetLocation, pointer });
708
- if (inlineIsSensitive)
709
- sensitive.add(overridden);
710
- return overridden;
950
+ if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
951
+ sensitive.add(result);
952
+ return result;
953
+ };
954
+ const rootRegistry = registryFor(rootLocation);
955
+ const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
956
+ if (hoists.size > 0) {
957
+ if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
958
+ const container = resolved;
959
+ const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
960
+ const insideWhole = /* @__PURE__ */ new Map();
961
+ for (const [key, { location, pointer }] of hoistTargets) {
962
+ const whole = `$ref ${location}#`;
963
+ if (pointer.length > 0 && hoists.has(whole))
964
+ insideWhole.set(key, { whole, suffix: pathToRef(pointer).slice(1) });
965
+ }
966
+ const taken = new Set([...Object.keys(defs), ...definitionNames(container), ...rootNames].map(nameKey));
967
+ const usedSuffixes = /* @__PURE__ */ new Map();
968
+ for (const [node, cacheKey] of hoistRefSites) {
969
+ const redirect = insideWhole.get(cacheKey);
970
+ const key = redirect?.whole ?? cacheKey;
971
+ const suffix = `${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`;
972
+ if (suffix !== "")
973
+ usedSuffixes.set(key, (usedSuffixes.get(key) ?? /* @__PURE__ */ new Set()).add(suffix));
974
+ }
975
+ const finalNames = /* @__PURE__ */ new Map();
976
+ for (const [cacheKey, name] of hoists) {
977
+ if (insideWhole.has(cacheKey))
978
+ continue;
979
+ const cached = refCache.get(cacheKey);
980
+ const value = cached !== void 0 && cached !== CYCLE && cached !== MISSING ? cached.value : void 0;
981
+ const nested = options.bundle === true ? containedNameMaps(value).flatMap((map) => nestedDefinitionNames(map)) : [];
982
+ const claims = (candidate) => [
983
+ candidate,
984
+ ...options.bundle === true ? [
985
+ ...nested.map((name2) => `${candidate}-${name2}`),
986
+ ...[...usedSuffixes.get(cacheKey) ?? []].map((suffix) => generatedName(`/$defs/${candidate}${suffix}`))
987
+ ] : []
988
+ ].map(nameKey);
989
+ let unique = name;
990
+ for (let n = 2; claims(unique).some((claim) => taken.has(claim)); n++)
991
+ unique = `${name}-${n}`;
992
+ for (const claim of claims(unique))
993
+ taken.add(claim);
994
+ finalNames.set(cacheKey, unique);
995
+ }
996
+ for (const [node, { key, id, suffix }] of uriRefSites) {
997
+ if (contestedIds.has(id))
998
+ assignKey(node, "$ref", `#/$defs/${finalNames.get(key)}${suffix}`);
999
+ }
1000
+ for (const [node, cacheKey] of hoistRefSites) {
1001
+ const redirect = insideWhole.get(cacheKey);
1002
+ const name = finalNames.get(redirect?.whole ?? cacheKey);
1003
+ assignKey(node, "$ref", `#/$defs/${name}${redirect?.suffix ?? ""}${hoistRefSuffixes.get(node) ?? ""}`);
711
1004
  }
712
- return resolved2;
1005
+ for (const [cacheKey] of hoists) {
1006
+ if (insideWhole.has(cacheKey))
1007
+ continue;
1008
+ const cached = refCache.get(cacheKey);
1009
+ const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
1010
+ assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
1011
+ }
1012
+ assignKey(container, "$defs", defs);
1013
+ } else {
1014
+ errors.push({
1015
+ message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
1016
+ path: []
1017
+ });
713
1018
  }
714
- const existingAllOf = Array.isArray(siblings["allOf"]) ? siblings["allOf"] : [];
715
- const merged = { ...siblings, allOf: [...existingAllOf, resolved2] };
716
- if (origins && !origins.has(merged))
717
- origins.set(merged, { location: targetLocation, pointer });
718
- if (inlineIsSensitive)
719
- sensitive.add(merged);
720
- return merged;
721
- }
722
- const result = {};
723
- for (const key of Object.keys(obj)) {
724
- const child = resolveAt(obj[key], baseLocation, nodeBase, depth + 1, childRole(role, key));
725
- assignKey(result, key, child);
726
- if (isScopeSensitive(sensitive, child))
727
- sensitive.add(result);
728
1019
  }
729
- if (isSchema && declaresAmbiguousAnchor(obj, ambiguousDynamicAnchors))
730
- sensitive.add(result);
731
- return result;
1020
+ return { result: origins ? { resolved, errors, origins } : { resolved, errors }, unplaceable };
732
1021
  };
733
- const rootRegistry = registryFor(rootLocation);
734
- const resolved = resolveAt(docCache.get(rootLocation), rootLocation, rootRegistry.rootBase, 0, "schema");
735
- if (hoists.size > 0) {
736
- if (resolved !== null && typeof resolved === "object" && !Array.isArray(resolved)) {
737
- const container = resolved;
738
- const defs = container["$defs"] !== null && typeof container["$defs"] === "object" && !Array.isArray(container["$defs"]) ? container["$defs"] : {};
739
- const taken = new Set(Object.keys(defs));
740
- const finalNames = /* @__PURE__ */ new Map();
741
- for (const [cacheKey, name] of hoists) {
742
- let unique = name;
743
- for (let n = 2; taken.has(unique); n++)
744
- unique = `${name}-${n}`;
745
- taken.add(unique);
746
- finalNames.set(cacheKey, unique);
747
- }
748
- for (const [node, cacheKey] of hoistRefSites) {
749
- const name = finalNames.get(cacheKey);
750
- if (name !== void 0)
751
- assignKey(node, "$ref", `#/$defs/${name}`);
752
- }
753
- for (const [cacheKey] of hoists) {
754
- const cached = refCache.get(cacheKey);
755
- const attachable = cached !== void 0 && cached !== CYCLE && cached !== MISSING;
756
- assignKey(defs, finalNames.get(cacheKey), attachable ? cached.value ?? {} : {});
757
- }
758
- assignKey(container, "$defs", defs);
759
- } else {
760
- errors.push({
761
- message: "Cannot attach hoisted cycle definitions: the resolved root document is not an object",
762
- path: []
763
- });
764
- }
765
- }
766
- return origins ? { resolved, errors, origins } : { resolved, errors };
1022
+ const settle = (inlineOnly) => {
1023
+ const { result, unplaceable } = resolvePass(inlineOnly);
1024
+ const more = [...unplaceable].filter((location) => !inlineOnly.has(location));
1025
+ if (more.length === 0)
1026
+ return result;
1027
+ errors.length = errorsBeforeResolve;
1028
+ depthLimitReported = depthReportedBeforeResolve;
1029
+ return settle(/* @__PURE__ */ new Set([...inlineOnly, ...more]));
1030
+ };
1031
+ return settle(/* @__PURE__ */ new Set());
767
1032
  };
768
1033
  export {
769
1034
  clearRemoteCache,
package/dist/types.d.ts CHANGED
@@ -152,6 +152,36 @@ export type ResolveOptions = {
152
152
  * to their source without re-walking the `$ref` chain. Defaults to `false`.
153
153
  */
154
154
  trackOrigins?: boolean;
155
+ /**
156
+ * Bundle instead of inlining: pull every other document a `$ref` reaches into
157
+ * the root's `$defs` and point the ref there, so the output is one
158
+ * self-contained document whose `$ref`s are all internal. A ref into the root
159
+ * document is kept as written, and each target is hoisted once however many
160
+ * refs name it. A code generator wants this: a shared schema stays one named
161
+ * definition rather than an inline copy at every use, which on schemas that
162
+ * reference each other in layers is exponential in the output's size.
163
+ *
164
+ * A document that declares an absolute `$id` at its root is embedded whole
165
+ * under the root's `$defs` with that `$id` kept — how JSON Schema bundles a
166
+ * resource — so the `#/...` pointers written inside it still read against it,
167
+ * and every ref to something in it names it by that URI: a `#/...` pointer from
168
+ * the root into a resource with its own `$id` is one JSON Schema does not
169
+ * promise to resolve. (When a second document claims the same `$id`, refs from
170
+ * the root's own resource fall back to the hoist's pointer, which names one.)
171
+ * Inside any embedded resource `#` names that resource, so a ref there is kept
172
+ * as written when it is a `#...` pointer (or resolves by `$id`) to a target in
173
+ * the same resource, names its target by absolute URI otherwise, and is
174
+ * inlined when the target has no URI (a document without an `$id`). A target
175
+ * with no URI that is part of a cycle cannot be inlined, and has no name that
176
+ * reads the same from inside the resource, so a document whose resource meets
177
+ * one is inlined instead, as without this option. (A resource nested in the
178
+ * root document cannot be inlined; there the ref is the root-relative pointer
179
+ * inlining has always written.) A document whose `$id` is relative, or whose
180
+ * `$id` another bundled document already claims, is inlined.
181
+ * `$dynamicRef` and `$recursiveRef` are resolved as without this option.
182
+ * Defaults to `false`.
183
+ */
184
+ bundle?: boolean;
155
185
  /**
156
186
  * Extra HTTP headers sent with remote `$ref` requests (e.g. an `Authorization`
157
187
  * token for a private schema registry) — a static record, or a function
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/resolve-refs",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
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
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -55,6 +55,6 @@
55
55
  }
56
56
  },
57
57
  "devDependencies": {
58
- "@amritk/runtime-validators": "^0.15.1"
58
+ "@amritk/runtime-validators": "^0.15.2"
59
59
  }
60
60
  }