forked from fastify/fast-json-stringify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
603 lines (541 loc) · 14.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
'use strict'
var fastSafeStringify = require('fast-safe-stringify')
var Ajv = require('ajv')
var uglify = null
var isLong
try {
isLong = require('long').isLong
} catch (e) {
isLong = null
}
var addComma = `
if (addComma) {
json += ','
}
addComma = true
`
function build (schema, options) {
options = options || {}
/* eslint no-new-func: "off" */
var code = `
'use strict'
`
// used to support patternProperties and additionalProperties
// they need to check if a field belongs to the properties in the schema
code += `
var properties = ${JSON.stringify(schema.properties)} || {}
`
code += `
${$asString.toString()}
${$asStringSmall.toString()}
${$asNumber.toString()}
${$asNull.toString()}
${$asBoolean.toString()}
`
// only handle longs if the module is used
if (isLong) {
code += `
var isLong = ${isLong.toString()}
${$asInteger.toString()}
`
} else {
code += `
var $asInteger = $asNumber
`
}
var main
switch (schema.type) {
case 'object':
main = '$main'
code = buildObject(schema, code, main, options.schema, schema)
break
case 'string':
main = $asString.name
break
case 'integer':
main = $asInteger.name
break
case 'number':
main = $asNumber.name
break
case 'boolean':
main = $asBoolean.name
break
case 'null':
main = $asNull.name
break
case 'array':
main = '$main'
code = buildArray(schema, code, main, options.schema, schema)
break
default:
throw new Error(`${schema.type} unsupported`)
}
code += `
;
return ${main}
`
if (options.uglify) {
code = uglifyCode(code)
}
var dependencies = []
var dependenciesName = []
if (hasAdditionalPropertiesTrue(schema)) {
dependencies.push(fastSafeStringify)
dependenciesName.push('fastSafeStringify')
}
if (hasAnyOf(schema)) {
dependencies.push(new Ajv())
dependenciesName.push('ajv')
}
dependenciesName.push(code)
return (Function.apply(null, dependenciesName).apply(null, dependencies))
}
function hasAdditionalPropertiesTrue (schema) {
if (schema.additionalProperties === true) { return true }
var objectKeys = Object.keys(schema)
for (var i = 0; i < objectKeys.length; i++) {
var value = schema[objectKeys[i]]
if (typeof value === 'object') {
if (hasAdditionalPropertiesTrue(value)) { return true }
}
}
return false
}
function hasAnyOf (schema) {
if ('anyOf' in schema) { return true }
var objectKeys = Object.keys(schema)
for (var i = 0; i < objectKeys.length; i++) {
var value = schema[objectKeys[i]]
if (typeof value === 'object') {
if (hasAnyOf(value)) { return true }
}
}
return false
}
function $asNull () {
return 'null'
}
function $asInteger (i) {
if (isLong && isLong(i)) {
return i.toString()
} else {
return $asNumber(i)
}
}
function $asNumber (i) {
var num = Number(i)
if (isNaN(num)) {
return 'null'
} else {
return '' + num
}
}
function $asBoolean (bool) {
return bool && 'true' || 'false' // eslint-disable-line
}
function $asString (str) {
if (str instanceof Date) {
return '"' + str.toISOString() + '"'
} else if (str === null) {
return '""'
} else if (str instanceof RegExp) {
str = str.source
} else if (typeof str !== 'string') {
str = str.toString()
}
if (str.length < 42) {
return $asStringSmall(str)
} else {
return JSON.stringify(str)
}
}
// magically escape strings for json
// relying on their charCodeAt
// everything below 32 needs JSON.stringify()
// 34 and 92 happens all the time, so we
// have a fast case for them
function $asStringSmall (str) {
var result = ''
var last = 0
var l = str.length
var point = 255
for (var i = 0; i < l && point >= 32; i++) {
point = str.charCodeAt(i)
if (point === 34 || point === 92) {
result += str.slice(last, i) + '\\'
last = i
}
}
if (last === 0) {
result = str
} else {
result += str.slice(last)
}
return point < 32 ? JSON.stringify(str) : '"' + result + '"'
}
function addPatternProperties (schema, externalSchema, fullSchema) {
var pp = schema.patternProperties
var code = `
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
if (properties[keys[i]]) continue
`
Object.keys(pp).forEach((regex, index) => {
if (pp[regex]['$ref']) {
pp[regex] = refFinder(pp[regex]['$ref'], fullSchema, externalSchema, fullSchema)
}
var type = pp[regex].type
code += `
if (/${regex}/.test(keys[i])) {
`
if (type === 'object') {
code += buildObject(pp[regex], '', 'buildObjectPP' + index, externalSchema, fullSchema)
code += `
${addComma}
json += $asString(keys[i]) + ':' + buildObjectPP${index}(obj[keys[i]])
`
} else if (type === 'array') {
code += buildArray(pp[regex], '', 'buildArrayPP' + index, externalSchema, fullSchema)
code += `
${addComma}
json += $asString(keys[i]) + ':' + buildArrayPP${index}(obj[keys[i]])
`
} else if (type === 'null') {
code += `
${addComma}
json += $asString(keys[i]) +':null'
`
} else if (type === 'string') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asString(obj[keys[i]])
`
} else if (type === 'integer') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asInteger(obj[keys[i]])
`
} else if (type === 'number') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asNumber(obj[keys[i]])
`
} else if (type === 'boolean') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asBoolean(obj[keys[i]])
`
} else {
code += `
throw new Error('Cannot coerce ' + obj[keys[i]] + ' to ${type}')
`
}
code += `
continue
}
`
})
if (schema.additionalProperties) {
code += additionalProperty(schema, externalSchema, fullSchema)
}
code += `
}
`
return code
}
function additionalProperty (schema, externalSchema, fullSchema) {
var ap = schema.additionalProperties
var code = ''
if (ap === true) {
return `
if (obj[keys[i]] !== undefined) {
${addComma}
json += $asString(keys[i]) + ':' + fastSafeStringify(obj[keys[i]])
}
`
}
if (ap['$ref']) {
ap = refFinder(ap['$ref'], fullSchema, externalSchema)
}
var type = ap.type
if (type === 'object') {
code += buildObject(ap, '', 'buildObjectAP', externalSchema)
code += `
${addComma}
json += $asString(keys[i]) + ':' + buildObjectAP(obj[keys[i]])
`
} else if (type === 'array') {
code += buildArray(ap, '', 'buildArrayAP', externalSchema, fullSchema)
code += `
${addComma}
json += $asString(keys[i]) + ':' + buildArrayAP(obj[keys[i]])
`
} else if (type === 'null') {
code += `
${addComma}
json += $asString(keys[i]) +':null'
`
} else if (type === 'string') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asString(obj[keys[i]])
`
} else if (type === 'integer') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asInteger(obj[keys[i]])
`
} else if (type === 'number') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asNumber(obj[keys[i]])
`
} else if (type === 'boolean') {
code += `
${addComma}
json += $asString(keys[i]) + ':' + $asBoolean(obj[keys[i]])
`
} else {
code += `
throw new Error('Cannot coerce ' + obj[keys[i]] + ' to ${type}')
`
}
return code
}
function addAdditionalProperties (schema, externalSchema, fullSchema) {
return `
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
if (properties[keys[i]]) continue
${additionalProperty(schema, externalSchema, fullSchema)}
}
`
}
function refFinder (ref, schema, externalSchema) {
// Split file from walk
ref = ref.split('#')
// If external file
if (ref[0]) {
schema = externalSchema[ref[0]]
}
var walk = ref[1].split('/')
var code = 'return schema'
for (var i = 1; i < walk.length; i++) {
code += `['${walk[i]}']`
}
return (new Function('schema', code))(schema)
}
function buildObject (schema, code, name, externalSchema, fullSchema) {
code += `
function ${name} (obj) {
var json = '{'
var addComma = false
`
if (schema.patternProperties) {
code += addPatternProperties(schema, externalSchema, fullSchema)
} else if (schema.additionalProperties && !schema.patternProperties) {
code += addAdditionalProperties(schema, externalSchema, fullSchema)
}
var laterCode = ''
Object.keys(schema.properties || {}).forEach((key, i, a) => {
// Using obj['key'] !== undefined instead of obj.hasOwnProperty(prop) for perf reasons,
// see https://github.com/mcollina/fast-json-stringify/pull/3 for discussion.
code += `
if (obj['${key}'] !== undefined) {
${addComma}
json += '${$asString(key)}:'
`
if (schema.properties[key]['$ref']) {
schema.properties[key] = refFinder(schema.properties[key]['$ref'], fullSchema, externalSchema)
}
var result = nested(laterCode, name, key, schema.properties[key], externalSchema, fullSchema)
code += result.code
laterCode = result.laterCode
if (schema.required && schema.required.indexOf(key) !== -1) {
code += `
} else {
throw new Error('${key} is required!')
`
}
code += `
}
`
})
// Removes the comma if is the last element of the string (in case there are not properties)
code += `
json += '}'
return json
}
`
code += laterCode
return code
}
function buildArray (schema, code, name, externalSchema, fullSchema) {
code += `
function ${name} (obj) {
var json = '['
`
var laterCode = ''
if (schema.items['$ref']) {
schema.items = refFinder(schema.items['$ref'], fullSchema, externalSchema)
}
var result = {code: '', laterCode: ''}
if (Array.isArray(schema.items)) {
result = schema.items.reduce((res, item, i) => {
var accessor = '[i]'
const tmpRes = nested(laterCode, name, accessor, item, externalSchema, fullSchema, i)
var condition = `i === ${i} && `
switch (item.type) {
case 'null':
condition += `obj${accessor} === null`
break
case 'string':
condition += `typeof obj${accessor} === 'string'`
break
case 'integer':
condition += `Number.isInteger(obj${accessor})`
break
case 'number':
condition += `Number.isFinite(obj${accessor})`
break
case 'boolean':
condition += `typeof obj${accessor} === 'boolean'`
break
case 'object':
condition += `obj${accessor} && typeof obj${accessor} === 'object' && obj${accessor}.constructor === Object`
break
case 'array':
condition += `Array.isArray(obj${accessor})`
break
default:
throw new Error(`${item.type} unsupported`)
}
return {
code: `${res.code}
${i > 0 ? 'else' : ''} if (${condition}) {
${tmpRes.code}
}`,
laterCode: `${res.laterCode}
${tmpRes.laterCode}`
}
}, result)
result.code += `
else {
throw new Error(\`Item at $\{i} does not match schema definition.\`)
}
`
} else {
result = nested(laterCode, name, '[i]', schema.items, externalSchema, fullSchema)
}
code += `
var l = obj.length
var w = l - 1
for (var i = 0; i < l; i++) {
if (i > 0) {
json += ','
}
${result.code}
}
`
laterCode = result.laterCode
code += `
json += ']'
return json
}
`
code += laterCode
return code
}
function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKey) {
var code = ''
var funcName
var type = schema.type
var accessor = key.indexOf('[') === 0 ? key : `['${key}']`
switch (type) {
case 'null':
code += `
json += $asNull()
`
break
case 'string':
code += `
json += $asString(obj${accessor})
`
break
case 'integer':
code += `
json += $asInteger(obj${accessor})
`
break
case 'number':
code += `
json += $asNumber(obj${accessor})
`
break
case 'boolean':
code += `
json += $asBoolean(obj${accessor})
`
break
case 'object':
funcName = (name + key + subKey).replace(/[-.\[\]]/g, '') // eslint-disable-line
laterCode = buildObject(schema, laterCode, funcName, externalSchema, fullSchema)
code += `
json += ${funcName}(obj${accessor})
`
break
case 'array':
funcName = (name + key + subKey).replace(/[-.\[\]]/g, '') // eslint-disable-line
laterCode = buildArray(schema, laterCode, funcName, externalSchema, fullSchema)
code += `
json += ${funcName}(obj${accessor})
`
break
case undefined:
if ('anyOf' in schema) {
schema.anyOf.forEach((s, index) => {
code += `
${index === 0 ? 'if' : 'else if'}(ajv.validate(${require('util').inspect(s, {depth: null})}, obj${accessor}))
${nested(laterCode, name, key, s, externalSchema, fullSchema, subKey).code}
`
})
code += `
else json+= null
`
} else throw new Error(`${schema} unsupported`)
break
default:
throw new Error(`${type} unsupported`)
}
return {
code,
laterCode
}
}
function uglifyCode (code) {
if (!uglify) {
loadUglify()
}
var uglified = uglify.minify(code, { parse: { bare_returns: true } })
if (uglified.error) {
throw uglified.error
}
return uglified.code
}
function loadUglify () {
try {
uglify = require('uglify-es')
var uglifyVersion = require('uglify-es/package.json').version
if (uglifyVersion[0] !== '3') {
throw new Error('Only version 3 of uglify-es is supported')
}
} catch (e) {
uglify = null
if (e.code === 'MODULE_NOT_FOUND') {
throw new Error('In order to use uglify, you have to manually install `uglify-es`')
}
throw e
}
}
module.exports = build