@apidevtools/json-schema-ref-parser 10.0.1 → 10.1.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 (103) hide show
  1. package/dist/lib/bundle.d.ts +10 -0
  2. package/dist/lib/bundle.js +265 -0
  3. package/dist/lib/dereference.d.ts +9 -0
  4. package/dist/lib/dereference.js +206 -0
  5. package/dist/lib/index.d.ts +206 -0
  6. package/dist/lib/index.js +223 -0
  7. package/dist/lib/normalize-args.d.ts +10 -0
  8. package/dist/lib/normalize-args.js +42 -0
  9. package/dist/lib/options.d.ts +77 -0
  10. package/dist/lib/options.js +119 -0
  11. package/dist/lib/parse.d.ts +8 -0
  12. package/dist/lib/parse.js +177 -0
  13. package/dist/lib/parsers/binary.d.ts +3 -0
  14. package/dist/lib/parsers/binary.js +35 -0
  15. package/dist/lib/parsers/json.d.ts +3 -0
  16. package/dist/lib/parsers/json.js +57 -0
  17. package/dist/lib/parsers/text.d.ts +3 -0
  18. package/dist/lib/parsers/text.js +42 -0
  19. package/dist/lib/parsers/yaml.d.ts +3 -0
  20. package/dist/lib/parsers/yaml.js +65 -0
  21. package/dist/lib/pointer.d.ts +87 -0
  22. package/dist/lib/pointer.js +256 -0
  23. package/dist/lib/ref.d.ts +181 -0
  24. package/dist/lib/ref.js +239 -0
  25. package/dist/lib/refs.d.ts +127 -0
  26. package/dist/lib/refs.js +223 -0
  27. package/dist/lib/resolve-external.d.ts +14 -0
  28. package/dist/lib/resolve-external.js +148 -0
  29. package/dist/lib/resolvers/file.d.ts +3 -0
  30. package/dist/lib/resolvers/file.js +76 -0
  31. package/dist/lib/resolvers/http.d.ts +3 -0
  32. package/dist/lib/resolvers/http.js +159 -0
  33. package/dist/lib/types/index.d.ts +104 -0
  34. package/dist/lib/types/index.js +2 -0
  35. package/dist/lib/util/errors.d.ts +50 -0
  36. package/dist/lib/util/errors.js +106 -0
  37. package/dist/lib/util/maybe.d.ts +3 -0
  38. package/dist/lib/util/maybe.js +24 -0
  39. package/dist/lib/util/next.d.ts +2 -0
  40. package/dist/lib/util/next.js +16 -0
  41. package/dist/lib/util/plugins.d.ts +36 -0
  42. package/dist/lib/util/plugins.js +144 -0
  43. package/dist/lib/util/url.d.ts +93 -0
  44. package/{cjs → dist/lib}/util/url.js +134 -102
  45. package/dist/vite.config.d.ts +2 -0
  46. package/dist/vite.config.js +23 -0
  47. package/lib/{bundle.js → bundle.ts} +105 -101
  48. package/lib/{dereference.js → dereference.ts} +113 -52
  49. package/lib/index.ts +413 -0
  50. package/lib/{normalize-args.js → normalize-args.ts} +7 -14
  51. package/lib/options.ts +202 -0
  52. package/lib/parse.ts +153 -0
  53. package/lib/parsers/binary.ts +39 -0
  54. package/lib/parsers/{json.js → json.ts} +9 -22
  55. package/lib/parsers/text.ts +46 -0
  56. package/lib/parsers/{yaml.js → yaml.ts} +15 -19
  57. package/lib/pointer.ts +296 -0
  58. package/lib/ref.ts +288 -0
  59. package/lib/refs.ts +238 -0
  60. package/lib/{resolve-external.js → resolve-external.ts} +39 -36
  61. package/lib/resolvers/file.ts +40 -0
  62. package/lib/resolvers/http.ts +136 -0
  63. package/lib/tsconfig.json +103 -0
  64. package/lib/types/index.ts +135 -0
  65. package/lib/util/errors.ts +141 -0
  66. package/lib/util/maybe.ts +22 -0
  67. package/lib/util/next.ts +13 -0
  68. package/lib/util/{plugins.js → plugins.ts} +58 -57
  69. package/lib/util/{url.js → url.ts} +64 -83
  70. package/package.json +44 -45
  71. package/cjs/bundle.js +0 -304
  72. package/cjs/dereference.js +0 -258
  73. package/cjs/index.js +0 -603
  74. package/cjs/normalize-args.js +0 -64
  75. package/cjs/options.js +0 -125
  76. package/cjs/package.json +0 -3
  77. package/cjs/parse.js +0 -338
  78. package/cjs/parsers/binary.js +0 -54
  79. package/cjs/parsers/json.js +0 -199
  80. package/cjs/parsers/text.js +0 -61
  81. package/cjs/parsers/yaml.js +0 -239
  82. package/cjs/pointer.js +0 -290
  83. package/cjs/ref.js +0 -333
  84. package/cjs/refs.js +0 -214
  85. package/cjs/resolve-external.js +0 -333
  86. package/cjs/resolvers/file.js +0 -106
  87. package/cjs/resolvers/http.js +0 -184
  88. package/cjs/util/errors.js +0 -401
  89. package/cjs/util/plugins.js +0 -159
  90. package/cjs/util/projectDir.cjs +0 -6
  91. package/lib/index.d.ts +0 -496
  92. package/lib/index.js +0 -290
  93. package/lib/options.js +0 -128
  94. package/lib/parse.js +0 -162
  95. package/lib/parsers/binary.js +0 -53
  96. package/lib/parsers/text.js +0 -64
  97. package/lib/pointer.js +0 -293
  98. package/lib/ref.js +0 -292
  99. package/lib/refs.js +0 -196
  100. package/lib/resolvers/file.js +0 -63
  101. package/lib/resolvers/http.js +0 -155
  102. package/lib/util/errors.js +0 -134
  103. package/lib/util/projectDir.cjs +0 -6
