@@ -7,6 +7,7 @@ import { URL } from "url";
7
7
import mime from "mime" ;
8
8
import yaml from "js-yaml" ;
9
9
import { parseRef } from "./utils.js" ;
10
+ import { Readable } from "stream" ;
10
11
11
12
type PartialSchema = Record < string , any > ; // not a very accurate type, but this is easier to deal with before we know we’re dealing with a valid spec
12
13
type SchemaMap = { [ url : string ] : PartialSchema } ;
@@ -95,13 +96,13 @@ interface LoadOptions extends GlobalContext {
95
96
96
97
/** Load a schema from local path or remote URL */
97
98
export default async function load (
98
- schema : URL | PartialSchema ,
99
+ schema : URL | PartialSchema | Readable ,
99
100
options : LoadOptions
100
101
) : Promise < { [ url : string ] : PartialSchema } > {
101
102
const urlCache = options . urlCache || new Set < string > ( ) ;
102
103
103
- const isJSON = schema instanceof URL === false ; // if this is dynamically-passed-in JSON, we’ll have to change a few things
104
- let schemaID = isJSON ? new URL ( VIRTUAL_JSON_URL ) . href : ( schema . href as string ) ;
104
+ const isJSON = schema instanceof URL === false && ! ( schema instanceof Readable ) ; // if this is dynamically-passed-in JSON, we’ll have to change a few things
105
+ let schemaID = isJSON || schema instanceof Readable ? new URL ( VIRTUAL_JSON_URL ) . href : ( schema . href as string ) ;
105
106
106
107
const schemas = options . schemas ;
107
108
@@ -116,9 +117,25 @@ export default async function load(
116
117
117
118
let contents = "" ;
118
119
let contentType = "" ;
119
- const schemaURL = schema as URL ; // helps TypeScript
120
-
121
- if ( isFile ( schemaURL ) ) {
120
+ const schemaURL = schema instanceof Readable ? new URL ( VIRTUAL_JSON_URL ) : ( schema as URL ) ; // helps TypeScript
121
+
122
+ if ( schema instanceof Readable ) {
123
+ const readable = schema ;
124
+ contents = await new Promise < string > ( ( resolve ) => {
125
+ readable . resume ( ) ;
126
+ readable . setEncoding ( "utf8" ) ;
127
+
128
+ let content = "" ;
129
+ readable . on ( "data" , ( chunk : string ) => {
130
+ content += chunk ;
131
+ } ) ;
132
+
133
+ readable . on ( "end" , ( ) => {
134
+ resolve ( content ) ;
135
+ } ) ;
136
+ } ) ;
137
+ contentType = "text/yaml" ;
138
+ } else if ( isFile ( schemaURL ) ) {
122
139
// load local
123
140
contents = fs . readFileSync ( schemaURL , "utf8" ) ;
124
141
contentType = mime . getType ( schemaID ) || "" ;
0 commit comments