1 import type Ajv from "../../core"
2 import type {SchemaObject} from "../../types"
3 import {jtdForms, JTDForm, SchemaObjectMap} from "./types"
4 import {SchemaEnv, getCompilingSchema} from ".."
5 import {_, str, and, getProperty, CodeGen, Code, Name} from "../codegen"
6 import MissingRefError from "../ref_error"
7 import N from "../names"
8 import {isOwnProperty} from "../../vocabularies/code"
9 import {hasRef} from "../../vocabularies/jtd/ref"
10 import {useFunc} from "../util"
11 import quote from "../../runtime/quote"
13 const genSerialize: {[F in JTDForm]: (cxt: SerializeCxt) => void} = {
14 elements: serializeElements,
15 values: serializeValues,
16 discriminator: serializeDiscriminator,
17 properties: serializeProperties,
18 optionalProperties: serializeProperties,
19 enum: serializeString,
24 interface SerializeCxt {
26 readonly self: Ajv // current Ajv instance
27 readonly schemaEnv: SchemaEnv
28 readonly definitions: SchemaObjectMap
33 export default function compileSerializer(
36 definitions: SchemaObjectMap
38 const _sch = getCompilingSchema.call(this, sch)
40 const {es5, lines} = this.opts.code
41 const {ownProperties} = this.opts
42 const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
43 const serializeName = gen.scopeName("serialize")
44 const cxt: SerializeCxt = {
47 schema: sch.schema as SchemaObject,
53 let sourceCode: string | undefined
55 this._compilations.add(sch)
56 sch.serializeName = serializeName
57 gen.func(serializeName, N.data, false, () => {
58 gen.let(N.json, str``)
62 gen.optimize(this.opts.code.optimize)
63 const serializeFuncCode = gen.toString()
64 sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}`
65 const makeSerialize = new Function(`${N.scope}`, sourceCode)
66 const serialize: (data: unknown) => string = makeSerialize(this.scope.get())
67 this.scope.value(serializeName, {ref: serialize})
68 sch.serialize = serialize
70 if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode)
72 delete sch.serializeName
75 this._compilations.delete(sch)
80 function serializeCode(cxt: SerializeCxt): void {
81 let form: JTDForm | undefined
82 for (const key of jtdForms) {
83 if (key in cxt.schema) {
88 serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty)
91 function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void {
92 const {gen, schema, data} = cxt
93 if (!schema.nullable) return serializeForm(cxt)
95 _`${data} === undefined || ${data} === null`,
96 () => gen.add(N.json, _`"null"`),
97 () => serializeForm(cxt)
101 function serializeElements(cxt: SerializeCxt): void {
102 const {gen, schema, data} = cxt
103 gen.add(N.json, str`[`)
104 const first = gen.let("first", true)
105 gen.forOf("el", data, (el) => {
107 serializeCode({...cxt, schema: schema.elements, data: el})
109 gen.add(N.json, str`]`)
112 function serializeValues(cxt: SerializeCxt): void {
113 const {gen, schema, data} = cxt
114 gen.add(N.json, str`{`)
115 const first = gen.let("first", true)
116 gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first))
117 gen.add(N.json, str`}`)
120 function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first: Name): void {
121 const {gen, data} = cxt
123 serializeString({...cxt, data: key})
124 gen.add(N.json, str`:`)
125 const value = gen.const("value", _`${data}${getProperty(key)}`)
126 serializeCode({...cxt, schema, data: value})
129 function serializeDiscriminator(cxt: SerializeCxt): void {
130 const {gen, schema, data} = cxt
131 const {discriminator} = schema
132 gen.add(N.json, str`{${JSON.stringify(discriminator)}:`)
133 const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`)
134 serializeString({...cxt, data: tag})
136 for (const tagValue in schema.mapping) {
137 gen.elseIf(_`${tag} === ${tagValue}`)
138 const sch = schema.mapping[tagValue]
139 serializeSchemaProperties({...cxt, schema: sch}, discriminator)
142 gen.add(N.json, str`}`)
145 function serializeProperties(cxt: SerializeCxt): void {
147 gen.add(N.json, str`{`)
148 serializeSchemaProperties(cxt)
149 gen.add(N.json, str`}`)
152 function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void {
153 const {gen, schema, data} = cxt
154 const {properties, optionalProperties} = schema
155 const props = keys(properties)
156 const optProps = keys(optionalProperties)
157 const allProps = allProperties(props.concat(optProps))
158 let first = !discriminator
159 for (const key of props) {
160 serializeProperty(key, properties[key], keyValue(key))
162 for (const key of optProps) {
163 const value = keyValue(key)
164 gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () =>
165 serializeProperty(key, optionalProperties[key], value)
168 if (schema.additionalProperties) {
169 gen.forIn("key", data, (key) =>
170 gen.if(isAdditional(key, allProps), () =>
171 serializeKeyValue(cxt, key, {}, gen.let("first", first))
176 function keys(ps?: SchemaObjectMap): string[] {
177 return ps ? Object.keys(ps) : []
180 function allProperties(ps: string[]): string[] {
181 if (discriminator) ps.push(discriminator)
182 if (new Set(ps).size !== ps.length) {
183 throw new Error("JTD: properties/optionalProperties/disciminator overlap")
188 function keyValue(key: string): Name {
189 return gen.const("value", _`${data}${getProperty(key)}`)
192 function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void {
193 if (first) first = false
194 else gen.add(N.json, str`,`)
195 gen.add(N.json, str`${JSON.stringify(key)}:`)
196 serializeCode({...cxt, schema: propSchema, data: value})
199 function isAdditional(key: Name, ps: string[]): Code | true {
200 return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true
204 function serializeType(cxt: SerializeCxt): void {
205 const {gen, schema, data} = cxt
206 switch (schema.type) {
208 gen.add(N.json, _`${data} ? "true" : "false"`)
215 _`${data} instanceof Date`,
216 () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`),
217 () => serializeString(cxt)
225 function serializeString({gen, data}: SerializeCxt): void {
226 gen.add(N.json, _`${useFunc(gen, quote)}(${data})`)
229 function serializeNumber({gen, data}: SerializeCxt): void {
230 gen.add(N.json, _`"" + ${data}`)
233 function serializeRef(cxt: SerializeCxt): void {
234 const {gen, self, data, definitions, schema, schemaEnv} = cxt
236 const refSchema = definitions[ref]
237 if (!refSchema) throw new MissingRefError("", ref, `No definition ${ref}`)
238 if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema})
239 const {root} = schemaEnv
240 const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions)
241 gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`)
244 function getSerialize(gen: CodeGen, sch: SchemaEnv): Code {
246 ? gen.scopeValue("serialize", {ref: sch.serialize})
247 : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize`
250 function serializeEmpty({gen, data}: SerializeCxt): void {
251 gen.add(N.json, _`JSON.stringify(${data})`)
254 function addComma({gen}: SerializeCxt, first: Name): void {
257 () => gen.assign(first, false),
258 () => gen.add(N.json, str`,`)