bundle.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. "use strict";
  2. const $Ref = require("./ref");
  3. const Pointer = require("./pointer");
  4. const url = require("./util/url");
  5. module.exports = bundle;
  6. /**
  7. * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
  8. * only has *internal* references, not any *external* references.
  9. * This method mutates the JSON schema object, adding new references and re-mapping existing ones.
  10. *
  11. * @param {$RefParser} parser
  12. * @param {$RefParserOptions} options
  13. */
  14. function bundle (parser, options) {
  15. // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
  16. // Build an inventory of all $ref pointers in the JSON Schema
  17. let inventory = [];
  18. crawl(parser, "schema", parser.$refs._root$Ref.path + "#", "#", 0, inventory, parser.$refs, options);
  19. // Remap all $ref pointers
  20. remap(inventory);
  21. }
  22. /**
  23. * Recursively crawls the given value, and inventories all JSON references.
  24. *
  25. * @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.
  26. * @param {string} key - The property key of `parent` to be crawled
  27. * @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash
  28. * @param {string} pathFromRoot - The path of the property being crawled, from the schema root
  29. * @param {object[]} inventory - An array of already-inventoried $ref pointers
  30. * @param {$Refs} $refs
  31. * @param {$RefParserOptions} options
  32. */
  33. function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) {
  34. let obj = key === null ? parent : parent[key];
  35. if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj)) {
  36. if ($Ref.isAllowed$Ref(obj)) {
  37. inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options);
  38. }
  39. else {
  40. // Crawl the object in a specific order that's optimized for bundling.
  41. // This is important because it determines how `pathFromRoot` gets built,
  42. // which later determines which keys get dereferenced and which ones get remapped
  43. let keys = Object.keys(obj)
  44. .sort((a, b) => {
  45. // Most people will expect references to be bundled into the the "definitions" property,
  46. // so we always crawl that property first, if it exists.
  47. if (a === "definitions") {
  48. return -1;
  49. }
  50. else if (b === "definitions") {
  51. return 1;
  52. }
  53. else {
  54. // Otherwise, crawl the keys based on their length.
  55. // This produces the shortest possible bundled references
  56. return a.length - b.length;
  57. }
  58. });
  59. // eslint-disable-next-line no-shadow
  60. for (let key of keys) {
  61. let keyPath = Pointer.join(path, key);
  62. let keyPathFromRoot = Pointer.join(pathFromRoot, key);
  63. let value = obj[key];
  64. if ($Ref.isAllowed$Ref(value)) {
  65. inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options);
  66. }
  67. else {
  68. crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options);
  69. }
  70. }
  71. }
  72. }
  73. }
  74. /**
  75. * Inventories the given JSON Reference (i.e. records detailed information about it so we can
  76. * optimize all $refs in the schema), and then crawls the resolved value.
  77. *
  78. * @param {object} $refParent - The object that contains a JSON Reference as one of its keys
  79. * @param {string} $refKey - The key in `$refParent` that is a JSON Reference
  80. * @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
  81. * @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root
  82. * @param {object[]} inventory - An array of already-inventoried $ref pointers
  83. * @param {$Refs} $refs
  84. * @param {$RefParserOptions} options
  85. */
  86. function inventory$Ref ($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) {
  87. let $ref = $refKey === null ? $refParent : $refParent[$refKey];
  88. let $refPath = url.resolve(path, $ref.$ref);
  89. let pointer = $refs._resolve($refPath, pathFromRoot, options);
  90. if (pointer === null) {
  91. return;
  92. }
  93. let depth = Pointer.parse(pathFromRoot).length;
  94. let file = url.stripHash(pointer.path);
  95. let hash = url.getHash(pointer.path);
  96. let external = file !== $refs._root$Ref.path;
  97. let extended = $Ref.isExtended$Ref($ref);
  98. indirections += pointer.indirections;
  99. let existingEntry = findInInventory(inventory, $refParent, $refKey);
  100. if (existingEntry) {
  101. // This $Ref has already been inventoried, so we don't need to process it again
  102. if (depth < existingEntry.depth || indirections < existingEntry.indirections) {
  103. removeFromInventory(inventory, existingEntry);
  104. }
  105. else {
  106. return;
  107. }
  108. }
  109. inventory.push({
  110. $ref, // The JSON Reference (e.g. {$ref: string})
  111. parent: $refParent, // The object that contains this $ref pointer
  112. key: $refKey, // The key in `parent` that is the $ref pointer
  113. pathFromRoot, // The path to the $ref pointer, from the JSON Schema root
  114. depth, // How far from the JSON Schema root is this $ref pointer?
  115. file, // The file that the $ref pointer resolves to
  116. hash, // The hash within `file` that the $ref pointer resolves to
  117. value: pointer.value, // The resolved value of the $ref pointer
  118. circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
  119. extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
  120. external, // Does this $ref pointer point to a file other than the main JSON Schema file?
  121. indirections, // The number of indirect references that were traversed to resolve the value
  122. });
  123. // Recursively crawl the resolved value
  124. if (!existingEntry) {
  125. crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options);
  126. }
  127. }
  128. /**
  129. * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.
  130. * Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same
  131. * value are re-mapped to point to the first reference.
  132. *
  133. * @example:
  134. * {
  135. * first: { $ref: somefile.json#/some/part },
  136. * second: { $ref: somefile.json#/another/part },
  137. * third: { $ref: somefile.json },
  138. * fourth: { $ref: somefile.json#/some/part/sub/part }
  139. * }
  140. *
  141. * In this example, there are four references to the same file, but since the third reference points
  142. * to the ENTIRE file, that's the only one we need to dereference. The other three can just be
  143. * remapped to point inside the third one.
  144. *
  145. * On the other hand, if the third reference DIDN'T exist, then the first and second would both need
  146. * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT
  147. * need to be dereferenced, because it can be remapped to point inside the first one.
  148. *
  149. * @param {object[]} inventory
  150. */
  151. function remap (inventory) {
  152. // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
  153. inventory.sort((a, b) => {
  154. if (a.file !== b.file) {
  155. // Group all the $refs that point to the same file
  156. return a.file < b.file ? -1 : +1;
  157. }
  158. else if (a.hash !== b.hash) {
  159. // Group all the $refs that point to the same part of the file
  160. return a.hash < b.hash ? -1 : +1;
  161. }
  162. else if (a.circular !== b.circular) {
  163. // If the $ref points to itself, then sort it higher than other $refs that point to this $ref
  164. return a.circular ? -1 : +1;
  165. }
  166. else if (a.extended !== b.extended) {
  167. // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
  168. return a.extended ? +1 : -1;
  169. }
  170. else if (a.indirections !== b.indirections) {
  171. // Sort direct references higher than indirect references
  172. return a.indirections - b.indirections;
  173. }
  174. else if (a.depth !== b.depth) {
  175. // Sort $refs by how close they are to the JSON Schema root
  176. return a.depth - b.depth;
  177. }
  178. else {
  179. // Determine how far each $ref is from the "definitions" property.
  180. // Most people will expect references to be bundled into the the "definitions" property if possible.
  181. let aDefinitionsIndex = a.pathFromRoot.lastIndexOf("/definitions");
  182. let bDefinitionsIndex = b.pathFromRoot.lastIndexOf("/definitions");
  183. if (aDefinitionsIndex !== bDefinitionsIndex) {
  184. // Give higher priority to the $ref that's closer to the "definitions" property
  185. return bDefinitionsIndex - aDefinitionsIndex;
  186. }
  187. else {
  188. // All else is equal, so use the shorter path, which will produce the shortest possible reference
  189. return a.pathFromRoot.length - b.pathFromRoot.length;
  190. }
  191. }
  192. });
  193. let file, hash, pathFromRoot;
  194. for (let entry of inventory) {
  195. // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot);
  196. if (!entry.external) {
  197. // This $ref already resolves to the main JSON Schema file
  198. entry.$ref.$ref = entry.hash;
  199. }
  200. else if (entry.file === file && entry.hash === hash) {
  201. // This $ref points to the same value as the prevous $ref, so remap it to the same path
  202. entry.$ref.$ref = pathFromRoot;
  203. }
  204. else if (entry.file === file && entry.hash.indexOf(hash + "/") === 0) {
  205. // This $ref points to a sub-value of the prevous $ref, so remap it beneath that path
  206. entry.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(entry.hash.replace(hash, "#")));
  207. }
  208. else {
  209. // We've moved to a new file or new hash
  210. file = entry.file;
  211. hash = entry.hash;
  212. pathFromRoot = entry.pathFromRoot;
  213. // This is the first $ref to point to this value, so dereference the value.
  214. // Any other $refs that point to the same value will point to this $ref instead
  215. entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value);
  216. if (entry.circular) {
  217. // This $ref points to itself
  218. entry.$ref.$ref = entry.pathFromRoot;
  219. }
  220. }
  221. // console.log(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]');
  222. }
  223. }
  224. /**
  225. * TODO
  226. */
  227. function findInInventory (inventory, $refParent, $refKey) {
  228. for (let i = 0; i < inventory.length; i++) {
  229. let existingEntry = inventory[i];
  230. if (existingEntry.parent === $refParent && existingEntry.key === $refKey) {
  231. return existingEntry;
  232. }
  233. }
  234. }
  235. function removeFromInventory (inventory, entry) {
  236. let index = inventory.indexOf(entry);
  237. inventory.splice(index, 1);
  238. }