@scalar/json-magic 0.6.1 → 0.8.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.
Files changed (67) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/CHANGELOG.md +26 -0
  3. package/dist/bundle/bundle.d.ts +1 -0
  4. package/dist/bundle/bundle.d.ts.map +1 -1
  5. package/dist/bundle/bundle.js +4 -4
  6. package/dist/bundle/bundle.js.map +2 -2
  7. package/dist/bundle/plugins/fetch-urls/index.d.ts.map +1 -1
  8. package/dist/bundle/plugins/fetch-urls/index.js +2 -1
  9. package/dist/bundle/plugins/fetch-urls/index.js.map +2 -2
  10. package/dist/bundle/plugins/parse-json/index.d.ts.map +1 -1
  11. package/dist/bundle/plugins/parse-json/index.js +7 -6
  12. package/dist/bundle/plugins/parse-json/index.js.map +2 -2
  13. package/dist/bundle/plugins/parse-yaml/index.d.ts.map +1 -1
  14. package/dist/bundle/plugins/parse-yaml/index.js +7 -6
  15. package/dist/bundle/plugins/parse-yaml/index.js.map +2 -2
  16. package/dist/bundle/plugins/read-files/index.d.ts.map +1 -1
  17. package/dist/bundle/plugins/read-files/index.js +2 -1
  18. package/dist/bundle/plugins/read-files/index.js.map +2 -2
  19. package/dist/bundle/value-generator.d.ts +6 -4
  20. package/dist/bundle/value-generator.d.ts.map +1 -1
  21. package/dist/bundle/value-generator.js +2 -5
  22. package/dist/bundle/value-generator.js.map +2 -2
  23. package/dist/diff/diff.d.ts.map +1 -1
  24. package/dist/diff/diff.js.map +2 -2
  25. package/dist/diff/utils.d.ts.map +1 -1
  26. package/dist/diff/utils.js.map +2 -2
  27. package/dist/helpers/generate-hash.d.ts +11 -0
  28. package/dist/helpers/generate-hash.d.ts.map +1 -0
  29. package/dist/helpers/generate-hash.js +16 -0
  30. package/dist/helpers/generate-hash.js.map +7 -0
  31. package/dist/magic-proxy/proxy.d.ts +1 -0
  32. package/dist/magic-proxy/proxy.d.ts.map +1 -1
  33. package/dist/magic-proxy/proxy.js +11 -1
  34. package/dist/magic-proxy/proxy.js.map +2 -2
  35. package/esbuild.ts +1 -0
  36. package/package.json +10 -4
  37. package/src/bundle/bundle.test.ts +293 -274
  38. package/src/bundle/bundle.ts +6 -5
  39. package/src/bundle/plugins/fetch-urls/index.test.ts +21 -24
  40. package/src/bundle/plugins/fetch-urls/index.ts +1 -0
  41. package/src/bundle/plugins/parse-json/index.test.ts +3 -1
  42. package/src/bundle/plugins/parse-json/index.ts +7 -6
  43. package/src/bundle/plugins/parse-yaml/index.test.ts +3 -1
  44. package/src/bundle/plugins/parse-yaml/index.ts +7 -6
  45. package/src/bundle/plugins/read-files/index.test.ts +4 -3
  46. package/src/bundle/plugins/read-files/index.ts +1 -0
  47. package/src/bundle/value-generator.test.ts +7 -8
  48. package/src/bundle/value-generator.ts +11 -15
  49. package/src/dereference/dereference.test.ts +10 -10
  50. package/src/diff/diff.ts +0 -1
  51. package/src/diff/utils.test.ts +2 -2
  52. package/src/diff/utils.ts +0 -2
  53. package/src/helpers/escape-json-pointer.test.ts +1 -1
  54. package/src/helpers/generate-hash.test.ts +74 -0
  55. package/src/helpers/generate-hash.ts +29 -0
  56. package/src/helpers/unescape-json-pointer.test.ts +1 -1
  57. package/src/magic-proxy/proxy.ts +14 -0
  58. package/dist/polyfills/index.d.ts +0 -2
  59. package/dist/polyfills/index.d.ts.map +0 -1
  60. package/dist/polyfills/index.js +0 -25
  61. package/dist/polyfills/index.js.map +0 -7
  62. package/dist/polyfills/path.d.ts +0 -24
  63. package/dist/polyfills/path.d.ts.map +0 -1
  64. package/dist/polyfills/path.js +0 -174
  65. package/dist/polyfills/path.js.map +0 -7
  66. package/src/polyfills/index.ts +0 -12
  67. package/src/polyfills/path.ts +0 -248
@@ -1,10 +1,10 @@
1
1
 
2
- > @scalar/json-magic@0.6.1 build /home/runner/work/scalar/scalar/packages/json-magic
2
+ > @scalar/json-magic@0.8.0 build /home/runner/work/scalar/scalar/packages/json-magic
3
3
  > scalar-build-esbuild
4
4
 
5
- @scalar/json-magic: Build completed in 25.49ms
5
+ @scalar/json-magic: Build completed in 31.84ms
6
6
 
7
- > @scalar/json-magic@0.6.1 types:build /home/runner/work/scalar/scalar/packages/json-magic
7
+ > @scalar/json-magic@0.8.0 types:build /home/runner/work/scalar/scalar/packages/json-magic
8
8
  > scalar-types-build
9
9
 
