[6a3a178] | 1 | import {
|
---|
| 2 | DefinedFormats,
|
---|
| 3 | FormatMode,
|
---|
| 4 | FormatName,
|
---|
| 5 | formatNames,
|
---|
| 6 | fastFormats,
|
---|
| 7 | fullFormats,
|
---|
| 8 | } from "./formats"
|
---|
| 9 | import formatLimit from "./limit"
|
---|
| 10 | import type Ajv from "ajv"
|
---|
| 11 | import type {Plugin, Format} from "ajv"
|
---|
| 12 | import {_, Name} from "ajv/dist/compile/codegen"
|
---|
| 13 |
|
---|
| 14 | export {FormatMode, FormatName} from "./formats"
|
---|
| 15 | export {LimitFormatError} from "./limit"
|
---|
| 16 | export interface FormatOptions {
|
---|
| 17 | mode?: FormatMode
|
---|
| 18 | formats?: FormatName[]
|
---|
| 19 | keywords?: boolean
|
---|
| 20 | }
|
---|
| 21 |
|
---|
| 22 | export type FormatsPluginOptions = FormatName[] | FormatOptions
|
---|
| 23 |
|
---|
| 24 | export interface FormatsPlugin extends Plugin<FormatsPluginOptions> {
|
---|
| 25 | get: (format: FormatName, mode?: FormatMode) => Format
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | const fullName = new Name("fullFormats")
|
---|
| 29 | const fastName = new Name("fastFormats")
|
---|
| 30 |
|
---|
| 31 | const formatsPlugin: FormatsPlugin = (
|
---|
| 32 | ajv: Ajv,
|
---|
| 33 | opts: FormatsPluginOptions = {keywords: true}
|
---|
| 34 | ): Ajv => {
|
---|
| 35 | if (Array.isArray(opts)) {
|
---|
| 36 | addFormats(ajv, opts, fullFormats, fullName)
|
---|
| 37 | return ajv
|
---|
| 38 | }
|
---|
| 39 | const [formats, exportName] =
|
---|
| 40 | opts.mode === "fast" ? [fastFormats, fastName] : [fullFormats, fullName]
|
---|
| 41 | const list = opts.formats || formatNames
|
---|
| 42 | addFormats(ajv, list, formats, exportName)
|
---|
| 43 | if (opts.keywords) formatLimit(ajv)
|
---|
| 44 | return ajv
|
---|
| 45 | }
|
---|
| 46 |
|
---|
| 47 | formatsPlugin.get = (name: FormatName, mode: FormatMode = "full"): Format => {
|
---|
| 48 | const formats = mode === "fast" ? fastFormats : fullFormats
|
---|
| 49 | const f = formats[name]
|
---|
| 50 | if (!f) throw new Error(`Unknown format "${name}"`)
|
---|
| 51 | return f
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | function addFormats(ajv: Ajv, list: FormatName[], fs: DefinedFormats, exportName: Name): void {
|
---|
| 55 | ajv.opts.code.formats ??= _`require("ajv-formats/dist/formats").${exportName}`
|
---|
| 56 | for (const f of list) ajv.addFormat(f, fs[f])
|
---|
| 57 | }
|
---|
| 58 |
|
---|
| 59 | module.exports = exports = formatsPlugin
|
---|
| 60 | Object.defineProperty(exports, "__esModule", {value: true})
|
---|
| 61 |
|
---|
| 62 | export default formatsPlugin
|
---|