@@ -0,0 +1,40 @@
1
+ import fs from "fs/promises";
2
+ import { ono } from "@jsdevtools/ono";
3
+ import * as url from "../util/url.js";
4
+ import { ResolverError } from "../util/errors.js";
5
+ import type { ResolverOptions } from "../types/index.js";
6
+ import type { FileInfo } from "../types/index.js";
7
+
8
+ export default {
9
+ /**
10
+ * The order that this resolver will run, in relation to other resolvers.
11
+ */
12
+ order: 100,
13
+
14
+ /**
15
+ * Determines whether this resolver can read a given file reference.
16
+ * Resolvers that return true will be tried, in order, until one successfully resolves the file.
17
+ * Resolvers that return false will not be given a chance to resolve the file.
18
+ */
19
+ canRead(file: FileInfo) {
20
+ return url.isFileSystemPath(file.url);
21
+ },
22
+
23
+ /**
24
+ * Reads the given file and returns its raw contents as a Buffer.
25
+ */
26
+ async read(file: FileInfo): Promise<Buffer> {
27
+ let path: string | undefined;
28
+ try {
29
+ path = url.toFileSystemPath(file.url);
30
+ } catch (err: any) {
31
+ throw new ResolverError(ono.uri(err, `Malformed URI: ${file.url}`), file.url);
32
+ }
33
+ try {
34
+ const data = await fs.readFile(path);
35
+ return data;
36
+ } catch (err: any) {
37
+ throw new ResolverError(ono(err, `Error opening file "${path}"`), path);
38
+ }
39
+ },
40
+ } as ResolverOptions;
@@ -0,0 +1,136 @@
1
+ import { ono } from "@jsdevtools/ono";
2
+ import * as url from "../util/url.js";
3
+ import { ResolverError } from "../util/errors.js";
4
+ import type { FileInfo, HTTPResolverOptions } from "../types/index.js";
5
+
6
+ export default {
7
+ /**
8
+ * The order that this resolver will run, in relation to other resolvers.
9
+ */
10
+ order: 200,
11
+
12
+ /**
13
+ * HTTP headers to send when downloading files.
14
+ *
15
+ * @example:
16
+ * {
17
+ * "User-Agent": "JSON Schema $Ref Parser",
18
+ * Accept: "application/json"
19
+ * }
20
+ */
21
+ headers: null,
22
+
23
+ /**
24
+ * HTTP request timeout (in milliseconds).
25
+ */
26
+ timeout: 5000, // 5 seconds
27
+
28
+ /**
29
+ * The maximum number of HTTP redirects to follow.
30
+ * To disable automatic following of redirects, set this to zero.
31
+ */
32
+ redirects: 5,
33
+
34
+ /**
35
+ * The `withCredentials` option of XMLHttpRequest.
36
+ * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
37
+ */
38
+ withCredentials: false,
39
+
40
+ /**
41
+ * Determines whether this resolver can read a given file reference.
42
+ * Resolvers that return true will be tried in order, until one successfully resolves the file.
43
+ * Resolvers that return false will not be given a chance to resolve the file.
44
+ */
45
+ canRead(file: FileInfo) {
46
+ return url.isHttp(file.url);
47
+ },
48
+
49
+ /**
50
+ * Reads the given URL and returns its raw contents as a Buffer.
51
+ */
52
+ read(file: FileInfo) {
53
+ const u = url.parse(file.url);
54
+
55
+ if (typeof window !== "undefined" && !u.protocol) {
56
+ // Use the protocol of the current page
57
+ u.protocol = url.parse(location.href).protocol;
58
+ }
59
+
60
+ return download(u, this);
61
+ },
62
+ } as HTTPResolverOptions;
63
+
64
+ /**
65
+ * Downloads the given file.
66
+ * @returns
67
+ * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.
68
+ */
69
+ async function download(u: URL | string, httpOptions: HTTPResolverOptions, _redirects?: string[]): Promise<Buffer> {
70
+ u = url.parse(u);
71
+ const redirects = _redirects || [];
72
+ redirects.push(u.href);
73
+
74
+ try {
75
+ const res = await get(u, httpOptions);
76
+ if (res.status >= 400) {
77
+ throw ono({ status: res.status }, `HTTP ERROR ${res.status}`);
78
+ } else if (res.status >= 300) {
79
+ if (!Number.isNaN(httpOptions.redirects) && redirects.length > httpOptions.redirects!) {
80
+ throw new ResolverError(
81
+ ono(
82
+ { status: res.status },
83
+ `Error downloading ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`,
84
+ ),
85
+ );
86
+ } else if (!("location" in res.headers) || !res.headers.location) {
87
+ throw ono({ status: res.status }, `HTTP ${res.status} redirect with no location header`);
88
+ } else {
89
+ const redirectTo = url.resolve(u, res.headers.location);
90
+ return download(redirectTo, httpOptions, redirects);
91
+ }
92
+ } else {
93
+ if (res.body) {
94
+ const buf = await res.arrayBuffer();
95
+ return Buffer.from(buf);
96
+ }
97
+ return Buffer.alloc(0);
98
+ }
99
+ } catch (err: any) {
100
+ throw new ResolverError(ono(err, `Error downloading ${u.href}`), u.href);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Sends an HTTP GET request.
106
+ * The promise resolves with the HTTP Response object.
107
+ */
108
+ async function get(u: RequestInfo | URL, httpOptions: HTTPResolverOptions) {
109
+ let controller: any;
110
+ let timeoutId: any;
111
+ if (httpOptions.timeout) {
112
+ controller = new AbortController();
113
+ timeoutId = setTimeout(() => controller.abort(), httpOptions.timeout);
114
+ }
115
+
116
+ if (!global.fetch) {
117
+ const { default: fetch, Request, Headers } = await import("node-fetch");
118
+ // @ts-ignore
119
+ global.fetch = fetch;
120
+ // @ts-ignore
121
+ global.Request = Request;
122
+ // @ts-ignore
123
+ global.Headers = Headers;
124
+ }
125
+ const response = await fetch(u, {
126
+ method: "GET",
127
+ headers: httpOptions.headers || {},
128
+ credentials: httpOptions.withCredentials ? "include" : "same-origin",
129
+ signal: controller ? controller.signal : null,
130
+ });
131
+ if (timeoutId) {
132
+ clearTimeout(timeoutId);
133
+ }
134
+
135
+ return response;
136
+ }
@@ -0,0 +1,103 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "resolveJsonModule": true, /* Enable importing .json files. */
39
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40
+
41
+ /* JavaScript Support */
42
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45
+
46
+ /* Emit */
47
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
49
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
53
+ // "removeComments": true, /* Disable emitting comments. */
54
+ // "noEmit": true, /* Disable emitting files from a compilation. */
55
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
64
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70
+
71
+ /* Interop Constraints */
72
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77
+
78
+ /* Type Checking */
79
+ "strict": true, /* Enable all strict type-checking options. */
80
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98
+
99
+ /* Completeness */
100
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
102
+ }
103
+ }
@@ -0,0 +1,135 @@
1
+ import type {
2
+ JSONSchema4,
3
+ JSONSchema4Object,
4
+ JSONSchema6,
5
+ JSONSchema6Object,
6
+ JSONSchema7,
7
+ JSONSchema7Object,
8
+ } from "json-schema";
9
+ import type $Refs from "../refs.js";
10
+
11
+ export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
12
+ export type JSONSchemaObject = JSONSchema4Object | JSONSchema6Object | JSONSchema7Object;
13
+ export type SchemaCallback = (err: Error | null, schema?: JSONSchema | object) => any;
14
+ export type $RefsCallback = (err: Error | null, $refs?: $Refs) => any;
15
+
16
+ /**
17
+ * See https://apitools.dev/json-schema-ref-parser/docs/options.html
18
+ */
19
+
20
+ export interface HTTPResolverOptions extends Partial<ResolverOptions> {
21
+ /**
22
+ * You can specify any HTTP headers that should be sent when downloading files. For example, some servers may require you to set the `Accept` or `Referrer` header.
23
+ */
24
+ headers?: HeadersInit | null;
25
+
26
+ /**
27
+ * The amount of time (in milliseconds) to wait for a response from the server when downloading files. The default is 5 seconds.
28
+ */
29
+ timeout?: number;
30
+
31
+ /**
32
+ * The maximum number of HTTP redirects to follow per file. The default is 5. To disable automatic following of redirects, set this to zero.
33
+ */
34
+ redirects?: number;
35
+
36
+ /**
37
+ * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
38
+ */
39
+ withCredentials?: boolean;
40
+ }
41
+
42
+ /**
43
+ * JSON Schema `$Ref` Parser comes with built-in resolvers for HTTP and HTTPS URLs, as well as local filesystem paths (when running in Node.js). You can add your own custom resolvers to support additional protocols, or even replace any of the built-in resolvers with your own custom implementation.
44
+ *
45
+ * See https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
46
+ */
47
+ export interface ResolverOptions {
48
+ name?: string;
49
+ /**
50
+ * All resolvers have an order property, even the built-in resolvers. If you don't specify an order property, then your resolver will run last. Specifying `order: 1`, like we did in this example, will make your resolver run first. Or you can squeeze your resolver in-between some of the built-in resolvers. For example, `order: 101` would make it run after the file resolver, but before the HTTP resolver. You can see the order of all the built-in resolvers by looking at their source code.
51
+ *
52
+ * The order property and canRead property are related to each other. For each file that JSON Schema $Ref Parser needs to resolve, it first determines which resolvers can read that file by checking their canRead property. If only one resolver matches a file, then only that one resolver is called, regardless of its order. If multiple resolvers match a file, then those resolvers are tried in order until one of them successfully reads the file. Once a resolver successfully reads the file, the rest of the resolvers are skipped.
53
+ */
54
+ order?: number;
55
+
56
+ /**
57
+ * The `canRead` property tells JSON Schema `$Ref` Parser what kind of files your resolver can read. In this example, we've simply specified a regular expression that matches "mogodb://" URLs, but we could have used a simple boolean, or even a function with custom logic to determine which files to resolve. Here are examples of each approach:
58
+ */
59
+ canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
60
+
61
+ /**
62
+ * This is where the real work of a resolver happens. The `read` method accepts the same file info object as the `canRead` function, but rather than returning a boolean value, the `read` method should return the contents of the file. The file contents should be returned in as raw a form as possible, such as a string or a byte array. Any further parsing or processing should be done by parsers.
63
+ *
64
+ * Unlike the `canRead` function, the `read` method can also be asynchronous. This might be important if your resolver needs to read data from a database or some other external source. You can return your asynchronous value using either an ES6 Promise or a Node.js-style error-first callback. Of course, if your resolver has the ability to return its data synchronously, then that's fine too. Here are examples of all three approaches:
65
+ */
66
+ read:
67
+ | string
68
+ | object
69
+ | ((
70
+ file: FileInfo,
71
+ callback?: (error: Error | null, data: string | null) => any,
72
+ ) => string | Buffer | JSONSchema | Promise<string | Buffer | JSONSchema>);
73
+ }
74
+
75
+ export interface Plugin {
76
+ name?: string;
77
+ /**
78
+ * Parsers run in a specific order, relative to other parsers. For example, a parser with `order: 5` will run before a parser with `order: 10`. If a parser is unable to successfully parse a file, then the next parser is tried, until one succeeds or they all fail.
79
+ *
80
+ * You can change the order in which parsers run, which is useful if you know that most of your referenced files will be a certain type, or if you add your own custom parser that you want to run first.
81
+ */
82
+ order?: number;
83
+
84
+ /**
85
+ * All of the built-in parsers allow empty files by default. The JSON and YAML parsers will parse empty files as `undefined`. The text parser will parse empty files as an empty string. The binary parser will parse empty files as an empty byte array.
86
+ *
87
+ * You can set `allowEmpty: false` on any parser, which will cause an error to be thrown if a file empty.
88
+ */
89
+ allowEmpty?: boolean;
90
+
91
+ /**
92
+ * The encoding that the text is expected to be in.
93
+ */
94
+ encoding?: BufferEncoding;
95
+ /**
96
+ * Determines which parsers will be used for which files.
97
+ *
98
+ * A regular expression can be used to match files by their full path. A string (or array of strings) can be used to match files by their file extension. Or a function can be used to perform more complex matching logic. See the custom parser docs for details.
99
+ */
100
+ canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
101
+
102
+ /**
103
+ * This is where the real work of a parser happens. The `parse` method accepts the same file info object as the `canParse` function, but rather than returning a boolean value, the `parse` method should return a JavaScript representation of the file contents. For our CSV parser, that is a two-dimensional array of lines and values. For your parser, it might be an object, a string, a custom class, or anything else.
104
+ *
105
+ * Unlike the `canParse` function, the `parse` method can also be asynchronous. This might be important if your parser needs to retrieve data from a database or if it relies on an external HTTP service to return the parsed value. You can return your asynchronous value via a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a Node.js-style error-first callback. Here are examples of both approaches:
106
+ */
107
+ parse:
108
+ | ((file: FileInfo, callback?: (error: Error | null, data: string | null) => any) => unknown | Promise<unknown>)
109
+ | number
110
+ | string;
111
+ }
112
+
113
+ /**
114
+ * JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canRead()`, `read()`, `canParse()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
115
+ *
116
+ * The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information.
117
+ *
118
+ * See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
119
+ */
120
+ export interface FileInfo {
121
+ /**
122
+ * The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js).
123
+ */
124
+ url: string;
125
+
126
+ /**
127
+ * The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
128
+ */
129
+ extension: string;
130
+
131
+ /**
132
+ * The raw file contents, in whatever form they were returned by the resolver that read the file.
133
+ */
134
+ data: string | Buffer;
135
+ }
@@ -0,0 +1,141 @@
1
+ import { Ono } from "@jsdevtools/ono";
2
+ import { stripHash, toFileSystemPath } from "./url.js";
3
+ import type $RefParser from "../index.js";
4
+
5
+ export type JSONParserErrorType =
6
+ | "EUNKNOWN"
7
+ | "EPARSER"
8
+ | "EUNMATCHEDPARSER"
9
+ | "ERESOLVER"
10
+ | "EUNMATCHEDRESOLVER"
11
+ | "EMISSINGPOINTER"
12
+ | "EINVALIDPOINTER";
13
+ export class JSONParserError extends Error {
14
+ public readonly name: string;
15
+ public readonly message: string;
16
+ public source: string | undefined;
17
+ public path: Array<string | number> | null;
18
+ public readonly code: JSONParserErrorType;
19
+ public constructor(message: string, source?: string) {
20
+ super();
21
+
22
+ this.code = "EUNKNOWN";
23
+ this.name = "JSONParserError";
24
+ this.message = message;
25
+ this.source = source;
26
+ this.path = null;
27
+
28
+ Ono.extend(this);
29
+ }
30
+
31
+ get footprint() {
32
+ return `${this.path}+${this.source}+${this.code}+${this.message}`;
33
+ }
34
+ }
35
+
36
+ export class JSONParserErrorGroup extends Error {
37
+ files: $RefParser;
38
+
39
+ constructor(parser: $RefParser) {
40
+ super();
41
+
42
+ this.files = parser;
43
+ this.name = "JSONParserErrorGroup";
44
+ this.message = `${this.errors.length} error${
45
+ this.errors.length > 1 ? "s" : ""
46
+ } occurred while reading '${toFileSystemPath(parser.$refs._root$Ref!.path)}'`;
47
+
48
+ Ono.extend(this);
49
+ }
50
+
51
+ static getParserErrors(parser: any) {
52
+ const errors = [];
53
+
54
+ for (const $ref of Object.values(parser.$refs._$refs)) {
55
+ // @ts-expect-error TS(2571): Object is of type 'unknown'.
56
+ if ($ref.errors) {
57
+ // @ts-expect-error TS(2571): Object is of type 'unknown'.
58
+ errors.push(...$ref.errors);
59
+ }
60
+ }
61
+
62
+ return errors;
63
+ }
64
+
65
+ get errors(): Array<
66
+ | JSONParserError
67
+ | InvalidPointerError
68
+ | ResolverError
69
+ | ParserError
70
+ | MissingPointerError
71
+ | UnmatchedParserError
72
+ | UnmatchedResolverError
73
+ > {
74
+ return JSONParserErrorGroup.getParserErrors(this.files);
75
+ }
76
+ }
77
+
78
+ export class ParserError extends JSONParserError {
79
+ code = "EPARSER" as JSONParserErrorType;
80
+ name = "ParserError";
81
+ constructor(message: any, source: any) {
82
+ super(`Error parsing ${source}: ${message}`, source);
83
+ }
84
+ }
85
+
86
+ export class UnmatchedParserError extends JSONParserError {
87
+ code = "EUNMATCHEDPARSER" as JSONParserErrorType;
88
+ name = "UnmatchedParserError";
89
+
90
+ constructor(source: string) {
91
+ super(`Could not find parser for "${source}"`, source);
92
+ }
93
+ }
94
+
95
+ export class ResolverError extends JSONParserError {
96
+ code = "ERESOLVER" as JSONParserErrorType;
97
+ name = "ResolverError";
98
+ ioErrorCode?: string;
99
+ constructor(ex: Error | any, source?: string) {
100
+ super(ex.message || `Error reading file "${source}"`, source);
101
+ if ("code" in ex) {
102
+ this.ioErrorCode = String(ex.code);
103
+ }
104
+ }
105
+ }
106
+
107
+ export class UnmatchedResolverError extends JSONParserError {
108
+ code = "EUNMATCHEDRESOLVER" as JSONParserErrorType;
109
+ name = "UnmatchedResolverError";
110
+ constructor(source: any) {
111
+ super(`Could not find resolver for "${source}"`, source);
112
+ }
113
+ }
114
+
115
+ export class MissingPointerError extends JSONParserError {
116
+ code = "EUNMATCHEDRESOLVER" as JSONParserErrorType;
117
+ name = "MissingPointerError";
118
+ constructor(token: any, path: any) {
119
+ super(`Token "${token}" does not exist.`, stripHash(path));
120
+ }
121
+ }
122
+
123
+ export class InvalidPointerError extends JSONParserError {
124
+ code = "EUNMATCHEDRESOLVER" as JSONParserErrorType;
125
+ name = "InvalidPointerError";
126
+ constructor(pointer: any, path: any) {
127
+ super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, stripHash(path));
128
+ }
129
+ }
130
+
131
+ export function isHandledError(err: any): err is JSONParserError {
132
+ return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;
133
+ }
134
+
135
+ export function normalizeError(err: any) {
136
+ if (err.path === null) {
137
+ err.path = [];
138
+ }
139
+
140
+ return err;
141
+ }
@@ -0,0 +1,22 @@
1
+ import next from "./next.js";
2
+
3
+ type MaybeParams<T> = (err: Error | any | null, result?: T) => void;
4
+ export default function maybe<T>(cb: MaybeParams<T> | undefined, promise: Promise<T>): Promise<T> | void {
5
+ if (cb) {
6
+ promise.then(
7
+ function (result) {
8
+ next(function () {
9
+ cb(null, result);
10
+ });
11
+ },
12
+ function (err) {
13
+ next(function () {
14
+ cb(err);
15
+ });
16
+ },
17
+ );
18
+ return undefined;
19
+ } else {
20
+ return promise;
21
+ }
22
+ }
@@ -0,0 +1,13 @@
1
+ function makeNext() {
2
+ if (typeof process === "object" && typeof process.nextTick === "function") {
3
+ return process.nextTick;
4
+ } else if (typeof setImmediate === "function") {
5
+ return setImmediate;
6
+ } else {
7
+ return function next(f: () => void) {
8
+ setTimeout(f, 0);
9
+ };
10
+ }
11
+ }
12
+
13
+ export default makeNext();