10
- Types build completed in 1.86s
10
+ Types build completed in 1.68s
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @scalar/json-magic
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#7235](https://github.com/scalar/scalar/pull/7235) [`c1ecd0c`](https://github.com/scalar/scalar/commit/c1ecd0c6096f3fbe2e3d8ad3794ea718bb6bce66) Thanks [@marcalexiei](https://github.com/marcalexiei)! - feat(json-magic): use `@scalar/helpers/node/path` polyfill
8
+
9
+ ### Patch Changes
10
+
11
+ - [#7266](https://github.com/scalar/scalar/pull/7266) [`fddf294`](https://github.com/scalar/scalar/commit/fddf294b00dd8c9eb5c713c338f2ec6e3f62523d) Thanks [@amritk](https://github.com/amritk)! - fix: remove useage of crypto.subtle in all contexts
12
+
13
+ - Updated dependencies [[`fddf294`](https://github.com/scalar/scalar/commit/fddf294b00dd8c9eb5c713c338f2ec6e3f62523d), [`c1ecd0c`](https://github.com/scalar/scalar/commit/c1ecd0c6096f3fbe2e3d8ad3794ea718bb6bce66)]:
14
+ - @scalar/helpers@0.1.0
15
+
16
+ ## 0.7.0
17
+
18
+ ### Minor Changes
19
+
20
+ - [#7185](https://github.com/scalar/scalar/pull/7185) [`6ca835e`](https://github.com/scalar/scalar/commit/6ca835e5afd3e8c603e073e7c83f2cdd961a0f69) Thanks [@DemonHa](https://github.com/DemonHa)! - feat: add support for watch mode
21
+
22
+ ### Patch Changes
23
+
24
+ - [#7213](https://github.com/scalar/scalar/pull/7213) [`43bc5e8`](https://github.com/scalar/scalar/commit/43bc5e8b90dc0edf7176d0ddfc64bf3212494458) Thanks [@DemonHa](https://github.com/DemonHa)! - fix: proxy performance issue because of multiple proxies
25
+
26
+ - Updated dependencies [[`6ec8c29`](https://github.com/scalar/scalar/commit/6ec8c299d912111b029e8058979d00968b70691a)]:
27
+ - @scalar/helpers@0.0.13
28
+
3
29
  ## 0.6.1
4
30
 
5
31
  ### Patch Changes
@@ -42,6 +42,7 @@ export declare function isLocalRef(value: string): boolean;
42
42
  export type ResolveResult = {
43
43
  ok: true;
44
44
  data: unknown;
45
+ raw: string;
45
46
  } | {
46
47
  ok: false;
47
48
  };
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../src/bundle/bundle.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAA;AAS5C;;;;;;;;;;;GAWG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,WAOxC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,WAEvC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEjD;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAA;CAAE,CAAA;AA2BvE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI,CAyBvE;AAuCD;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAMhE;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,0BAA0B,CAAC,KAAK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;IAEhB;;;OAGG;IACH,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAA;IAEtD;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;QACd;;;WAGG;QACH,cAAc,EAAE,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;QACvE;;;WAGG;QACH,cAAc,EAAE,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;QACvE;;;WAGG;QACH,gBAAgB,EAAE,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAA;QACzE;;;WAGG;QACH,mBAAmB,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;QAC/F;;;WAGG;QACH,kBAAkB,EAAE,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,kBAAkB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;KAC/F,CAAC,CAAA;CACH,CAAA;AAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AACH,wBAAsB,MAAM,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,EAAE,MAAM,EAAE,MAAM,mBA0SzE"}
@@ -1,7 +1,7 @@
1
+ import { path } from "@scalar/helpers/node/path";
1
2
  import { convertToLocalRef } from "../helpers/convert-to-local-ref.js";
2
3
  import { getId, getSchemas } from "../helpers/get-schemas.js";
3
4
  import { getValueByPath } from "../helpers/get-value-by-path.js";
4
- import path from "../polyfills/path.js";
5
5
  import { escapeJsonPointer } from "../helpers/escape-json-pointer.js";
6
6
  import { getSegmentsFromPath } from "../helpers/get-segments-from-path.js";
7
7
  import { isJsonObject } from "../helpers/is-json-object.js";
@@ -22,14 +22,14 @@ function isFilePath(value) {
22
22
  function isLocalRef(value) {
23
23
  return value.startsWith("#");
24
24
  }
25
- async function resolveContents(value, plugins) {
25
+ function resolveContents(value, plugins) {
26
26
  const plugin = plugins.find((p) => p.validate(value));
27
27
  if (plugin) {
28
28
  return plugin.exec(value);
29
29
  }
30
- return {
30
+ return Promise.resolve({
31
31
  ok: false
32
- };
32
+ });
33
33
  }
34
34
  function setValueAtPath(obj, path2, value) {
35
35
  if (path2 === "") {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/bundle/bundle.ts"],
4
- "sourcesContent": ["import { convertToLocalRef } from '@/helpers/convert-to-local-ref'\nimport { getId, getSchemas } from '@/helpers/get-schemas'\nimport { getValueByPath } from '@/helpers/get-value-by-path'\nimport path from '@/polyfills/path'\nimport type { UnknownObject } from '@/types'\n\nimport { escapeJsonPointer } from '../helpers/escape-json-pointer'\nimport { getSegmentsFromPath } from '../helpers/get-segments-from-path'\nimport { isJsonObject } from '../helpers/is-json-object'\nimport { isObject } from '../helpers/is-object'\nimport { isYaml } from '../helpers/is-yaml'\nimport { getHash, uniqueValueGeneratorFactory } from './value-generator'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string) {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * Checks if a string represents a file path by ensuring it's not a remote URL,\n * YAML content, or JSON content.\n *\n * @param value - The string to check\n * @returns true if the string appears to be a file path, false otherwise\n * @example\n * ```ts\n * isFilePath('./schemas/user.json') // true\n * isFilePath('https://example.com/schema.json') // false\n * isFilePath('{\"type\": \"object\"}') // false\n * isFilePath('type: object') // false\n * ```\n */\nexport function isFilePath(value: string) {\n return !isRemoteUrl(value) && !isYaml(value) && !isJsonObject(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nasync function resolveContents(value: string, plugins: LoaderPlugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return {\n ok: false,\n }\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n // If the url stars with a / we want it to resolve from the origin so we replace the pathname\n if (relativePath.startsWith('/')) {\n url.pathname = relativePath\n return url.toString()\n }\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n input['$ref'] = prefixInternalRef(ref, prefix)\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param bundleLocalRefs - Also bundles the local refs\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nexport const resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n bundleLocalRefs = false,\n processedNodes = new Set(),\n) => {\n const referencedValue = getValueByPath(sourceDocument, getSegmentsFromPath(referencePath)).value\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n externalRefsKey,\n documentKey,\n bundleLocalRefs,\n processedNodes,\n )\n }\n // Bundle the local refs as well\n else if (bundleLocalRefs) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n externalRefsKey,\n documentKey,\n bundleLocalRefs,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * A loader plugin for resolving external references during bundling.\n * Loader plugins are responsible for handling specific types of external references,\n * such as files, URLs, or custom protocols. Each loader plugin must provide:\n *\n * - A `validate` function to determine if the plugin can handle a given reference string.\n * - An `exec` function to asynchronously fetch and resolve the referenced data,\n * returning a Promise that resolves to a `ResolveResult`.\n *\n * Loader plugins enable extensible support for different reference sources in the bundler.\n *\n * @property type - The plugin type, always 'loader' for loader plugins.\n * @property validate - Function to check if the plugin can handle a given reference value.\n * @property exec - Function to fetch and resolve the reference, returning the resolved data.\n */\nexport type LoaderPlugin = {\n type: 'loader'\n // Returns true if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Asynchronously fetches and resolves the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Context information for a node during traversal or processing.\n *\n * Note: The `path` parameter represents the path to the current node being processed.\n * If you are performing a partial bundle (i.e., providing a custom root), this path will be relative\n * to the root you provide, not the absolute root of the original document. You may need to prefix\n * it with your own base path if you want to construct a full path from the absolute document root.\n *\n * - `path`: The JSON pointer path (as an array of strings) from the document root to the current node.\n * - `resolutionCache`: A cache for storing promises of resolved references.\n */\ntype NodeProcessContext = {\n path: readonly string[]\n resolutionCache: Map<string, Promise<Readonly<ResolveResult>>>\n parentNode: UnknownObject | null\n rootNode: UnknownObject\n loaders: LoaderPlugin[]\n}\n\n/**\n * A plugin type for lifecycle hooks, allowing custom logic to be injected into the bundler's process.\n * This type extends the Config['hooks'] interface and is identified by type: 'lifecycle'.\n */\nexport type LifecyclePlugin = { type: 'lifecycle' } & Config['hooks']\n\n/**\n * Represents a plugin used by the bundler for extensibility.\n *\n * Plugins can be either:\n * - Loader plugins: Responsible for resolving and loading external references (e.g., from files, URLs, or custom sources).\n * - Lifecycle plugins: Provide lifecycle hooks to customize or extend the bundling process.\n *\n * Loader plugins must implement:\n * - `validate`: Checks if the plugin can handle a given reference value.\n * - `exec`: Asynchronously resolves and returns the referenced data.\n *\n * Lifecycle plugins extend the bundler's lifecycle hooks for custom logic.\n */\nexport type Plugin = LoaderPlugin | LifecyclePlugin\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional maximum depth for reference resolution.\n * Limits how deeply the bundler will follow and resolve nested $ref pointers.\n * Useful for preventing infinite recursion or excessive resource usage.\n */\n depth?: number\n\n /**\n * Optional origin path for the bundler.\n * Used to resolve relative paths in references, especially when the input is a string URL or file path.\n * If not provided, the bundler will use the input value as the origin.\n */\n origin?: string\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional function to compress input URLs or file paths before bundling.\n * Returns either a Promise resolving to the compressed string or the compressed string directly.\n */\n compress?: (value: string) => Promise<string> | string\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /**\n * Optional hook called when the bundler starts resolving a $ref.\n * Useful for tracking or logging the beginning of a reference resolution.\n */\n onResolveStart: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook called when the bundler fails to resolve a $ref.\n * Can be used for error handling, logging, or custom error reporting.\n */\n onResolveError: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook called when the bundler successfully resolves a $ref.\n * Useful for tracking successful resolutions or custom post-processing.\n */\n onResolveSuccess: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook invoked before processing a node.\n * Can be used for preprocessing, mutation, or custom logic before the node is handled by the bundler.\n */\n onBeforeNodeProcess: (node: UnknownObject, context: NodeProcessContext) => void | Promise<void>\n /**\n * Optional hook invoked after processing a node.\n * Useful for postprocessing, cleanup, or custom logic after the node has been handled by the bundler.\n */\n onAfterNodeProcess: (node: UnknownObject, context: NodeProcessContext) => void | Promise<void>\n }>\n}\n\n/**\n * Extension keys used for bundling external references in OpenAPI documents.\n * These custom extensions help maintain the structure and traceability of bundled documents.\n */\nconst extensions = {\n /**\n * Custom OpenAPI extension key used to store external references.\n * This key will contain all bundled external documents.\n * The x-ext key is used to maintain a clean separation between the main\n * OpenAPI document and its bundled external references.\n */\n externalDocuments: 'x-ext',\n\n /**\n * Custom OpenAPI extension key used to maintain a mapping between\n * hashed keys and their original URLs in x-ext.\n * This mapping is essential for tracking the source of bundled references\n */\n externalDocumentsMappings: 'x-ext-urls',\n} as const\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification to bundle. Can be either an object or string.\n * If a string is provided, it will be resolved using the provided plugins.\n * If no plugin can process the input, the onReferenceError hook will be invoked\n * and an error will be emitted to the console.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n const loaderPlugins = config.plugins.filter((it) => it.type === 'loader')\n const lifecyclePlugin = config.plugins.filter((it) => it.type === 'lifecycle')\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, loaderPlugins)\n\n if (result.ok && typeof result.data === 'object') {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Extract all $id and $anchor values from the document to identify local schemas\n const schemas = getSchemas(documentRoot)\n\n // Determines if the bundling operation is partial.\n // Partial bundling occurs when:\n // - A root document is provided that is different from the raw specification being bundled, or\n // - A maximum depth is specified in the config.\n // In these cases, only a subset of the document may be bundled.\n const isPartialBundling =\n (config.root !== undefined && config.root !== rawSpecification) || config.depth !== undefined\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n // Determines the initial origin path for the bundler based on the input type.\n // For string inputs that are URLs or file paths, uses the input as the origin.\n // For non-string inputs or other string types, returns an empty string.\n const defaultOrigin = () => {\n if (config.origin) {\n return config.origin\n }\n\n if (typeof input !== 'string') {\n return ''\n }\n\n if (isRemoteUrl(input) || isFilePath(input)) {\n return input\n }\n\n return ''\n }\n\n // Create the cache to store the compressed values to their map values\n if (documentRoot[extensions.externalDocumentsMappings] === undefined) {\n documentRoot[extensions.externalDocumentsMappings] = {}\n }\n const { generate } = uniqueValueGeneratorFactory(\n config.compress ?? getHash,\n documentRoot[extensions.externalDocumentsMappings],\n )\n\n const bundler = async (\n root: unknown,\n origin: string = defaultOrigin(),\n isChunkParent = false,\n depth = 0,\n currentPath: readonly string[] = [],\n parent: UnknownObject = null,\n ) => {\n // If a maximum depth is set in the config, stop bundling when the current depth reaches or exceeds it\n if (config.depth !== undefined && depth > config.depth) {\n return\n }\n\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n // Invoke the onBeforeNodeProcess hook for the current node before any further processing\n await config.hooks?.onBeforeNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n // Invoke onBeforeNodeProcess hooks from all registered lifecycle plugins\n for (const plugin of lifecyclePlugin) {\n await plugin.onBeforeNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n }\n\n const id = getId(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n // Try to convert the reference to a local reference if possible\n // This handles cases where the reference points to a local schema using $id or $anchor\n // If it can be converted to a local reference, we do not need to bundle it\n // and can skip further processing for this reference\n // In case of partial bundling, we still need to ensure that all dependencies\n // of the local reference are bundled to create a complete and self-contained partial bundle\n // This is important to maintain the integrity of the partial bundle\n const localRef = convertToLocalRef(ref, id ?? origin, schemas)\n\n if (localRef !== undefined) {\n if (isPartialBundling) {\n const segments = getSegmentsFromPath(`/${localRef}`)\n const parent = segments.length > 0 ? getValueByPath(documentRoot, segments.slice(0, -1)).value : undefined\n\n const targetValue = getValueByPath(documentRoot, segments)\n\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(targetValue.value, targetValue.context, isChunkParent, depth + 1, segments, parent)\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(id ?? origin, prefix)\n\n // Generate a unique compressed path for the external document\n // This is used as a key to store and reference the bundled external document\n // The compression helps reduce the overall file size of the bundled document\n const compressedPath = await generate(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, loaderPlugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveStart?.(root))\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk, depth + 1, [\n extensions.externalDocuments,\n compressedPath,\n documentRoot[extensions.externalDocumentsMappings],\n ])\n\n // Store the mapping between hashed keys and original URLs in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n setValueAtPath(\n documentRoot,\n `/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,\n resolvedPath,\n )\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [extensions.externalDocuments]: { [compressedPath]: result.data } },\n prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath]).substring(1),\n extensions.externalDocuments,\n compressedPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath])\n\n config?.hooks?.onResolveSuccess?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveSuccess?.(root))\n\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveError?.(root))\n\n return console.warn(\n `Failed to resolve external reference \"${resolvedPath}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively traverse all child properties of the current object to resolve nested $ref references.\n // This step ensures that any $refs located deeper within the object hierarchy are discovered and processed.\n // We explicitly skip the extension keys (x-ext and x-ext-urls) to avoid reprocessing already bundled or mapped content.\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === extensions.externalDocuments || key === extensions.externalDocumentsMappings) {\n return\n }\n\n await bundler(value, id ?? origin, isChunkParent, depth + 1, [...currentPath, key], root as UnknownObject)\n }),\n )\n\n // Invoke the optional onAfterNodeProcess hook from the config, if provided.\n // This allows for custom post-processing logic after a node has been handled by the bundler.\n await config.hooks?.onAfterNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n\n // Iterate through all lifecycle plugins and invoke their onAfterNodeProcess hooks, if defined.\n // This enables plugins to perform additional post-processing or cleanup after the node is processed.\n for (const plugin of lifecyclePlugin) {\n await plugin.onAfterNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n }\n }\n\n await bundler(rawSpecification)\n\n // Keep urlMappings when doing partial bundling to track hash values and handle collisions\n // For full bundling without urlMap config, remove the mappings to clean up the output\n if (!config.urlMap && !isPartialBundling) {\n // Remove the external document mappings from the output when doing a full bundle without urlMap config\n delete documentRoot[extensions.externalDocumentsMappings]\n }\n\n return rawSpecification\n}\n"],
5
- "mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,OAAO,kBAAkB;AAClC,SAAS,sBA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WAAW,qBAAqB,QAAQ,WAAW,2BAA2B;AACxF;AAAA,QACF;AAEA,cAAM,QAAQ,OAAO,MAAM,QAAQ,eAAe,QAAQ,GAAG,CAAC,GAAG,aAAa,GAAG,GAAG,IAAqB;AAAA,MAC3G,CAAC;AAAA,IACH;AAIA,UAAM,OAAO,OAAO,qBAAqB,MAAuB;AAAA,MAC9D,MAAM;AAAA,MACN,iBAAiB;AAAA,MACjB,YAAY;AAAA,MACZ,UAAU;AAAA,MACV,SAAS;AAAA,IACX,CAAC;AAID,eAAW,UAAU,iBAAiB;AACpC,YAAM,OAAO,qBAAqB,MAAuB;AAAA,QACvD,MAAM;AAAA,QACN,iBAAiB;AAAA,QACjB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,QAAQ,gBAAgB;AAI9B,MAAI,CAAC,OAAO,UAAU,CAAC,mBAAmB;AAExC,WAAO,aAAa,WAAW,yBAAyB;AAAA,EAC1D;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["import { path } from '@scalar/helpers/node/path'\n\nimport { convertToLocalRef } from '@/helpers/convert-to-local-ref'\nimport { getId, getSchemas } from '@/helpers/get-schemas'\nimport { getValueByPath } from '@/helpers/get-value-by-path'\nimport type { UnknownObject } from '@/types'\n\nimport { escapeJsonPointer } from '../helpers/escape-json-pointer'\nimport { getSegmentsFromPath } from '../helpers/get-segments-from-path'\nimport { isJsonObject } from '../helpers/is-json-object'\nimport { isObject } from '../helpers/is-object'\nimport { isYaml } from '../helpers/is-yaml'\nimport { getHash, uniqueValueGeneratorFactory } from './value-generator'\n\n/**\n * Checks if a string is a remote URL (starts with http:// or https://)\n * @param value - The URL string to check\n * @returns true if the string is a remote URL, false otherwise\n * @example\n * ```ts\n * isRemoteUrl('https://example.com/schema.json') // true\n * isRemoteUrl('http://api.example.com/schemas/user.json') // true\n * isRemoteUrl('#/components/schemas/User') // false\n * isRemoteUrl('./local-schema.json') // false\n * ```\n */\nexport function isRemoteUrl(value: string) {\n try {\n const url = new URL(value)\n return url.protocol === 'http:' || url.protocol === 'https:'\n } catch {\n return false\n }\n}\n\n/**\n * Checks if a string represents a file path by ensuring it's not a remote URL,\n * YAML content, or JSON content.\n *\n * @param value - The string to check\n * @returns true if the string appears to be a file path, false otherwise\n * @example\n * ```ts\n * isFilePath('./schemas/user.json') // true\n * isFilePath('https://example.com/schema.json') // false\n * isFilePath('{\"type\": \"object\"}') // false\n * isFilePath('type: object') // false\n * ```\n */\nexport function isFilePath(value: string) {\n return !isRemoteUrl(value) && !isYaml(value) && !isJsonObject(value)\n}\n\n/**\n * Checks if a string is a local reference (starts with #)\n * @param value - The reference string to check\n * @returns true if the string is a local reference, false otherwise\n * @example\n * ```ts\n * isLocalRef('#/components/schemas/User') // true\n * isLocalRef('https://example.com/schema.json') // false\n * isLocalRef('./local-schema.json') // false\n * ```\n */\nexport function isLocalRef(value: string): boolean {\n return value.startsWith('#')\n}\n\nexport type ResolveResult = { ok: true; data: unknown; raw: string } | { ok: false }\n\n/**\n * Resolves a string by finding and executing the appropriate plugin.\n * @param value - The string to resolve (URL, file path, etc)\n * @param plugins - Array of plugins that can handle different types of strings\n * @returns A promise that resolves to either the content or an error result\n * @example\n * // Using a URL plugin\n * await resolveContents('https://example.com/schema.json', [urlPlugin])\n * // Using a file plugin\n * await resolveContents('./schemas/user.json', [filePlugin])\n * // No matching plugin returns { ok: false }\n * await resolveContents('#/components/schemas/User', [urlPlugin, filePlugin])\n */\nfunction resolveContents(value: string, plugins: LoaderPlugin[]): Promise<ResolveResult> {\n const plugin = plugins.find((p) => p.validate(value))\n\n if (plugin) {\n return plugin.exec(value)\n }\n\n return Promise.resolve({\n ok: false,\n })\n}\n\n/**\n * Sets a value at a specified path in an object, creating intermediate objects/arrays as needed.\n * This function traverses the object structure and creates any missing intermediate objects\n * or arrays based on the path segments. If the next segment is a numeric string, it creates\n * an array instead of an object.\n *\n * \u26A0\uFE0F Warning: Be careful with object keys that look like numbers (e.g. \"123\") as this function\n * will interpret them as array indices and create arrays instead of objects. If you need to\n * use numeric-looking keys, consider prefixing them with a non-numeric character.\n *\n * @param obj - The target object to set the value in\n * @param path - The JSON pointer path where the value should be set\n * @param value - The value to set at the specified path\n * @throws {Error} If attempting to set a value at the root path ('')\n *\n * @example\n * const obj = {}\n * setValueAtPath(obj, '/foo/bar/0', 'value')\n * // Result:\n * // {\n * // foo: {\n * // bar: ['value']\n * // }\n * // }\n *\n * @example\n * const obj = { existing: { path: 'old' } }\n * setValueAtPath(obj, '/existing/path', 'new')\n * // Result:\n * // {\n * // existing: {\n * // path: 'new'\n * // }\n * // }\n *\n * @example\n * // \u26A0\uFE0F Warning: This will create an array instead of an object with key \"123\"\n * setValueAtPath(obj, '/foo/123/bar', 'value')\n * // Result:\n * // {\n * // foo: [\n * // undefined,\n * // undefined,\n * // undefined,\n * // { bar: 'value' }\n * // ]\n * // }\n */\nexport function setValueAtPath(obj: any, path: string, value: any): void {\n if (path === '') {\n throw new Error(\"Cannot set value at root ('') pointer\")\n }\n\n const parts = getSegmentsFromPath(path)\n\n let current = obj\n\n for (let i = 0; i < parts.length; i++) {\n const key = parts[i]\n const isLast = i === parts.length - 1\n\n const nextKey = parts[i + 1]\n const shouldBeArray = /^\\d+$/.test(nextKey ?? '')\n\n if (isLast) {\n current[key] = value\n } else {\n if (!(key in current) || typeof current[key] !== 'object') {\n current[key] = shouldBeArray ? [] : {}\n }\n current = current[key]\n }\n }\n}\n\n/**\n * Resolves a reference path by combining a base path with a relative path.\n * Handles both remote URLs and local file paths.\n *\n * @param base - The base path (can be a URL or local file path)\n * @param relativePath - The relative path to resolve against the base\n * @returns The resolved absolute path\n * @example\n * // Resolve remote URL\n * resolveReferencePath('https://example.com/api/schema.json', 'user.json')\n * // Returns: 'https://example.com/api/user.json'\n *\n * // Resolve local path\n * resolveReferencePath('/path/to/schema.json', 'user.json')\n * // Returns: '/path/to/user.json'\n */\nfunction resolveReferencePath(base: string, relativePath: string) {\n if (isRemoteUrl(relativePath)) {\n return relativePath\n }\n\n if (isRemoteUrl(base)) {\n const url = new URL(base)\n\n // If the url stars with a / we want it to resolve from the origin so we replace the pathname\n if (relativePath.startsWith('/')) {\n url.pathname = relativePath\n return url.toString()\n }\n\n const mergedPath = path.join(path.dirname(url.pathname), relativePath)\n return new URL(mergedPath, base).toString()\n }\n\n return path.join(path.dirname(base), relativePath)\n}\n\n/**\n * Prefixes an internal JSON reference with a given path prefix.\n * Takes a local reference (starting with #) and prepends the provided prefix segments.\n *\n * @param input - The internal reference string to prefix (must start with #)\n * @param prefix - Array of path segments to prepend to the reference\n * @returns The prefixed reference string\n * @throws Error if input is not a local reference\n * @example\n * prefixInternalRef('#/components/schemas/User', ['definitions'])\n * // Returns: '#/definitions/components/schemas/User'\n */\nexport function prefixInternalRef(input: string, prefix: string[]) {\n if (!isLocalRef(input)) {\n throw 'Please provide an internal ref'\n }\n\n return `#/${prefix.map(escapeJsonPointer).join('/')}${input.substring(1)}`\n}\n\n/**\n * Updates internal references in an object by adding a prefix to their paths.\n * Recursively traverses the input object and modifies any local $ref references\n * by prepending the given prefix to their paths. This is used when embedding external\n * documents to maintain correct reference paths relative to the main document.\n *\n * @param input - The object to update references in\n * @param prefix - Array of path segments to prepend to internal reference paths\n * @returns void\n * @example\n * ```ts\n * const input = {\n * foo: {\n * $ref: '#/components/schemas/User'\n * }\n * }\n * prefixInternalRefRecursive(input, ['definitions'])\n * // Result:\n * // {\n * // foo: {\n * // $ref: '#/definitions/components/schemas/User'\n * // }\n * // }\n * ```\n */\nexport function prefixInternalRefRecursive(input: unknown, prefix: string[]) {\n if (!isObject(input)) {\n return\n }\n\n Object.values(input).forEach((el) => prefixInternalRefRecursive(el, prefix))\n\n if (typeof input === 'object' && '$ref' in input && typeof input['$ref'] === 'string') {\n const ref = input['$ref']\n\n if (!isLocalRef(ref)) {\n return\n }\n\n input['$ref'] = prefixInternalRef(ref, prefix)\n }\n}\n\n/**\n * Resolves and copies referenced values from a source document to a target document.\n * This function traverses the document and copies referenced values to the target document,\n * while tracking processed references to avoid duplicates. It only processes references\n * that belong to the same external document.\n *\n * @param targetDocument - The document to copy referenced values to\n * @param sourceDocument - The source document containing the references\n * @param referencePath - The JSON pointer path to the reference\n * @param externalRefsKey - The key used for external references (e.g. 'x-ext')\n * @param documentKey - The key identifying the external document\n * @param bundleLocalRefs - Also bundles the local refs\n * @param processedNodes - Set of already processed nodes to prevent duplicates\n * @example\n * ```ts\n * const source = {\n * components: {\n * schemas: {\n * User: {\n * $ref: '#/x-ext/users~1schema/definitions/Person'\n * }\n * }\n * }\n * }\n *\n * const target = {}\n * resolveAndCopyReferences(\n * target,\n * source,\n * '/components/schemas/User',\n * 'x-ext',\n * 'users/schema'\n * )\n * // Result: target will contain the User schema with resolved references\n * ```\n */\nexport const resolveAndCopyReferences = (\n targetDocument: unknown,\n sourceDocument: unknown,\n referencePath: string,\n externalRefsKey: string,\n documentKey: string,\n bundleLocalRefs = false,\n processedNodes = new Set(),\n) => {\n const referencedValue = getValueByPath(sourceDocument, getSegmentsFromPath(referencePath)).value\n\n if (processedNodes.has(referencedValue)) {\n return\n }\n processedNodes.add(referencedValue)\n\n setValueAtPath(targetDocument, referencePath, referencedValue)\n\n // Do the same for each local ref\n const traverse = (node: unknown) => {\n if (!node || typeof node !== 'object') {\n return\n }\n\n if ('$ref' in node && typeof node['$ref'] === 'string') {\n // We only process references from the same external document because:\n // 1. Other documents will be handled in separate recursive branches\n // 2. The source document only contains the current document's content\n // This prevents undefined behavior and maintains proper document boundaries\n if (node['$ref'].startsWith(`#/${externalRefsKey}/${escapeJsonPointer(documentKey)}`)) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n externalRefsKey,\n documentKey,\n bundleLocalRefs,\n processedNodes,\n )\n }\n // Bundle the local refs as well\n else if (bundleLocalRefs) {\n resolveAndCopyReferences(\n targetDocument,\n sourceDocument,\n node['$ref'].substring(1),\n externalRefsKey,\n documentKey,\n bundleLocalRefs,\n processedNodes,\n )\n }\n }\n\n for (const value of Object.values(node)) {\n traverse(value)\n }\n }\n\n traverse(referencedValue)\n}\n\n/**\n * A loader plugin for resolving external references during bundling.\n * Loader plugins are responsible for handling specific types of external references,\n * such as files, URLs, or custom protocols. Each loader plugin must provide:\n *\n * - A `validate` function to determine if the plugin can handle a given reference string.\n * - An `exec` function to asynchronously fetch and resolve the referenced data,\n * returning a Promise that resolves to a `ResolveResult`.\n *\n * Loader plugins enable extensible support for different reference sources in the bundler.\n *\n * @property type - The plugin type, always 'loader' for loader plugins.\n * @property validate - Function to check if the plugin can handle a given reference value.\n * @property exec - Function to fetch and resolve the reference, returning the resolved data.\n */\nexport type LoaderPlugin = {\n type: 'loader'\n // Returns true if this plugin can handle the given reference value\n validate: (value: string) => boolean\n // Asynchronously fetches and resolves the reference, returning the resolved data\n exec: (value: string) => Promise<ResolveResult>\n}\n\n/**\n * Context information for a node during traversal or processing.\n *\n * Note: The `path` parameter represents the path to the current node being processed.\n * If you are performing a partial bundle (i.e., providing a custom root), this path will be relative\n * to the root you provide, not the absolute root of the original document. You may need to prefix\n * it with your own base path if you want to construct a full path from the absolute document root.\n *\n * - `path`: The JSON pointer path (as an array of strings) from the document root to the current node.\n * - `resolutionCache`: A cache for storing promises of resolved references.\n */\ntype NodeProcessContext = {\n path: readonly string[]\n resolutionCache: Map<string, Promise<Readonly<ResolveResult>>>\n parentNode: UnknownObject | null\n rootNode: UnknownObject\n loaders: LoaderPlugin[]\n}\n\n/**\n * A plugin type for lifecycle hooks, allowing custom logic to be injected into the bundler's process.\n * This type extends the Config['hooks'] interface and is identified by type: 'lifecycle'.\n */\nexport type LifecyclePlugin = { type: 'lifecycle' } & Config['hooks']\n\n/**\n * Represents a plugin used by the bundler for extensibility.\n *\n * Plugins can be either:\n * - Loader plugins: Responsible for resolving and loading external references (e.g., from files, URLs, or custom sources).\n * - Lifecycle plugins: Provide lifecycle hooks to customize or extend the bundling process.\n *\n * Loader plugins must implement:\n * - `validate`: Checks if the plugin can handle a given reference value.\n * - `exec`: Asynchronously resolves and returns the referenced data.\n *\n * Lifecycle plugins extend the bundler's lifecycle hooks for custom logic.\n */\nexport type Plugin = LoaderPlugin | LifecyclePlugin\n\n/**\n * Configuration options for the bundler.\n * Controls how external references are resolved and processed during bundling.\n */\ntype Config = {\n /**\n * Array of plugins that handle resolving references from different sources.\n * Each plugin is responsible for fetching and processing data from specific sources\n * like URLs or the filesystem.\n */\n plugins: Plugin[]\n\n /**\n * Optional root object that serves as the base document when bundling a subpart.\n * This allows resolving references relative to the root document's location,\n * ensuring proper path resolution for nested references.\n */\n root?: UnknownObject\n\n /**\n * Optional maximum depth for reference resolution.\n * Limits how deeply the bundler will follow and resolve nested $ref pointers.\n * Useful for preventing infinite recursion or excessive resource usage.\n */\n depth?: number\n\n /**\n * Optional origin path for the bundler.\n * Used to resolve relative paths in references, especially when the input is a string URL or file path.\n * If not provided, the bundler will use the input value as the origin.\n */\n origin?: string\n\n /**\n * Optional cache to store promises of resolved references.\n * Helps avoid duplicate fetches/reads of the same resource by storing\n * the resolution promises for reuse.\n */\n cache?: Map<string, Promise<ResolveResult>>\n\n /**\n * Cache of visited nodes during partial bundling.\n * Used to prevent re-bundling the same tree multiple times when doing partial bundling,\n * improving performance by avoiding redundant processing of already bundled sections.\n */\n visitedNodes?: Set<unknown>\n\n /**\n * Enable tree shaking to optimize the bundle size.\n * When enabled, only the parts of external documents that are actually referenced\n * will be included in the final bundle.\n */\n treeShake: boolean\n\n /**\n * Optional flag to generate a URL map.\n * When enabled, tracks the original source URLs of bundled references\n * in an x-ext-urls section for reference mapping.\n */\n urlMap?: boolean\n\n /**\n * Optional function to compress input URLs or file paths before bundling.\n * Returns either a Promise resolving to the compressed string or the compressed string directly.\n */\n compress?: (value: string) => Promise<string> | string\n\n /**\n * Optional hooks to monitor the bundler's lifecycle.\n * Allows tracking the progress and status of reference resolution.\n */\n hooks?: Partial<{\n /**\n * Optional hook called when the bundler starts resolving a $ref.\n * Useful for tracking or logging the beginning of a reference resolution.\n */\n onResolveStart: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook called when the bundler fails to resolve a $ref.\n * Can be used for error handling, logging, or custom error reporting.\n */\n onResolveError: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook called when the bundler successfully resolves a $ref.\n * Useful for tracking successful resolutions or custom post-processing.\n */\n onResolveSuccess: (node: UnknownObject & Record<'$ref', unknown>) => void\n /**\n * Optional hook invoked before processing a node.\n * Can be used for preprocessing, mutation, or custom logic before the node is handled by the bundler.\n */\n onBeforeNodeProcess: (node: UnknownObject, context: NodeProcessContext) => void | Promise<void>\n /**\n * Optional hook invoked after processing a node.\n * Useful for postprocessing, cleanup, or custom logic after the node has been handled by the bundler.\n */\n onAfterNodeProcess: (node: UnknownObject, context: NodeProcessContext) => void | Promise<void>\n }>\n}\n\n/**\n * Extension keys used for bundling external references in OpenAPI documents.\n * These custom extensions help maintain the structure and traceability of bundled documents.\n */\nconst extensions = {\n /**\n * Custom OpenAPI extension key used to store external references.\n * This key will contain all bundled external documents.\n * The x-ext key is used to maintain a clean separation between the main\n * OpenAPI document and its bundled external references.\n */\n externalDocuments: 'x-ext',\n\n /**\n * Custom OpenAPI extension key used to maintain a mapping between\n * hashed keys and their original URLs in x-ext.\n * This mapping is essential for tracking the source of bundled references\n */\n externalDocumentsMappings: 'x-ext-urls',\n} as const\n\n/**\n * Bundles an OpenAPI specification by resolving all external references.\n * This function traverses the input object recursively and embeds external $ref\n * references into an x-ext section. External references can be URLs or local files.\n * The original $refs are updated to point to their embedded content in the x-ext section.\n * If the input is an object, it will be modified in place by adding an x-ext\n * property to store resolved external references.\n *\n * @param input - The OpenAPI specification to bundle. Can be either an object or string.\n * If a string is provided, it will be resolved using the provided plugins.\n * If no plugin can process the input, the onReferenceError hook will be invoked\n * and an error will be emitted to the console.\n * @param config - Configuration object containing plugins and options for bundling OpenAPI specifications\n * @returns A promise that resolves to the bundled specification with all references embedded\n * @example\n * // Example with object input\n * const spec = {\n * paths: {\n * '/users': {\n * $ref: 'https://example.com/schemas/users.yaml'\n * }\n * }\n * }\n *\n * const bundled = await bundle(spec, {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // Result:\n * // {\n * // paths: {\n * // '/users': {\n * // $ref: '#/x-ext/abc123'\n * // }\n * // },\n * // 'x-ext': {\n * // 'abc123': {\n * // // Resolved content from users.yaml\n * // }\n * // },\n * // 'x-ext-urls': {\n * // 'https://example.com/schemas/users.yaml': 'abc123'\n * // }\n * // }\n *\n * // Example with URL input\n * const bundledFromUrl = await bundle('https://example.com/openapi.yaml', {\n * plugins: [fetchUrls()],\n * treeShake: true,\n * urlMap: true,\n * hooks: {\n * onResolveStart: (ref) => console.log('Resolving:', ref.$ref),\n * onResolveSuccess: (ref) => console.log('Resolved:', ref.$ref),\n * onResolveError: (ref) => console.log('Failed to resolve:', ref.$ref)\n * }\n * })\n * // The function will first fetch the OpenAPI spec from the URL,\n * // then bundle all its external references into the x-ext section\n */\nexport async function bundle(input: UnknownObject | string, config: Config) {\n // Cache for storing promises of resolved external references (URLs and local files)\n // to avoid duplicate fetches/reads of the same resource\n const cache = config.cache ?? new Map<string, Promise<ResolveResult>>()\n\n const loaderPlugins = config.plugins.filter((it) => it.type === 'loader')\n const lifecyclePlugin = config.plugins.filter((it) => it.type === 'lifecycle')\n\n /**\n * Resolves the input value by either returning it directly if it's not a string,\n * or attempting to resolve it using the provided plugins if it is a string.\n * @returns The resolved input data or throws an error if resolution fails\n */\n const resolveInput = async () => {\n if (typeof input !== 'string') {\n return input\n }\n const result = await resolveContents(input, loaderPlugins)\n\n if (result.ok && typeof result.data === 'object') {\n return result.data\n }\n\n throw new Error(\n 'Failed to resolve input: Please provide a valid string value or pass a loader to process the input',\n )\n }\n\n // Resolve the input specification, which could be either a direct object or a string URL/path\n const rawSpecification = await resolveInput()\n\n // Document root used to write all external documents\n // We need this when we want to do a partial bundle of a document\n const documentRoot = config.root ?? rawSpecification\n\n // Extract all $id and $anchor values from the document to identify local schemas\n const schemas = getSchemas(documentRoot)\n\n // Determines if the bundling operation is partial.\n // Partial bundling occurs when:\n // - A root document is provided that is different from the raw specification being bundled, or\n // - A maximum depth is specified in the config.\n // In these cases, only a subset of the document may be bundled.\n const isPartialBundling =\n (config.root !== undefined && config.root !== rawSpecification) || config.depth !== undefined\n\n // Set of nodes that have already been processed during bundling to prevent duplicate processing\n const processedNodes = config.visitedNodes ?? new Set()\n\n // Determines the initial origin path for the bundler based on the input type.\n // For string inputs that are URLs or file paths, uses the input as the origin.\n // For non-string inputs or other string types, returns an empty string.\n const defaultOrigin = () => {\n if (config.origin) {\n return config.origin\n }\n\n if (typeof input !== 'string') {\n return ''\n }\n\n if (isRemoteUrl(input) || isFilePath(input)) {\n return input\n }\n\n return ''\n }\n\n // Create the cache to store the compressed values to their map values\n if (documentRoot[extensions.externalDocumentsMappings] === undefined) {\n documentRoot[extensions.externalDocumentsMappings] = {}\n }\n const { generate } = uniqueValueGeneratorFactory(\n config.compress ?? getHash,\n documentRoot[extensions.externalDocumentsMappings],\n )\n\n const bundler = async (\n root: unknown,\n origin: string = defaultOrigin(),\n isChunkParent = false,\n depth = 0,\n currentPath: readonly string[] = [],\n parent: UnknownObject = null,\n ) => {\n // If a maximum depth is set in the config, stop bundling when the current depth reaches or exceeds it\n if (config.depth !== undefined && depth > config.depth) {\n return\n }\n\n if (!isObject(root) && !Array.isArray(root)) {\n return\n }\n\n // Skip if this node has already been processed to prevent infinite recursion\n // and duplicate processing of the same node\n if (processedNodes.has(root)) {\n return\n }\n // Mark this node as processed before continuing\n processedNodes.add(root)\n\n // Invoke the onBeforeNodeProcess hook for the current node before any further processing\n await config.hooks?.onBeforeNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n // Invoke onBeforeNodeProcess hooks from all registered lifecycle plugins\n for (const plugin of lifecyclePlugin) {\n await plugin.onBeforeNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n }\n\n const id = getId(root)\n\n if (typeof root === 'object' && '$ref' in root && typeof root['$ref'] === 'string') {\n const ref = root['$ref']\n const isChunk = '$global' in root && typeof root['$global'] === 'boolean' && root['$global']\n\n // Try to convert the reference to a local reference if possible\n // This handles cases where the reference points to a local schema using $id or $anchor\n // If it can be converted to a local reference, we do not need to bundle it\n // and can skip further processing for this reference\n // In case of partial bundling, we still need to ensure that all dependencies\n // of the local reference are bundled to create a complete and self-contained partial bundle\n // This is important to maintain the integrity of the partial bundle\n const localRef = convertToLocalRef(ref, id ?? origin, schemas)\n\n if (localRef !== undefined) {\n if (isPartialBundling) {\n const segments = getSegmentsFromPath(`/${localRef}`)\n const parent = segments.length > 0 ? getValueByPath(documentRoot, segments.slice(0, -1)).value : undefined\n\n const targetValue = getValueByPath(documentRoot, segments)\n\n // When doing partial bundling, we need to recursively bundle all dependencies\n // referenced by this local reference to ensure the partial bundle is complete.\n // This includes not just the direct reference but also all its dependencies,\n // creating a complete and self-contained partial bundle.\n await bundler(targetValue.value, targetValue.context, isChunkParent, depth + 1, segments, parent)\n }\n return\n }\n\n const [prefix, path = ''] = ref.split('#', 2)\n\n // Combine the current origin with the new path to resolve relative references\n // correctly within the context of the external file being processed\n const resolvedPath = resolveReferencePath(id ?? origin, prefix)\n\n // Generate a unique compressed path for the external document\n // This is used as a key to store and reference the bundled external document\n // The compression helps reduce the overall file size of the bundled document\n const compressedPath = await generate(resolvedPath)\n\n const seen = cache.has(resolvedPath)\n\n if (!seen) {\n cache.set(resolvedPath, resolveContents(resolvedPath, loaderPlugins))\n }\n\n config?.hooks?.onResolveStart?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveStart?.(root))\n\n // Resolve the remote document\n const result = await cache.get(resolvedPath)\n\n if (result.ok) {\n // Process the result only once to avoid duplicate processing and prevent multiple prefixing\n // of internal references, which would corrupt the reference paths\n if (!seen) {\n // Skip prefixing for chunks since they are meant to be self-contained and their\n // internal references should remain relative to their original location. Chunks\n // are typically used for modular components that need to maintain their own\n // reference context without being affected by the main document's structure.\n if (!isChunk) {\n // Update internal references in the resolved document to use the correct base path.\n // When we embed external documents, their internal references need to be updated to\n // maintain the correct path context relative to the main document. This is crucial\n // because internal references in the external document are relative to its original\n // location, but when embedded, they need to be relative to their new location in\n // the main document's x-ext section. Without this update, internal references\n // would point to incorrect locations and break the document structure.\n prefixInternalRefRecursive(result.data, [extensions.externalDocuments, compressedPath])\n }\n\n // Recursively process the resolved content\n // to handle any nested references it may contain. We pass the resolvedPath as the new origin\n // to ensure any relative references within this content are resolved correctly relative to\n // their new location in the bundled document.\n await bundler(result.data, isChunk ? origin : resolvedPath, isChunk, depth + 1, [\n extensions.externalDocuments,\n compressedPath,\n documentRoot[extensions.externalDocumentsMappings],\n ])\n\n // Store the mapping between hashed keys and original URLs in x-ext-urls\n // This allows tracking which external URLs were bundled and their corresponding locations\n setValueAtPath(\n documentRoot,\n `/${extensions.externalDocumentsMappings}/${escapeJsonPointer(compressedPath)}`,\n resolvedPath,\n )\n }\n\n if (config.treeShake === true) {\n // Store only the subtree that is actually used\n // This optimizes the bundle size by only including the parts of the external document\n // that are referenced, rather than the entire document\n resolveAndCopyReferences(\n documentRoot,\n { [extensions.externalDocuments]: { [compressedPath]: result.data } },\n prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath]).substring(1),\n extensions.externalDocuments,\n compressedPath,\n )\n } else if (!seen) {\n // Store the external document in the main document's x-ext key\n // When tree shaking is disabled, we include the entire external document\n // This preserves all content and is faster since we don't need to analyze and copy\n // specific parts. This approach is ideal when storing the result in memory\n // as it avoids the overhead of tree shaking operations\n setValueAtPath(documentRoot, `/${extensions.externalDocuments}/${compressedPath}`, result.data)\n }\n\n // Update the $ref to point to the embedded document in x-ext\n // This is necessary because we need to maintain the correct path context\n // for the embedded document while preserving its internal structure\n root.$ref = prefixInternalRef(`#${path}`, [extensions.externalDocuments, compressedPath])\n\n config?.hooks?.onResolveSuccess?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveSuccess?.(root))\n\n return\n }\n\n config?.hooks?.onResolveError?.(root)\n lifecyclePlugin.forEach((it) => it.onResolveError?.(root))\n\n return console.warn(\n `Failed to resolve external reference \"${resolvedPath}\". The reference may be invalid, inaccessible, or missing a loader for this type of reference.`,\n )\n }\n\n // Recursively traverse all child properties of the current object to resolve nested $ref references.\n // This step ensures that any $refs located deeper within the object hierarchy are discovered and processed.\n // We explicitly skip the extension keys (x-ext and x-ext-urls) to avoid reprocessing already bundled or mapped content.\n await Promise.all(\n Object.entries(root).map(async ([key, value]) => {\n if (key === extensions.externalDocuments || key === extensions.externalDocumentsMappings) {\n return\n }\n\n await bundler(value, id ?? origin, isChunkParent, depth + 1, [...currentPath, key], root as UnknownObject)\n }),\n )\n\n // Invoke the optional onAfterNodeProcess hook from the config, if provided.\n // This allows for custom post-processing logic after a node has been handled by the bundler.\n await config.hooks?.onAfterNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n\n // Iterate through all lifecycle plugins and invoke their onAfterNodeProcess hooks, if defined.\n // This enables plugins to perform additional post-processing or cleanup after the node is processed.\n for (const plugin of lifecyclePlugin) {\n await plugin.onAfterNodeProcess?.(root as UnknownObject, {\n path: currentPath,\n resolutionCache: cache,\n parentNode: parent,\n rootNode: documentRoot as UnknownObject,\n loaders: loaderPlugins,\n })\n }\n }\n\n await bundler(rawSpecification)\n\n // Keep urlMappings when doing partial bundling to track hash values and handle collisions\n // For full bundling without urlMap config, remove the mappings to clean up the output\n if (!config.urlMap && !isPartialBundling) {\n // Remove the external document mappings from the output when doing a full bundle without urlMap config\n delete documentRoot[extensions.externalDocumentsMappings]\n }\n\n return rawSpecification\n}\n"],
5
+ "mappings": "AAAA,SAAS,YAAY;AAErB,SAAS,yBAAyB;AAClC,SAAS,OAAO,kBAAkB;AAClC,SAAS,sBAAsB;AAG/B,SAAS,yBAAyB;AAClC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,cAAc;AACvB,SAAS,SAAS,mCAAmC;AAc9C,SAAS,YAAY,OAAe;AACzC,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,KAAK;AACzB,WAAO,IAAI,aAAa,WAAW,IAAI,aAAa;AAAA,EACtD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,WAAW,OAAe;AACxC,SAAO,CAAC,YAAY,KAAK,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,aAAa,KAAK;AACrE;AAaO,SAAS,WAAW,OAAwB;AACjD,SAAO,MAAM,WAAW,GAAG;AAC7B;AAiBA,SAAS,gBAAgB,OAAe,SAAiD;AACvF,QAAM,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,KAAK,CAAC;AAEpD,MAAI,QAAQ;AACV,WAAO,OAAO,KAAK,KAAK;AAAA,EAC1B;AAEA,SAAO,QAAQ,QAAQ;AAAA,IACrB,IAAI;AAAA,EACN,CAAC;AACH;AAkDO,SAAS,eAAe,KAAUA,OAAc,OAAkB;AACvE,MAAIA,UAAS,IAAI;AACf,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAEA,QAAM,QAAQ,oBAAoBA,KAAI;AAEtC,MAAI,UAAU;AAEd,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,UAAM,MAAM,MAAM,CAAC;AACnB,UAAM,SAAS,MAAM,MAAM,SAAS;AAEpC,UAAM,U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AAE,WAAW,GACnB,OAAO,CAAC,aAAa,CAAC,CA0CxB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC,GAAG,YAAY,CAShG"}
@@ -22,7 +22,8 @@ async function fetchUrl(url, limiter, config) {
22
22
  const body = await result.text();
23
23
  return {
24
24
  ok: true,
25
- data: normalize(body)
25
+ data: normalize(body),
26
+ raw: body
26
27
  };
27
28
  }
28
29
  const contentType = result.headers.get("Content-Type") ?? "";
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundle/plugins/fetch-urls/index.ts"],
4
- "sourcesContent": ["import type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isRemoteUrl } from '@/bundle/bundle'\nimport { createLimiter } from '@/bundle/create-limiter'\nimport { normalize } from '@/helpers/normalize'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Safely checks for host from a URL\n * Needed because we cannot create a URL from a relative remote URL ex: examples/openapi.json\n */\nconst getHost = (url: string): string | null => {\n try {\n return new URL(url).host\n } catch {\n return null\n }\n}\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const host = getHost(url)\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === host) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n }\n }\n\n const contentType = result.headers.get('Content-Type') ?? ''\n\n // Warn if the content type is HTML or XML as we only support JSON/YAML\n if (['text/html', 'application/xml'].includes(contentType)) {\n console.warn(`[WARN] We only support JSON/YAML formats, received ${contentType}`)\n }\n\n console.warn(`[WARN] Fetch failed with status ${result.status} ${result.statusText} for URL: ${url}`)\n return {\n ok: false,\n }\n } catch {\n console.warn(`[WARN] Failed to parse JSON/YAML from URL: ${url}`)\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): LoaderPlugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n type: 'loader',\n validate: isRemoteUrl,\n exec: (value) => fetchUrl(value, limiter, config),\n }\n}\n"],
5
- "mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAW1B,MAAM,UAAU,CAAC,QAA+B;AAC9C,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAgBA,eAAsB,SACpB,KACA,SACA,QACwB;AACxB,MAAI;AACF,UAAM,OAAO,QAAQ,GAAG;AAGxB,UAAM,UAAU,QAAQ,SAAS,KAAK,CAAC,MAAM,EAAE,QAAQ,KAAK,CAAC,MAAM,MAAM,IAAI,MAAM,MAAS,GAAG;AAE/F,UAAM,OAAO,QAAQ,SAAS;AAE9B,UAAM,SAAS,MAAM;AAAA,MAAQ,MAC3B,KAAK,KAAK;AAAA,QACR;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,OAAO,IAAI;AACb,YAAM,OAAO,MAAM,OAAO,KAAK;AAE/B,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,MAAM,UAAU,IAAI;AAAA,MACtB;AAAA,IACF;AAEA,UAAM,cAAc,OAAO,QAAQ,IAAI,cAAc,KAAK;AAG1D,QAAI,CAAC,aAAa,iBAAiB,EAAE,SAAS,WAAW,GAAG;AAC1D,cAAQ,KAAK,sDAAsD,WAAW,EAAE;AAAA,IAClF;AAEA,YAAQ,KAAK,mCAAmC,OAAO,MAAM,IAAI,OAAO,UAAU,aAAa,GAAG,EAAE;AACpG,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF,QAAQ;AACN,YAAQ,KAAK,8CAA8C,GAAG,EAAE;AAChE,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,UAAU,QAAwE;AAEhG,QAAM,UAAU,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAI,OAAyB,GAAG;AAE9F,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM,CAAC,UAAU,SAAS,OAAO,SAAS,MAAM;AAAA,EAClD;AACF;",
4
+ "sourcesContent": ["import type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isRemoteUrl } from '@/bundle/bundle'\nimport { createLimiter } from '@/bundle/create-limiter'\nimport { normalize } from '@/helpers/normalize'\n\ntype FetchConfig = Partial<{\n headers: { headers: HeadersInit; domains: string[] }[]\n fetch: (input: string | URL | globalThis.Request, init?: RequestInit) => Promise<Response>\n}>\n\n/**\n * Safely checks for host from a URL\n * Needed because we cannot create a URL from a relative remote URL ex: examples/openapi.json\n */\nconst getHost = (url: string): string | null => {\n try {\n return new URL(url).host\n } catch {\n return null\n }\n}\n\n/**\n * Fetches and normalizes data from a remote URL\n * @param url - The URL to fetch data from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await fetchUrl('https://api.example.com/data.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to fetch data')\n * }\n * ```\n */\nexport async function fetchUrl(\n url: string,\n limiter: <T>(fn: () => Promise<T>) => Promise<T>,\n config?: FetchConfig,\n): Promise<ResolveResult> {\n try {\n const host = getHost(url)\n\n // Get the headers that match the domain\n const headers = config?.headers?.find((a) => a.domains.find((d) => d === host) !== undefined)?.headers\n\n const exec = config?.fetch ?? fetch\n\n const result = await limiter(() =>\n exec(url, {\n headers,\n }),\n )\n\n if (result.ok) {\n const body = await result.text()\n\n return {\n ok: true,\n data: normalize(body),\n raw: body,\n }\n }\n\n const contentType = result.headers.get('Content-Type') ?? ''\n\n // Warn if the content type is HTML or XML as we only support JSON/YAML\n if (['text/html', 'application/xml'].includes(contentType)) {\n console.warn(`[WARN] We only support JSON/YAML formats, received ${contentType}`)\n }\n\n console.warn(`[WARN] Fetch failed with status ${result.status} ${result.statusText} for URL: ${url}`)\n return {\n ok: false,\n }\n } catch {\n console.warn(`[WARN] Failed to parse JSON/YAML from URL: ${url}`)\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling remote URL references.\n * This plugin validates and fetches data from HTTP/HTTPS URLs.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const urlPlugin = fetchUrls()\n * if (urlPlugin.validate('https://example.com/schema.json')) {\n * const result = await urlPlugin.exec('https://example.com/schema.json')\n * }\n */\nexport function fetchUrls(config?: FetchConfig & Partial<{ limit: number | null }>): LoaderPlugin {\n // If there is a limit specified we limit the number of concurrent calls\n const limiter = config?.limit ? createLimiter(config.limit) : <T>(fn: () => Promise<T>) => fn()\n\n return {\n type: 'loader',\n validate: isRemoteUrl,\n exec: (value) => fetchUrl(value, limiter, config),\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,mBAA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S,MAAM;AAAA,EAClD;AACF;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/parse-json/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,UAAU,CAAA;AAG3D;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAiBxC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/parse-json/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAG5C;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAkBxC"}
@@ -3,16 +3,17 @@ function parseJson() {
3
3
  return {
4
4
  type: "loader",
5
5
  validate: isJsonObject,
6
- exec: async (value) => {
6
+ exec: (value) => {
7
7
  try {
8
- return {
8
+ return Promise.resolve({
9
9
  ok: true,
10
- data: JSON.parse(value)
11
- };
10
+ data: JSON.parse(value),
11
+ raw: value
12
+ });
12
13
  } catch {
13
- return {
14
+ return Promise.resolve({
14
15
  ok: false
15
- };
16
+ });
16
17
  }
17
18
  }
18
19
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundle/plugins/parse-json/index.ts"],
4
- "sourcesContent": ["import type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isJsonObject } from '@/helpers/is-json-object'\n\n/**\n * Creates a plugin that parses JSON strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const jsonPlugin = parseJson()\n * const result = jsonPlugin.exec('{\"name\": \"John\", \"age\": 30}')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseJson(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isJsonObject,\n exec: async (value): Promise<ResolveResult> => {\n try {\n return {\n ok: true,\n data: JSON.parse(value),\n }\n } catch {\n return {\n ok: false,\n }\n }\n },\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAYtB,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM,OAAO,UAAkC;AAC7C,UAAI;AACF,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,KAAK;AAAA,QACxB;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,UACL,IAAI;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { LoaderPlugin } from '@/bundle'\nimport { isJsonObject } from '@/helpers/is-json-object'\n\n/**\n * Creates a plugin that parses JSON strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const jsonPlugin = parseJson()\n * const result = jsonPlugin.exec('{\"name\": \"John\", \"age\": 30}')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseJson(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isJsonObject,\n exec: (value) => {\n try {\n return Promise.resolve({\n ok: true,\n data: JSON.parse(value),\n raw: value,\n })\n } catch {\n return Promise.resolve({\n ok: false,\n })\n }\n },\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAYtB,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM,CAAC,UAAU;AACf,UAAI;AACF,eAAO,QAAQ,QAAQ;AAAA,UACrB,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,KAAK;AAAA,UACtB,KAAK;AAAA,QACP,CAAC;AAAA,MACH,QAAQ;AACN,eAAO,QAAQ,QAAQ;AAAA,UACrB,IAAI;AAAA,QACN,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/parse-yaml/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,UAAU,CAAA;AAG3D;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAiBxC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/parse-yaml/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AAG5C;;;;;;;;;GASG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAkBxC"}
@@ -4,16 +4,17 @@ function parseYaml() {
4
4
  return {
5
5
  type: "loader",
6
6
  validate: isYaml,
7
- exec: async (value) => {
7
+ exec: (value) => {
8
8
  try {
9
- return {
9
+ return Promise.resolve({
10
10
  ok: true,
11
- data: YAML.parse(value, { merge: true, maxAliasCount: 1e4 })
12
- };
11
+ data: YAML.parse(value, { merge: true, maxAliasCount: 1e4 }),
12
+ raw: value
13
+ });
13
14
  } catch {
14
- return {
15
+ return Promise.resolve({
15
16
  ok: false
16
- };
17
+ });
17
18
  }
18
19
  }
19
20
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundle/plugins/parse-yaml/index.ts"],
4
- "sourcesContent": ["import YAML from 'yaml'\n\nimport type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isYaml } from '@/helpers/is-yaml'\n\n/**\n * Creates a plugin that parses YAML strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const yamlPlugin = parseYaml()\n * const result = yamlPlugin.exec('name: John\\nage: 30')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseYaml(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isYaml,\n exec: async (value): Promise<ResolveResult> => {\n try {\n return {\n ok: true,\n data: YAML.parse(value, { merge: true, maxAliasCount: 10000 }),\n }\n } catch {\n return {\n ok: false,\n }\n }\n },\n }\n}\n"],
5
- "mappings": "AAAA,OAAO,UAAU;AAGjB,SAAS,cAAc;AAYhB,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM,OAAO,UAAkC;AAC7C,UAAI;AACF,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,OAAO,EAAE,OAAO,MAAM,eAAe,IAAM,CAAC;AAAA,QAC/D;AAAA,MACF,QAAQ;AACN,eAAO;AAAA,UACL,IAAI;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import YAML from 'yaml'\n\nimport type { LoaderPlugin } from '@/bundle'\nimport { isYaml } from '@/helpers/is-yaml'\n\n/**\n * Creates a plugin that parses YAML strings into JavaScript objects.\n * @returns A plugin object with validate and exec functions\n * @example\n * ```ts\n * const yamlPlugin = parseYaml()\n * const result = yamlPlugin.exec('name: John\\nage: 30')\n * // result = { name: 'John', age: 30 }\n * ```\n */\nexport function parseYaml(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isYaml,\n exec: (value) => {\n try {\n return Promise.resolve({\n ok: true,\n data: YAML.parse(value, { merge: true, maxAliasCount: 10000 }),\n raw: value,\n })\n } catch {\n return Promise.resolve({\n ok: false,\n })\n }\n },\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,UAAU;AAGjB,SAAS,cAAc;AAYhB,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM,CAAC,UAAU;AACf,UAAI;AACF,eAAO,QAAQ,QAAQ;AAAA,UACrB,IAAI;AAAA,UACJ,MAAM,KAAK,MAAM,OAAO,EAAE,OAAO,MAAM,eAAe,IAAM,CAAC;AAAA,UAC7D,KAAK;AAAA,QACP,CAAC;AAAA,MACH,QAAQ;AACN,eAAO,QAAQ,QAAQ;AAAA,UACrB,IAAI;AAAA,QACN,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/read-files/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAI3D;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAmBnE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAMxC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/bundle/plugins/read-files/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAI3D;;;;;;;;;;;;;GAaG;AACH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAoBnE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,IAAI,YAAY,CAMxC"}
@@ -9,7 +9,8 @@ async function readFile(path) {
9
9
  const fileContents = await fs.readFile(path, { encoding: "utf-8" });
10
10
  return {
11
11
  ok: true,
12
- data: normalize(fileContents)
12
+ data: normalize(fileContents),
13
+ raw: fileContents
13
14
  };
14
15
  } catch {
15
16
  return {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundle/plugins/read-files/index.ts"],
4
- "sourcesContent": ["import type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isFilePath } from '@/bundle/bundle'\nimport { normalize } from '@/helpers/normalize'\n\n/**\n * Reads and normalizes data from a local file\n * @param path - The file path to read from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await readFile('./schemas/user.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to read file')\n * }\n * ```\n */\nexport async function readFile(path: string): Promise<ResolveResult> {\n const fs = typeof window === 'undefined' ? await import('node:fs/promises') : undefined\n\n if (fs === undefined) {\n throw 'Can not use readFiles plugin outside of a node environment'\n }\n\n try {\n const fileContents = await fs.readFile(path, { encoding: 'utf-8' })\n\n return {\n ok: true,\n data: normalize(fileContents),\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling local file references.\n * This plugin validates and reads data from local filesystem paths.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const filePlugin = readFiles()\n * if (filePlugin.validate('./local-schema.json')) {\n * const result = await filePlugin.exec('./local-schema.json')\n * }\n */\nexport function readFiles(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isFilePath,\n exec: readFile,\n }\n}\n"],
5
- "mappings": "AACA,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAgB1B,eAAsB,SAAS,MAAsC;AACnE,QAAM,KAAK,OAAO,WAAW,cAAc,MAAM,OAAO,kBAAkB,IAAI;AAE9E,MAAI,OAAO,QAAW;AACpB,UAAM;AAAA,EACR;AAEA,MAAI;AACF,UAAM,eAAe,MAAM,GAAG,SAAS,MAAM,EAAE,UAAU,QAAQ,CAAC;AAElE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,MAAM,UAAU,YAAY;AAAA,IAC9B;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import type { LoaderPlugin, ResolveResult } from '@/bundle'\nimport { isFilePath } from '@/bundle/bundle'\nimport { normalize } from '@/helpers/normalize'\n\n/**\n * Reads and normalizes data from a local file\n * @param path - The file path to read from\n * @returns A promise that resolves to either the normalized data or an error result\n * @example\n * ```ts\n * const result = await readFile('./schemas/user.json')\n * if (result.ok) {\n * console.log(result.data) // The normalized data\n * } else {\n * console.log('Failed to read file')\n * }\n * ```\n */\nexport async function readFile(path: string): Promise<ResolveResult> {\n const fs = typeof window === 'undefined' ? await import('node:fs/promises') : undefined\n\n if (fs === undefined) {\n throw 'Can not use readFiles plugin outside of a node environment'\n }\n\n try {\n const fileContents = await fs.readFile(path, { encoding: 'utf-8' })\n\n return {\n ok: true,\n data: normalize(fileContents),\n raw: fileContents,\n }\n } catch {\n return {\n ok: false,\n }\n }\n}\n\n/**\n * Creates a plugin for handling local file references.\n * This plugin validates and reads data from local filesystem paths.\n *\n * @returns A plugin object with validate and exec functions\n * @example\n * const filePlugin = readFiles()\n * if (filePlugin.validate('./local-schema.json')) {\n * const result = await filePlugin.exec('./local-schema.json')\n * }\n */\nexport function readFiles(): LoaderPlugin {\n return {\n type: 'loader',\n validate: isFilePath,\n exec: readFile,\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAgB1B,eAAsB,SAAS,MAAsC;AACnE,QAAM,KAAK,OAAO,WAAW,cAAc,MAAM,OAAO,kBAAkB,IAAI;AAE9E,MAAI,OAAO,QAAW;AACpB,UAAM;AAAA,EACR;AAEA,MAAI;AACF,UAAM,eAAe,MAAM,GAAG,SAAS,MAAM,EAAE,UAAU,QAAQ,CAAC;AAElE,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,MAAM,UAAU,YAAY;AAAA,MAC5B,KAAK;AAAA,IACP;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,MACL,IAAI;AAAA,IACN;AAAA,EACF;AACF;AAaO,SAAS,YAA0B;AACxC,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,MAAM;AAAA,EACR;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,12 +1,14 @@
1
1
  /**
2
- * Generates a short SHA-1 hash from a string value.
2
+ * Generates a short hash from a string value using xxhash.
3
+ *
3
4
  * This function is used to create unique identifiers for external references
4
- * while keeping the hash length manageable. It uses the Web Crypto API to
5
- * generate a SHA-1 hash and returns the first 7 characters of the hex string.
5
+ * while keeping the hash length manageable. It uses xxhash-wasm instead of
6
+ * crypto.subtle because crypto.subtle is only available in secure contexts (HTTPS) or on localhost.
7
+ * Returns the first 7 characters of the hash string.
6
8
  * If the hash would be all numbers, it ensures at least one letter is included.
7
9
  *
8
10
  * @param value - The string to hash
9
- * @returns A 7-character hexadecimal hash with at least one letter
11
+ * @returns A Promise that resolves to a 7-character hexadecimal hash with at least one letter
10
12
  * @example
11
13
  * // Returns "2ae91d7"
12
14
  * await getHash("https://example.com/schema.json")
@@ -1 +1 @@
1
- {"version":3,"file":"value-generator.d.ts","sourceRoot":"","sources":["../../src/bundle/value-generator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAAC,KAAK,EAAE,MAAM,mBAe1C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,EACrD,KAAK,EAAE,MAAM,EACb,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACzC,mBAAmB,CAAC,EAAE,MAAM,EAC5B,KAAK,SAAI,mBAoBV;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,2BAA2B,GACtC,UAAU,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,EACrD,mBAAmB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAMvC;;;;;;;;;;;;OAYG;sBACqB,MAAM;CAqBjC,CAAA"}
1
+ {"version":3,"file":"value-generator.d.ts","sourceRoot":"","sources":["../../src/bundle/value-generator.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAO5D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,EACrD,KAAK,EAAE,MAAM,EACb,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACzC,mBAAmB,CAAC,EAAE,MAAM,EAC5B,KAAK,SAAI,mBAoBV;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,2BAA2B,GACtC,UAAU,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,EACrD,mBAAmB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IAMvC;;;;;;;;;;;;OAYG;sBACqB,MAAM;CAqBjC,CAAA"}
@@ -1,9 +1,6 @@
1
+ import { generateHash } from "../helpers/generate-hash.js";
1
2
  async function getHash(value) {
2
- const encoder = new TextEncoder();
3
- const data = encoder.encode(value);
4
- const hashBuffer = await crypto.subtle.digest("SHA-1", data);
5
- const hashArray = Array.from(new Uint8Array(hashBuffer));
6
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
3
+ const hashHex = await generateHash(value);
7
4
  const hash = hashHex.substring(0, 7);
8
5
  return hash.match(/^\d+$/) ? "a" + hash.substring(1) : hash;
9
6
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/bundle/value-generator.ts"],
4
- "sourcesContent": ["/**\n * Generates a short SHA-1 hash from a string value.\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses the Web Crypto API to\n * generate a SHA-1 hash and returns the first 7 characters of the hex string.\n * If the hash would be all numbers, it ensures at least one letter is included.\n *\n * @param value - The string to hash\n * @returns A 7-character hexadecimal hash with at least one letter\n * @example\n * // Returns \"2ae91d7\"\n * await getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string) {\n // Convert string to ArrayBuffer\n const encoder = new TextEncoder()\n const data = encoder.encode(value)\n\n // Hash the data\n const hashBuffer = await crypto.subtle.digest('SHA-1', data)\n\n // Convert buffer to hex string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n\n // Return first 7 characters of the hash, ensuring at least one letter\n const hash = hashHex.substring(0, 7)\n return hash.match(/^\\d+$/) ? 'a' + hash.substring(1) : hash\n}\n\n/**\n * Generates a unique compressed value for a string, handling collisions by recursively compressing\n * until a unique value is found. This is used to create unique identifiers for external\n * references in the bundled OpenAPI document.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param value - The original string value to compress\n * @param compressedToValue - Object mapping compressed values to their original values\n * @param prevCompressedValue - Optional previous compressed value to use as input for generating a new value\n * @param depth - Current recursion depth to prevent infinite loops\n * @returns A unique compressed value that doesn't conflict with existing values\n *\n * @example\n * const valueMap = {}\n * // First call generates compressed value for \"example.com/schema.json\"\n * const value1 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns something like \"2ae91d7\"\n *\n * // Second call with same value returns same compressed value\n * const value2 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns same value as value1\n *\n * // Call with different value generates new unique compressed value\n * const value3 = await generateUniqueValue(compress, \"example.com/other.json\", valueMap)\n * // Returns different value like \"3bf82e9\"\n */\nexport async function generateUniqueValue(\n compress: (value: string) => Promise<string> | string,\n value: string,\n compressedToValue: Record<string, string>,\n prevCompressedValue?: string,\n depth = 0,\n) {\n // Prevent infinite recursion by limiting depth\n const MAX_DEPTH = 100\n\n if (depth >= MAX_DEPTH) {\n throw 'Can not generate unique compressed values'\n }\n\n // Compress the value, using previous compressed value if provided\n const compressedValue = await compress(prevCompressedValue ?? value)\n\n // Handle collision by recursively trying with compressed value as input\n if (compressedToValue[compressedValue] !== undefined && compressedToValue[compressedValue] !== value) {\n return generateUniqueValue(compress, value, compressedToValue, compressedValue, depth + 1)\n }\n\n // Store mapping and return unique compressed value\n compressedToValue[compressedValue] = value\n return compressedValue\n}\n\n/**\n * Factory function that creates a value generator with caching capabilities.\n * The generator maintains a bidirectional mapping between original values and their compressed forms.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param compressedToValue - Initial mapping of compressed values to their original values\n * @returns An object with a generate method that produces unique compressed values\n *\n * @example\n * const compress = (value) => value.substring(0, 6) // Simple compression example\n * const initialMap = { 'abc123': 'example.com/schema.json' }\n * const generator = uniqueValueGeneratorFactory(compress, initialMap)\n *\n * // Generate compressed value for new string\n * const compressed = await generator.generate('example.com/other.json')\n * // Returns something like 'example'\n *\n * // Generate compressed value for existing string\n * const cached = await generator.generate('example.com/schema.json')\n * // Returns 'abc123' from cache\n */\nexport const uniqueValueGeneratorFactory = (\n compress: (value: string) => Promise<string> | string,\n compressedToValue: Record<string, string>,\n) => {\n // Create a reverse mapping from original values to their compressed forms\n const valueToCompressed = Object.fromEntries(Object.entries(compressedToValue).map(([key, value]) => [value, key]))\n\n return {\n /**\n * Generates a unique compressed value for the given input string.\n * First checks if a compressed value already exists in the cache.\n * If not, generates a new unique compressed value and stores it in the cache.\n *\n * @param value - The original string value to compress\n * @returns A Promise that resolves to the compressed string value\n *\n * @example\n * const generator = uniqueValueGeneratorFactory(compress, {})\n * const compressed = await generator.generate('example.com/schema.json')\n * // Returns a unique compressed value like 'example'\n */\n generate: async (value: string) => {\n // Check if we already have a compressed value for this input\n const cache = valueToCompressed[value]\n if (cache) {\n return cache\n }\n\n // Generate a new unique compressed value\n const generatedValue = await generateUniqueValue(compress, value, compressedToValue)\n\n // Ensure the generated string contains at least one non-numeric character\n // This prevents the `setValueAtPath` function from interpreting the value as an array index\n // by forcing it to be treated as an object property name\n const compressedValue = generatedValue.match(/^\\d+$/) ? `a${generatedValue}` : generatedValue\n\n // Store the new mapping in our cache\n valueToCompressed[value] = compressedValue\n\n return compressedValue\n },\n }\n}\n"],
5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AAe,MAAM,OAAO,IAAI,IAAI,cAAc,KAAK;AAG/E,wBAAkB,KAAK,IAAI;AAE3B,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { generateHash } from '@/helpers/generate-hash'\n\n/**\n * Generates a short hash from a string value using xxhash.\n *\n * This function is used to create unique identifiers for external references\n * while keeping the hash length manageable. It uses xxhash-wasm instead of\n * crypto.subtle because crypto.subtle is only available in secure contexts (HTTPS) or on localhost.\n * Returns the first 7 characters of the hash string.\n * If the hash would be all numbers, it ensures at least one letter is included.\n *\n * @param value - The string to hash\n * @returns A Promise that resolves to a 7-character hexadecimal hash with at least one letter\n * @example\n * // Returns \"2ae91d7\"\n * await getHash(\"https://example.com/schema.json\")\n */\nexport async function getHash(value: string): Promise<string> {\n // Hash the data using xxhash\n const hashHex = await generateHash(value)\n\n // Return first 7 characters of the hash, ensuring at least one letter\n const hash = hashHex.substring(0, 7)\n return hash.match(/^\\d+$/) ? 'a' + hash.substring(1) : hash\n}\n\n/**\n * Generates a unique compressed value for a string, handling collisions by recursively compressing\n * until a unique value is found. This is used to create unique identifiers for external\n * references in the bundled OpenAPI document.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param value - The original string value to compress\n * @param compressedToValue - Object mapping compressed values to their original values\n * @param prevCompressedValue - Optional previous compressed value to use as input for generating a new value\n * @param depth - Current recursion depth to prevent infinite loops\n * @returns A unique compressed value that doesn't conflict with existing values\n *\n * @example\n * const valueMap = {}\n * // First call generates compressed value for \"example.com/schema.json\"\n * const value1 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns something like \"2ae91d7\"\n *\n * // Second call with same value returns same compressed value\n * const value2 = await generateUniqueValue(compress, \"example.com/schema.json\", valueMap)\n * // Returns same value as value1\n *\n * // Call with different value generates new unique compressed value\n * const value3 = await generateUniqueValue(compress, \"example.com/other.json\", valueMap)\n * // Returns different value like \"3bf82e9\"\n */\nexport async function generateUniqueValue(\n compress: (value: string) => Promise<string> | string,\n value: string,\n compressedToValue: Record<string, string>,\n prevCompressedValue?: string,\n depth = 0,\n) {\n // Prevent infinite recursion by limiting depth\n const MAX_DEPTH = 100\n\n if (depth >= MAX_DEPTH) {\n throw 'Can not generate unique compressed values'\n }\n\n // Compress the value, using previous compressed value if provided\n const compressedValue = await compress(prevCompressedValue ?? value)\n\n // Handle collision by recursively trying with compressed value as input\n if (compressedToValue[compressedValue] !== undefined && compressedToValue[compressedValue] !== value) {\n return generateUniqueValue(compress, value, compressedToValue, compressedValue, depth + 1)\n }\n\n // Store mapping and return unique compressed value\n compressedToValue[compressedValue] = value\n return compressedValue\n}\n\n/**\n * Factory function that creates a value generator with caching capabilities.\n * The generator maintains a bidirectional mapping between original values and their compressed forms.\n *\n * @param compress - Function that generates a compressed value from a string\n * @param compressedToValue - Initial mapping of compressed values to their original values\n * @returns An object with a generate method that produces unique compressed values\n *\n * @example\n * const compress = (value) => value.substring(0, 6) // Simple compression example\n * const initialMap = { 'abc123': 'example.com/schema.json' }\n * const generator = uniqueValueGeneratorFactory(compress, initialMap)\n *\n * // Generate compressed value for new string\n * const compressed = await generator.generate('example.com/other.json')\n * // Returns something like 'example'\n *\n * // Generate compressed value for existing string\n * const cached = await generator.generate('example.com/schema.json')\n * // Returns 'abc123' from cache\n */\nexport const uniqueValueGeneratorFactory = (\n compress: (value: string) => Promise<string> | string,\n compressedToValue: Record<string, string>,\n) => {\n // Create a reverse mapping from original values to their compressed forms\n const valueToCompressed = Object.fromEntries(Object.entries(compressedToValue).map(([key, value]) => [value, key]))\n\n return {\n /**\n * Generates a unique compressed value for the given input string.\n * First checks if a compressed value already exists in the cache.\n * If not, generates a new unique compressed value and stores it in the cache.\n *\n * @param value - The original string value to compress\n * @returns A Promise that resolves to the compressed string value\n *\n * @example\n * const generator = uniqueValueGeneratorFactory(compress, {})\n * const compressed = await generator.generate('example.com/schema.json')\n * // Returns a unique compressed value like 'example'\n */\n generate: async (value: string) => {\n // Check if we already have a compressed value for this input\n const cache = valueToCompressed[value]\n if (cache) {\n return cache\n }\n\n // Generate a new unique compressed value\n const generatedValue = await generateUniqueValue(compress, value, compressedToValue)\n\n // Ensure the generated string contains at least one non-numeric character\n // This prevents the `setValueAtPath` function from interpreting the value as an array index\n // by forcing it to be treated as an object property name\n const compressedValue = generatedValue.match(/^\\d+$/) ? `a${generatedValue}` : generatedValue\n\n // Store the new mapping in our cache\n valueToCompressed[value] = compressedValue\n\n return compressedValue\n },\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAiB7B,eAAsB,QAAQ,OAAgC;AAE5D,QAAM,UAAU,MAAM,aAAa,KAAK;AAGxC,QAAM,OAAO,QAAQ,UAAU,GAAG,CAAC;AACnC,SAAO,KAAK,MAAM,OAAO,IAAI,MAAM,KAAK,UAAU,CAAC,IAAI;AACzD;AA4BA,eAAsB,oBACpB,UACA,OACA,mBACA,qBACA,QAAQ,GACR;AAEA,QAAM,YAAY;AAElB,MAAI,SAAS,WAAW;AACtB,UAAM;AAAA,EACR;AAGA,QAAM,kBAAkB,MAAM,SAAS,uBAAuB,KAAK;AAGnE,MAAI,kBAAkB,eAAe,MAAM,UAAa,kBAAkB,eAAe,MAAM,OAAO;AACpG,WAAO,oBAAoB,UAAU,OAAO,mBAAmB,iBAAiB,QAAQ,CAAC;AAAA,EAC3F;AAGA,oBAAkB,eAAe,IAAI;AACrC,SAAO;AACT;AAuBO,MAAM,8BAA8B,CACzC,UACA,sBACG;AAEH,QAAM,oBAAoB,OAAO,YAAY,OAAO,QAAQ,iBAAiB,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,MAAM,CAAC,OAAO,GAAG,CAAC,CAAC;AAElH,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcL,UAAU,OAAO,UAAkB;AAEjC,YAAM,QAAQ,kBAAkB,KAAK;AACrC,UAAI,OAAO;AACT,eAAO;AAAA,MACT;AAGA,YAAM,iBAAiB,MAAM,oBAAoB,UAAU,OAAO,iBAAiB;AAKnF,YAAM,kBAAkB,eAAe,MAAM,OAAO,IAAI,IAAI,cAAc,KAAK;AAG/E,wBAAkB,KAAK,IAAI;AAE3B,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["../../src/diff/diff.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,KAAK,UAAU,GAAG,KAAK,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAE7C;;;;;GAKG;AACH,MAAM,MAAM,UAAU,CAAC,EAAE,IAAI;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAA;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,IAAI,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,oBA0C7F,CAAA"}
1
+ {"version":3,"file":"diff.d.ts","sourceRoot":"","sources":["../../src/diff/diff.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,KAAK,UAAU,GAAG,KAAK,GAAG,QAAQ,GAAG,QAAQ,CAAA;AAE7C;;;;;GAKG;AACH,MAAM,MAAM,UAAU,CAAC,EAAE,IAAI;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,UAAU,CAAA;CAAE,CAAA;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,IAAI,GAAI,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,oBAyC7F,CAAA"}