From 362bfecd09c50a7c075c77bbb31bd64c52a31862 Mon Sep 17 00:00:00 2001 From: Martin Seidel Date: Thu, 2 Nov 2023 12:29:37 +0100 Subject: [PATCH 1/2] Fixed case when serializing const type with value that contains ' character --- index.js | 2 +- test/const.test.js | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 2c08bfba..6666776e 100644 --- a/index.js +++ b/index.js @@ -834,7 +834,7 @@ function buildConstSerializer (location, input) { ` } - code += `json += '${JSON.stringify(schema.const)}'` + code += `json += '${JSON.stringify(schema.const).replaceAll("'", "\\'")}'` if (hasNullType) { code += ` diff --git a/test/const.test.js b/test/const.test.js index c0b0b0aa..644c27f6 100644 --- a/test/const.test.js +++ b/test/const.test.js @@ -82,6 +82,26 @@ test('schema with const string and no input', (t) => { t.ok(validate(JSON.parse(output)), 'valid schema') }) +test('schema with const string that contains \'', (t) => { + t.plan(2) + + const schema = { + type: 'object', + properties: { + foo: { const: "'bar'" } + } + } + + const validate = validator(schema) + const stringify = build(schema) + const output = stringify({ + foo: "'bar'" + }) + + t.equal(output, '{"foo":"\'bar\'"}') + t.ok(validate(JSON.parse(output)), 'valid schema') +}) + test('schema with const number', (t) => { t.plan(2) From 8ee2f461869b5b8b4279861ce83684eb90e1d030 Mon Sep 17 00:00:00 2001 From: Martin Seidel Date: Thu, 2 Nov 2023 13:52:20 +0100 Subject: [PATCH 2/2] Extracted single quote as regex and used replace instead of replaceAll --- index.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 6666776e..f2a0d98a 100644 --- a/index.js +++ b/index.js @@ -12,6 +12,8 @@ const Serializer = require('./lib/serializer') const Validator = require('./lib/validator') const Location = require('./lib/location') +const SINGLE_TICK = /'/g + let largeArraySize = 2e4 let largeArrayMechanism = 'default' @@ -834,7 +836,7 @@ function buildConstSerializer (location, input) { ` } - code += `json += '${JSON.stringify(schema.const).replaceAll("'", "\\'")}'` + code += `json += '${JSON.stringify(schema.const).replace(SINGLE_TICK, "\\'")}'` if (hasNullType) { code += `