Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to override protocol from http:// to file:// in schema ids #615

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ main(
help: ['h'],
input: ['i'],
output: ['o'],
overrideHttpId: ['m'],
},
boolean: [
'additionalProperties',
Expand All @@ -40,6 +41,8 @@ async function main(argv: minimist.ParsedArgs) {
const argIn: string = argv._[0] || argv.input
const argOut: string | undefined = argv._[1] || argv.output // the output can be omitted so this can be undefined

const overrideHttpId: {[key: string]: string} = parseOverrideHttpIdArgs(argv.overrideHttpId)

const ISGLOB = isGlob(argIn)
const ISDIR = isDir(argIn)

Expand All @@ -52,11 +55,11 @@ async function main(argv: minimist.ParsedArgs) {
try {
// Process input as either glob, directory, or single file
if (ISGLOB) {
await processGlob(argIn, argOut, argv as Partial<Options>)
await processGlob(argIn, argOut, {...argv, overrideHttpId} as Partial<Options>)
} else if (ISDIR) {
await processDir(argIn, argOut, argv as Partial<Options>)
await processDir(argIn, argOut, {...argv, overrideHttpId} as Partial<Options>)
} else {
const result = await processFile(argIn, argv as Partial<Options>)
const result = await processFile(argIn, {...argv, overrideHttpId} as Partial<Options>)
outputResult(result, argOut)
}
} catch (e) {
Expand Down Expand Up @@ -160,6 +163,19 @@ async function readStream(stream: NodeJS.ReadStream): Promise<string> {
return Buffer.concat(chunks).toString('utf8')
}

function parseOverrideHttpIdArgs(overrideHttpId: any) {
const overrideHttpIdArg: {[key: string]: string} =
typeof overrideHttpId === 'string' ? {'0': overrideHttpId} : overrideHttpId
const result: {[key: string]: string} = {}
if (overrideHttpIdArg !== null) {
for (const [, value] of Object.entries(overrideHttpIdArg)) {
const [originalSchemaUrl, overrideSchemaUrl] = value.split(' ')
result[originalSchemaUrl] = overrideSchemaUrl
}
}
return Object.freeze(result)
}

function printHelp() {
const pkg = require('../../package.json')

Expand Down Expand Up @@ -192,6 +208,12 @@ Boolean values can be set to false using the 'no-' prefix.
array types, before falling back to emitting unbounded arrays. Increase
this to improve precision of emitted types, decrease it to improve
performance, or set it to -1 to ignore minItems and maxItems.
--overrideHttpId
Define overrides for HTTP schema ids to map it to file system.
--overrideHttpId=http://schemas.example.org/ file:///home/me/my-project/src/schemas/
or
--overrideHttpId.1=http://schemas1.example.org/ file:///home/me/my-project1/src/schemas/
--overrideHttpId.2=http://schemas2.example.org/ file:///home/me/my-project2/src/schemas/
--style.XXX=YYY
Prettier configuration
--unknownAny
Expand Down
11 changes: 11 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ export interface Options {
* Prepend enums with [`const`](https://www.typescriptlang.org/docs/handbook/enums.html#computed-and-constant-members)?
*/
enableConstEnums: boolean
/**
* Define overrides for HTTP schema ids to map it to file system.
*
* @example
* {
* "http://schemas1.example.org/": "file:///home/me/my-project1/src/schemas/",
* "http://schemas2.example.org/": "file:///home/me/my-project2/src/schemas/"
* }
*/
overrideHttpId: {[key: string]: string} | null
/**
* Create enums from JSON enums with eponymous keys
*/
Expand Down Expand Up @@ -101,6 +111,7 @@ export const DEFAULT_OPTIONS: Options = {
enableConstEnums: true,
inferStringEnumKeysFromValues: false,
format: true,
overrideHttpId: null,
ignoreMinAndMaxItems: false,
maxItems: 20,
strictIndexSignatures: false,
Expand Down
70 changes: 68 additions & 2 deletions src/resolver.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import {$RefParser, ParserOptions as $RefOptions} from '@apidevtools/json-schema-ref-parser'
import {readFile} from 'fs/promises'
import {
$RefParser,
ParserOptions as $RefOptions,
HTTPResolverOptions,
FileInfo,
} from '@apidevtools/json-schema-ref-parser'
import {JSONSchema} from './types/JSONSchema'
import {log} from './utils'

export type DereferencedPaths = WeakMap<JSONSchema, string>

export async function dereference(
schema: JSONSchema,
{cwd, $refOptions}: {cwd: string; $refOptions: $RefOptions},
{
cwd,
$refOptions,
overrideHttpId,
}: {cwd: string; overrideHttpId: {[key: string]: string} | null; $refOptions: $RefOptions},
): Promise<{dereferencedPaths: DereferencedPaths; dereferencedSchema: JSONSchema}> {
log('green', 'dereferencer', 'Dereferencing input schema:', cwd, schema)
const parser = new $RefParser()
const myResolver = new MyResolver(overrideHttpId)
const dereferencedPaths: DereferencedPaths = new WeakMap()
const dereferencedSchema = (await parser.dereference(cwd, schema, {
...$refOptions,
Expand All @@ -19,6 +30,61 @@ export async function dereference(
dereferencedPaths.set(schema, $ref)
},
},
resolve: {
httpOverride: {
order: 1,
canRead(file: FileInfo) {
return myResolver.canRead(file)
},
read(file: FileInfo) {
return myResolver.read(file)
},
},
},
})) as any // TODO: fix types
return {dereferencedPaths, dereferencedSchema}
}

class MyResolver implements HTTPResolverOptions {
private readonly overrideHttpId: ReadonlyArray<{originalSchemaUrl: URL; overrideSchemaUrl: URL}> | null

public constructor(overrideHttpId: {[key: string]: string} | null) {
if (overrideHttpId !== null) {
const result: Array<{originalSchemaUrl: URL; overrideSchemaUrl: URL}> = []
for (const [originalSchemaUrl, overrideSchemaUrl] of Object.entries(overrideHttpId)) {
result.push({originalSchemaUrl: new URL(originalSchemaUrl), overrideSchemaUrl: new URL(overrideSchemaUrl)})
}
this.overrideHttpId = Object.freeze(result)
} else {
this.overrideHttpId = null
}
}

public canRead(file: FileInfo): boolean {
if (this.overrideHttpId !== null) {
for (const {originalSchemaUrl} of this.overrideHttpId) {
const originalSchemaUrlStr: string = originalSchemaUrl.toString()
if (file.url.startsWith(originalSchemaUrlStr)) {
return true
}
}
}
return false
}

public async read(file: FileInfo): Promise<string | Buffer> {
if (this.overrideHttpId !== null) {
for (const {originalSchemaUrl, overrideSchemaUrl} of this.overrideHttpId) {
const originalSchemaUrlStr: string = originalSchemaUrl.toString()
if (file.url.startsWith(originalSchemaUrlStr)) {
const overrideSchemaUrlStr: string = overrideSchemaUrl.toString()
const newUrl: URL = new URL(file.url.replace(originalSchemaUrlStr, overrideSchemaUrlStr))
const fileData = await readFile(newUrl)
return fileData
}
}
}

throw new Error('Шось пішло не так')
}
}
Loading