    C C C {"files":{"dist":{"files":{"main":{"files":{"index.js":{"size":266048,"offset":"0","integrity":{"algorithm":"SHA256","hash":"44fc5e7a4eb2c9387b8fd8647d22480e7f7bdc5a877a7faec171cb0c6f92554e","blockSize":4194304,"blocks":["44fc5e7a4eb2c9387b8fd8647d22480e7f7bdc5a877a7faec171cb0c6f92554e"]}}}},"preload":{"files":{"index.js":{"size":76679,"offset":"266048","integrity":{"algorithm":"SHA256","hash":"a1b39d22ba2381f581e92e4483bea1a51cba4d464b64d8a3fb854ee458cc71e8","blockSize":4194304,"blocks":["a1b39d22ba2381f581e92e4483bea1a51cba4d464b64d8a3fb854ee458cc71e8"]}}}}}},"node_modules":{"files":{"ajv":{"files":{".tonic_example.js":{"size":439,"offset":"757036","integrity":{"algorithm":"SHA256","hash":"6df193499f7d9f042775bc44c78e586f332b114bbc066aaea6f6ff5ba91dd22b","blockSize":4194304,"blocks":["6df193499f7d9f042775bc44c78e586f332b114bbc066aaea6f6ff5ba91dd22b"]}},"LICENSE":{"size":1090,"offset":"757475","integrity":{"algorithm":"SHA256","hash":"e85e131fa4ed25538ff1f4962ced1fb6f68b079bd9164a790597a0f30b8fd030","blockSize":4194304,"blocks":["e85e131fa4ed25538ff1f4962ced1fb6f68b079bd9164a790597a0f30b8fd030"]}},"README.md":{"size":86876,"offset":"758565","integrity":{"algorithm":"SHA256","hash":"9f4a3d6e74123a325a21efc8494cac6d01f9fe1781bcf63976a2e118260b4d89","blockSize":4194304,"blocks":["9f4a3d6e74123a325a21efc8494cac6d01f9fe1781bcf63976a2e118260b4d89"]}},"dist":{"files":{"ajv.bundle.js":{"size":273216,"offset":"845441","integrity":{"algorithm":"SHA256","hash":"f49bf8a27a25ba0e6aa9274d01481c748e344ee9a186346f5e0b8055dafeaad9","blockSize":4194304,"blocks":["f49bf8a27a25ba0e6aa9274d01481c748e344ee9a186346f5e0b8055dafeaad9"]}},"ajv.min.js":{"size":119444,"offset":"1118657","integrity":{"algorithm":"SHA256","hash":"e03fc6014680bd4a07160361ed07c0c8df08e87a7aa60671dcdf3d9a77c623a3","blockSize":4194304,"blocks":["e03fc6014680bd4a07160361ed07c0c8df08e87a7aa60671dcdf3d9a77c623a3"]}}}},"lib":{"files":{"ajv.js":{"size":15837,"offset":"1238101","integrity":{"algorithm":"SHA256","hash":"cc30899a3c8232e1183d6f4d26a54396213f68f7476c3492f783d08e25401023","blockSize":4194304,"blocks":["cc30899a3c8232e1183d6f4d26a54396213f68f7476c3492f783d08e25401023"]}},"cache.js":{"size":409,"offset":"1253938","integrity":{"algorithm":"SHA256","hash":"e46dcc11c6e844f644ca331bf7d5caeb3ad1357ca540215da9668f6c58c6aa89","blockSize":4194304,"blocks":["e46dcc11c6e844f644ca331bf7d5caeb3ad1357ca540215da9668f6c58c6aa89"]}},"compile":{"files":{"async.js":{"size":2644,"offset":"1254347","integrity":{"algorithm":"SHA256","hash":"4bfa8664a637f31818f9a88b5151ed7e8fd986bc0664b674654b610d5e4c80d2","blockSize":4194304,"blocks":["4bfa8664a637f31818f9a88b5151ed7e8fd986bc0664b674654b610d5e4c80d2"]}},"equal.js":{"size":176,"offset":"1256991","integrity":{"algorithm":"SHA256","hash":"a32f0fd0f8794ed157804169c7a32ac9a89e2e5762d427bb2b424a70ba2be763","blockSize":4194304,"blocks":["a32f0fd0f8794ed157804169c7a32ac9a89e2e5762d427bb2b424a70ba2be763"]}},"error_classes.js":{"size":828,"offset":"1257167","integrity":{"algorithm":"SHA256","hash":"dd1dec6c510cd07e796c6ba1b746cf1efc4eed57c79ef790417d50497ee9af02","blockSize":4194304,"blocks":["dd1dec6c510cd07e796c6ba1b746cf1efc4eed57c79ef790417d50497ee9af02"]}},"formats.js":{"size":12081,"offset":"1257995","integrity":{"algorithm":"SHA256","hash":"ba0cde9da30782c10d237df4e3e92d32da9c3bc2d278d89b4355e4a6f540ccf7","blockSize":4194304,"blocks":["ba0cde9da30782c10d237df4e3e92d32da9c3bc2d278d89b4355e4a6f540ccf7"]}},"index.js":{"size":10807,"offset":"1270076","integrity":{"algorithm":"SHA256","hash":"ee3290acb345cc37b1412c45d53f7d200a824eb35ec060279a25c6e703513bcc","blockSize":4194304,"blocks":["ee3290acb345cc37b1412c45d53f7d200a824eb35ec060279a25c6e703513bcc"]}},"resolve.js":{"size":7847,"offset":"1280883","integrity":{"algorithm":"SHA256","hash":"61735e559ac4ff73d3b5a85d0f7e7d248bf53eaa47f9fd80cb950f59a9aca80c","blockSize":4194304,"blocks":["61735e559ac4ff73d3b5a85d0f7e7d248bf53eaa47f9fd80cb950f59a9aca80c"]}},"rules.js":{"size":2021,"offset":"1288730","integrity":{"algorithm":"SHA256","hash":"ee1d720ece5b85634762672652cb1daf4074ab3535da2cc8b8c002eb4dd536ba","blockSize":4194304,"blocks":["ee1d720ece5b85634762672652cb1daf4074ab3535da2cc8b8c002eb4dd536ba"]}},"schema_obj.js":{"size":133,"offset":"1290751","integrity":{"algorithm":"SHA256","hash":"42e3892ff6d470c9fb601dc7bbde42c6909fcf00c0d86fdbbab0deaf9c37b598","blockSize":4194304,"blocks":["42e3892ff6d470c9fb601dc7bbde42c6909fcf00c0d86fdbbab0deaf9c37b598"]}},"ucs2length.js":{"size":558,"offset":"1290884","integrity":{"algorithm":"SHA256","hash":"b60efae2495d93ce8db6eb79c690448038269e720d89b846bae2fc1f7ae764cc","blockSize":4194304,"blocks":["b60efae2495d93ce8db6eb79c690448038269e720d89b846bae2fc1f7ae764cc"]}},"util.js":{"size":6974,"offset":"1291442","integrity":{"algorithm":"SHA256","hash":"329aa7f0b435a37096f1a1c4dc8f06f56110d68d69189ad5d4809de86422f651","blockSize":4194304,"blocks":["329aa7f0b435a37096f1a1c4dc8f06f56110d68d69189ad5d4809de86422f651"]}}}},"data.js":{"size":1048,"offset":"1298416","integrity":{"algorithm":"SHA256","hash":"c8540b06ec80ba7ab9078d38c4818b82097a282159981f377fa283186cc64492","blockSize":4194304,"blocks":["c8540b06ec80ba7ab9078d38c4818b82097a282159981f377fa283186cc64492"]}},"definition_schema.js":{"size":872,"offset":"1299464","integrity":{"algorithm":"SHA256","hash":"d050d4982e55cbf963425bf8a42ab1b9d365e2a53e1cc03208a6d2b30bdfccdf","blockSize":4194304,"blocks":["d050d4982e55cbf963425bf8a42ab1b9d365e2a53e1cc03208a6d2b30bdfccdf"]}},"dot":{"files":{"_limit.jst":{"size":3932,"offset":"1300336","integrity":{"algorithm":"SHA256","hash":"5a359e1fea273dc74ec451ecabb37e69330b38d65a85edca91d3d2edeeea52d6","blockSize":4194304,"blocks":["5a359e1fea273dc74ec451ecabb37e69330b38d65a85edca91d3d2edeeea52d6"]}},"_limitItems.jst":{"size":353,"offset":"1304268","integrity":{"algorithm":"SHA256","hash":"dd288000fc1a50c87095896710e86d934cee2642a06f0d6d8337997e7419c996","blockSize":4194304,"blocks":["dd288000fc1a50c87095896710e86d934cee2642a06f0d6d8337997e7419c996"]}},"_limitLength.jst":{"size":358,"offset":"1304621","integrity":{"algorithm":"SHA256","hash":"9bb203beb1705c226e9e3ce22dbbca3920b6f652b1afd8a0d42cc5a6c32d9452","blockSize":4194304,"blocks":["9bb203beb1705c226e9e3ce22dbbca3920b6f652b1afd8a0d42cc5a6c32d9452"]}},"_limitProperties.jst":{"size":376,"offset":"1304979","integrity":{"algorithm":"SHA256","hash":"a8f0f1effb40478156e2deb98f2c532cb7c75ece19df64f2d23cbdb8af3e306c","blockSize":4194304,"blocks":["a8f0f1effb40478156e2deb98f2c532cb7c75ece19df64f2d23cbdb8af3e306c"]}},"allOf.jst":{"size":609,"offset":"1305355","integrity":{"algorithm":"SHA256","hash":"ee4e6c238cfd04c4acb42d44f14547f2f2010a522784ff31085b93e4e5281dc7","blockSize":4194304,"blocks":["ee4e6c238cfd04c4acb42d44f14547f2f2010a522784ff31085b93e4e5281dc7"]}},"anyOf.jst":{"size":921,"offset":"1305964","integrity":{"algorithm":"SHA256","hash":"67bf7efc9a7d001acd1d0e635b83d9ad45fb259c5044141ed91975497304c9da","blockSize":4194304,"blocks":["67bf7efc9a7d001acd1d0e635b83d9ad45fb259c5044141ed91975497304c9da"]}},"coerce.def":{"size":1979,"offset":"1306885","integrity":{"algorithm":"SHA256","hash":"55a8ad7fad7aab2fbd65eaafec5cdefd3f08761b6a80969ae8321a3591143eb3","blockSize":4194304,"blocks":["55a8ad7fad7aab2fbd65eaafec5cdefd3f08761b6a80969ae8321a3591143eb3"]}},"comment.jst":{"size":322,"offset":"1308864","integrity":{"algorithm":"SHA256","hash":"9ae60097b70de6628841168ba9013555d29bbe5aa9c3fc546cdb502d385ce536","blockSize":4194304,"blocks":["9ae60097b70de6628841168ba9013555d29bbe5aa9c3fc546cdb502d385ce536"]}},"const.jst":{"size":280,"offset":"1309186","integrity":{"algorithm":"SHA256","hash":"6d2fcb0689dd1376e54321076f9808b2bf6901dca3b5308ac826f012005c02a2","blockSize":4194304,"blocks":["6d2fcb0689dd1376e54321076f9808b2bf6901dca3b5308ac826f012005c02a2"]}},"contains.jst":{"size":1188,"offset":"1309466","integrity":{"algorithm":"SHA256","hash":"86efacd183d38376d2fe0f1502b2d344c294a136b8219cdef4e409a0dc9028c3","blockSize":4194304,"blocks":["86efacd183d38376d2fe0f1502b2d344c294a136b8219cdef4e409a0dc9028c3"]}},"custom.jst":{"size":4945,"offset":"1310654","integrity":{"algorithm":"SHA256","hash":"450510c02f23ca48cf1cf98a92c3de346d8fbfb47b53da460ba5ec7e3c898c80","blockSize":4194304,"blocks":["450510c02f23ca48cf1cf98a92c3de346d8fbfb47b53da460ba5ec7e3c898c80"]}},"defaults.def":{"size":1285,"offset":"1315599","integrity":{"algorithm":"SHA256","hash":"6686d2936716a9e18a2efc66bce7563e479d14fd3ab40f0d9251eaab81233ac1","blockSize":4194304,"blocks":["6686d2936716a9e18a2efc66bce7563e479d14fd3ab40f0d9251eaab81233ac1"]}},"definitions.def":{"size":4022,"offset":"1316884","integrity":{"algorithm":"SHA256","hash":"546bfcfd7846af2b218c487ec46e801efb409838b4bcd6c2a4cef843a390615a","blockSize":4194304,"blocks":["546bfcfd7846af2b218c487ec46e801efb409838b4bcd6c2a4cef843a390615a"]}},"dependencies.jst":{"size":1868,"offset":"1320906","integrity":{"algorithm":"SHA256","hash":"7e307f0f74f72b3ea2498787d2ddf0d32a68d2c111578697a9614d372babb7c1","blockSize":4194304,"blocks":["7e307f0f74f72b3ea2498787d2ddf0d32a68d2c111578697a9614d372babb7c1"]}},"enum.jst":{"size":552,"offset":"1322774","integrity":{"algorithm":"SHA256","hash":"088fd6c53a93c4e4633ecf2e873340f84e94939316f64b776c9a81bb732a1ba9","blockSize":4194304,"blocks":["088fd6c53a93c4e4633ecf2e873340f84e94939316f64b776c9a81bb732a1ba9"]}},"errors.def":{"size":8282,"offset":"1323326","integrity":{"algorithm":"SHA256","hash":"2e67bc06f4ec877190d3d52863aa6b671384ddbb99b4c8ba840df542838e0c68","blockSize":4194304,"blocks":["2e67bc06f4ec877190d3d52863aa6b671384ddbb99b4c8ba840df542838e0c68"]}},"format.jst":{"size":3136,"offset":"1331608","integrity":{"algorithm":"SHA256","hash":"8e6bc9e02190a1e1103cac4704465bcc47a4edd596f4d2eb73e39110ab83df74","blockSize":4194304,"blocks":["8e6bc9e02190a1e1103cac4704465bcc47a4edd596f4d2eb73e39110ab83df74"]}},"if.jst":{"size":1618,"offset":"1334744","integrity":{"algorithm":"SHA256","hash":"a084c8301cfa186f0460a4e88387ea3150ad52d2a114fbd11e6fbf85fc912c62","blockSize":4194304,"blocks":["a084c8301cfa186f0460a4e88387ea3150ad52d2a114fbd11e6fbf85fc912c62"]}},"items.jst":{"size":2610,"offset":"1336362","integrity":{"algorithm":"SHA256","hash":"cbc3d15b52c4169d750ff6f842208e3ccd5d8dcae6a2cff52cd4e7325ceb1e92","blockSize":4194304,"blocks":["cbc3d15b52c4169d750ff6f842208e3ccd5d8dcae6a2cff52cd4e7325ceb1e92"]}},"missing.def":{"size":1194,"offset":"1338972","integrity":{"algorithm":"SHA256","hash":"bb52cb196254320b3a80782b1dac6636debcbe04bf1e48df5b81fec3886456d8","blockSize":4194304,"blocks":["bb52cb196254320b3a80782b1dac6636debcbe04bf1e48df5b81fec3886456d8"]}},"multipleOf.jst":{"size":644,"offset":"1340166","integrity":{"algorithm":"SHA256","hash":"34d7a719b015fd7500ac8ec31a5199775dba55ccc49a0547715d5ac0bafbcb66","blockSize":4194304,"blocks":["34d7a719b015fd7500ac8ec31a5199775dba55ccc49a0547715d5ac0bafbcb66"]}},"not.jst":{"size":861,"offset":"1340810","integrity":{"algorithm":"SHA256","hash":"6a5d0d66c1182464d9b85ff393b56830f0702c8942d9a19d42657620bb6d25a4","blockSize":4194304,"blocks":["6a5d0d66c1182464d9b85ff393b56830f0702c8942d9a19d42657620bb6d25a4"]}},"oneOf.jst":{"size":1150,"offset":"1341671","integrity":{"algorithm":"SHA256","hash":"d1d91a376cb3383e4c595a34b596fdff9cc0fd6187879b6a86e2ea7846d2b7d3","blockSize":4194304,"blocks":["d1d91a376cb3383e4c595a34b596fdff9cc0fd6187879b6a86e2ea7846d2b7d3"]}},"pattern.jst":{"size":576,"offset":"1342821","integrity":{"algorithm":"SHA256","hash":"7e7c04ee8ee2f1a4bcab5d65b2493a1da1fdce37f3416fe17630a54a12a97899","blockSize":4194304,"blocks":["7e7c04ee8ee2f1a4bcab5d65b2493a1da1fdce37f3416fe17630a54a12a97899"]}},"properties.jst":{"size":7725,"offset":"1343397","integrity":{"algorithm":"SHA256","hash":"3518d27bf09a1dd4d35530681f196c9f6e1744c10cd1c632b4645ee6ca3f7969","blockSize":4194304,"blocks":["3518d27bf09a1dd4d35530681f196c9f6e1744c10cd1c632b4645ee6ca3f7969"]}},"propertyNames.jst":{"size":1284,"offset":"1351122","integrity":{"algorithm":"SHA256","hash":"f306ced709b3f0d12ee9f4b863ddbb3b176b018fc577d6d9296208df8d8e2fe1","blockSize":4194304,"blocks":["f306ced709b3f0d12ee9f4b863ddbb3b176b018fc577d6d9296208df8d8e2fe1"]}},"ref.jst":{"size":2454,"offset":"1352406","integrity":{"algorithm":"SHA256","hash":"bdb99d7e81d98330463e10b41a08335439e3a9965dc9031c54263ee3fbc500c3","blockSize":4194304,"blocks":["bdb99d7e81d98330463e10b41a08335439e3a9965dc9031c54263ee3fbc500c3"]}},"required.jst":{"size":2868,"offset":"1354860","integrity":{"algorithm":"SHA256","hash":"21b390b530ac65f59eb585fbd2ace68eae8e04dfe8af9a3574e49ae07e0c1f58","blockSize":4194304,"blocks":["21b390b530ac65f59eb585fbd2ace68eae8e04dfe8af9a3574e49ae07e0c1f58"]}},"uniqueItems.jst":{"size":1696,"offset":"1357728","integrity":{"algorithm":"SHA256","hash":"4c2afcc9877a02b58fd00c4dc36187d3cd1e0e8ff5761ddaf1c666b7d3a25263","blockSize":4194304,"blocks":["4c2afcc9877a02b58fd00c4dc36187d3cd1e0e8ff5761ddaf1c666b7d3a25263"]}},"validate.jst":{"size":7717,"offset":"1359424","integrity":{"algorithm":"SHA256","hash":"4b3ce454d8cefb6a77846f97069b812f386a312e84f1182ad38a409a6f51d0c7","blockSize":4194304,"blocks":["4b3ce454d8cefb6a77846f97069b812f386a312e84f1182ad38a409a6f51d0c7"]}}}},"dotjs":{"files":{"README.md":{"size":149,"offset":"1367141","integrity":{"algorithm":"SHA256","hash":"30eeee72a46d849c941e3e9446e0bca66ed905a72ade2716119ef26c14c0dac9","blockSize":4194304,"blocks":["30eeee72a46d849c941e3e9446e0bca66ed905a72ade2716119ef26c14c0dac9"]}},"_limit.js":{"size":7395,"offset":"1367290","integrity":{"algorithm":"SHA256","hash":"1cf617f09077f153168137651a53abc2088d80591d5d577e276d1b7023523ba1","blockSize":4194304,"blocks":["1cf617f09077f153168137651a53abc2088d80591d5d577e276d1b7023523ba1"]}},"_limitItems.js":{"size":2704,"offset":"1374685","integrity":{"algorithm":"SHA256","hash":"a20128ce95a4267bc026f72da633d8f81f23d5d6d664a5503529279b1fe98574","blockSize":4194304,"blocks":["a20128ce95a4267bc026f72da633d8f81f23d5d6d664a5503529279b1fe98574"]}},"_limitLength.js":{"size":2825,"offset":"1377389","integrity":{"algorithm":"SHA256","hash":"abc90262f31f548f6593855e82cbea1a0a5d7199a511c43e766357af39af93cc","blockSize":4194304,"blocks":["abc90262f31f548f6593855e82cbea1a0a5d7199a511c43e766357af39af93cc"]}},"_limitProperties.js":{"size":2742,"offset":"1380214","integrity":{"algorithm":"SHA256","hash":"36c8b6512cc53fe730990c9cdc0d9da2fbbfb10b9a60d96ac3b35d75ef66503b","blockSize":4194304,"blocks":["36c8b6512cc53fe730990c9cdc0d9da2fbbfb10b9a60d96ac3b35d75ef66503b"]}},"allOf.js":{"size":1349,"offset":"1382956","integrity":{"algorithm":"SHA256","hash":"8f73c7d4242793a3b485dce5e1a46861ccb6af1935f3b7565cd7f1c71c79f70d","blockSize":4194304,"blocks":["8f73c7d4242793a3b485dce5e1a46861ccb6af1935f3b7565cd7f1c71c79f70d"]}},"anyOf.js":{"size":2925,"offset":"1384305","integrity":{"algorithm":"SHA256","hash":"c6fd31c9e66cea3f16017c5cfbe6c8eb25ea8248b8520026e05ff4c5802cbe99","blockSize":4194304,"blocks":["c6fd31c9e66cea3f16017c5cfbe6c8eb25ea8248b8520026e05ff4c5802cbe99"]}},"comment.js":{"size":573,"offset":"1387230","integrity":{"algorithm":"SHA256","hash":"7f96f44c08b52e9b4658d40fd65382dc89cf4e73116479c6211582147c4b0048","blockSize":4194304,"blocks":["7f96f44c08b52e9b4658d40fd65382dc89cf4e73116479c6211582147c4b0048"]}},"const.js":{"size":2113,"offset":"1387803","integrity":{"algorithm":"SHA256","hash":"1bcb376424595c3b2be687118bc7a2ace072cc87f31363b28892c6b28c3b160e","blockSize":4194304,"blocks":["1bcb376424595c3b2be687118bc7a2ace072cc87f31363b28892c6b28c3b160e"]}},"contains.js":{"size":3370,"offset":"1389916","integrity":{"algorithm":"SHA256","hash":"cb182b4d4e1eb540f1ab0e216165b654fd11692ad21405fc6d1a13dd14143213","blockSize":4194304,"blocks":["cb182b4d4e1eb540f1ab0e216165b654fd11692ad21405fc6d1a13dd14143213"]}},"custom.js":{"size":9770,"offset":"1393286","integrity":{"algorithm":"SHA256","hash":"3e42bc285568af0fa8977ce2fd14b592ff8b8716921868a46e18d4dc4e21a81b","blockSize":4194304,"blocks":["3e42bc285568af0fa8977ce2fd14b592ff8b8716921868a46e18d4dc4e21a81b"]}},"dependencies.js":{"size":7720,"offset":"1403056","integrity":{"algorithm":"SHA256","hash":"6ec373cb168e6bfe6dcf5b4e492ac67114e4a176aaaae643d12f804e86306523","blockSize":4194304,"blocks":["6ec373cb168e6bfe6dcf5b4e492ac67114e4a176aaaae643d12f804e86306523"]}},"enum.js":{"size":2586,"offset":"1410776","integrity":{"algorithm":"SHA256","hash":"7ed0f983a5d98c2bf8980b04cc49d80a4a4c543b99eb4c0296e6fce84075ec9c","blockSize":4194304,"blocks":["7ed0f983a5d98c2bf8980b04cc49d80a4a4c543b99eb4c0296e6fce84075ec9c"]}},"format.js":{"size":5565,"offset":"1413362","integrity":{"algorithm":"SHA256","hash":"652a1fb810cb4cb7b19907e58da3433336197f7c8b28db458fce75b473cd51cb","blockSize":4194304,"blocks":["652a1fb810cb4cb7b19907e58da3433336197f7c8b28db458fce75b473cd51cb"]}},"if.js":{"size":4159,"offset":"1418927","integrity":{"algorithm":"SHA256","hash":"2479d874860ae5857974d20c0d5908532c435327a70bdd982f2a747ac129eecc","blockSize":4194304,"blocks":["2479d874860ae5857974d20c0d5908532c435327a70bdd982f2a747ac129eecc"]}},"index.js":{"size":1100,"offset":"1423086","integrity":{"algorithm":"SHA256","hash":"5370d6a29859f9eca7e989aabb4a377bc030af34a77960aff373478a30c26c1e","blockSize":4194304,"blocks":["5370d6a29859f9eca7e989aabb4a377bc030af34a77960aff373478a30c26c1e"]}},"items.js":{"size":6214,"offset":"1424186","integrity":{"algorithm":"SHA256","hash":"5abe003d9fe397ac60140c8bda4890ac0ba6059e8d29876699fefc7e052dbd13","blockSize":4194304,"blocks":["5abe003d9fe397ac60140c8bda4890ac0ba6059e8d29876699fefc7e052dbd13"]}},"multipleOf.js":{"size":2807,"offset":"1430400","integrity":{"algorithm":"SHA256","hash":"a7331e809a6c3f968f2b8aa507ad6a6cca91eeff693e141620b8b9170a83bf4f","blockSize":4194304,"blocks":["a7331e809a6c3f968f2b8aa507ad6a6cca91eeff693e141620b8b9170a83bf4f"]}},"not.js":{"size":3460,"offset":"1433207","integrity":{"algorithm":"SHA256","hash":"6685973fcbc5a8c4271ab1c59a11a80a599c8cc919e78c3f3c899b74adcee63b","blockSize":4194304,"blocks":["6685973fcbc5a8c4271ab1c59a11a80a599c8cc919e78c3f3c899b74adcee63b"]}},"oneOf.js":{"size":3188,"offset":"1436667","integrity":{"algorithm":"SHA256","hash":"ef2d63612fdf85e16eb8af8fe9eed5151bddf394d821d6219c98aed822b23c6d","blockSize":4194304,"blocks":["ef2d63612fdf85e16eb8af8fe9eed5151bddf394d821d6219c98aed822b23c6d"]}},"pattern.js":{"size":3025,"offset":"1439855","integrity":{"algorithm":"SHA256","hash":"6bc3e0fb7bd34cba177e1e63909314fba393e7c6c92b494ad083a64406693611","blockSize":4194304,"blocks":["6bc3e0fb7bd34cba177e1e63909314fba393e7c6c92b494ad083a64406693611"]}},"properties.js":{"size":15121,"offset":"1442880","integrity":{"algorithm":"SHA256","hash":"deddeaac1178b03ed0ef4581f5e538e57be39acb4cacd3e297627e2ed724b8f3","blockSize":4194304,"blocks":["deddeaac1178b03ed0ef4581f5e538e57be39acb4cacd3e297627e2ed724b8f3"]}},"propertyNames.js":{"size":3607,"offset":"1458001","integrity":{"algorithm":"SHA256","hash":"55ff82517e1bf3823a43612541c75e6df74fb404beb934d8512708595f68813a","blockSize":4194304,"blocks":["55ff82517e1bf3823a43612541c75e6df74fb404beb934d8512708595f68813a"]}},"ref.js":{"size":4711,"offset":"1461608","integrity":{"algorithm":"SHA256","hash":"efdf5f24dd240a9aa6cd9cd757b82e7b7cb3d2d9c21730734516223fcb416021","blockSize":4194304,"blocks":["efdf5f24dd240a9aa6cd9cd757b82e7b7cb3d2d9c21730734516223fcb416021"]}},"required.js":{"size":12395,"offset":"1466319","integrity":{"algorithm":"SHA256","hash":"71411bc4c49c0a9bf1ee7e86758b400955015346801cbe3cec1d2e2ee0db94e0","blockSize":4194304,"blocks":["71411bc4c49c0a9bf1ee7e86758b400955015346801cbe3cec1d2e2ee0db94e0"]}},"uniqueItems.js":{"size":3694,"offset":"1478714","integrity":{"algorithm":"SHA256","hash":"5c5a4de99d43a2afc530ef356f97d9d64420dad276c7c2302763a122df4a48bd","blockSize":4194304,"blocks":["5c5a4de99d43a2afc530ef356f97d9d64420dad276c7c2302763a122df4a48bd"]}},"validate.js":{"size":20018,"offset":"1482408","integrity":{"algorithm":"SHA256","hash":"f0f8768cf0d5707a35b1524259483d146aa5f8ab55c8f0e43b06dc96e218576d","blockSize":4194304,"blocks":["f0f8768cf0d5707a35b1524259483d146aa5f8ab55c8f0e43b06dc96e218576d"]}}}},"keyword.js":{"size":3911,"offset":"1502426","integrity":{"algorithm":"SHA256","hash":"28b5706754b43356efd830465bb2b4b0f68e94cc56cb068020c7a96b2a432e3d","blockSize":4194304,"blocks":["28b5706754b43356efd830465bb2b4b0f68e94cc56cb068020c7a96b2a432e3d"]}},"refs":{"files":{"data.json":{"size":551,"offset":"1506337","integrity":{"algorithm":"SHA256","hash":"c99e189cc843d5c835a0b8d6059cd33d7330d31ae99d8d7c99d307e0b38bd1a8","blockSize":4194304,"blocks":["c99e189cc843d5c835a0b8d6059cd33d7330d31ae99d8d7c99d307e0b38bd1a8"]}},"json-schema-draft-04.json":{"size":4357,"offset":"1506888","integrity":{"algorithm":"SHA256","hash":"e1489d0b4755f02793302591d3fcb8f07b6893a82a94f24895f8e4edf11b82e2","blockSize":4194304,"blocks":["e1489d0b4755f02793302591d3fcb8f07b6893a82a94f24895f8e4edf11b82e2"]}},"json-schema-draft-06.json":{"size":4445,"offset":"1511245","integrity":{"algorithm":"SHA256","hash":"47a0be9bec080b114a30a83d99143610838369aadba28ab1e27e29f2bab96646","blockSize":4194304,"blocks":["47a0be9bec080b114a30a83d99143610838369aadba28ab1e27e29f2bab96646"]}},"json-schema-draft-07.json":{"size":4879,"offset":"1515690","integrity":{"algorithm":"SHA256","hash":"7f5fd717194bd954bbb04c833f6116f727d899c7bc977c26abcb2607aa51d66a","blockSize":4194304,"blocks":["7f5fd717194bd954bbb04c833f6116f727d899c7bc977c26abcb2607aa51d66a"]}},"json-schema-secure.json":{"size":2572,"offset":"1520569","integrity":{"algorithm":"SHA256","hash":"27a688d91d55baab0d04b84eddc76d6e325683643c62ab843f639344d5e218e1","blockSize":4194304,"blocks":["27a688d91d55baab0d04b84eddc76d6e325683643c62ab843f639344d5e218e1"]}}}}}},"package.json":{"size":3142,"offset":"1523141","integrity":{"algorithm":"SHA256","hash":"e49a32f08ddc384209169c76b30766d3e0764731a88cbaba92c5634875326f66","blockSize":4194304,"blocks":["e49a32f08ddc384209169c76b30766d3e0764731a88cbaba92c5634875326f66"]}},"scripts":{"files":{".eslintrc.yml":{"size":62,"offset":"1526283","integrity":{"algorithm":"SHA256","hash":"814c6f190dd9e82d2bd59ed462347d2368b5d1319176976c8e873ad5b941c0fd","blockSize":4194304,"blocks":["814c6f190dd9e82d2bd59ed462347d2368b5d1319176976c8e873ad5b941c0fd"]}},"bundle.js":{"size":1795,"offset":"1526345","integrity":{"algorithm":"SHA256","hash":"572324063ceb1b1a6c80658110863b0dfe75d7d801030f5fd1838c8519d29264","blockSize":4194304,"blocks":["572324063ceb1b1a6c80658110863b0dfe75d7d801030f5fd1838c8519d29264"]}},"compile-dots.js":{"size":2431,"offset":"1528140","integrity":{"algorithm":"SHA256","hash":"80618e4ac58cddc6a0c8989b3b29534ff1f32c279ba385332bdffdbe96380eb2","blockSize":4194304,"blocks":["80618e4ac58cddc6a0c8989b3b29534ff1f32c279ba385332bdffdbe96380eb2"]}},"info":{"size":289,"offset":"1530571","executable":true,"integrity":{"algorithm":"SHA256","hash":"ac6b35ca053000ddd18d728d182ca6d28fe557396ec2150f5cc7206f2564c182","blockSize":4194304,"blocks":["ac6b35ca053000ddd18d728d182ca6d28fe557396ec2150f5cc7206f2564c182"]}},"prepare-tests":{"size":269,"offset":"1530860","executable":true,"integrity":{"algorithm":"SHA256","hash":"e14b646f4624b96e46c8d61806d89cbe1cddab78c2429d3f71f2a6f1a1548c13","blockSize":4194304,"blocks":["e14b646f4624b96e46c8d61806d89cbe1cddab78c2429d3f71f2a6f1a1548c13"]}},"publish-built-version":{"size":842,"offset":"1531129","executable":true,"integrity":{"algorithm":"SHA256","hash":"b1db1ae1a4ed95c48fbee1e9bc3b5dfed1ed74d9075fcb6b20989a4cf66d33c1","blockSize":4194304,"blocks":["b1db1ae1a4ed95c48fbee1e9bc3b5dfed1ed74d9075fcb6b20989a4cf66d33c1"]}},"travis-gh-pages":{"size":874,"offset":"1531971","executable":true,"integrity":{"algorithm":"SHA256","hash":"a237607f9992de6e13a77c10a05557cd071425b7bdb6341578b0b83da3d07264","blockSize":4194304,"blocks":["a237607f9992de6e13a77c10a05557cd071425b7bdb6341578b0b83da3d07264"]}}}}}},"ajv-formats":{"files":{"LICENSE":{"size":1074,"offset":"342727","integrity":{"algorithm":"SHA256","hash":"9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf","blockSize":4194304,"blocks":["9df3bb69929a3b650ed73b3bfa1756725aaff0ac296461605753547004eafeaf"]}},"README.md":{"size":6052,"offset":"343801","integrity":{"algorithm":"SHA256","hash":"94a341854ce2561e7484f927c65d4da699be47097964e97cfb044d8516b856a8","blockSize":4194304,"blocks":["94a341854ce2561e7484f927c65d4da699be47097964e97cfb044d8516b856a8"]}},"dist":{"files":{"formats.js":{"size":10870,"offset":"349853","integrity":{"algorithm":"SHA256","hash":"0970043fe6605b30a696562ff8f1ff621eff5f1250f961a92668db8ad9d0cf8c","blockSize":4194304,"blocks":["0970043fe6605b30a696562ff8f1ff621eff5f1250f961a92668db8ad9d0cf8c"]}},"index.js":{"size":1498,"offset":"360723","integrity":{"algorithm":"SHA256","hash":"25ae29038da0fd1021a623de0db504f2eff2d2e1fed832f3a41b795833182dde","blockSize":4194304,"blocks":["25ae29038da0fd1021a623de0db504f2eff2d2e1fed832f3a41b795833182dde"]}},"limit.js":{"size":2850,"offset":"362221","integrity":{"algorithm":"SHA256","hash":"8ed43a480952d8aa1afa2da3c41450cadf9a39995be7c4e0e54cd75a9c373944","blockSize":4194304,"blocks":["8ed43a480952d8aa1afa2da3c41450cadf9a39995be7c4e0e54cd75a9c373944"]}}}},"node_modules":{"files":{"ajv":{"files":{".runkit_example.js":{"size":496,"offset":"365071","integrity":{"algorithm":"SHA256","hash":"e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf","blockSize":4194304,"blocks":["e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf"]}},"LICENSE":{"size":1090,"offset":"365567","integrity":{"algorithm":"SHA256","hash":"a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3","blockSize":4194304,"blocks":["a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]}},"README.md":{"size":13781,"offset":"366657","integrity":{"algorithm":"SHA256","hash":"57d9f5c9d12d019ee1c42fcd7be6a1c5b2944608b011714146ecdd20972374ed","blockSize":4194304,"blocks":["57d9f5c9d12d019ee1c42fcd7be6a1c5b2944608b011714146ecdd20972374ed"]}},"dist":{"files":{"2019.js":{"size":3188,"offset":"380438","integrity":{"algorithm":"SHA256","hash":"4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4","blockSize":4194304,"blocks":["4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4"]}},"2020.js":{"size":2894,"offset":"383626","integrity":{"algorithm":"SHA256","hash":"908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a","blockSize":4194304,"blocks":["908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a"]}},"ajv.js":{"size":2841,"offset":"386520","integrity":{"algorithm":"SHA256","hash":"edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297","blockSize":4194304,"blocks":["edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297"]}},"compile":{"files":{"codegen":{"files":{"code.js":{"size":4676,"offset":"389361","integrity":{"algorithm":"SHA256","hash":"1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d","blockSize":4194304,"blocks":["1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d"]}},"index.js":{"size":23127,"offset":"394037","integrity":{"algorithm":"SHA256","hash":"f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c","blockSize":4194304,"blocks":["f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c"]}},"scope.js":{"size":5198,"offset":"417164","integrity":{"algorithm":"SHA256","hash":"d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286","blockSize":4194304,"blocks":["d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286"]}}}},"errors.js":{"size":5771,"offset":"422362","integrity":{"algorithm":"SHA256","hash":"53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2","blockSize":4194304,"blocks":["53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2"]}},"index.js":{"size":10046,"offset":"428133","integrity":{"algorithm":"SHA256","hash":"05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac","blockSize":4194304,"blocks":["05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac"]}},"jtd":{"files":{"parse.js":{"size":13727,"offset":"438179","integrity":{"algorithm":"SHA256","hash":"548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f","blockSize":4194304,"blocks":["548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f"]}},"serialize.js":{"size":9391,"offset":"451906","integrity":{"algorithm":"SHA256","hash":"1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0","blockSize":4194304,"blocks":["1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0"]}},"types.js":{"size":291,"offset":"461297","integrity":{"algorithm":"SHA256","hash":"e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78","blockSize":4194304,"blocks":["e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78"]}}}},"names.js":{"size":1440,"offset":"461588","integrity":{"algorithm":"SHA256","hash":"3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493","blockSize":4194304,"blocks":["3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493"]}},"ref_error.js":{"size":543,"offset":"463028","integrity":{"algorithm":"SHA256","hash":"81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7","blockSize":4194304,"blocks":["81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7"]}},"resolve.js":{"size":5006,"offset":"463571","integrity":{"algorithm":"SHA256","hash":"df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9","blockSize":4194304,"blocks":["df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9"]}},"rules.js":{"size":918,"offset":"468577","integrity":{"algorithm":"SHA256","hash":"ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9","blockSize":4194304,"blocks":["ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9"]}},"util.js":{"size":7103,"offset":"469495","integrity":{"algorithm":"SHA256","hash":"fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5","blockSize":4194304,"blocks":["fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5"]}},"validate":{"files":{"applicability.js":{"size":853,"offset":"476598","integrity":{"algorithm":"SHA256","hash":"50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0","blockSize":4194304,"blocks":["50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0"]}},"boolSchema.js":{"size":1531,"offset":"477451","integrity":{"algorithm":"SHA256","hash":"c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f","blockSize":4194304,"blocks":["c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f"]}},"dataType.js":{"size":8409,"offset":"478982","integrity":{"algorithm":"SHA256","hash":"697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52","blockSize":4194304,"blocks":["697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52"]}},"defaults.js":{"size":1448,"offset":"487391","integrity":{"algorithm":"SHA256","hash":"05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428","blockSize":4194304,"blocks":["05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428"]}},"index.js":{"size":20552,"offset":"488839","integrity":{"algorithm":"SHA256","hash":"cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd","blockSize":4194304,"blocks":["cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd"]}},"keyword.js":{"size":5695,"offset":"509391","integrity":{"algorithm":"SHA256","hash":"ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76","blockSize":4194304,"blocks":["ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76"]}},"subschema.js":{"size":3858,"offset":"515086","integrity":{"algorithm":"SHA256","hash":"ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc","blockSize":4194304,"blocks":["ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc"]}}}}}},"core.js":{"size":25185,"offset":"518944","integrity":{"algorithm":"SHA256","hash":"7fdd03e949ecb3d020e560f669da71ce69a70f4bca28e5aff2ebc34d15bc2134","blockSize":4194304,"blocks":["7fdd03e949ecb3d020e560f669da71ce69a70f4bca28e5aff2ebc34d15bc2134"]}},"jtd.js":{"size":3360,"offset":"544129","integrity":{"algorithm":"SHA256","hash":"9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44","blockSize":4194304,"blocks":["9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44"]}},"refs":{"files":{"data.json":{"size":409,"offset":"547489","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"index.js":{"size":938,"offset":"547898","integrity":{"algorithm":"SHA256","hash":"ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d","blockSize":4194304,"blocks":["ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d"]}},"meta":{"files":{"applicator.json":{"size":1566,"offset":"548836","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"550402","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"550879","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"552152","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"552527","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"553285","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"555549","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"index.js":{"size":1026,"offset":"557128","integrity":{"algorithm":"SHA256","hash":"2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1","blockSize":4194304,"blocks":["2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1"]}},"meta":{"files":{"applicator.json":{"size":1441,"offset":"558154","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"559595","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"560074","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"561418","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"561838","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"562596","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"563068","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"565332","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"567498","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"570947","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"574758","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}},"jtd-schema.js":{"size":2882,"offset":"577279","integrity":{"algorithm":"SHA256","hash":"ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92","blockSize":4194304,"blocks":["ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92"]}}}},"runtime":{"files":{"equal.js":{"size":286,"offset":"580161","integrity":{"algorithm":"SHA256","hash":"c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274","blockSize":4194304,"blocks":["c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274"]}},"parseJson.js":{"size":5401,"offset":"580447","integrity":{"algorithm":"SHA256","hash":"1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e","blockSize":4194304,"blocks":["1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e"]}},"quote.js":{"size":943,"offset":"585848","integrity":{"algorithm":"SHA256","hash":"1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2","blockSize":4194304,"blocks":["1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2"]}},"re2.js":{"size":213,"offset":"586791","integrity":{"algorithm":"SHA256","hash":"e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361","blockSize":4194304,"blocks":["e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361"]}},"timestamp.js":{"size":1536,"offset":"587004","integrity":{"algorithm":"SHA256","hash":"05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef","blockSize":4194304,"blocks":["05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef"]}},"ucs2length.js":{"size":808,"offset":"588540","integrity":{"algorithm":"SHA256","hash":"1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890","blockSize":4194304,"blocks":["1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890"]}},"uri.js":{"size":218,"offset":"589348","integrity":{"algorithm":"SHA256","hash":"d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578","blockSize":4194304,"blocks":["d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578"]}},"validation_error.js":{"size":337,"offset":"589566","integrity":{"algorithm":"SHA256","hash":"11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815","blockSize":4194304,"blocks":["11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815"]}}}},"standalone":{"files":{"index.js":{"size":4480,"offset":"589903","integrity":{"algorithm":"SHA256","hash":"361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f","blockSize":4194304,"blocks":["361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f"]}},"instance.js":{"size":1015,"offset":"594383","integrity":{"algorithm":"SHA256","hash":"4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3","blockSize":4194304,"blocks":["4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3"]}}}},"types":{"files":{"index.js":{"size":110,"offset":"595398","integrity":{"algorithm":"SHA256","hash":"fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71","blockSize":4194304,"blocks":["fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71"]}},"json-schema.js":{"size":116,"offset":"595508","integrity":{"algorithm":"SHA256","hash":"2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28","blockSize":4194304,"blocks":["2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28"]}},"jtd-schema.js":{"size":115,"offset":"595624","integrity":{"algorithm":"SHA256","hash":"6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d","blockSize":4194304,"blocks":["6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d"]}}}},"vocabularies":{"files":{"applicator":{"files":{"additionalItems.js":{"size":1931,"offset":"595739","integrity":{"algorithm":"SHA256","hash":"7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099","blockSize":4194304,"blocks":["7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099"]}},"additionalProperties.js":{"size":4309,"offset":"597670","integrity":{"algorithm":"SHA256","hash":"e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a","blockSize":4194304,"blocks":["e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a"]}},"allOf.js":{"size":756,"offset":"601979","integrity":{"algorithm":"SHA256","hash":"98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7","blockSize":4194304,"blocks":["98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7"]}},"anyOf.js":{"size":343,"offset":"602735","integrity":{"algorithm":"SHA256","hash":"8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5","blockSize":4194304,"blocks":["8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5"]}},"contains.js":{"size":3680,"offset":"603078","integrity":{"algorithm":"SHA256","hash":"56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c","blockSize":4194304,"blocks":["56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c"]}},"dependencies.js":{"size":3198,"offset":"606758","integrity":{"algorithm":"SHA256","hash":"c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b","blockSize":4194304,"blocks":["c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b"]}},"dependentSchemas.js":{"size":354,"offset":"609956","integrity":{"algorithm":"SHA256","hash":"d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e","blockSize":4194304,"blocks":["d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e"]}},"if.js":{"size":2438,"offset":"610310","integrity":{"algorithm":"SHA256","hash":"42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4","blockSize":4194304,"blocks":["42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4"]}},"index.js":{"size":1529,"offset":"612748","integrity":{"algorithm":"SHA256","hash":"5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3","blockSize":4194304,"blocks":["5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3"]}},"items.js":{"size":1993,"offset":"614277","integrity":{"algorithm":"SHA256","hash":"fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e","blockSize":4194304,"blocks":["fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e"]}},"items2020.js":{"size":1037,"offset":"616270","integrity":{"algorithm":"SHA256","hash":"c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f","blockSize":4194304,"blocks":["c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f"]}},"not.js":{"size":773,"offset":"617307","integrity":{"algorithm":"SHA256","hash":"ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718","blockSize":4194304,"blocks":["ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718"]}},"oneOf.js":{"size":2257,"offset":"618080","integrity":{"algorithm":"SHA256","hash":"e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2","blockSize":4194304,"blocks":["e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2"]}},"patternProperties.js":{"size":3236,"offset":"620337","integrity":{"algorithm":"SHA256","hash":"0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655","blockSize":4194304,"blocks":["0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655"]}},"prefixItems.js":{"size":354,"offset":"623573","integrity":{"algorithm":"SHA256","hash":"16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23","blockSize":4194304,"blocks":["16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23"]}},"properties.js":{"size":2153,"offset":"623927","integrity":{"algorithm":"SHA256","hash":"c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f","blockSize":4194304,"blocks":["c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f"]}},"propertyNames.js":{"size":1221,"offset":"626080","integrity":{"algorithm":"SHA256","hash":"b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7","blockSize":4194304,"blocks":["b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7"]}},"thenElse.js":{"size":446,"offset":"627301","integrity":{"algorithm":"SHA256","hash":"9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d","blockSize":4194304,"blocks":["9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d"]}}}},"code.js":{"size":6216,"offset":"627747","integrity":{"algorithm":"SHA256","hash":"9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63","blockSize":4194304,"blocks":["9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63"]}},"core":{"files":{"id.js":{"size":267,"offset":"633963","integrity":{"algorithm":"SHA256","hash":"49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11","blockSize":4194304,"blocks":["49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11"]}},"index.js":{"size":357,"offset":"634230","integrity":{"algorithm":"SHA256","hash":"f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e","blockSize":4194304,"blocks":["f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e"]}},"ref.js":{"size":5234,"offset":"634587","integrity":{"algorithm":"SHA256","hash":"1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1","blockSize":4194304,"blocks":["1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1"]}}}},"discriminator":{"files":{"index.js":{"size":4845,"offset":"639821","integrity":{"algorithm":"SHA256","hash":"b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e","blockSize":4194304,"blocks":["b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e"]}},"types.js":{"size":308,"offset":"644666","integrity":{"algorithm":"SHA256","hash":"2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa","blockSize":4194304,"blocks":["2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa"]}}}},"draft2020.js":{"size":762,"offset":"644974","integrity":{"algorithm":"SHA256","hash":"2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445","blockSize":4194304,"blocks":["2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445"]}},"draft7.js":{"size":557,"offset":"645736","integrity":{"algorithm":"SHA256","hash":"8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170","blockSize":4194304,"blocks":["8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170"]}},"dynamic":{"files":{"dynamicAnchor.js":{"size":1261,"offset":"646293","integrity":{"algorithm":"SHA256","hash":"78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7","blockSize":4194304,"blocks":["78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7"]}},"dynamicRef.js":{"size":1985,"offset":"647554","integrity":{"algorithm":"SHA256","hash":"acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917","blockSize":4194304,"blocks":["acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917"]}},"index.js":{"size":457,"offset":"649539","integrity":{"algorithm":"SHA256","hash":"8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b","blockSize":4194304,"blocks":["8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b"]}},"recursiveAnchor.js":{"size":522,"offset":"649996","integrity":{"algorithm":"SHA256","hash":"9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76","blockSize":4194304,"blocks":["9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76"]}},"recursiveRef.js":{"size":325,"offset":"650518","integrity":{"algorithm":"SHA256","hash":"7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d","blockSize":4194304,"blocks":["7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d"]}}}},"errors.js":{"size":111,"offset":"650843","integrity":{"algorithm":"SHA256","hash":"7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc","blockSize":4194304,"blocks":["7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc"]}},"format":{"files":{"format.js":{"size":4317,"offset":"650954","integrity":{"algorithm":"SHA256","hash":"6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f","blockSize":4194304,"blocks":["6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f"]}},"index.js":{"size":209,"offset":"655271","integrity":{"algorithm":"SHA256","hash":"d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67","blockSize":4194304,"blocks":["d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67"]}}}},"jtd":{"files":{"discriminator.js":{"size":2785,"offset":"655480","integrity":{"algorithm":"SHA256","hash":"14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2","blockSize":4194304,"blocks":["14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2"]}},"elements.js":{"size":949,"offset":"658265","integrity":{"algorithm":"SHA256","hash":"b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b","blockSize":4194304,"blocks":["b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b"]}},"enum.js":{"size":1745,"offset":"659214","integrity":{"algorithm":"SHA256","hash":"4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154","blockSize":4194304,"blocks":["4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154"]}},"error.js":{"size":893,"offset":"660959","integrity":{"algorithm":"SHA256","hash":"d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9","blockSize":4194304,"blocks":["d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9"]}},"index.js":{"size":962,"offset":"661852","integrity":{"algorithm":"SHA256","hash":"c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d","blockSize":4194304,"blocks":["c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d"]}},"metadata.js":{"size":810,"offset":"662814","integrity":{"algorithm":"SHA256","hash":"237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68","blockSize":4194304,"blocks":["237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68"]}},"nullable.js":{"size":859,"offset":"663624","integrity":{"algorithm":"SHA256","hash":"ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a","blockSize":4194304,"blocks":["ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a"]}},"optionalProperties.js":{"size":436,"offset":"664483","integrity":{"algorithm":"SHA256","hash":"82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62","blockSize":4194304,"blocks":["82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62"]}},"properties.js":{"size":6320,"offset":"664919","integrity":{"algorithm":"SHA256","hash":"4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35","blockSize":4194304,"blocks":["4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35"]}},"ref.js":{"size":2648,"offset":"671239","integrity":{"algorithm":"SHA256","hash":"4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460","blockSize":4194304,"blocks":["4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460"]}},"type.js":{"size":2706,"offset":"673887","integrity":{"algorithm":"SHA256","hash":"f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c","blockSize":4194304,"blocks":["f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c"]}},"union.js":{"size":343,"offset":"676593","integrity":{"algorithm":"SHA256","hash":"f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280","blockSize":4194304,"blocks":["f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280"]}},"values.js":{"size":1838,"offset":"676936","integrity":{"algorithm":"SHA256","hash":"6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2","blockSize":4194304,"blocks":["6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2"]}}}},"metadata.js":{"size":427,"offset":"678774","integrity":{"algorithm":"SHA256","hash":"45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609","blockSize":4194304,"blocks":["45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609"]}},"next.js":{"size":433,"offset":"679201","integrity":{"algorithm":"SHA256","hash":"491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7","blockSize":4194304,"blocks":["491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7"]}},"unevaluated":{"files":{"index.js":{"size":350,"offset":"679634","integrity":{"algorithm":"SHA256","hash":"4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4","blockSize":4194304,"blocks":["4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4"]}},"unevaluatedItems.js":{"size":1588,"offset":"679984","integrity":{"algorithm":"SHA256","hash":"4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda","blockSize":4194304,"blocks":["4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda"]}},"unevaluatedProperties.js":{"size":2608,"offset":"681572","integrity":{"algorithm":"SHA256","hash":"665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe","blockSize":4194304,"blocks":["665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe"]}}}},"validation":{"files":{"const.js":{"size":852,"offset":"684180","integrity":{"algorithm":"SHA256","hash":"ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a","blockSize":4194304,"blocks":["ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a"]}},"dependentRequired.js":{"size":403,"offset":"685032","integrity":{"algorithm":"SHA256","hash":"cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa","blockSize":4194304,"blocks":["cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa"]}},"enum.js":{"size":1901,"offset":"685435","integrity":{"algorithm":"SHA256","hash":"61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22","blockSize":4194304,"blocks":["61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22"]}},"index.js":{"size":1036,"offset":"687336","integrity":{"algorithm":"SHA256","hash":"4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4","blockSize":4194304,"blocks":["4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4"]}},"limitContains.js":{"size":495,"offset":"688372","integrity":{"algorithm":"SHA256","hash":"0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d","blockSize":4194304,"blocks":["0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d"]}},"limitItems.js":{"size":852,"offset":"688867","integrity":{"algorithm":"SHA256","hash":"49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec","blockSize":4194304,"blocks":["49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec"]}},"limitLength.js":{"size":1130,"offset":"689719","integrity":{"algorithm":"SHA256","hash":"379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2","blockSize":4194304,"blocks":["379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2"]}},"limitNumber.js":{"size":1036,"offset":"690849","integrity":{"algorithm":"SHA256","hash":"3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65","blockSize":4194304,"blocks":["3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65"]}},"limitProperties.js":{"size":896,"offset":"691885","integrity":{"algorithm":"SHA256","hash":"8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac","blockSize":4194304,"blocks":["8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac"]}},"multipleOf.js":{"size":1023,"offset":"692781","integrity":{"algorithm":"SHA256","hash":"df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd","blockSize":4194304,"blocks":["df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd"]}},"pattern.js":{"size":1323,"offset":"693804","integrity":{"algorithm":"SHA256","hash":"86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195","blockSize":4194304,"blocks":["86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195"]}},"required.js":{"size":3188,"offset":"695127","integrity":{"algorithm":"SHA256","hash":"b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054","blockSize":4194304,"blocks":["b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054"]}},"uniqueItems.js":{"size":3037,"offset":"698315","integrity":{"algorithm":"SHA256","hash":"666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52","blockSize":4194304,"blocks":["666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52"]}}}}}}}},"lib":{"files":{"compile":{"files":{"codegen":{"files":{}},"jtd":{"files":{}},"validate":{"files":{}}}},"refs":{"files":{"data.json":{"size":409,"offset":"701352","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"meta":{"files":{"applicator.json":{"size":1566,"offset":"701761","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"703327","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"703804","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"705077","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"705452","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"706210","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"708474","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"meta":{"files":{"applicator.json":{"size":1441,"offset":"710053","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"711494","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"711973","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"713317","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"713737","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"714495","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"714967","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"717231","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"719397","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"722846","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"726657","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}}}},"runtime":{"files":{}},"standalone":{"files":{}},"types":{"files":{}},"vocabularies":{"files":{"applicator":{"files":{}},"core":{"files":{}},"discriminator":{"files":{}},"dynamic":{"files":{}},"format":{"files":{}},"jtd":{"files":{}},"unevaluated":{"files":{}},"validation":{"files":{}}}}}},"package.json":{"size":4481,"offset":"729178","integrity":{"algorithm":"SHA256","hash":"720f862de3e496df05e074c33df5174db92c47e60726e41ab1338cfefda9754c","blockSize":4194304,"blocks":["720f862de3e496df05e074c33df5174db92c47e60726e41ab1338cfefda9754c"]}}}},"json-schema-traverse":{"files":{".eslintrc.yml":{"size":630,"offset":"733659","integrity":{"algorithm":"SHA256","hash":"b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc","blockSize":4194304,"blocks":["b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc"]}},".github":{"files":{"FUNDING.yml":{"size":57,"offset":"734289","integrity":{"algorithm":"SHA256","hash":"83e77adf3dbe6261917b160553f75cbb96de8e99c3259f4f1de85e1c6e4bd156","blockSize":4194304,"blocks":["83e77adf3dbe6261917b160553f75cbb96de8e99c3259f4f1de85e1c6e4bd156"]}},"workflows":{"files":{"build.yml":{"size":582,"offset":"734346","integrity":{"algorithm":"SHA256","hash":"f0f23bb3b380800e214b19abfd69c1b093131bb030c056fabdd9cddec7e785c5","blockSize":4194304,"blocks":["f0f23bb3b380800e214b19abfd69c1b093131bb030c056fabdd9cddec7e785c5"]}},"publish.yml":{"size":678,"offset":"734928","integrity":{"algorithm":"SHA256","hash":"56cbec53748d486f04b5c37bec8ea5e5588e02fb2882db8ce36c6e9689bfd2fc","blockSize":4194304,"blocks":["56cbec53748d486f04b5c37bec8ea5e5588e02fb2882db8ce36c6e9689bfd2fc"]}}}}}},"LICENSE":{"size":1074,"offset":"735606","integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]}},"README.md":{"size":3350,"offset":"736680","integrity":{"algorithm":"SHA256","hash":"e6137660d373bc510f4d41789d7fea74e0ed9f94c99d4892dee22292ac2a39a7","blockSize":4194304,"blocks":["e6137660d373bc510f4d41789d7fea74e0ed9f94c99d4892dee22292ac2a39a7"]}},"index.js":{"size":2428,"offset":"740030","integrity":{"algorithm":"SHA256","hash":"024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350","blockSize":4194304,"blocks":["024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350"]}},"package.json":{"size":1004,"offset":"742458","integrity":{"algorithm":"SHA256","hash":"156fb24af02845c190701360d06dfda35ef04282e34a734289ea9535ad9819ae","blockSize":4194304,"blocks":["156fb24af02845c190701360d06dfda35ef04282e34a734289ea9535ad9819ae"]}},"spec":{"files":{".eslintrc.yml":{"size":91,"offset":"743462","integrity":{"algorithm":"SHA256","hash":"8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c","blockSize":4194304,"blocks":["8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c"]}},"fixtures":{"files":{"schema.js":{"size":5544,"offset":"743553","integrity":{"algorithm":"SHA256","hash":"0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27","blockSize":4194304,"blocks":["0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27"]}}}},"index.spec.js":{"size":6042,"offset":"749097","integrity":{"algorithm":"SHA256","hash":"40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69","blockSize":4194304,"blocks":["40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69"]}}}}}}}},"package.json":{"size":1897,"offset":"755139","integrity":{"algorithm":"SHA256","hash":"dab973bf13d8248fc5f6b2b0b7b3e87fd1dc92a71abdc559fbcbb5c29ed48e63","blockSize":4194304,"blocks":["dab973bf13d8248fc5f6b2b0b7b3e87fd1dc92a71abdc559fbcbb5c29ed48e63"]}},"src":{"files":{}}}},"atomically":{"files":{".editorconfig":{"size":189,"offset":"1532845","integrity":{"algorithm":"SHA256","hash":"42a82ef9e641f12b19ae3919e6fe8ef14f9c4c3b4185df730a82d04300b4620e","blockSize":4194304,"blocks":["42a82ef9e641f12b19ae3919e6fe8ef14f9c4c3b4185df730a82d04300b4620e"]}},".nvmrc":{"size":9,"offset":"1533034","integrity":{"algorithm":"SHA256","hash":"890a9ba685b9cb0ecf37267be4c5b5f76a404598d26897d9b0ab9b95c3fc308b","blockSize":4194304,"blocks":["890a9ba685b9cb0ecf37267be4c5b5f76a404598d26897d9b0ab9b95c3fc308b"]}},"LICENSE":{"size":1091,"offset":"1533043","integrity":{"algorithm":"SHA256","hash":"716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500","blockSize":4194304,"blocks":["716bd9213ef82d9017ed813688703837aaa99fc56de205a7b97475d40056a500"]}},"README.md":{"size":8539,"offset":"1534134","integrity":{"algorithm":"SHA256","hash":"8908888894cb0abf6589618019f38ce8196e2399030c73a772fe60f31441af91","blockSize":4194304,"blocks":["8908888894cb0abf6589618019f38ce8196e2399030c73a772fe60f31441af91"]}},"dist":{"files":{"consts.js":{"size":1572,"offset":"1542673","integrity":{"algorithm":"SHA256","hash":"feb31cc92d3c258df9008e9584d74362e661cac42ad6abb4cc305ff2d7432337","blockSize":4194304,"blocks":["feb31cc92d3c258df9008e9584d74362e661cac42ad6abb4cc305ff2d7432337"]}},"index.js":{"size":7780,"offset":"1544245","integrity":{"algorithm":"SHA256","hash":"95c30ea2977ce45e25f8b42ae64b58f8c90543cbd9763c828f6170e554ff680a","blockSize":4194304,"blocks":["95c30ea2977ce45e25f8b42ae64b58f8c90543cbd9763c828f6170e554ff680a"]}},"types.js":{"size":89,"offset":"1552025","integrity":{"algorithm":"SHA256","hash":"b4435decae0d0ea87851e7cdd3139043de0246a78302b6f355e5b059b50e6553","blockSize":4194304,"blocks":["b4435decae0d0ea87851e7cdd3139043de0246a78302b6f355e5b059b50e6553"]}},"utils":{"files":{"attemptify.js":{"size":788,"offset":"1552114","integrity":{"algorithm":"SHA256","hash":"f570e6c261b2c413992073e48023163b21afb5f4cf1ad7ee2d230566595ddf82","blockSize":4194304,"blocks":["f570e6c261b2c413992073e48023163b21afb5f4cf1ad7ee2d230566595ddf82"]}},"fs.js":{"size":3037,"offset":"1552902","integrity":{"algorithm":"SHA256","hash":"b15a3ea242de95a06402dd37172412553e481c67f7cd9bbaf4f8a3edeaca52e6","blockSize":4194304,"blocks":["b15a3ea242de95a06402dd37172412553e481c67f7cd9bbaf4f8a3edeaca52e6"]}},"fs_handlers.js":{"size":865,"offset":"1555939","integrity":{"algorithm":"SHA256","hash":"b7cb366f755bb3297cf90797a6b0db7a1c7c0e23f2350eb09cffb16eecab16d9","blockSize":4194304,"blocks":["b7cb366f755bb3297cf90797a6b0db7a1c7c0e23f2350eb09cffb16eecab16d9"]}},"lang.js":{"size":356,"offset":"1556804","integrity":{"algorithm":"SHA256","hash":"e84c44f703058eca395c41920501b3c450de15d687e1b509716fcda3e029d822","blockSize":4194304,"blocks":["e84c44f703058eca395c41920501b3c450de15d687e1b509716fcda3e029d822"]}},"retryify.js":{"size":1653,"offset":"1557160","integrity":{"algorithm":"SHA256","hash":"2bd96d6f5af98a990f6774f28a943a2126d98df3bd66e25eb5bc546ac12b7338","blockSize":4194304,"blocks":["2bd96d6f5af98a990f6774f28a943a2126d98df3bd66e25eb5bc546ac12b7338"]}},"retryify_queue.js":{"size":1836,"offset":"1558813","integrity":{"algorithm":"SHA256","hash":"9b6e5ad524ac9f29d9fab8fe740b660caebf54f0da7554541c8edb4c74710951","blockSize":4194304,"blocks":["9b6e5ad524ac9f29d9fab8fe740b660caebf54f0da7554541c8edb4c74710951"]}},"scheduler.js":{"size":860,"offset":"1560649","integrity":{"algorithm":"SHA256","hash":"f32626546190ecb8dd54cdf66ccf6a82f17b23efb8d287ed656e189086b34de6","blockSize":4194304,"blocks":["f32626546190ecb8dd54cdf66ccf6a82f17b23efb8d287ed656e189086b34de6"]}},"temp.js":{"size":2458,"offset":"1561509","integrity":{"algorithm":"SHA256","hash":"f4dad31de0b8d678dacbf7b6ee0f182575dc6555871a42a3a73506f9c37090b5","blockSize":4194304,"blocks":["f4dad31de0b8d678dacbf7b6ee0f182575dc6555871a42a3a73506f9c37090b5"]}}}}}},"package.json":{"size":1322,"offset":"1563967","executable":true,"integrity":{"algorithm":"SHA256","hash":"6b62f6dae967b0926c57559b4bab73016d22427413edc992f31a1420d92d10e5","blockSize":4194304,"blocks":["6b62f6dae967b0926c57559b4bab73016d22427413edc992f31a1420d92d10e5"]}},"src":{"files":{"utils":{"files":{}}}},"tasks":{"files":{"benchmark.js":{"size":2747,"offset":"1565289","integrity":{"algorithm":"SHA256","hash":"988ecbd8462edfc5867759fc55613c0d90462d43b54078b13124b0301be040ce","blockSize":4194304,"blocks":["988ecbd8462edfc5867759fc55613c0d90462d43b54078b13124b0301be040ce"]}}}},"test":{"files":{"basic.js":{"size":18318,"offset":"1568036","executable":true,"integrity":{"algorithm":"SHA256","hash":"e231cd79b5b915fb40aa3b2e025dbd038e20c2ade38befb424fc2b8185ada815","blockSize":4194304,"blocks":["e231cd79b5b915fb40aa3b2e025dbd038e20c2ade38befb424fc2b8185ada815"]}},"concurrency.js":{"size":4429,"offset":"1586354","executable":true,"integrity":{"algorithm":"SHA256","hash":"c7f21b4bf4b888e09667ba57acb1cf2a479063f8f333ab1cd1b203f0c40d52db","blockSize":4194304,"blocks":["c7f21b4bf4b888e09667ba57acb1cf2a479063f8f333ab1cd1b203f0c40d52db"]}},"integration.js":{"size":8145,"offset":"1590783","executable":true,"integrity":{"algorithm":"SHA256","hash":"007711314b99ee02bae3c8b0aef3205e1dbf7535fa0c60bbc64e73b7362f878a","blockSize":4194304,"blocks":["007711314b99ee02bae3c8b0aef3205e1dbf7535fa0c60bbc64e73b7362f878a"]}}}},"tsconfig.json":{"size":687,"offset":"1598928","executable":true,"integrity":{"algorithm":"SHA256","hash":"be665bb12b0c8433412ccc07afdcffbb5cd4b5770a028ff39067cb177c4f85d0","blockSize":4194304,"blocks":["be665bb12b0c8433412ccc07afdcffbb5cd4b5770a028ff39067cb177c4f85d0"]}}}},"conf":{"files":{"dist":{"files":{"source":{"files":{"index.js":{"size":20779,"offset":"1599615","integrity":{"algorithm":"SHA256","hash":"bb9f43d6800ae8a54239dffdb4d8bf9532a3620454d2195762e91daf4303e586","blockSize":4194304,"blocks":["bb9f43d6800ae8a54239dffdb4d8bf9532a3620454d2195762e91daf4303e586"]}},"types.js":{"size":77,"offset":"1620394","integrity":{"algorithm":"SHA256","hash":"d43aa81f5bc89faa359e0f97c814ba25155591ff078fbb9bfd40f8c7c9683230","blockSize":4194304,"blocks":["d43aa81f5bc89faa359e0f97c814ba25155591ff078fbb9bfd40f8c7c9683230"]}}}}}},"license":{"size":1117,"offset":"1620471","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"node_modules":{"files":{".bin":{"files":{"semver":{"link":"node_modules/conf/node_modules/.bin/workspace/bigjakk/Krunker-Civilian-Client-Test/node_modules/conf/node_modules/semver/bin/semver.js"}}},"ajv":{"files":{".runkit_example.js":{"size":496,"offset":"1621588","integrity":{"algorithm":"SHA256","hash":"e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf","blockSize":4194304,"blocks":["e37e85bf1db5d53a6e4e38a9cac83db25208f28c09a2fa19e3971877c8a7b8cf"]}},"LICENSE":{"size":1090,"offset":"1622084","integrity":{"algorithm":"SHA256","hash":"a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3","blockSize":4194304,"blocks":["a05350a88e318e4f5f2c2a1ff1e2e88daa4dd38e6e78b71cccae422bdc762cc3"]}},"README.md":{"size":13781,"offset":"1623174","integrity":{"algorithm":"SHA256","hash":"57d9f5c9d12d019ee1c42fcd7be6a1c5b2944608b011714146ecdd20972374ed","blockSize":4194304,"blocks":["57d9f5c9d12d019ee1c42fcd7be6a1c5b2944608b011714146ecdd20972374ed"]}},"dist":{"files":{"2019.js":{"size":3188,"offset":"1636955","integrity":{"algorithm":"SHA256","hash":"4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4","blockSize":4194304,"blocks":["4a1b1d479d0b946af0119f3a3960fcabfd964e1c20e87f7a9575f8f9e705d0c4"]}},"2020.js":{"size":2894,"offset":"1640143","integrity":{"algorithm":"SHA256","hash":"908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a","blockSize":4194304,"blocks":["908e9670b478b2ba126802a221b7e47006f50cf467e2c5dd7935d3dbef10a20a"]}},"ajv.js":{"size":2841,"offset":"1643037","integrity":{"algorithm":"SHA256","hash":"edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297","blockSize":4194304,"blocks":["edaed56fc546f5551b0d6dc2ff2a9cc25c2d6c83318a086eaa8c3ad0b2479297"]}},"compile":{"files":{"codegen":{"files":{"code.js":{"size":4676,"offset":"1645878","integrity":{"algorithm":"SHA256","hash":"1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d","blockSize":4194304,"blocks":["1287153722f1fc3c5342647de7ae1d7b6fb68bdb3378a0776a937d273fc97e0d"]}},"index.js":{"size":23127,"offset":"1650554","integrity":{"algorithm":"SHA256","hash":"f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c","blockSize":4194304,"blocks":["f03b2b72597ef86878d1d4030580c2d0964046efad4867f3d05aa91065ba034c"]}},"scope.js":{"size":5198,"offset":"1673681","integrity":{"algorithm":"SHA256","hash":"d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286","blockSize":4194304,"blocks":["d2a0a97af2faa2cad88702314fe421e235ab17f11e0d62883d58d8d4dc734286"]}}}},"errors.js":{"size":5771,"offset":"1678879","integrity":{"algorithm":"SHA256","hash":"53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2","blockSize":4194304,"blocks":["53990f8f2cc05922bba410ae68231d3f869de4f8343277ede5b4834fa564c6c2"]}},"index.js":{"size":10046,"offset":"1684650","integrity":{"algorithm":"SHA256","hash":"05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac","blockSize":4194304,"blocks":["05b34da22814f3787bfa3ac68dad59c9047f56e55a607e0a20719ebf5afe69ac"]}},"jtd":{"files":{"parse.js":{"size":13727,"offset":"1694696","integrity":{"algorithm":"SHA256","hash":"548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f","blockSize":4194304,"blocks":["548b7e6ee5558360945f261e092cd328662868995877140ed2ae7ff981300b7f"]}},"serialize.js":{"size":9391,"offset":"1708423","integrity":{"algorithm":"SHA256","hash":"1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0","blockSize":4194304,"blocks":["1f8b1873fbd899240cd625144d3cd10630b3cf1b0c69c640566f6e25c80765c0"]}},"types.js":{"size":291,"offset":"1717814","integrity":{"algorithm":"SHA256","hash":"e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78","blockSize":4194304,"blocks":["e92a89e57c3b7d228be4e2e74c71ef3af52320bf061b411add9dccc34ddb0a78"]}}}},"names.js":{"size":1440,"offset":"1718105","integrity":{"algorithm":"SHA256","hash":"3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493","blockSize":4194304,"blocks":["3cab37a2240b996b9bed92fe7a041d91689cfe3ad2e9ae4c0ab99e4146408493"]}},"ref_error.js":{"size":543,"offset":"1719545","integrity":{"algorithm":"SHA256","hash":"81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7","blockSize":4194304,"blocks":["81c98fdf34c3037c91bfcc02277ec32156c71e34048f36cfe4e084416e916cb7"]}},"resolve.js":{"size":5006,"offset":"1720088","integrity":{"algorithm":"SHA256","hash":"df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9","blockSize":4194304,"blocks":["df75af0e0cf03fa1c6452e8dc61019f5aec645a8a5f6f494dc4e13cb5502d2d9"]}},"rules.js":{"size":918,"offset":"1725094","integrity":{"algorithm":"SHA256","hash":"ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9","blockSize":4194304,"blocks":["ec1d86500f497aa8e20f9f0c1695951159d9a909669d00a261ce1bb22b3cf0a9"]}},"util.js":{"size":7103,"offset":"1726012","integrity":{"algorithm":"SHA256","hash":"fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5","blockSize":4194304,"blocks":["fa911f5631f29d4d6420adfe086cb693b94b08de2719475c78c54bcb82f831a5"]}},"validate":{"files":{"applicability.js":{"size":853,"offset":"1733115","integrity":{"algorithm":"SHA256","hash":"50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0","blockSize":4194304,"blocks":["50c5cba5894a7fb9874b3432355b46ec71b73c9368dafb1323ded8567cca8fc0"]}},"boolSchema.js":{"size":1531,"offset":"1733968","integrity":{"algorithm":"SHA256","hash":"c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f","blockSize":4194304,"blocks":["c08abdbdbd3d8b1dcc0552a20fbc7d837ed44f4ca6abb2e464985590ac94377f"]}},"dataType.js":{"size":8409,"offset":"1735499","integrity":{"algorithm":"SHA256","hash":"697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52","blockSize":4194304,"blocks":["697bd7005361ec7066a23c18830a10b0ef28aec1a33138b4e3098bf78c4fae52"]}},"defaults.js":{"size":1448,"offset":"1743908","integrity":{"algorithm":"SHA256","hash":"05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428","blockSize":4194304,"blocks":["05721971df94faa57b09c8cfd60c2eef81b6d14910a7dea5f539d693a029c428"]}},"index.js":{"size":20552,"offset":"1745356","integrity":{"algorithm":"SHA256","hash":"cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd","blockSize":4194304,"blocks":["cb2103e5f890e04592c10d24b45857dad91155bae9f9460138a2459bdaaea2cd"]}},"keyword.js":{"size":5695,"offset":"1765908","integrity":{"algorithm":"SHA256","hash":"ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76","blockSize":4194304,"blocks":["ab8f070c75c25eee9be5c837f364748909b58f5db66149a2beccbd2f66afeb76"]}},"subschema.js":{"size":3858,"offset":"1771603","integrity":{"algorithm":"SHA256","hash":"ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc","blockSize":4194304,"blocks":["ca783d6052af91e65ebb59a5b48b47fb459a2241d37ca6a042f767d4ce451bdc"]}}}}}},"core.js":{"size":25185,"offset":"1775461","integrity":{"algorithm":"SHA256","hash":"7fdd03e949ecb3d020e560f669da71ce69a70f4bca28e5aff2ebc34d15bc2134","blockSize":4194304,"blocks":["7fdd03e949ecb3d020e560f669da71ce69a70f4bca28e5aff2ebc34d15bc2134"]}},"jtd.js":{"size":3360,"offset":"1800646","integrity":{"algorithm":"SHA256","hash":"9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44","blockSize":4194304,"blocks":["9554827c19abbb10694cafb71edd72a8303ea71e56b9eb7253200f5395610e44"]}},"refs":{"files":{"data.json":{"size":409,"offset":"1804006","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"index.js":{"size":938,"offset":"1804415","integrity":{"algorithm":"SHA256","hash":"ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d","blockSize":4194304,"blocks":["ec400bdf35a0f290266811503cdbfffd7c18c4a690379988b8062c57b48f946d"]}},"meta":{"files":{"applicator.json":{"size":1566,"offset":"1805353","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"1806919","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"1807396","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"1808669","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"1809044","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"1809802","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"1812066","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"index.js":{"size":1026,"offset":"1813645","integrity":{"algorithm":"SHA256","hash":"2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1","blockSize":4194304,"blocks":["2e39089b0aaa14efa7901ecf5384622ec3d5897b206e1d589d2420f17b9fa6e1"]}},"meta":{"files":{"applicator.json":{"size":1441,"offset":"1814671","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"1816112","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"1816591","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"1817935","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"1818355","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"1819113","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"1819585","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"1821849","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"1824015","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"1827464","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"1831275","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}},"jtd-schema.js":{"size":2882,"offset":"1833796","integrity":{"algorithm":"SHA256","hash":"ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92","blockSize":4194304,"blocks":["ed529445bf027885182bbed71e5458baecec2d356a788b636ed9f0c7cdaccd92"]}}}},"runtime":{"files":{"equal.js":{"size":286,"offset":"1836678","integrity":{"algorithm":"SHA256","hash":"c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274","blockSize":4194304,"blocks":["c94467da09ee94e5d194483a7ab821b9bb3bf1c04397270f2ab53dea9de59274"]}},"parseJson.js":{"size":5401,"offset":"1836964","integrity":{"algorithm":"SHA256","hash":"1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e","blockSize":4194304,"blocks":["1bc006064c98afbbb4fc03bef49db7e85dd9493fb54a7dc647d4344ad043848e"]}},"quote.js":{"size":943,"offset":"1842365","integrity":{"algorithm":"SHA256","hash":"1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2","blockSize":4194304,"blocks":["1061132b1475fce15821d2b41c74b9ac710f278a33f5dae3385458715cc962b2"]}},"re2.js":{"size":213,"offset":"1843308","integrity":{"algorithm":"SHA256","hash":"e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361","blockSize":4194304,"blocks":["e1a6849652ae9a099c36c9aee9d2efc7412c8f83c4b285142413af99a7238361"]}},"timestamp.js":{"size":1536,"offset":"1843521","integrity":{"algorithm":"SHA256","hash":"05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef","blockSize":4194304,"blocks":["05cd4fc283b82af25a2a71ee5e587640c1d42945c74cea790627135fff338bef"]}},"ucs2length.js":{"size":808,"offset":"1845057","integrity":{"algorithm":"SHA256","hash":"1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890","blockSize":4194304,"blocks":["1df012dd3d23fced07255a7204798004509687cb1f431ae0ab976db436bbd890"]}},"uri.js":{"size":218,"offset":"1845865","integrity":{"algorithm":"SHA256","hash":"d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578","blockSize":4194304,"blocks":["d1d61baf97ed87d7310df847a78ed73d19c8cc003207bf5aaec977500bdb1578"]}},"validation_error.js":{"size":337,"offset":"1846083","integrity":{"algorithm":"SHA256","hash":"11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815","blockSize":4194304,"blocks":["11bf5b4affc8114e5e7cdf65b93006c2d997ab60ada1152c22e136f9b828b815"]}}}},"standalone":{"files":{"index.js":{"size":4480,"offset":"1846420","integrity":{"algorithm":"SHA256","hash":"361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f","blockSize":4194304,"blocks":["361d58a7523548bb1b9c782135fae27e76d93c8feaba8c4d613331dbcd3b888f"]}},"instance.js":{"size":1015,"offset":"1850900","integrity":{"algorithm":"SHA256","hash":"4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3","blockSize":4194304,"blocks":["4e14aa01e0cb8288fbb75deeb2e738950b0560bd02e1ad8974f391af4c9fc6f3"]}}}},"types":{"files":{"index.js":{"size":110,"offset":"1851915","integrity":{"algorithm":"SHA256","hash":"fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71","blockSize":4194304,"blocks":["fc9c6096246805c2075c83ab1b96082eda2fc98c240a2502caa82f1966096b71"]}},"json-schema.js":{"size":116,"offset":"1852025","integrity":{"algorithm":"SHA256","hash":"2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28","blockSize":4194304,"blocks":["2e30aa0c0789b5af8248b081ddc14b439b48937730eb1be0ab28de2ca2353b28"]}},"jtd-schema.js":{"size":115,"offset":"1852141","integrity":{"algorithm":"SHA256","hash":"6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d","blockSize":4194304,"blocks":["6755d0ec5a09cc74205d46089f814c88c1ce4363e56a55486c12a0a86942bd8d"]}}}},"vocabularies":{"files":{"applicator":{"files":{"additionalItems.js":{"size":1931,"offset":"1852256","integrity":{"algorithm":"SHA256","hash":"7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099","blockSize":4194304,"blocks":["7beb0fbda5e349907067c8398bb8cc3260a6267b6e5dff9793a5ab2171934099"]}},"additionalProperties.js":{"size":4309,"offset":"1854187","integrity":{"algorithm":"SHA256","hash":"e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a","blockSize":4194304,"blocks":["e237cb180cd2e3f2e676feb714d7dcc6a42116640f9db2ad830cd20d9dfc540a"]}},"allOf.js":{"size":756,"offset":"1858496","integrity":{"algorithm":"SHA256","hash":"98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7","blockSize":4194304,"blocks":["98f46a6434ebe5f851b406480e18b776dd7f1bcc275e28c16a13bfef3cc067c7"]}},"anyOf.js":{"size":343,"offset":"1859252","integrity":{"algorithm":"SHA256","hash":"8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5","blockSize":4194304,"blocks":["8d7368d4aebad0514b713191b934993b4f0bf570e1bab93b07dc69712db2cec5"]}},"contains.js":{"size":3680,"offset":"1859595","integrity":{"algorithm":"SHA256","hash":"56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c","blockSize":4194304,"blocks":["56165dc93cd8b0b4611db50a97f1e7d7f9af6c5ffe95a7a5b054d6eeaa7f6a8c"]}},"dependencies.js":{"size":3198,"offset":"1863275","integrity":{"algorithm":"SHA256","hash":"c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b","blockSize":4194304,"blocks":["c1a83bf484b6fde4d268935f079ddba5e74a2f589dfc6d15ca2e20ba4d06ee5b"]}},"dependentSchemas.js":{"size":354,"offset":"1866473","integrity":{"algorithm":"SHA256","hash":"d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e","blockSize":4194304,"blocks":["d17d23755b0cf8699c180dd98b8b7270b688d2e4fe5a4c4fcc53ffdcc18ee58e"]}},"if.js":{"size":2438,"offset":"1866827","integrity":{"algorithm":"SHA256","hash":"42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4","blockSize":4194304,"blocks":["42374ee5dc681433579cc689b0c4ae5343f5bf78d4d6a561722b9277c5335ec4"]}},"index.js":{"size":1529,"offset":"1869265","integrity":{"algorithm":"SHA256","hash":"5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3","blockSize":4194304,"blocks":["5a61978f6d81bbabfa8b9ccb71d7de816ed6dd1fd7de5c72657439a76c2a7cb3"]}},"items.js":{"size":1993,"offset":"1870794","integrity":{"algorithm":"SHA256","hash":"fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e","blockSize":4194304,"blocks":["fa87f74adc3aac1f1b5e3e7dddf73294e6850e1dd49ed131fca4352e9645c54e"]}},"items2020.js":{"size":1037,"offset":"1872787","integrity":{"algorithm":"SHA256","hash":"c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f","blockSize":4194304,"blocks":["c449ef64aec16263c7935293ed450cfc2da3ba66f6df5f99c3198c05f169838f"]}},"not.js":{"size":773,"offset":"1873824","integrity":{"algorithm":"SHA256","hash":"ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718","blockSize":4194304,"blocks":["ab2f2758d4ea97ac8763fe5540dd0f4d877859676fe5d6c750a18deca387f718"]}},"oneOf.js":{"size":2257,"offset":"1874597","integrity":{"algorithm":"SHA256","hash":"e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2","blockSize":4194304,"blocks":["e2aeb6c22d49fd5f348bedcf7f5c4d7b31f5a05dd7ff1a0c531374c6968792a2"]}},"patternProperties.js":{"size":3236,"offset":"1876854","integrity":{"algorithm":"SHA256","hash":"0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655","blockSize":4194304,"blocks":["0d43da49a82452c439ba990de7372ad5cedb663717918a5f6dae07025abff655"]}},"prefixItems.js":{"size":354,"offset":"1880090","integrity":{"algorithm":"SHA256","hash":"16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23","blockSize":4194304,"blocks":["16264f7b3233a6dcb98b48700643efbd3ebc4d11e27b3eacffc83ccb5f44fb23"]}},"properties.js":{"size":2153,"offset":"1880444","integrity":{"algorithm":"SHA256","hash":"c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f","blockSize":4194304,"blocks":["c896873ae7251093a2c8880545b69b6e8cb55c44817a53ec830a49818d74104f"]}},"propertyNames.js":{"size":1221,"offset":"1882597","integrity":{"algorithm":"SHA256","hash":"b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7","blockSize":4194304,"blocks":["b3411cfeaff8efd5e6de12971bb5dc339e64b61fbe62d3b950794c077315c2e7"]}},"thenElse.js":{"size":446,"offset":"1883818","integrity":{"algorithm":"SHA256","hash":"9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d","blockSize":4194304,"blocks":["9bc42eb8699d57188a7ec2a710d3f38052f92bd78c5d4d0442cf98cf2ebbe22d"]}}}},"code.js":{"size":6216,"offset":"1884264","integrity":{"algorithm":"SHA256","hash":"9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63","blockSize":4194304,"blocks":["9212ddf8bd0a4c3b1c4b44cdadd141183b2b36f561b91d13df53c83911e3bf63"]}},"core":{"files":{"id.js":{"size":267,"offset":"1890480","integrity":{"algorithm":"SHA256","hash":"49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11","blockSize":4194304,"blocks":["49c8eff694ce4371450c1f9986e934fcbf4bd143311caef5332113f29175bc11"]}},"index.js":{"size":357,"offset":"1890747","integrity":{"algorithm":"SHA256","hash":"f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e","blockSize":4194304,"blocks":["f420e1011b95e27b54c58323a7ed4ffbd0a88cdb4496f771bb6782c2aa22d23e"]}},"ref.js":{"size":5234,"offset":"1891104","integrity":{"algorithm":"SHA256","hash":"1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1","blockSize":4194304,"blocks":["1422c1454b3621d890066042048f37746fe1cf213088307099816199889bbfd1"]}}}},"discriminator":{"files":{"index.js":{"size":4845,"offset":"1896338","integrity":{"algorithm":"SHA256","hash":"b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e","blockSize":4194304,"blocks":["b58b58025d2dbe5a6967376faec9295b860a338664c47037e9a1035c1e8fb88e"]}},"types.js":{"size":308,"offset":"1901183","integrity":{"algorithm":"SHA256","hash":"2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa","blockSize":4194304,"blocks":["2365341d1f30dc72cece7703e908e47aacb8f904b9f66ec4019fe889ae1e57fa"]}}}},"draft2020.js":{"size":762,"offset":"1901491","integrity":{"algorithm":"SHA256","hash":"2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445","blockSize":4194304,"blocks":["2d0dc3a14abd48a45ad1407a97f23a0f943fa5244923037f86e95a7de04a7445"]}},"draft7.js":{"size":557,"offset":"1902253","integrity":{"algorithm":"SHA256","hash":"8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170","blockSize":4194304,"blocks":["8c62022c6c3aa302c3ea6f6709a697fc9eb6385d243fa7c2156dbe9f02228170"]}},"dynamic":{"files":{"dynamicAnchor.js":{"size":1261,"offset":"1902810","integrity":{"algorithm":"SHA256","hash":"78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7","blockSize":4194304,"blocks":["78222a5b42bab186253d880f9af4b012394ae5988bfab78e79f2510caed0ccf7"]}},"dynamicRef.js":{"size":1985,"offset":"1904071","integrity":{"algorithm":"SHA256","hash":"acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917","blockSize":4194304,"blocks":["acc2913c91d11ff57150dde1751cdd5d9f486a0cb156037870ede203273af917"]}},"index.js":{"size":457,"offset":"1906056","integrity":{"algorithm":"SHA256","hash":"8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b","blockSize":4194304,"blocks":["8c05d09948653957427f351d9c6172965b932a5663f7dcb63014a491a533cc0b"]}},"recursiveAnchor.js":{"size":522,"offset":"1906513","integrity":{"algorithm":"SHA256","hash":"9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76","blockSize":4194304,"blocks":["9f6cb7e509f9deada1b884010f08c52876f8eace32dcf0e7da28f6d0d91f3f76"]}},"recursiveRef.js":{"size":325,"offset":"1907035","integrity":{"algorithm":"SHA256","hash":"7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d","blockSize":4194304,"blocks":["7b0c651e2c5b5218639cd3ad7e5162f1e226fc9814107a85f4c3e47f5138670d"]}}}},"errors.js":{"size":111,"offset":"1907360","integrity":{"algorithm":"SHA256","hash":"7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc","blockSize":4194304,"blocks":["7758b311e7cba27a8ff8b99a5fcd8db6804265cbc48d2867b72bfe56823d36bc"]}},"format":{"files":{"format.js":{"size":4317,"offset":"1907471","integrity":{"algorithm":"SHA256","hash":"6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f","blockSize":4194304,"blocks":["6fae0d5124fd821b1a9959492f7d6d7b528bee8830d49a7a4759fc9a9ab81d5f"]}},"index.js":{"size":209,"offset":"1911788","integrity":{"algorithm":"SHA256","hash":"d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67","blockSize":4194304,"blocks":["d5dad5f95c9c5f48f8ca956cdbb927aafc7b56baabfca8c0b0403d92c5ebeb67"]}}}},"jtd":{"files":{"discriminator.js":{"size":2785,"offset":"1911997","integrity":{"algorithm":"SHA256","hash":"14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2","blockSize":4194304,"blocks":["14df845b5ef760d96a3c62db8d4446840e3d408a248d1b92ba6db2260fca4da2"]}},"elements.js":{"size":949,"offset":"1914782","integrity":{"algorithm":"SHA256","hash":"b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b","blockSize":4194304,"blocks":["b2cad5c59d7c8ce936cea240d70beb41404c729901a60f32013c4facdcacfd5b"]}},"enum.js":{"size":1745,"offset":"1915731","integrity":{"algorithm":"SHA256","hash":"4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154","blockSize":4194304,"blocks":["4a8b7fa05f94b2e67275445c6e8437c337b92f709d243ed30a48ba6a08a9a154"]}},"error.js":{"size":893,"offset":"1917476","integrity":{"algorithm":"SHA256","hash":"d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9","blockSize":4194304,"blocks":["d6896337eedc9b71a742912f776580918cb4de58a90b434cd39f152896da16f9"]}},"index.js":{"size":962,"offset":"1918369","integrity":{"algorithm":"SHA256","hash":"c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d","blockSize":4194304,"blocks":["c57d340cd0709479d8ea9f102549a8fd2a47a2c1f2e6fe7f0e14067fe6385d7d"]}},"metadata.js":{"size":810,"offset":"1919331","integrity":{"algorithm":"SHA256","hash":"237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68","blockSize":4194304,"blocks":["237a4bcc04f1a59628ba35aab9bd7c02fa19a007bf026f75c562c20c7a63ab68"]}},"nullable.js":{"size":859,"offset":"1920141","integrity":{"algorithm":"SHA256","hash":"ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a","blockSize":4194304,"blocks":["ba6494ac04fb1c2654951e8c8a57861e324fafa0f6c3bd2e1716bea8eb5c823a"]}},"optionalProperties.js":{"size":436,"offset":"1921000","integrity":{"algorithm":"SHA256","hash":"82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62","blockSize":4194304,"blocks":["82b67841649a948b069c8e0cfab712eb883579690065a05658b7df7e4eddcc62"]}},"properties.js":{"size":6320,"offset":"1921436","integrity":{"algorithm":"SHA256","hash":"4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35","blockSize":4194304,"blocks":["4a392193b708f69c25511ed059e80a70ea084585731817ad8e459364f479eb35"]}},"ref.js":{"size":2648,"offset":"1927756","integrity":{"algorithm":"SHA256","hash":"4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460","blockSize":4194304,"blocks":["4736880c610f3664a8c714fdb5cf4e9db9fcda1721691dcacad2e9796e937460"]}},"type.js":{"size":2706,"offset":"1930404","integrity":{"algorithm":"SHA256","hash":"f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c","blockSize":4194304,"blocks":["f97e19f2c3042938f433cfad0c4500b3342d869719550246bd4fced479db8e1c"]}},"union.js":{"size":343,"offset":"1933110","integrity":{"algorithm":"SHA256","hash":"f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280","blockSize":4194304,"blocks":["f8404ab539ecfc5f6eb1bc489cc541aad6bf79cf58beecfcfe671226678c3280"]}},"values.js":{"size":1838,"offset":"1933453","integrity":{"algorithm":"SHA256","hash":"6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2","blockSize":4194304,"blocks":["6b98eb1fbe2686a7f26fbf1e8860f61bdc81fe47117c4f5a79d5ca1fc92138f2"]}}}},"metadata.js":{"size":427,"offset":"1935291","integrity":{"algorithm":"SHA256","hash":"45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609","blockSize":4194304,"blocks":["45c178744a7ec57e20c85ceeaea8d9f36b5663636ab7e495ea2c3c1bf4a58609"]}},"next.js":{"size":433,"offset":"1935718","integrity":{"algorithm":"SHA256","hash":"491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7","blockSize":4194304,"blocks":["491c4d9738e50a6c22b3090cb1df49911b4bb7c3b7dcafc2f2dd4c074c4d82e7"]}},"unevaluated":{"files":{"index.js":{"size":350,"offset":"1936151","integrity":{"algorithm":"SHA256","hash":"4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4","blockSize":4194304,"blocks":["4e7936d1a55051e70e2ebbbfc8de94fbe7f1e7b055252df5a984481ea7c156a4"]}},"unevaluatedItems.js":{"size":1588,"offset":"1936501","integrity":{"algorithm":"SHA256","hash":"4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda","blockSize":4194304,"blocks":["4d7010c39f1b7af4a2fe1a62e5b65c8f763d4e58ac3d710099d367659f5e4fda"]}},"unevaluatedProperties.js":{"size":2608,"offset":"1938089","integrity":{"algorithm":"SHA256","hash":"665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe","blockSize":4194304,"blocks":["665029a99612ec32e9bef99c9c4b09a4dc0be6c71d7b920594d414d404806ebe"]}}}},"validation":{"files":{"const.js":{"size":852,"offset":"1940697","integrity":{"algorithm":"SHA256","hash":"ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a","blockSize":4194304,"blocks":["ace994e9ab97a70899a9484794794f4be5ee03bfb3cf32242d3f091d77f0329a"]}},"dependentRequired.js":{"size":403,"offset":"1941549","integrity":{"algorithm":"SHA256","hash":"cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa","blockSize":4194304,"blocks":["cd69a90089328b24d2232c12edae57858c14f66aaa56923c12929eb3d673e8fa"]}},"enum.js":{"size":1901,"offset":"1941952","integrity":{"algorithm":"SHA256","hash":"61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22","blockSize":4194304,"blocks":["61062b318a40eb52fc5a8283e7f4781db98349841744961ef4fe04a4722ebf22"]}},"index.js":{"size":1036,"offset":"1943853","integrity":{"algorithm":"SHA256","hash":"4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4","blockSize":4194304,"blocks":["4a1839832de5f10ff423c1c0c6cb232b5b6e1b34980a28862cf56b2763136de4"]}},"limitContains.js":{"size":495,"offset":"1944889","integrity":{"algorithm":"SHA256","hash":"0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d","blockSize":4194304,"blocks":["0ea6f2e43359add298e1ed9306fe5020c62e086392f2915f10226b01394b200d"]}},"limitItems.js":{"size":852,"offset":"1945384","integrity":{"algorithm":"SHA256","hash":"49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec","blockSize":4194304,"blocks":["49f0427d29b38aef2fa8aead26e68bda12deb9a2da22f7a7804ba0fed44e1fec"]}},"limitLength.js":{"size":1130,"offset":"1946236","integrity":{"algorithm":"SHA256","hash":"379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2","blockSize":4194304,"blocks":["379c28317faaf7784680b6049c3562692d3df6d65cce33f48e6c6c723beeeec2"]}},"limitNumber.js":{"size":1036,"offset":"1947366","integrity":{"algorithm":"SHA256","hash":"3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65","blockSize":4194304,"blocks":["3dd4bd41dbfc76c522078ff54b6479683485c4e97faa04cfcfaf2d8cb0fb8e65"]}},"limitProperties.js":{"size":896,"offset":"1948402","integrity":{"algorithm":"SHA256","hash":"8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac","blockSize":4194304,"blocks":["8523a3f7b36c34882ca32b0ec71a2157d7930907cb86b778a97c1514fa6258ac"]}},"multipleOf.js":{"size":1023,"offset":"1949298","integrity":{"algorithm":"SHA256","hash":"df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd","blockSize":4194304,"blocks":["df128c2a6ca74ae57c65fbfe3aea8a101447a3ae8c41fd53cfc5693fa23cc8bd"]}},"pattern.js":{"size":1323,"offset":"1950321","integrity":{"algorithm":"SHA256","hash":"86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195","blockSize":4194304,"blocks":["86e84206bfc6a66ef18bf1fe43fbc56ebe7f7f4d57841197b6d044c529e0c195"]}},"required.js":{"size":3188,"offset":"1951644","integrity":{"algorithm":"SHA256","hash":"b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054","blockSize":4194304,"blocks":["b953bc18d94274bd73374dd5b4282d7a21159cec8c0e7a357e1eaf3f326b9054"]}},"uniqueItems.js":{"size":3037,"offset":"1954832","integrity":{"algorithm":"SHA256","hash":"666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52","blockSize":4194304,"blocks":["666d1a2aa25c0dfe3cf41312d0f9d40e9f99eb2c19be7469134ad89005aadd52"]}}}}}}}},"lib":{"files":{"compile":{"files":{"codegen":{"files":{}},"jtd":{"files":{}},"validate":{"files":{}}}},"refs":{"files":{"data.json":{"size":409,"offset":"1957869","integrity":{"algorithm":"SHA256","hash":"d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3","blockSize":4194304,"blocks":["d24ab8a97c18b3f5afdde7d7024a0e0ac1df0614a16a41cb88f81379edcc2db3"]}},"json-schema-2019-09":{"files":{"meta":{"files":{"applicator.json":{"size":1566,"offset":"1958278","integrity":{"algorithm":"SHA256","hash":"9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a","blockSize":4194304,"blocks":["9c356a52b0ad5da7d4c1b69f61dff5277c2af46221bc0b0521bbdbf3a12d3a2a"]}},"content.json":{"size":477,"offset":"1959844","integrity":{"algorithm":"SHA256","hash":"cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267","blockSize":4194304,"blocks":["cf4792ae93f4a4580ec9523640945f7756f75fd624935ebf15194b0ac3909267"]}},"core.json":{"size":1273,"offset":"1960321","integrity":{"algorithm":"SHA256","hash":"629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe","blockSize":4194304,"blocks":["629c017994ffaa33f573a96cf01b9dac6cae80c7d5d17dad5e823a3afa18d5fe"]}},"format.json":{"size":375,"offset":"1961594","integrity":{"algorithm":"SHA256","hash":"018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8","blockSize":4194304,"blocks":["018ef7c81bcca9e40a4a02ed236e7cabb3a630f2b1ea01fbdeed2f882c15ddc8"]}},"meta-data.json":{"size":758,"offset":"1961969","integrity":{"algorithm":"SHA256","hash":"e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e","blockSize":4194304,"blocks":["e038593d36bf1855875a13b8812469d6a2d62ed309436b9c9a2fa5a4ba59085e"]}},"validation.json":{"size":2264,"offset":"1962727","integrity":{"algorithm":"SHA256","hash":"aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6","blockSize":4194304,"blocks":["aaba7f2d6fcbdfa6ca97fdc3d3da1ae7d66ca3322b7e90cf5a98b067555d06e6"]}}}},"schema.json":{"size":1579,"offset":"1964991","integrity":{"algorithm":"SHA256","hash":"264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15","blockSize":4194304,"blocks":["264720afa0dd61919e21bbe9bc1312121b70e43019ac696240e069adc72cce15"]}}}},"json-schema-2020-12":{"files":{"meta":{"files":{"applicator.json":{"size":1441,"offset":"1966570","integrity":{"algorithm":"SHA256","hash":"f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4","blockSize":4194304,"blocks":["f1e465ff0c0cc86bee5c0cc4b51d2734c532e6ea12c75b60a2ac093a4577b2d4"]}},"content.json":{"size":479,"offset":"1968011","integrity":{"algorithm":"SHA256","hash":"7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516","blockSize":4194304,"blocks":["7ede86f2c48d646202bf1332aefaf46db268c943d59752727db7247dc2920516"]}},"core.json":{"size":1344,"offset":"1968490","integrity":{"algorithm":"SHA256","hash":"c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49","blockSize":4194304,"blocks":["c3a5947992d4fe67c95cda7910911207376bbae41c0a124ec9e7e699172e7a49"]}},"format-annotation.json":{"size":420,"offset":"1969834","integrity":{"algorithm":"SHA256","hash":"1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d","blockSize":4194304,"blocks":["1e31131b1ed21f98c007f04deb501343b8c4dd77f1c5a8494a9c2085f68d769d"]}},"meta-data.json":{"size":758,"offset":"1970254","integrity":{"algorithm":"SHA256","hash":"eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273","blockSize":4194304,"blocks":["eb008c756b29bdaa237c1f06d32ea4a21f6ef22148b03c6372cea5e4c0782273"]}},"unevaluated.json":{"size":472,"offset":"1971012","integrity":{"algorithm":"SHA256","hash":"8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca","blockSize":4194304,"blocks":["8f7f75f4274745faa32e4abdba12de99f49b21df225f52f723b5c62043b0edca"]}},"validation.json":{"size":2264,"offset":"1971484","integrity":{"algorithm":"SHA256","hash":"3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092","blockSize":4194304,"blocks":["3cae7069843679429e4ada7df261bb8961fa34cac15be89296026e69af312092"]}}}},"schema.json":{"size":2166,"offset":"1973748","integrity":{"algorithm":"SHA256","hash":"5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56","blockSize":4194304,"blocks":["5333c7df76bceee098e865881d0808238dea836126c6c60b49299ec85c6c7a56"]}}}},"json-schema-draft-06.json":{"size":3449,"offset":"1975914","integrity":{"algorithm":"SHA256","hash":"a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687","blockSize":4194304,"blocks":["a9b6a00af20105009f0924cd7c02d811bbf70c579a96f1552579c3457111f687"]}},"json-schema-draft-07.json":{"size":3811,"offset":"1979363","integrity":{"algorithm":"SHA256","hash":"f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773","blockSize":4194304,"blocks":["f7e8b13cad4fecff9771f3626fef33e20e59027b90938a28fd9d2f6c17cd0773"]}},"json-schema-secure.json":{"size":2521,"offset":"1983174","integrity":{"algorithm":"SHA256","hash":"b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421","blockSize":4194304,"blocks":["b7840b4f1526eee47ac19780906a436d0c39df2aa3d505388caf18864085a421"]}}}},"runtime":{"files":{}},"standalone":{"files":{}},"types":{"files":{}},"vocabularies":{"files":{"applicator":{"files":{}},"core":{"files":{}},"discriminator":{"files":{}},"dynamic":{"files":{}},"format":{"files":{}},"jtd":{"files":{}},"unevaluated":{"files":{}},"validation":{"files":{}}}}}},"package.json":{"size":4481,"offset":"1985695","integrity":{"algorithm":"SHA256","hash":"720f862de3e496df05e074c33df5174db92c47e60726e41ab1338cfefda9754c","blockSize":4194304,"blocks":["720f862de3e496df05e074c33df5174db92c47e60726e41ab1338cfefda9754c"]}}}},"json-schema-traverse":{"files":{".eslintrc.yml":{"size":630,"offset":"1990176","integrity":{"algorithm":"SHA256","hash":"b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc","blockSize":4194304,"blocks":["b1ea981e2461f053646b08a616efcaba0d3b278b223957e9eb931bcbc3971ccc"]}},".github":{"files":{"FUNDING.yml":{"size":57,"offset":"1990806","integrity":{"algorithm":"SHA256","hash":"83e77adf3dbe6261917b160553f75cbb96de8e99c3259f4f1de85e1c6e4bd156","blockSize":4194304,"blocks":["83e77adf3dbe6261917b160553f75cbb96de8e99c3259f4f1de85e1c6e4bd156"]}},"workflows":{"files":{"build.yml":{"size":582,"offset":"1990863","integrity":{"algorithm":"SHA256","hash":"f0f23bb3b380800e214b19abfd69c1b093131bb030c056fabdd9cddec7e785c5","blockSize":4194304,"blocks":["f0f23bb3b380800e214b19abfd69c1b093131bb030c056fabdd9cddec7e785c5"]}},"publish.yml":{"size":678,"offset":"1991445","integrity":{"algorithm":"SHA256","hash":"56cbec53748d486f04b5c37bec8ea5e5588e02fb2882db8ce36c6e9689bfd2fc","blockSize":4194304,"blocks":["56cbec53748d486f04b5c37bec8ea5e5588e02fb2882db8ce36c6e9689bfd2fc"]}}}}}},"LICENSE":{"size":1074,"offset":"1992123","integrity":{"algorithm":"SHA256","hash":"7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a","blockSize":4194304,"blocks":["7bf9b2de73a6b356761c948d0e9eeb4be6c1270bd04c79cd489c1e400ffdfc1a"]}},"README.md":{"size":3350,"offset":"1993197","integrity":{"algorithm":"SHA256","hash":"e6137660d373bc510f4d41789d7fea74e0ed9f94c99d4892dee22292ac2a39a7","blockSize":4194304,"blocks":["e6137660d373bc510f4d41789d7fea74e0ed9f94c99d4892dee22292ac2a39a7"]}},"index.js":{"size":2428,"offset":"1996547","integrity":{"algorithm":"SHA256","hash":"024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350","blockSize":4194304,"blocks":["024191b747afac01b28ff11d744e9f82720bbad5f716163ba5c962eb62aa2350"]}},"package.json":{"size":1004,"offset":"1998975","integrity":{"algorithm":"SHA256","hash":"156fb24af02845c190701360d06dfda35ef04282e34a734289ea9535ad9819ae","blockSize":4194304,"blocks":["156fb24af02845c190701360d06dfda35ef04282e34a734289ea9535ad9819ae"]}},"spec":{"files":{".eslintrc.yml":{"size":91,"offset":"1999979","integrity":{"algorithm":"SHA256","hash":"8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c","blockSize":4194304,"blocks":["8df0cb64273b71c11db4f99be49c92e6f80f10a13de4599743e4372c8a0be82c"]}},"fixtures":{"files":{"schema.js":{"size":5544,"offset":"2000070","integrity":{"algorithm":"SHA256","hash":"0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27","blockSize":4194304,"blocks":["0262591e321bc88b22dc33ec78bcded5ab664e2fce2c10b9e0c35d3eb6030d27"]}}}},"index.spec.js":{"size":6042,"offset":"2005614","integrity":{"algorithm":"SHA256","hash":"40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69","blockSize":4194304,"blocks":["40e6986bda700387e2d397971087a3977d6801bf954591505229691a267c5f69"]}}}}}},"semver":{"files":{"LICENSE":{"size":765,"offset":"2011656","integrity":{"algorithm":"SHA256","hash":"4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b","blockSize":4194304,"blocks":["4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b"]}},"README.md":{"size":24811,"offset":"2012421","integrity":{"algorithm":"SHA256","hash":"5d2d39fa26b5d8a0c49de7543a68a5deba374858f5286aa83b5a80879e0cd7a5","blockSize":4194304,"blocks":["5d2d39fa26b5d8a0c49de7543a68a5deba374858f5286aa83b5a80879e0cd7a5"]}},"bin":{"files":{"semver.js":{"size":4748,"offset":"2037232","executable":true,"integrity":{"algorithm":"SHA256","hash":"82c28f9bc9e598d255edd507d1e9b157f37b8dac0f2da25a813b5e7121600be8","blockSize":4194304,"blocks":["82c28f9bc9e598d255edd507d1e9b157f37b8dac0f2da25a813b5e7121600be8"]}}}},"classes":{"files":{"comparator.js":{"size":3631,"offset":"2041980","integrity":{"algorithm":"SHA256","hash":"054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac","blockSize":4194304,"blocks":["054202956430d63d5ff4599fae09760ce465b489e4f0b5ef5ce7cc7ac21157ac"]}},"index.js":{"size":143,"offset":"2045611","integrity":{"algorithm":"SHA256","hash":"3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17","blockSize":4194304,"blocks":["3bb69280c2a788d0eb16f915bb9df4dbe812075182024c753dca2283bcea1b17"]}},"range.js":{"size":14977,"offset":"2045754","integrity":{"algorithm":"SHA256","hash":"cf8f8eb6934663ae2a9d04838d4d71555427a2abd3c8748ee5219507969a6b46","blockSize":4194304,"blocks":["cf8f8eb6934663ae2a9d04838d4d71555427a2abd3c8748ee5219507969a6b46"]}},"semver.js":{"size":9480,"offset":"2060731","integrity":{"algorithm":"SHA256","hash":"d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083","blockSize":4194304,"blocks":["d5ba57e5c93f031b1d234fca4bb746746fcd1fe51be7e5ee895601e2c12e2083"]}}}},"functions":{"files":{"clean.js":{"size":205,"offset":"2070211","integrity":{"algorithm":"SHA256","hash":"4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f","blockSize":4194304,"blocks":["4eadb0892844cf3ae295121a86163a66c73f89acd1b7f0b114ec115b4539512f"]}},"cmp.js":{"size":961,"offset":"2070416","integrity":{"algorithm":"SHA256","hash":"a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3","blockSize":4194304,"blocks":["a63d74e87b73788e78e9ce0a4892b5333d6b809c0de88b31e4ed76cbf17f94b3"]}},"coerce.js":{"size":2004,"offset":"2071377","integrity":{"algorithm":"SHA256","hash":"28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a","blockSize":4194304,"blocks":["28a251c5ab210ddf9e97551b9f37a53329fcce91f0c3943dcbc02de1a1de915a"]}},"compare-build.js":{"size":281,"offset":"2073381","integrity":{"algorithm":"SHA256","hash":"5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c","blockSize":4194304,"blocks":["5ab651d5b40af289bd85c645a92b6d8cfe1a986dc413c797cfcc8d623d7c844c"]}},"compare-loose.js":{"size":132,"offset":"2073662","integrity":{"algorithm":"SHA256","hash":"07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78","blockSize":4194304,"blocks":["07b6a3a1db0a5210ceb784c1708bd4679f3a94fc73a9c9eb349349e7070a6f78"]}},"compare.js":{"size":170,"offset":"2073794","integrity":{"algorithm":"SHA256","hash":"d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c","blockSize":4194304,"blocks":["d404b5aa48aaddc8a654c5da8fb7d4443404b7948589b21ac4b045d1cee4e34c"]}},"diff.js":{"size":1423,"offset":"2073964","integrity":{"algorithm":"SHA256","hash":"7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31","blockSize":4194304,"blocks":["7a11fd39b987cdf06c65e928cb1aca49bec583feb86fb5c8fe47a6fd61d7de31"]}},"eq.js":{"size":126,"offset":"2075387","integrity":{"algorithm":"SHA256","hash":"b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936","blockSize":4194304,"blocks":["b6e30a7168e52723216fc163d300e2bbabf92ec0251f9ac5438bb6ccf57c8936"]}},"gt.js":{"size":124,"offset":"2075513","integrity":{"algorithm":"SHA256","hash":"135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93","blockSize":4194304,"blocks":["135523704aa48cd98834dd170ee9f74f0e68043b379f32d021db11e6304c5c93"]}},"gte.js":{"size":127,"offset":"2075637","integrity":{"algorithm":"SHA256","hash":"991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d","blockSize":4194304,"blocks":["991c5bbe48ecb210a562646872f05862ad9fc0d42186d85aa60bdc6fa323eb9d"]}},"inc.js":{"size":478,"offset":"2075764","integrity":{"algorithm":"SHA256","hash":"952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493","blockSize":4194304,"blocks":["952069fc8690b7d3af0fe9d55f7c54fe2ac067b48c5e74f6a54f9ce19a334493"]}},"lt.js":{"size":124,"offset":"2076242","integrity":{"algorithm":"SHA256","hash":"1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25","blockSize":4194304,"blocks":["1c897a9bc849320e2e9dc0f6c09555c01ee3ddf30734515d717b88ad7740ea25"]}},"lte.js":{"size":127,"offset":"2076366","integrity":{"algorithm":"SHA256","hash":"3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800","blockSize":4194304,"blocks":["3a8d0b1d00423f60cc7cb810b36ab77b61330831ad237dbe73eb5cecfa412800"]}},"major.js":{"size":136,"offset":"2076493","integrity":{"algorithm":"SHA256","hash":"5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276","blockSize":4194304,"blocks":["5c678480d882f511200fed2c16ec3847dfedb08a1d70328dc2f031d35d825276"]}},"minor.js":{"size":136,"offset":"2076629","integrity":{"algorithm":"SHA256","hash":"1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6","blockSize":4194304,"blocks":["1b051794f1713adec2a236517196691687c35f82e0b596ff3316a78b3cc10ae6"]}},"neq.js":{"size":128,"offset":"2076765","integrity":{"algorithm":"SHA256","hash":"a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127","blockSize":4194304,"blocks":["a662883751918822c162183b46b9e20d09489132f82686c92ab78bee67f3a127"]}},"parse.js":{"size":331,"offset":"2076893","integrity":{"algorithm":"SHA256","hash":"29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad","blockSize":4194304,"blocks":["29a69e15b6d02fe381d573f861881a89590e9d0f0f0ca740c5f85eaf0234c4ad"]}},"patch.js":{"size":136,"offset":"2077224","integrity":{"algorithm":"SHA256","hash":"f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd","blockSize":4194304,"blocks":["f02d3c1b059fe3d96ce124886f7eef321d381a95638fd3c4a8d5ccd8e76ffadd"]}},"prerelease.js":{"size":234,"offset":"2077360","integrity":{"algorithm":"SHA256","hash":"baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593","blockSize":4194304,"blocks":["baedbf503d5610ad041bfb56071efa48feb331ca278295c399537d35d3ffb593"]}},"rcompare.js":{"size":132,"offset":"2077594","integrity":{"algorithm":"SHA256","hash":"84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0","blockSize":4194304,"blocks":["84fa5e88adf08d15c993cac8cdec6d1a65045b7e95a9c55184230a7f807f4dc0"]}},"rsort.js":{"size":163,"offset":"2077726","integrity":{"algorithm":"SHA256","hash":"6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3","blockSize":4194304,"blocks":["6ec659ce3b6c2b173c719286caab04409adba046c0917874ec3b5e36ddfbc7e3"]}},"satisfies.js":{"size":247,"offset":"2077889","integrity":{"algorithm":"SHA256","hash":"8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946","blockSize":4194304,"blocks":["8cf5e122b757251671ed6c9d9680904b71cd375845853f05312e608cf2cc2946"]}},"sort.js":{"size":161,"offset":"2078136","integrity":{"algorithm":"SHA256","hash":"c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8","blockSize":4194304,"blocks":["c2fe2d3ed0be8a4e9de8f02abdfd5d9c0d3bcc510d88e87af84185592882c4b8"]}},"valid.js":{"size":176,"offset":"2078297","integrity":{"algorithm":"SHA256","hash":"0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025","blockSize":4194304,"blocks":["0de7ea736cb7807179d46dfac09c830a9338e02b6a07db12d7040cde2def6025"]}}}},"index.js":{"size":2630,"offset":"2078473","integrity":{"algorithm":"SHA256","hash":"646e0b707f56dca7cb90cebc6fe687278bcc1a16fdcc83756dbe23083ff15e06","blockSize":4194304,"blocks":["646e0b707f56dca7cb90cebc6fe687278bcc1a16fdcc83756dbe23083ff15e06"]}},"internal":{"files":{"constants.js":{"size":873,"offset":"2081103","integrity":{"algorithm":"SHA256","hash":"38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9","blockSize":4194304,"blocks":["38a112baf27ceca0260082ff26ac2fd7a9861cab1af12dd65e720277f68e6ce9"]}},"debug.js":{"size":240,"offset":"2081976","integrity":{"algorithm":"SHA256","hash":"8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3","blockSize":4194304,"blocks":["8a9f420572260f3cf944463b5090d62a60f0730589dc23a7ec4ca25e2ee41bb3"]}},"identifiers.js":{"size":525,"offset":"2082216","integrity":{"algorithm":"SHA256","hash":"b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7","blockSize":4194304,"blocks":["b4916b09dc7869ae0eb05e71c855c942a3a7365f7e6e89185d59a9e45a2451d7"]}},"lrucache.js":{"size":802,"offset":"2082741","integrity":{"algorithm":"SHA256","hash":"14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f","blockSize":4194304,"blocks":["14d087c87da87b6f5c36fc4cdd7d2d14077874b14a68e20fce5b6138fa2ca34f"]}},"parse-options.js":{"size":338,"offset":"2083543","integrity":{"algorithm":"SHA256","hash":"fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01","blockSize":4194304,"blocks":["fdf51d0de8d5442c35a997ef58cd530d239ce206f961d14c5121354451b01d01"]}},"re.js":{"size":8138,"offset":"2083881","integrity":{"algorithm":"SHA256","hash":"6a47e73c279fa8c4011f670471f50830a39922b43797b2884e6cc03f65b64d6c","blockSize":4194304,"blocks":["6a47e73c279fa8c4011f670471f50830a39922b43797b2884e6cc03f65b64d6c"]}}}},"package.json":{"size":1663,"offset":"2092019","integrity":{"algorithm":"SHA256","hash":"ba0d1b548512e65c15b1cddbcd6caa16cc9070e8af8987d02ba929a1f06c0177","blockSize":4194304,"blocks":["ba0d1b548512e65c15b1cddbcd6caa16cc9070e8af8987d02ba929a1f06c0177"]}},"preload.js":{"size":83,"offset":"2093682","integrity":{"algorithm":"SHA256","hash":"edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba","blockSize":4194304,"blocks":["edb6808911bebcb324b2df57e5c9935149e56984ff083b74c6cfe215f5b710ba"]}},"range.bnf":{"size":619,"offset":"2093765","integrity":{"algorithm":"SHA256","hash":"ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a","blockSize":4194304,"blocks":["ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a"]}},"ranges":{"files":{"gtr.js":{"size":231,"offset":"2094384","integrity":{"algorithm":"SHA256","hash":"8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19","blockSize":4194304,"blocks":["8fadad28e36d28e93d498ac7ac20badba2a407312845eabc18e82e90a0732b19"]}},"intersects.js":{"size":224,"offset":"2094615","integrity":{"algorithm":"SHA256","hash":"fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f","blockSize":4194304,"blocks":["fe87ac5d3020010ad3ec00636dadbf0c669ff07d0f57e0a8165a8264f79a676f"]}},"ltr.js":{"size":227,"offset":"2094839","integrity":{"algorithm":"SHA256","hash":"e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038","blockSize":4194304,"blocks":["e5186fcc03018acf9be6d968755d4c49727aeb0d981d179eb568ae5fbe983038"]}},"max-satisfying.js":{"size":593,"offset":"2095066","integrity":{"algorithm":"SHA256","hash":"e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416","blockSize":4194304,"blocks":["e1a2c0d6144cc772cd20bbc8ecb9e8a3a4074e9172a3d8e794838b591cdeb416"]}},"min-satisfying.js":{"size":591,"offset":"2095659","integrity":{"algorithm":"SHA256","hash":"2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca","blockSize":4194304,"blocks":["2681abf54098aa670f12826b76a6ec77a2441186ae4243afde3be8ae4908f7ca"]}},"min-version.js":{"size":1514,"offset":"2096250","integrity":{"algorithm":"SHA256","hash":"fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b","blockSize":4194304,"blocks":["fefba0a88c2bf74d5cede504b5ae50a8dc3edfd69cf0174a491e2cf3e442614b"]}},"outside.js":{"size":2204,"offset":"2097764","integrity":{"algorithm":"SHA256","hash":"3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca","blockSize":4194304,"blocks":["3a2b0b23593d2f49419c06af2af75450cab103b0c25d665d48fe5bca495a21ca"]}},"simplify.js":{"size":1355,"offset":"2099968","integrity":{"algorithm":"SHA256","hash":"7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934","blockSize":4194304,"blocks":["7b78581c13322bc68ece2088685386b2a9b51c15b94d0a2063bdf2546bd41934"]}},"subset.js":{"size":7524,"offset":"2101323","integrity":{"algorithm":"SHA256","hash":"87387952fbe154f5874d5f09dd2173e782e894a76fa8370ce23f4120e2ae7eae","blockSize":4194304,"blocks":["87387952fbe154f5874d5f09dd2173e782e894a76fa8370ce23f4120e2ae7eae"]}},"to-comparators.js":{"size":282,"offset":"2108847","integrity":{"algorithm":"SHA256","hash":"6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9","blockSize":4194304,"blocks":["6c5e966210cff270fa2850668aaf8460fac7759f8d99f282521ef7a78f4564e9"]}},"valid.js":{"size":326,"offset":"2109129","integrity":{"algorithm":"SHA256","hash":"5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac","blockSize":4194304,"blocks":["5ef6f995af801868925940cf8df5735d565ebabb090b068695cae65218bcd3ac"]}}}}}}}},"package.json":{"size":1831,"offset":"2109455","integrity":{"algorithm":"SHA256","hash":"fa2205e5ada480ebab68cc652800a8e1857780d629874a18c8c1bb1fb0f1b9a2","blockSize":4194304,"blocks":["fa2205e5ada480ebab68cc652800a8e1857780d629874a18c8c1bb1fb0f1b9a2"]}},"readme.md":{"size":13240,"offset":"2111286","integrity":{"algorithm":"SHA256","hash":"f1398e85b1c1c2924c5ec4a153e685aba6781ff51f0f9f6f462b191b63779c91","blockSize":4194304,"blocks":["f1398e85b1c1c2924c5ec4a153e685aba6781ff51f0f9f6f462b191b63779c91"]}}}},"debounce-fn":{"files":{"index.js":{"size":1080,"offset":"2124526","integrity":{"algorithm":"SHA256","hash":"c9b8c0476e48445718d35a34c18dae9eb7b07f63e84cb827f4eeb26c13508ea6","blockSize":4194304,"blocks":["c9b8c0476e48445718d35a34c18dae9eb7b07f63e84cb827f4eeb26c13508ea6"]}},"license":{"size":1117,"offset":"2125606","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":716,"offset":"2126723","integrity":{"algorithm":"SHA256","hash":"6e0812316bd0c2f48a279327d4846aee74b9ebab3c816ab348b17dd5cc3dff8c","blockSize":4194304,"blocks":["6e0812316bd0c2f48a279327d4846aee74b9ebab3c816ab348b17dd5cc3dff8c"]}},"readme.md":{"size":1362,"offset":"2127439","integrity":{"algorithm":"SHA256","hash":"583cc7808e3ee85aca69e581bf6573f6528b9eae80001e224e21dc423a4fc5e7","blockSize":4194304,"blocks":["583cc7808e3ee85aca69e581bf6573f6528b9eae80001e224e21dc423a4fc5e7"]}}}},"dot-prop":{"files":{"index.js":{"size":2705,"offset":"2128801","integrity":{"algorithm":"SHA256","hash":"9f475c2dcec98af9a2b7fa5017f09e734808aa0c1c8c61ac38ad161764b47c65","blockSize":4194304,"blocks":["9f475c2dcec98af9a2b7fa5017f09e734808aa0c1c8c61ac38ad161764b47c65"]}},"license":{"size":1117,"offset":"2131506","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":896,"offset":"2132623","integrity":{"algorithm":"SHA256","hash":"277e0aee4f3623d350ee747a3025b4eeb9f1dd53215a5f0398ed8b69ab32498e","blockSize":4194304,"blocks":["277e0aee4f3623d350ee747a3025b4eeb9f1dd53215a5f0398ed8b69ab32498e"]}},"readme.md":{"size":2689,"offset":"2133519","integrity":{"algorithm":"SHA256","hash":"8f2fc1dfe2b68b8d3548be0ce7be7c093db08e69d3eed5b496e15fc1060f2850","blockSize":4194304,"blocks":["8f2fc1dfe2b68b8d3548be0ce7be7c093db08e69d3eed5b496e15fc1060f2850"]}}}},"electron-store":{"files":{"index.js":{"size":1869,"offset":"2136208","integrity":{"algorithm":"SHA256","hash":"addc2492877598e1f510627408578aef5087b63897c15d79d928f0cc7c762f22","blockSize":4194304,"blocks":["addc2492877598e1f510627408578aef5087b63897c15d79d928f0cc7c762f22"]}},"license":{"size":1117,"offset":"2138077","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":979,"offset":"2139194","integrity":{"algorithm":"SHA256","hash":"0abe95307dcd0ab794751d5f4c139debed31368c18eb0d8fdb8ac27f8f475ff0","blockSize":4194304,"blocks":["0abe95307dcd0ab794751d5f4c139debed31368c18eb0d8fdb8ac27f8f475ff0"]}},"readme.md":{"size":13978,"offset":"2140173","integrity":{"algorithm":"SHA256","hash":"302a7c408745d1e24f0dc5f92df479bde44b128eff5e7aced85f8ffe764a7d19","blockSize":4194304,"blocks":["302a7c408745d1e24f0dc5f92df479bde44b128eff5e7aced85f8ffe764a7d19"]}}}},"env-paths":{"files":{"index.js":{"size":2155,"offset":"2154151","integrity":{"algorithm":"SHA256","hash":"84351667051b005f9856319267407b06affad12888355462c7c8740f22ca3999","blockSize":4194304,"blocks":["84351667051b005f9856319267407b06affad12888355462c7c8740f22ca3999"]}},"license":{"size":1109,"offset":"2156306","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":698,"offset":"2157415","integrity":{"algorithm":"SHA256","hash":"b92833e5851ec53bd4cd8093f6099d0c6e6818c4374ec1d09aa25d4f9ba91ec4","blockSize":4194304,"blocks":["b92833e5851ec53bd4cd8093f6099d0c6e6818c4374ec1d09aa25d4f9ba91ec4"]}},"readme.md":{"size":3127,"offset":"2158113","integrity":{"algorithm":"SHA256","hash":"0e7e14cbbc73f780195e6115b26acfb561741bab0860e954b1780271b1566966","blockSize":4194304,"blocks":["0e7e14cbbc73f780195e6115b26acfb561741bab0860e954b1780271b1566966"]}}}},"find-up":{"files":{"index.js":{"size":968,"offset":"2161240","integrity":{"algorithm":"SHA256","hash":"b2b7a4a3a202785dfc044bc9d3798df684c9983008254e44e23258f80c7aba54","blockSize":4194304,"blocks":["b2b7a4a3a202785dfc044bc9d3798df684c9983008254e44e23258f80c7aba54"]}},"license":{"size":1109,"offset":"2162208","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":750,"offset":"2163317","integrity":{"algorithm":"SHA256","hash":"2a2df73310e2581d941e5c1b5e8bc93abfb1737c04d5e175651bbec692d8a9d4","blockSize":4194304,"blocks":["2a2df73310e2581d941e5c1b5e8bc93abfb1737c04d5e175651bbec692d8a9d4"]}},"readme.md":{"size":2018,"offset":"2164067","integrity":{"algorithm":"SHA256","hash":"3884d34601cfe2581ddaae7dce6982798a6cfe01dab2b76c239c19f09f666f75","blockSize":4194304,"blocks":["3884d34601cfe2581ddaae7dce6982798a6cfe01dab2b76c239c19f09f666f75"]}}}},"json-schema-typed":{"files":{"LICENSE":{"size":1386,"offset":"2166085","integrity":{"algorithm":"SHA256","hash":"59992f12a42bfad11b6586e1bffda51749bb468847ca27c7070647462a66ed7b","blockSize":4194304,"blocks":["59992f12a42bfad11b6586e1bffda51749bb468847ca27c7070647462a66ed7b"]}},"README.md":{"size":2025,"offset":"2167471","integrity":{"algorithm":"SHA256","hash":"7d2e7c3aa03cd83054560a45c957acd9b0a55e7551ccd8017c20307fdad72510","blockSize":4194304,"blocks":["7d2e7c3aa03cd83054560a45c957acd9b0a55e7551ccd8017c20307fdad72510"]}},"dist-node":{"files":{"index.js":{"size":2596,"offset":"2169496","integrity":{"algorithm":"SHA256","hash":"9fbf92ce11a8e03f63fca828fb7aa814b8f35f0e9d78ed95242988c71a82a3e2","blockSize":4194304,"blocks":["9fbf92ce11a8e03f63fca828fb7aa814b8f35f0e9d78ed95242988c71a82a3e2"]}}}},"dist-src":{"files":{"index.js":{"size":2511,"offset":"2172092","integrity":{"algorithm":"SHA256","hash":"d7019674db69d5a5b7443d643a5c909b7b0a320183cb9a149603fb35fa16bf06","blockSize":4194304,"blocks":["d7019674db69d5a5b7443d643a5c909b7b0a320183cb9a149603fb35fa16bf06"]}}}},"dist-types":{"files":{"__tests__":{"files":{}}}},"dist-web":{"files":{"index.js":{"size":2592,"offset":"2174603","integrity":{"algorithm":"SHA256","hash":"2720267bff58c5728dd9ea8cfb1de124ce525003ea58a692c0bdb473f2a8d7e0","blockSize":4194304,"blocks":["2720267bff58c5728dd9ea8cfb1de124ce525003ea58a692c0bdb473f2a8d7e0"]}}}},"package.json":{"size":1936,"offset":"2177195","integrity":{"algorithm":"SHA256","hash":"ca6961fa381a3e69966864830b5b6b65c0ed8245a094a7415383dd30910048cc","blockSize":4194304,"blocks":["ca6961fa381a3e69966864830b5b6b65c0ed8245a094a7415383dd30910048cc"]}}}},"locate-path":{"files":{"index.js":{"size":539,"offset":"2179131","integrity":{"algorithm":"SHA256","hash":"0d01be23e2a31212f61ae8856bd916709156f2c56c7434dbe97ea29624b77fd7","blockSize":4194304,"blocks":["0d01be23e2a31212f61ae8856bd916709156f2c56c7434dbe97ea29624b77fd7"]}},"license":{"size":1109,"offset":"2179670","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":694,"offset":"2180779","integrity":{"algorithm":"SHA256","hash":"e66ebe46039c86b953484b10b8a64b620d3851cf35eeebb16c2d0a60ada5e41b","blockSize":4194304,"blocks":["e66ebe46039c86b953484b10b8a64b620d3851cf35eeebb16c2d0a60ada5e41b"]}},"readme.md":{"size":1527,"offset":"2181473","integrity":{"algorithm":"SHA256","hash":"f91cb3b67e01a6eba365555ed7f995597d72d4ecda6f5771a333504e784f1bd8","blockSize":4194304,"blocks":["f91cb3b67e01a6eba365555ed7f995597d72d4ecda6f5771a333504e784f1bd8"]}}}},"mimic-fn":{"files":{"index.js":{"size":2930,"offset":"2183000","integrity":{"algorithm":"SHA256","hash":"d4a832347a07a4df9b32a010fc5ffb1c4447c51769423cd5a3a47da0213fe5c0","blockSize":4194304,"blocks":["d4a832347a07a4df9b32a010fc5ffb1c4447c51769423cd5a3a47da0213fe5c0"]}},"license":{"size":1109,"offset":"2185930","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":641,"offset":"2187039","integrity":{"algorithm":"SHA256","hash":"71fa24afc41e43246126eaef9f0c4dd7a94047e8a67456d02c9b56924dbf0969","blockSize":4194304,"blocks":["71fa24afc41e43246126eaef9f0c4dd7a94047e8a67456d02c9b56924dbf0969"]}},"readme.md":{"size":2205,"offset":"2187680","integrity":{"algorithm":"SHA256","hash":"34bd638efee6163692ed1b27e47a1783488f6e20dbfa88e6546431723191952d","blockSize":4194304,"blocks":["34bd638efee6163692ed1b27e47a1783488f6e20dbfa88e6546431723191952d"]}}}},"onetime":{"files":{"index.js":{"size":1120,"offset":"2189885","integrity":{"algorithm":"SHA256","hash":"59a0b25379fff19195343d47759339397c689e8ab93270adcab2d106a80e1625","blockSize":4194304,"blocks":["59a0b25379fff19195343d47759339397c689e8ab93270adcab2d106a80e1625"]}},"license":{"size":1117,"offset":"2191005","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"node_modules":{"files":{"mimic-fn":{"files":{"index.js":{"size":300,"offset":"2192122","integrity":{"algorithm":"SHA256","hash":"9ca2b409cdf1718ce957292dc479c83516e4ea369f4b2cb3510066d4e50074e2","blockSize":4194304,"blocks":["9ca2b409cdf1718ce957292dc479c83516e4ea369f4b2cb3510066d4e50074e2"]}},"license":{"size":1109,"offset":"2192422","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":641,"offset":"2193531","integrity":{"algorithm":"SHA256","hash":"4601a9fd2b6cdcc0ee3220f2544523bea4366099ac356ca6a6d2fb73b5d4fef6","blockSize":4194304,"blocks":["4601a9fd2b6cdcc0ee3220f2544523bea4366099ac356ca6a6d2fb73b5d4fef6"]}},"readme.md":{"size":1196,"offset":"2194172","integrity":{"algorithm":"SHA256","hash":"4bd571e682d96c3915f33f19c0ba15879879f1dac5a91ac1079d7b6b9aa53c8a","blockSize":4194304,"blocks":["4bd571e682d96c3915f33f19c0ba15879879f1dac5a91ac1079d7b6b9aa53c8a"]}}}}}},"package.json":{"size":715,"offset":"2195368","integrity":{"algorithm":"SHA256","hash":"2ccc81d28d7d13e2868eaf69e8e7fcdac6a4ae912235707cbdaef321385344b7","blockSize":4194304,"blocks":["2ccc81d28d7d13e2868eaf69e8e7fcdac6a4ae912235707cbdaef321385344b7"]}},"readme.md":{"size":1962,"offset":"2196083","integrity":{"algorithm":"SHA256","hash":"ff63f66c164b2869e1963865c4f77875fa26f47e8ace82691e1e81b053c0e07a","blockSize":4194304,"blocks":["ff63f66c164b2869e1963865c4f77875fa26f47e8ace82691e1e81b053c0e07a"]}}}},"p-limit":{"files":{"index.js":{"size":1521,"offset":"2198045","integrity":{"algorithm":"SHA256","hash":"ec25b742450df200d287bd9790451e203e2a99066f615b43f034e731afa0697f","blockSize":4194304,"blocks":["ec25b742450df200d287bd9790451e203e2a99066f615b43f034e731afa0697f"]}},"license":{"size":1117,"offset":"2199566","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":928,"offset":"2200683","integrity":{"algorithm":"SHA256","hash":"0de84d3e2ad5bc3a7bac54354fe6f049ce7b351d67fcc57eda6660f9fa2e83b5","blockSize":4194304,"blocks":["0de84d3e2ad5bc3a7bac54354fe6f049ce7b351d67fcc57eda6660f9fa2e83b5"]}},"readme.md":{"size":2770,"offset":"2201611","integrity":{"algorithm":"SHA256","hash":"20c5386b5a6d769b0d0a54652870dea0f004b2588239bd731fca53721d674291","blockSize":4194304,"blocks":["20c5386b5a6d769b0d0a54652870dea0f004b2588239bd731fca53721d674291"]}}}},"p-locate":{"files":{"index.js":{"size":1042,"offset":"2204381","integrity":{"algorithm":"SHA256","hash":"8e5e49ae61d019cf6f74e59e114190fc06bafa85c2084d1731b3ccbeb445e572","blockSize":4194304,"blocks":["8e5e49ae61d019cf6f74e59e114190fc06bafa85c2084d1731b3ccbeb445e572"]}},"license":{"size":1109,"offset":"2205423","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"node_modules":{"files":{"p-limit":{"files":{"index.js":{"size":1114,"offset":"2206532","integrity":{"algorithm":"SHA256","hash":"b005ce7e192e136df67e3b724bfc156c396ac46928c79508d6fd532bef98cbec","blockSize":4194304,"blocks":["b005ce7e192e136df67e3b724bfc156c396ac46928c79508d6fd532bef98cbec"]}},"license":{"size":1109,"offset":"2207646","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":924,"offset":"2208755","integrity":{"algorithm":"SHA256","hash":"d4529e88d06488042103f25322b0b60d90dfc5de0ed61c3b7c7d27f2ac3fe1bb","blockSize":4194304,"blocks":["d4529e88d06488042103f25322b0b60d90dfc5de0ed61c3b7c7d27f2ac3fe1bb"]}},"readme.md":{"size":2894,"offset":"2209679","integrity":{"algorithm":"SHA256","hash":"f33a3fea32927b4a53e8a07ccff4e6722c5e1e8c4c44175f266a914816d88903","blockSize":4194304,"blocks":["f33a3fea32927b4a53e8a07ccff4e6722c5e1e8c4c44175f266a914816d88903"]}}}}}},"package.json":{"size":823,"offset":"2212573","integrity":{"algorithm":"SHA256","hash":"e319842e7dae3cf6a281799f69d1b1cbb11cb98a92a02e7a2bac27d9d6f31570","blockSize":4194304,"blocks":["e319842e7dae3cf6a281799f69d1b1cbb11cb98a92a02e7a2bac27d9d6f31570"]}},"readme.md":{"size":2081,"offset":"2213396","integrity":{"algorithm":"SHA256","hash":"5478269bf3241e8ac647fdb50a0bf9e4c9a84e7cd81cb468afb1af8d6355d52d","blockSize":4194304,"blocks":["5478269bf3241e8ac647fdb50a0bf9e4c9a84e7cd81cb468afb1af8d6355d52d"]}}}},"path-exists":{"files":{"index.js":{"size":252,"offset":"2215477","integrity":{"algorithm":"SHA256","hash":"2557a5378ea2cab729e51b6fce5da24c782940d219a6bd6ade069190e919894f","blockSize":4194304,"blocks":["2557a5378ea2cab729e51b6fce5da24c782940d219a6bd6ade069190e919894f"]}},"license":{"size":1119,"offset":"2215729","integrity":{"algorithm":"SHA256","hash":"6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c","blockSize":4194304,"blocks":["6fb9754611c20f6649f68805e8c990e83261f29316e29de9e6cedae607b8634c"]}},"package.json":{"size":641,"offset":"2216848","integrity":{"algorithm":"SHA256","hash":"1df6a195380a8d52cff58f4b13a9ff57d3f96aee725d7d69819b44c9e056fd9a","blockSize":4194304,"blocks":["1df6a195380a8d52cff58f4b13a9ff57d3f96aee725d7d69819b44c9e056fd9a"]}},"readme.md":{"size":1304,"offset":"2217489","integrity":{"algorithm":"SHA256","hash":"36f7a7e9eb9d8c462c5ccdf3f2f7dc2e3307a960c0f1b08b2f5b66fb124b48b0","blockSize":4194304,"blocks":["36f7a7e9eb9d8c462c5ccdf3f2f7dc2e3307a960c0f1b08b2f5b66fb124b48b0"]}}}},"pkg-up":{"files":{"index.js":{"size":194,"offset":"2218793","integrity":{"algorithm":"SHA256","hash":"424a480322b22b7315bddab07ef565f450f6f63b5ab920d853237b986d419df2","blockSize":4194304,"blocks":["424a480322b22b7315bddab07ef565f450f6f63b5ab920d853237b986d419df2"]}},"license":{"size":1109,"offset":"2218987","integrity":{"algorithm":"SHA256","hash":"48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0","blockSize":4194304,"blocks":["48da2f39e100d4085767e94966b43f4fa95ff6a0698fba57ed460914e35f94a0"]}},"package.json":{"size":762,"offset":"2220096","integrity":{"algorithm":"SHA256","hash":"dc9df43a568637b6bb93feadf9aeee769fe24f183481d2259c47953c55464645","blockSize":4194304,"blocks":["dc9df43a568637b6bb93feadf9aeee769fe24f183481d2259c47953c55464645"]}},"readme.md":{"size":1271,"offset":"2220858","integrity":{"algorithm":"SHA256","hash":"2f81a8fff9a5449eb953477f2a4104480aeedf30dca450ebbcb31519b0271a6f","blockSize":4194304,"blocks":["2f81a8fff9a5449eb953477f2a4104480aeedf30dca450ebbcb31519b0271a6f"]}}}},"semver":{"files":{"LICENSE":{"size":765,"offset":"2222129","integrity":{"algorithm":"SHA256","hash":"4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b","blockSize":4194304,"blocks":["4ec3d4c66cd87f5c8d8ad911b10f99bf27cb00cdfcff82621956e379186b016b"]}},"README.md":{"size":16974,"offset":"2222894","integrity":{"algorithm":"SHA256","hash":"c7d817091c6747e4f4fb7006bf60bd2040fd955ab7c37520f834c2af265876c6","blockSize":4194304,"blocks":["c7d817091c6747e4f4fb7006bf60bd2040fd955ab7c37520f834c2af265876c6"]}},"bin":{"files":{"semver.js":{"size":4717,"offset":"2239868","executable":true,"integrity":{"algorithm":"SHA256","hash":"a3ed56435cbd4b3f07a80c4a343edd86d787f89bf2cee0105bdf68cb653ba2a0","blockSize":4194304,"blocks":["a3ed56435cbd4b3f07a80c4a343edd86d787f89bf2cee0105bdf68cb653ba2a0"]}}}},"package.json":{"size":981,"offset":"2244585","integrity":{"algorithm":"SHA256","hash":"aa906c5bf8a2fa68683cae07d18553ae2538ed0d5a567911980b2ef25ee8b9ba","blockSize":4194304,"blocks":["aa906c5bf8a2fa68683cae07d18553ae2538ed0d5a567911980b2ef25ee8b9ba"]}},"range.bnf":{"size":619,"offset":"2245566","integrity":{"algorithm":"SHA256","hash":"ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a","blockSize":4194304,"blocks":["ed628fdaff64be366d07f6cc4559eae4de109826f743ea7f5e1588c370bca49a"]}},"semver.js":{"size":44287,"offset":"2246185","integrity":{"algorithm":"SHA256","hash":"d89ed53251e85463bf4300ae9a3e258dc75eb73eb2820d524bd05f4451bed3d4","blockSize":4194304,"blocks":["d89ed53251e85463bf4300ae9a3e258dc75eb73eb2820d524bd05f4451bed3d4"]}}}},"type-fest":{"files":{"package.json":{"size":1134,"offset":"2290472","integrity":{"algorithm":"SHA256","hash":"253bf6cd34d58314361fcda6d7eeaa12974cbf4f251e3171e0fb9ffccb1b07f4","blockSize":4194304,"blocks":["253bf6cd34d58314361fcda6d7eeaa12974cbf4f251e3171e0fb9ffccb1b07f4"]}},"readme.md":{"size":43433,"offset":"2291606","integrity":{"algorithm":"SHA256","hash":"15b3ed208ed59be2601610ceb50b906914766bb681632980af727d960f882cf3","blockSize":4194304,"blocks":["15b3ed208ed59be2601610ceb50b906914766bb681632980af727d960f882cf3"]}},"source":{"files":{}}}},"yocto-queue":{"files":{"index.js":{"size":949,"offset":"2335039","integrity":{"algorithm":"SHA256","hash":"03423d2c5abaa4c0c64eac47cc67f29cb7c7ed716393aad5b10ccfd27e947949","blockSize":4194304,"blocks":["03423d2c5abaa4c0c64eac47cc67f29cb7c7ed716393aad5b10ccfd27e947949"]}},"license":{"size":1117,"offset":"2335988","integrity":{"algorithm":"SHA256","hash":"5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3","blockSize":4194304,"blocks":["5c932d88256b4ab958f64a856fa48e8bd1f55bc1d96b8149c65689e0c61789d3"]}},"package.json":{"size":725,"offset":"2337105","integrity":{"algorithm":"SHA256","hash":"e94d571d03c65c94eab2216f4fde773918a152d5d36e5672e1f5c158ff6ac42d","blockSize":4194304,"blocks":["e94d571d03c65c94eab2216f4fde773918a152d5d36e5672e1f5c158ff6ac42d"]}},"readme.md":{"size":2096,"offset":"2337830","integrity":{"algorithm":"SHA256","hash":"adf5a71d52fc4fabb51c09aa67d58f8f61baa138c6d0705b1a805958f0c584a5","blockSize":4194304,"blocks":["adf5a71d52fc4fabb51c09aa67d58f8f61baa138c6d0705b1a805958f0c584a5"]}}}}}},"package.json":{"size":1706,"offset":"2339926","integrity":{"algorithm":"SHA256","hash":"bdb3dcc010713e99a34b5fa421619d4d1ecb71776e99e64999143454134ab68f","blockSize":4194304,"blocks":["bdb3dcc010713e99a34b5fa421619d4d1ecb71776e99e64999143454134ab68f"]}}}} "use strict";const i=require("electron"),q=require("path"),u=require("fs"),F=require("https"),O=require("child_process"),xe=require("os"),Fe=require("electron-store"),Ye=require("crypto"),ve=require("net");function Ke(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const A=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,A.get?A:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const de=Ke(xe);function Ue(){const a=process.platform,e=a==="win32",t=a==="linux";return{os:a,isWindows:e,isLinux:t,useNativeTitlebar:t,gpuBackend:e?"angle":"default"}}function Ne(a,e,t){t.fpsUnlocked&&(i.app.commandLine.appendSwitch("disable-frame-rate-limit"),i.app.commandLine.appendSwitch("disable-gpu-vsync"),i.app.commandLine.appendSwitch("max-gum-fps","9999"),i.app.commandLine.appendSwitch("enable-features","ImplLatencyRecovery,MainLatencyRecovery")),i.app.commandLine.appendSwitch("disable-backgrounding-occluded-windows"),i.app.commandLine.appendSwitch("disable-threaded-scrolling"),i.app.commandLine.appendSwitch("overscroll-history-navigation","0"),i.app.commandLine.appendSwitch("pull-to-refresh","0"),i.app.commandLine.appendSwitch("ignore-gpu-blocklist"),e.angleBackend&&e.angleBackend!=="default"?i.app.commandLine.appendSwitch("use-angle",e.angleBackend):a.isWindows&&i.app.commandLine.appendSwitch("use-angle","d3d11"),a.isWindows&&i.app.commandLine.appendSwitch("disable-features","CalculateNativeWinOcclusion,HardwareMediaKeyHandling"),a.isLinux&&(i.app.commandLine.appendSwitch("ozone-platform-hint","auto"),i.app.commandLine.appendSwitch("disable-gpu-sandbox")),e.removeUselessFeatures&&(i.app.commandLine.appendSwitch("disable-breakpad"),i.app.commandLine.appendSwitch("disable-crash-reporter"),i.app.commandLine.appendSwitch("disable-crashpad-forwarding"),i.app.commandLine.appendSwitch("disable-print-preview"),i.app.commandLine.appendSwitch("disable-metrics-reporting"),i.app.commandLine.appendSwitch("disable-metrics"),i.app.commandLine.appendSwitch("disable-2d-canvas-clip-aa"),i.app.commandLine.appendSwitch("disable-logging"),i.app.commandLine.appendSwitch("disable-hang-monitor"),i.app.commandLine.appendSwitch("disable-component-update"),i.app.commandLine.appendSwitch("disable-bundled-ppapi-flash"),i.app.commandLine.appendSwitch("disable-nacl"),i.app.commandLine.appendSwitch("disable-features","NativeNotifications,MediaRouter,PerformanceInterventionUI,HappinessTrackingSurveysForDesktopDemo")),e.gpuRasterizing&&(i.app.commandLine.appendSwitch("enable-gpu-rasterization"),i.app.commandLine.appendSwitch("disable-zero-copy"),i.app.commandLine.appendSwitch("disable-software-rasterizer"),i.app.commandLine.appendSwitch("disable-gpu-driver-bug-workarounds")),e.helpfulFlags&&(i.app.commandLine.appendSwitch("enable-javascript-harmony"),i.app.commandLine.appendSwitch("enable-future-v8-vm-features"),i.app.commandLine.appendSwitch("enable-webgl"),i.app.commandLine.appendSwitch("disable-background-timer-throttling"),i.app.commandLine.appendSwitch("disable-renderer-backgrounding"),i.app.commandLine.appendSwitch("disable-best-effort-tasks"),i.app.commandLine.appendSwitch("autoplay-policy","no-user-gesture-required"),i.app.commandLine.appendSwitch("enable-features","V8VmFuture,WebAssemblyBaseline,WebAssemblyTiering,WebAssemblyLazyCompilation")),e.increaseLimits&&(i.app.commandLine.appendSwitch("renderer-process-limit","100"),i.app.commandLine.appendSwitch("max-active-webgl-contexts","100"),i.app.commandLine.appendSwitch("webrtc-max-cpu-consumption-percentage","100"),i.app.commandLine.appendSwitch("ignore-gpu-blocklist")),e.lowLatency&&(i.app.commandLine.appendSwitch("force-high-performance-gpu"),i.app.commandLine.appendSwitch("enable-quic"),i.app.commandLine.appendSwitch("quic-max-packet-length","1460"),i.app.commandLine.appendSwitch("raise-timer-frequency")),e.experimentalFlags&&(i.app.commandLine.appendSwitch("disable-low-end-device-mode"),i.app.commandLine.appendSwitch("disable-gpu-watchdog"),i.app.commandLine.appendSwitch("ignore-gpu-blocklist"),i.app.commandLine.appendSwitch("no-pings"),i.app.commandLine.appendSwitch("no-proxy-server"),i.app.commandLine.appendSwitch("enable-features","BlinkCompositorUseDisplayThreadPriority,GpuUseDisplayThreadPriority"))}const Qe={reload:{key:"F5",ctrl:!1,shift:!1,alt:!1},newMatch:{key:"F4",ctrl:!1,shift:!1,alt:!1},copyGameLink:{key:"l",ctrl:!0,shift:!1,alt:!1},joinFromClipboard:{key:"j",ctrl:!0,shift:!1,alt:!1},devTools:{key:"F12",ctrl:!1,shift:!1,alt:!1},matchmaker:{key:"F6",ctrl:!1,shift:!1,alt:!1},matchmakerCancel:{key:"Escape",ctrl:!1,shift:!1,alt:!1},fullscreenToggle:{key:"F11",ctrl:!1,shift:!1,alt:!1}},f=new Fe({name:"krunker-civilian-config",defaults:{window:{width:1600,height:900,x:void 0,y:void 0,maximized:!1,fullscreen:!1},performance:{fpsUnlocked:!0,hardwareAccel:!0,gpuPreference:"high-performance",cpuThrottleGame:1,cpuThrottleMenu:1.5,processPriority:"Normal"},game:{lastServer:"",socialTabBehaviour:"New Window",rememberTabs:!1,joinAsSpectator:!1,rawInput:!0,betterChat:!0,chatHistorySize:200,showPing:!0,hpEnemyCounter:!0},swapper:{enabled:!1,path:""},matchmaker:{enabled:!0,regions:[],gamemodes:[],maps:[],minPlayers:1,maxPlayers:6,minRemainingTime:120,openServerBrowser:!0,sortByPlayers:!1},keybinds:Qe,userscripts:{enabled:!1,path:""},ui:{showExitButton:!0,deathscreenAnimation:!0,hideMenuPopups:!1,menuTimer:!0,doublePing:!0,cssTheme:"disabled",loadingTheme:"disabled",backgroundUrl:"",showChangelog:!0,lastSeenVersion:""},discord:{enabled:!0},translator:{enabled:!0,targetLanguage:"en",showLanguageTag:!0},advanced:{removeUselessFeatures:!0,gpuRasterizing:!1,helpfulFlags:!0,increaseLimits:!1,lowLatency:!1,experimentalFlags:!1,angleBackend:"default",verboseLogging:!1},accounts:[],tabWindow:{width:1280,height:720,x:void 0,y:void 0,maximized:!0},savedTabs:[]}}),J="kpc-swap",Re="krunker.io";function Le(a){const e=a.replace(/\\/g,"/"),t=e.match(/^([A-Za-z]):\/(.*)/);return t?`${J}://${t[1]}/${t[2]}`:`${J}://${e}`}function He(){i.protocol.registerSchemesAsPrivileged([{scheme:J,privileges:{standard:!0,secure:!0,corsEnabled:!0,bypassCSP:!0}}])}function Pe(a){a.protocol.handle(J,async e=>{const t=new URL(e.url);let A;t.hostname?A=`${t.hostname}:${t.pathname}`:A=t.pathname;try{return await i.net.fetch(`file://${A}`)}catch{return new Response("Not found",{status:404})}})}class Oe{swapDir;swapFiles=new Map;ready=!1;scanPromise;constructor(e){this.swapDir=e,u.existsSync(this.swapDir)||u.mkdirSync(this.swapDir,{recursive:!0}),this.scanPromise=this.scanAsync("")}async waitForReady(){await this.scanPromise,this.ready=!0}async rescan(){this.swapFiles.clear(),await this.scanAsync(""),this.ready=!0}get patterns(){return this.swapFiles.size>0?[`*://*.${Re}/*`]:[]}getRedirect(e){if(!this.ready)return null;try{const t=e.indexOf("//");if(t===-1)return null;const A=e.indexOf("/",t+2);if(A===-1)return null;const o=e.indexOf("?",A);let r=o===-1?e.substring(A):e.substring(A,o);r.startsWith("/assets/")&&(r=r.substring(7));const d=this.swapFiles.get(r);if(d)return Le(d)}catch{}return null}async scanAsync(e){try{const t=await u.promises.readdir(q.join(this.swapDir,e),{withFileTypes:!0});for(const A of t){const o=`${e}/${A.name}`;A.isDirectory()?await this.scanAsync(o):this.swapFiles.set(o,q.join(this.swapDir,o))}}catch{console.error(`Failed to scan swap directory prefix: ${e}`)}}}class Je{scriptsDir;prefsDir;trackerPath;constructor(e){this.scriptsDir=q.join(e,"scripts"),this.prefsDir=q.join(this.scriptsDir,"preferences"),this.trackerPath=q.join(this.scriptsDir,"tracker.json"),u.mkdirSync(this.scriptsDir,{recursive:!0}),u.mkdirSync(this.prefsDir,{recursive:!0})}get dir(){return this.scriptsDir}async scanScripts(){const e=[];try{for(const t of await u.promises.readdir(this.scriptsDir,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(".js"))continue;const A=q.join(this.scriptsDir,t.name);try{const o=await u.promises.readFile(A,"utf-8");e.push({filename:t.name,content:o,fullpath:A})}catch{}}}catch{}return e}async loadTracker(e){let t;try{t=JSON.parse(await u.promises.readFile(this.trackerPath,"utf-8"))}catch{t={}}const A=new Set(e.map(r=>r.filename));let o=!1;for(const r of A)r in t||(t[r]=!1,o=!0);for(const r of Object.keys(t))A.has(r)||(delete t[r],o=!0);return o&&await this.saveTracker(t),t}async saveTracker(e){try{await u.promises.writeFile(this.trackerPath,JSON.stringify(e,null,2),"utf-8")}catch{}}async loadScriptPrefs(e){const t=q.parse(e).name,A=q.join(this.prefsDir,t+".json");try{return JSON.parse(await u.promises.readFile(A,"utf-8"))}catch{}return{}}async saveScriptPrefs(e,t){const A=q.parse(e).name,o=q.join(this.prefsDir,A+".json");try{await u.promises.writeFile(o,JSON.stringify(t,null,2),"utf-8")}catch{}}}const be=`
:root {
  /* ── Surfaces ── */
  --kpc-surface-card: rgba(255,255,255,0.04);
  --kpc-surface-input: rgba(255,255,255,0.08);
  --kpc-surface-hover: rgba(255,255,255,0.1);
  --kpc-surface-hover-strong: rgba(255,255,255,0.15);
  --kpc-surface-dialog: #1a1a1a;
  --kpc-surface-raised: #212121;

  /* ── Text ── */
  --kpc-text-primary: rgba(255,255,255,0.9);
  --kpc-text-secondary: rgba(255,255,255,0.7);
  --kpc-text-muted: rgba(255,255,255,0.5);
  --kpc-text-faint: rgba(255,255,255,0.35);
  --kpc-text-dim: rgba(255,255,255,0.3);
  --kpc-text-info: #888;

  /* ── Borders ── */
  --kpc-border-subtle: rgba(255,255,255,0.06);
  --kpc-border-default: rgba(255,255,255,0.1);
  --kpc-border-medium: rgba(255,255,255,0.15);
  --kpc-border-focus: rgba(255,255,255,0.35);

  /* ── Accents ── */
  --kpc-green: #4CAF50;
  --kpc-green-hover: #66bb6a;
  --kpc-red: #ef5350;
  --kpc-red-hover: #e57373;
  --kpc-blue: #42a5f5;
  --kpc-blue-hover: #64b5f6;
  --kpc-orange: #ff9800;
  --kpc-orange-hover: #ffb74d;
  --kpc-yellow: #ffc107;
  --kpc-magenta: #fc03ec;

  /* ── Controls ── */
  --kpc-toggle-off: rgba(255,255,255,0.12);

  /* ── Z-index layers ── */
  --kpc-z-notification: 100000;
  --kpc-z-overlay: 10000000;
  --kpc-z-popup: 10000001;
}
`,We=`
${be}
/* ── Crankshaft-style settings (Krunker-native classes) ── */

.kpc-settings .settName,
.kpc-settings .settName .setting-title {
	color: rgba(255,255,255,.6) !important;
}

.kpc-settings .settName {
	display: grid;
	grid-auto-columns: 1fr;
	grid-template-columns: 0fr 1fr 0fr;
	grid-template-areas:
	"icon title input"
	"desc desc desc";
	grid-template-rows: 0fr min-content;
	align-items: center;
}
.kpc-settings .settName.multisel {
	grid-template-rows: min-content 1fr;
	grid-template-columns: 0fr 1fr;
	grid-template-areas:
	"icon title"
	"input input";
}
.kpc-settings .settName.has-button {
	grid-template-areas:
	"icon title button input"
	"desc desc desc desc";
	grid-template-columns: 0fr 1fr min-content 0fr;
}
.kpc-settings .settName.has-button .settingsBtn {
	grid-area: button;
	margin: 0 .5rem;
}

.kpc-settings .settName.kpc-button-holder {
	grid-template-columns: 1fr;
	grid-auto-columns: min-content;
	column-gap: 0.25rem;
	grid-template-areas: unset;
	grid-template-rows: 0fr;
	grid-auto-flow: column;
}
.kpc-settings .kpc-button-holder .buttons-title, .material-icons { color: inherit; }
.kpc-settings .kpc-button-holder .settingsBtn,
.kpc-settings .settName.has-button .settingsBtn {
	width: max-content;
}

/* type: num */
.kpc-settings .settName.num .setting-input-wrapper {
	display: flex;
}
.kpc-settings .settName.num .setting-input-wrapper .slidecontainer {
	margin-top: -8px;
}

/* type: multisel */
.kpc-multisel-parent {
	display: grid;
	grid-template-columns: repeat(5, 1fr);
	grid-auto-rows: 1fr;
	gap: .25rem;
	background: #232323;
	border-radius: 10px;
	margin-top: 0.8rem;
}
.kpc-multisel-parent label.hostOpt {
	width: 100%;
	margin: 0;
	box-sizing: border-box;
}

.kpc-settings .settName.multisel label {
	font-size: 1.1rem;
}
.kpc-settings .settName.multisel input {
	margin-left: .25rem;
}

/* general settings */
.kpc-settings .settName .setting-title {
	grid-area: title;
}

.kpc-settings .settName .s-update:disabled,
.kpc-settings .settName .s-update:disabled+.slider.round {
	opacity: 0.5;
	pointer-events: none;
}

.kpc-settings .setting .switch {
	box-sizing: border-box;
}

.kpc-settings .setting .desc-icon {
	grid-area: icon;
	cursor: pointer;
	font-size: 1rem;
	width: 2.2rem;
	height: 2.2rem;
	line-height: 2.2rem;
	border-radius: 5px !important;
	color: #969696;
	background-color: rgba(99, 99, 99, 0.16);
	border: 2px solid rgba(78, 78, 78, 0.81);
	margin-right: 10px;
	display: flex;
	justify-content: center;
	align-items: center;
}

.kpc-settings .setting .desc-icon.instant {
	background-color: rgba(1, 89, 220, 0.16);
	border: 2px solid rgba(3, 133, 255, 0.81);
}

.kpc-settings .setting .desc-icon.instant svg path {
	color: #0385ff;
	fill: currentColor;
}

.kpc-settings .setting.settName .inputGrey2,
.kpc-settings .setting.settName .switch,
.kpc-settings .setting.settName .kpc-multisel-parent,
.kpc-settings .setting.settName .setting-input-wrapper,
.kpc-settings .setting.settName .keyIcon {
	grid-area: input;
}

.kpc-settings .setting.safety-1 .desc-icon,
.kpc-settings .setting .desc-icon.refresh-icon,
.kpc-settings .setting .desc-icon.restart-icon {
	background-color: rgba(99, 99, 99, 0.16);
	border: 2px solid rgba(78, 78, 78, 0.81);
}

.kpc-settings .setting.safety-1 .desc-icon svg path,
.kpc-settings .setting .desc-icon.refresh-icon svg path,
.kpc-settings .setting .desc-icon.restart-icon svg path {
	color: #969696;
	fill: currentColor;
}

.kpc-settings .setting.safety-2 .desc-icon {
	background-color: rgba(220, 180, 1, 0.16);
	border: 2px solid rgba(241, 186, 6, 0.81);
}

.kpc-settings .setting.safety-2 .desc-icon svg path {
	color: #ffd903;
	fill: currentColor;
}

.kpc-settings .setting.safety-3 .desc-icon {
	background-color: rgba(220, 118, 1, 0.16);
	border: 2px solid rgba(241, 131, 6, 0.81);
}

.kpc-settings .setting.safety-3 .desc-icon svg path {
	color: #ff9203;
	fill: currentColor;
}

.kpc-settings .setting.safety-4 .desc-icon {
	background-color: rgba(220, 17, 1, 0.16);
	border: 2px solid rgba(239, 6, 6, 0.81);
}

.kpc-settings .setting.safety-4 .desc-icon svg path {
	color: #ff0303;
	fill: currentColor;
}

.desc-icon {
	position: relative;
}

.setting-desc-new {
	display: block;
	width: fit-content;
	max-width: 50ch;
	line-height: 30px;
	font-size: 15px;
	letter-spacing: 0.5px;
	word-wrap: break-word;
	color: rgba(255, 255, 255, 0.4) !important;
	overflow: hidden;
	max-height: 500px;
	margin-top: 6px;
	grid-area: desc;
}

.setting-desc-new a {
	font-size: inherit !important;
	font-family: inherit !important;
}

.setting-category-collapsed {
	display: none;
}

/* keybind display */
.keyIcon.kpc-keyIcon:hover {
	transform: scale(1.25);
	cursor: pointer;
}

.keyIcon.kpc-keyIcon {
	display: inline-block;
	transition: 0s;
}

/* ── KPC action button grid ── */
.kpc-action-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  padding: 0 12px 12px;
}
.kpc-action-btn {
  background: var(--kpc-surface-card);
  color: var(--kpc-text-primary);
  border: 2px solid var(--kpc-border-medium);
  padding: 10px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  text-align: center;
  transition: background 0.15s, border-color 0.15s;
  user-select: none;
}
.kpc-action-btn:hover {
  background: var(--kpc-surface-hover);
  border-color: var(--kpc-border-focus);
}
.kpc-action-btn:active {
  transform: scale(0.97);
}
.kpc-action-btn.full {
  grid-column: 1 / -1;
}
.kpc-action-btn.kpc-ab-purple { border-color: #ab47bc; }
.kpc-action-btn.kpc-ab-purple:hover { border-color: #ce93d8; }
.kpc-action-btn.kpc-ab-cyan { border-color: #00bcd4; }
.kpc-action-btn.kpc-ab-cyan:hover { border-color: #4dd0e1; }
.kpc-action-btn.kpc-ab-pink { border-color: #ec407a; }
.kpc-action-btn.kpc-ab-pink:hover { border-color: #f48fb1; }
.kpc-action-btn.kpc-ab-red { border-color: var(--kpc-red); }
.kpc-action-btn.kpc-ab-red:hover { border-color: var(--kpc-red-hover); }
.kpc-action-btn.kpc-ab-orange { border-color: var(--kpc-orange); }
.kpc-action-btn.kpc-ab-orange:hover { border-color: var(--kpc-orange-hover); }

/* floating toasts css that is required */
.kpc-holder-update {
	position: absolute;
	font-size: 1.125rem !important;
	color: rgba(255, 255, 255, 0.7);
	display: block !important;
	top: 20px;
	left: 20px;
	background-color: black;
	padding: 1rem;
	border-radius: 0.5rem;
	width: max-content;
	z-index: 10;
}

/* settings refresh popup */
.refresh-popup {
	height: min-content;
	left: 50%;
	transform: translateX(-50%);
	color: rgba(255,255,255,0.6)
}
.refresh-popup span {
	display: flex;
	align-items: center;
	column-gap: 0.5rem;
	color: rgba(255,255,255,0.6);
}
.refresh-popup,
.refresh-popup span,
.refresh-popup a {
	vertical-align: middle;
	font-size: .8rem;
	line-height: .8rem;
	z-index: 12;
}
.refresh-popup svg { fill: rgba(255,255,255,0.6); }
.refresh-popup code {
    color: white;
    font-size: 1.2rem;
    line-height: 1.2rem;
	font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', Menlo, Consolas, 'DejaVu Sans Mono', monospace;
    background-color: #232323;
    padding: 0.08rem 0.4rem;
    border-radius: 3px;
    border: 2px solid #333333
}
/* ── Keybind capture dialog ── */
.kpc-keybind-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: var(--kpc-z-overlay);
  background: rgba(0,0,0,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}
.kpc-keybind-dialog {
  background: var(--kpc-surface-dialog);
  border: 1px solid var(--kpc-border-medium);
  border-radius: 10px;
  padding: 24px 32px;
  min-width: 400px;
  position: relative;
}
.kpc-keybind-dialog-title {
  color: var(--kpc-text-primary);
  font-size: 18px;
  margin-bottom: 6px;
}
.kpc-keybind-dialog-sub {
  color: var(--kpc-text-muted);
  font-size: 13px;
  margin-bottom: 16px;
}
.kpc-keybind-dialog-sub code {
  color: #64b5f6;
}
.kpc-keybind-dialog-modifiers {
  display: flex;
  gap: 8px;
  font-size: 14px;
}
.kpc-keybind-modifier {
  background: var(--kpc-surface-raised);
  color: var(--kpc-text-faint);
  flex: 1;
  text-align: center;
  padding: 10px 0;
  border-radius: 6px;
  transition: background 0.15s, color 0.15s;
}
.kpc-keybind-modifier.active {
  background: #1976d2;
  color: #fff;
}
.kpc-keybind-dialog-cancel {
  position: absolute;
  top: 12px;
  right: 16px;
  color: #64b5f6;
  cursor: pointer;
  font-size: 14px;
}
.kpc-keybind-dialog-cancel:hover {
  text-decoration: underline;
}
/* ── Preserved: color input, userscript meta ── */
.kpc-color-input {
  width: 36px;
  height: 28px;
  border: 1px solid var(--kpc-border-default);
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  padding: 0;
  flex-shrink: 0;
}
.kpc-color-input::-webkit-color-swatch-wrapper {
  padding: 2px;
}
.kpc-color-input::-webkit-color-swatch {
  border: none;
  border-radius: 2px;
}
.kpc-us-meta {
  color: var(--kpc-text-dim);
  font-size: 11px;
  margin-top: 2px;
}
.kpc-us-settings {
  padding: 4px 0 4px 20px;
}
#chatList, #chatList * {
  user-select: text !important;
  cursor: text;
}
#chatList.kpc-chat-paused {
  border-left: 2px solid var(--kpc-yellow);
}
`,je=`
@keyframes matchmakerPopupSlideDown {
  0% { transform: translate(-50%, -500%); }
  100% { transform: translate(-50%, 0%); }
}
.onGame #matchmakerPopupContainer:not(.searching) {
  opacity: 0 !important;
}
#matchmakerPopupContainer {
  position: absolute;
  top: 10em;
  left: 50%;
  z-index: var(--kpc-z-popup);
  box-sizing: border-box;
  width: 35em;
  aspect-ratio: 2.5/1;
  border-radius: 1.2em;
  overflow: hidden;
  background-size: 100% 100%;
  pointer-events: all;
  background-color: var(--kpc-surface-raised);
  animation: matchmakerPopupSlideDown 0.5s ease forwards;
}
#matchmakerPopupTitle {
  font-size: 1.8em;
  color: white;
  padding: 0.3em 0.7em;
  background: rgba(0,0,0,0.5);
  margin-bottom: 0.3em;
}
#matchmakerPopupDescription {
  background: rgba(0,0,0,0.5);
  color: var(--kpc-yellow);
  box-sizing: border-box;
  padding: 0.6em 1em;
}
#matchmakerPopupOptions {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
}
.matchmakerPopupButton {
  text-align: center;
  border: 0.3em solid;
  box-sizing: border-box;
  margin: 0.5em;
  color: white;
  border-radius: 0.3em;
  font-size: 1.3em;
  background-color: rgba(0,0,0,0.5);
  padding: 0.2em 1.4em;
  transition: all 0.08s;
}
#matchmakerConfirmButton {
  border-color: var(--kpc-green);
  flex-grow: 1;
}
#matchmakerCancelButton {
  border-color: var(--kpc-red);
}
.matchmakerPopupButton:hover {
  cursor: pointer;
  border-color: white !important;
  transform: scale(0.95);
}
.matchmakerPopupButton:active {
  transform: scale(0.85);
}

/* ── Search phase ── */
#matchmakerPopupContainer.searching {
  background-image: none !important;
  background: var(--kpc-surface-raised);
  width: 24em;
  aspect-ratio: auto;
  padding: 1em 1.5em;
}
#matchmakerPopupContainer.searching #matchmakerPopupTitle,
#matchmakerPopupContainer.searching #matchmakerPopupDescription,
#matchmakerPopupContainer.searching #matchmakerPopupOptions {
  display: none;
}
#matchmakerPopupContainer:not(.searching) #matchmakerSearchContainer {
  display: none;
}
#matchmakerSearchStatus {
  font-size: 1.4em;
  color: var(--kpc-blue);
  margin-bottom: 0.6em;
  text-align: center;
}
#matchmakerSearchFeed {
  display: flex;
  flex-direction: column;
  gap: 0.15em;
  overflow: hidden;
  min-height: 5.6em;
  margin-bottom: 0.6em;
}
@keyframes mmFeedSlideIn {
  from { opacity: 0; transform: translateX(1em); }
  to { opacity: 1; transform: translateX(0); }
}
.mm-feed-entry {
  display: flex;
  gap: 0.8em;
  padding: 0.2em 0.5em;
  font-size: 0.95em;
  font-family: 'GameFont', monospace;
  border-radius: 0.2em;
  animation: mmFeedSlideIn 0.12s ease forwards;
}
.mm-feed-entry.mm-pass { background: rgba(76,175,80,0.1); }
.mm-feed-entry.mm-pass .mm-feed-region { color: var(--kpc-blue); }
.mm-feed-entry.mm-pass .mm-feed-map { color: var(--kpc-text-primary, rgba(255,255,255,0.9)); }
.mm-feed-entry.mm-pass .mm-feed-players { color: var(--kpc-green); }
.mm-feed-entry.mm-fail { background: rgba(255,255,255,0.02); }
.mm-feed-entry.mm-fail .mm-feed-region { color: var(--kpc-text-dim, rgba(255,255,255,0.3)); }
.mm-feed-entry.mm-fail .mm-feed-map { color: var(--kpc-text-muted, rgba(255,255,255,0.5)); }
.mm-feed-entry.mm-fail .mm-feed-players { color: var(--kpc-red); }
.mm-feed-entry:last-child::before {
  content: '\\25B8 ';
  color: var(--kpc-yellow);
}
.mm-feed-region { min-width: 2.5em; font-weight: bold; }
.mm-feed-map { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mm-feed-players { min-width: 3em; text-align: right; font-weight: 600; }
#matchmakerSearchCounter {
  font-size: 0.85em;
  color: var(--kpc-yellow);
  text-align: center;
  margin-bottom: 0.5em;
}
#matchmakerSearchCancel {
  text-align: center;
  border: 0.2em solid var(--kpc-red);
  color: white;
  border-radius: 0.3em;
  font-size: 1.1em;
  background: rgba(0,0,0,0.3);
  padding: 0.2em 1.2em;
  cursor: pointer;
  margin: 0 auto;
  width: fit-content;
  transition: all 0.08s;
}
#matchmakerSearchCancel:hover {
  border-color: white;
  transform: scale(0.95);
}
#matchmakerSearchCancel:active {
  transform: scale(0.85);
}
`,Xe=`
.kcc-translation {
  color: #88ff88;
  font-style: italic;
  margin-left: 8px;
  margin-top: 2px;
}
`,ze=`
.kpc-acc-form { display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px; }
.kpc-acc-form input {
  background: var(--kpc-surface-input); border: 1px solid var(--kpc-border); border-radius: 4px;
  color: #fff; padding: 6px 10px; font-size: 13px; outline: none; font-family: inherit;
}
.kpc-acc-form input:focus { border-color: var(--kpc-accent); }
.kpc-acc-form input::placeholder { color: rgba(255,255,255,0.3); }
.kpc-acc-form-buttons { display: flex; gap: 8px; }
.kpc-acc-form-buttons button {
  padding: 6px 16px; border: none; border-radius: 4px; cursor: pointer;
  font-size: 13px; font-family: inherit;
}
.kpc-acc-form-buttons .kpc-acc-save {
  background: var(--kpc-accent); color: #fff;
}
.kpc-acc-form-buttons .kpc-acc-save:hover { filter: brightness(1.2); }
.kpc-acc-form-buttons .kpc-acc-cancel {
  background: var(--kpc-surface-hover); color: #fff;
}
.kpc-acc-form-buttons .kpc-acc-cancel:hover { background: var(--kpc-surface-hover-strong); }
.kpc-acc-item {
  display: flex; align-items: center; justify-content: space-between;
  padding: 8px 12px; background: var(--kpc-surface-card); border-radius: 6px; margin-bottom: 6px;
}
.kpc-acc-item-info { display: flex; align-items: center; gap: 8px; }
.kpc-acc-item-label { color: #fff; font-size: 14px; font-weight: 500; }
.kpc-acc-item-role {
  font-size: 11px; padding: 2px 6px; border-radius: 3px;
  background: rgba(255,255,255,0.1); color: rgba(255,255,255,0.6);
}
.kpc-acc-item-actions { display: flex; gap: 6px; }
.kpc-acc-item-actions button {
  padding: 4px 12px; border: none; border-radius: 4px; cursor: pointer;
  font-size: 12px; font-family: inherit;
}
.kpc-acc-switch { background: var(--kpc-accent); color: #fff; }
.kpc-acc-switch:hover { filter: brightness(1.2); }
.kpc-acc-delete { background: rgba(255,80,80,0.2); color: #ff5050; }
.kpc-acc-delete:hover { background: rgba(255,80,80,0.35); }
.kpc-acc-empty { color: rgba(255,255,255,0.4); font-size: 13px; text-align: center; padding: 16px 0; }
.kpc-alt-overlay-backdrop {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 99998;
  background: rgba(0,0,0,0.5);
}
.kpc-alt-overlay {
  position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
  background: var(--kpc-surface-dialog, #1a1a1a); border-radius: 8px;
  padding: 16px; min-width: 280px; max-width: 360px; z-index: 99999;
  box-shadow: 0 8px 32px rgba(0,0,0,0.6);
}
.kpc-alt-overlay h3 {
  margin: 0 0 12px; color: #fff; font-size: 16px; font-weight: 600;
}
`,Ze=`
.kpc-hp-counter .pointVal {
  color: #ff4444; font-size: 15px; font-weight: bold;
}
`,_e=`
#claimAllBtn.disabled { opacity: 0.4; pointer-events: none; }
`,$e=`
#kpc-elo-tracker { width: 100%; margin: 8px 0; }
.kpc-elo-info-row { display: flex; align-items: center; gap: 8px; }
.kpc-rank-container { display: flex; align-items: center; gap: 4px; white-space: nowrap; font-size: 12px; color: #ccc; }
.kpc-elo-rank-img { width: 20px; height: 20px; }
.kpc-elo-bar-bg { flex: 1; height: 14px; background: rgba(255,255,255,0.1); border-radius: 7px; position: relative; overflow: hidden; }
.kpc-elo-bar-fill { height: 100%; background: linear-gradient(90deg, #388E3C, #4CAF50); border-radius: 7px; transition: width 0.3s; }
.kpc-elo-bar-text { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,0.5); }
#kpc-rank-list-btn { position: absolute; bottom: 8px; right: 8px; cursor: pointer; padding: 6px 14px; border-radius: 6px; font-size: 12px; background: rgba(76,175,80,0.3); color: #4CAF50; border: 1px solid rgba(76,175,80,0.4); z-index: 1; }
#kpc-rank-list-btn:hover { background: rgba(76,175,80,0.5); color: #fff; }
#kpc-rank-overlay { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.75); z-index: 9998; display: flex; justify-content: center; align-items: center; }
.kpc-rank-popup { background: #1a1a2e; border-radius: 12px; padding: 20px; min-width: 340px; max-width: 500px; box-shadow: 0 8px 32px rgba(0,0,0,0.6); }
.kpc-rank-popup-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.kpc-rank-popup-header h2 { margin: 0; color: #fff; font-size: 16px; }
.kpc-rank-popup-close { cursor: pointer; color: #888; font-size: 18px; padding: 4px 8px; }
.kpc-rank-popup-close:hover { color: #fff; }
.kpc-rank-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; max-height: 60vh; overflow-y: auto; }
.kpc-rank-grid-item { display: flex; align-items: center; gap: 8px; padding: 6px 10px; background: rgba(255,255,255,0.05); border-radius: 6px; }
.kpc-rank-grid-item img { width: 28px; height: 28px; }
.kpc-rank-name { font-size: 13px; font-weight: 600; }
.kpc-rank-elo { font-size: 11px; color: #888; }

/* Ranked queue button in ranked menu footer */
#kpc-ranked-queue-btn {
  background-color: #5ce05a;
  color: #fff;
  border: none;
  border-radius: 9px;
  padding: 12px 14px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s ease;
}
#kpc-ranked-queue-btn:hover { background-color: #4bc94a; }
`,Se=`${We}
${je}
${Xe}
${ze}
${Ze}
${_e}
${$e}`,et=7;let v,ne,ge=!1;function tt(){const a=new Date;return`${a.getFullYear()}-${String(a.getMonth()+1).padStart(2,"0")}-${String(a.getDate()).padStart(2,"0")}`}function At(a){try{const e=Date.now()-et*864e5;for(const t of u.readdirSync(a)){const A=t.match(/^electron-(\d{4}-\d{2}-\d{2})\.log$/);if(!A)continue;if(new Date(A[1]+"T00:00:00").getTime()<e)try{u.unlinkSync(q.join(a,t))}catch{}}}catch{}}function R(){if(ge)return;const a=q.join(i.app.getPath("userData"),"logs");u.existsSync(a)||u.mkdirSync(a,{recursive:!0}),At(a);const e=tt();ne=q.join(a,`electron-${e}.log`),v=u.createWriteStream(ne,{flags:"a"});const t=`
${"=".repeat(60)}
  Session started ${new Date().toISOString()}
${"=".repeat(60)}
`;v.write(t),ge=!0}function $(){return new Date().toISOString()}function ee(...a){return a.map(e=>{if(e instanceof Error)return`${e.message}
${e.stack}`;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(" ")}function it(a){return{log:(...e)=>{R();const t=ee(...e);console.log(t),L||a().write(`[${$()}] ${t}
`)},warn:(...e)=>{R();const t=ee(...e);console.warn(t),L||a().write(`[${$()}] WARN: ${t}
`)},error:(...e)=>{R();const t=ee(...e);console.error(t),L||a().write(`[${$()}] ERROR: ${t}
`)}}}const p=it(()=>v);function at(){return R(),ne}let L=!1;function ot(){L=!0,v&&v.end()}const he={github:{checkUrl:"https://api.github.com/repos/bigjakk/Krunker-Civilian-Client/releases/latest",allowedHosts:["github.com","githubusercontent.com"],checksumSource:"digest"},gitea:{checkUrl:"https://gitea.crjlab.net/api/v1/repos/bigjakk/Krunker-Civilian-Client-Test/releases/latest",allowedHosts:["gitea.crjlab.net"],checksumSource:"file"}},nt="gitea",H=he[nt]||he.github,te={asar:/^app\.asar$/i,setup:/Setup\.exe$/i,checksums:/^checksums\.sha256$/i},re=1e4,rt=3e5,st=`param(
    [int]$ProcessId,
    [string]$ResourcesDir,
    [string]$ExePath
)

try {
    $proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
    if ($proc) { $proc.WaitForExit(30000) | Out-Null }
} catch {}

Start-Sleep -Milliseconds 500

$asar = Join-Path $ResourcesDir "app.asar"
$pending = Join-Path $ResourcesDir "app-pending.asar"
$backup = Join-Path $ResourcesDir "app-backup.asar"

if (-not (Test-Path $pending)) { exit 1 }

try {
    if (Test-Path $backup) { Remove-Item $backup -Force }
    Rename-Item $asar $backup -Force
    Rename-Item $pending $asar -Force
    if (Test-Path $backup) { Remove-Item $backup -Force }
} catch {
    if ((Test-Path $backup) -and -not (Test-Path $asar)) {
        Rename-Item $backup $asar -Force
    }
    exit 1
}

Start-Process $ExePath
`,ct=`#!/bin/bash
PID="$1"
RESOURCES_DIR="$2"
EXE_PATH="$3"

while kill -0 "$PID" 2>/dev/null; do sleep 0.2; done
sleep 0.5

ASAR="$RESOURCES_DIR/app.asar"
PENDING="$RESOURCES_DIR/app-pending.asar"
BACKUP="$RESOURCES_DIR/app-backup.asar"

[ -f "$PENDING" ] || exit 1

rm -f "$BACKUP"
mv "$ASAR" "$BACKUP" && mv "$PENDING" "$ASAR" && rm -f "$BACKUP" || {
    [ -f "$BACKUP" ] && [ ! -f "$ASAR" ] && mv "$BACKUP" "$ASAR"
    exit 1
}

"$EXE_PATH" &
`;function W(a){try{const e=new URL(a);return H.allowedHosts.some(t=>e.hostname===t||e.hostname.endsWith("."+t))}catch{return!1}}function lt(a,e){const t=a.split(".").map(Number),A=e.split(".").map(Number),o=Math.max(t.length,A.length);for(let r=0;r<o;r++){const d=t[r]||0,g=A[r]||0;if(d<g)return!0;if(d>g)return!1}return!1}function pt(a){return new Promise((e,t)=>{function A(o,r=0){if(r>5){t(new Error("Too many redirects"));return}const d=F.get(o,{headers:{"User-Agent":"KrunkerCivilianClient"}},g=>{if(g.statusCode&&g.statusCode>=300&&g.statusCode<400&&g.headers.location){if(!W(g.headers.location)){t(new Error("Redirect to untrusted host: "+g.headers.location));return}A(g.headers.location,r+1);return}if(g.statusCode!==200){t(new Error("HTTP "+g.statusCode));return}let m="";g.on("data",C=>{m+=C}),g.on("end",()=>e(m)),g.on("error",t)});d.setTimeout(re,()=>{d.destroy(),t(new Error("Request timed out"))}),d.on("error",t)}A(a)})}async function dt(a){const e=await pt(a),t=new Map;for(const A of e.split(`
`)){const o=A.trim().match(/^([a-f0-9]{64})\s+(.+)$/i);o&&t.set(o[2].trim(),o[1].toLowerCase())}return t}function gt(a){return new Promise(e=>{p.log("[KCC-Update] Checking for updates at:",H.checkUrl),p.log("[KCC-Update] Current version:",a);const t=F.get(H.checkUrl,{headers:{"User-Agent":"KrunkerCivilianClient/"+a}},o=>{if(p.log("[KCC-Update] Check response status:",o.statusCode),o.statusCode&&o.statusCode>=300&&o.statusCode<400&&o.headers.location){const r=o.headers.location;if(p.log("[KCC-Update] Redirected to:",r),!W(r)){p.error("[KCC-Update] Redirect to untrusted host blocked:",r),e(null);return}F.get(r,{headers:{"User-Agent":"KrunkerCivilianClient/"+a}},d=>{p.log("[KCC-Update] Redirect response status:",d.statusCode),A(d)}).on("error",d=>{p.error("[KCC-Update] Redirect error:",d),e(null)});return}A(o)});async function A(o){if(o.statusCode!==200){p.error("[KCC-Update] Check returned status",o.statusCode),e(null);return}let r="";o.on("data",d=>{r+=d}),o.on("end",async()=>{try{const d=JSON.parse(r),m=(d.tag_name||"").replace(/^v/i,"");if(p.log("[KCC-Update] Latest release:",m,"| Current:",a),!m||!lt(a,m)){p.log("[KCC-Update] Already up to date"),e(null);return}const C=d.assets||[],c=C.find(D=>te.asar.test(D.name)),w=C.find(D=>te.setup.test(D.name)),B=c||w,S=c?"minor":"major";if(!B){p.error("[KCC-Update] No app.asar or Setup.exe asset found in release",m),e(null);return}if(!W(B.browser_download_url)){p.error("[KCC-Update] Download URL points to untrusted host:",B.browser_download_url),e(null);return}let I="";if(H.checksumSource==="digest"){if(I=(B.digest||"").replace(/^sha256:/i,""),!I){p.error("[KCC-Update] No SHA-256 digest found for asset"),e(null);return}}else{const D=C.find(E=>te.checksums.test(E.name));if(D)try{I=(await dt(D.browser_download_url)).get(B.name)||""}catch(E){p.error("[KCC-Update] Failed to fetch checksums:",E)}I||p.warn("[KCC-Update] No checksum available — proceeding without verification")}p.log("[KCC-Update] Update available:",m,"| Type:",S,"| SHA-256:",I?I.substring(0,16)+"...":"none"),e({version:m,updateType:S,downloadUrl:B.browser_download_url,fileSize:B.size,sha256:I})}catch(d){p.error("[KCC-Update] Failed to parse release data:",d),e(null)}}),o.on("error",d=>{p.error("[KCC-Update] Response error:",d),e(null)})}t.setTimeout(re,()=>{p.error("[KCC-Update] Check timed out after",re,"ms"),t.destroy(),e(null)}),t.on("error",o=>{p.error("[KCC-Update] Check error:",o),e(null)})})}function ht(a,e){return new Promise((t,A)=>{const o=Ye.createHash("sha256"),r=u.createReadStream(a);r.on("data",d=>o.update(d)),r.on("end",()=>{const d=o.digest("hex");p.log("[KCC-Update] SHA-256 expected:",e),p.log("[KCC-Update] SHA-256 actual:  ",d),t(d===e)}),r.on("error",A)})}function qe(a,e,t,A){return new Promise((o,r)=>{const d=e+".tmp";function g(m,C=0){if(C>5){r(new Error("Too many redirects"));return}p.log("[KCC-Update] Downloading from:",m);const c=F.get(m,{headers:{"User-Agent":"KrunkerCivilianClient"}},w=>{if(w.statusCode&&w.statusCode>=300&&w.statusCode<400&&w.headers.location){const D=w.headers.location;if(p.log("[KCC-Update] Download redirected to:",D),!W(D)){p.error("[KCC-Update] Download redirect to untrusted host blocked:",D),r(new Error("Download redirect to untrusted host: "+D));return}g(D,C+1);return}if(w.statusCode!==200){p.error("[KCC-Update] Download returned status",w.statusCode,"from:",m),r(new Error("Download returned status "+w.statusCode));return}const B=parseInt(w.headers["content-length"]||"0",10);let S=0;const I=u.createWriteStream(d);w.on("data",D=>{S+=D.length,B>0&&t(Math.round(100*S/B))}),w.pipe(I),I.on("finish",()=>{I.close(async()=>{try{if(A){if(!await ht(d,A)){p.error("[KCC-Update] Checksum mismatch — file may be corrupted or tampered");try{u.unlinkSync(d)}catch{}r(new Error("SHA-256 checksum mismatch"));return}p.log("[KCC-Update] Checksum verified")}u.existsSync(e)&&u.unlinkSync(e),u.renameSync(d,e),o()}catch(D){r(D)}})}),I.on("error",D=>{try{u.unlinkSync(d)}catch{}r(D)}),w.on("error",D=>{try{u.unlinkSync(d)}catch{}r(D)})});c.setTimeout(rt,()=>{c.destroy();try{u.unlinkSync(d)}catch{}r(new Error("Download timed out"))}),c.on("error",w=>{try{u.unlinkSync(d)}catch{}r(w)})}g(a)})}function qt(a){p.log("[KCC-Update] Launching installer:",a),O.spawn(a,[],{detached:!0,stdio:"ignore"}).unref(),i.app.quit()}function ut(a){const e=q.dirname(a),t=i.app.getPath("exe"),A=q.join(i.app.getPath("temp"),"kcc-update");if(u.existsSync(A)||u.mkdirSync(A,{recursive:!0}),p.log("[KCC-Update] Applying minor update via swap script"),p.log("[KCC-Update] Resources dir:",e),p.log("[KCC-Update] Exe path:",t),p.log("[KCC-Update] PID:",process.pid),process.platform==="win32"){const o=q.join(A,"swap-asar.ps1");u.writeFileSync(o,st),O.spawn("powershell.exe",["-ExecutionPolicy","Bypass","-File",o,"-ProcessId",String(process.pid),"-ResourcesDir",e,"-ExePath",t],{detached:!0,stdio:"ignore"}).unref()}else{const o=q.join(A,"swap-asar.sh");u.writeFileSync(o,ct,{mode:493}),O.spawn("bash",[o,String(process.pid),e,t],{detached:!0,stdio:"ignore"}).unref()}i.app.quit()}const mt=`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: #1a1a2e;
    color: #e0e0e0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    padding: 20px;
  }
  h2 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 16px;
    color: #fff;
  }
  #status {
    font-size: 13px;
    margin-bottom: 12px;
    color: #ccc;
    text-align: center;
  }
  .progress-container {
    width: 100%;
    height: 8px;
    background: #16213e;
    border-radius: 4px;
    overflow: hidden;
  }
  .progress-bar {
    height: 100%;
    width: 0%;
    background: #0f3460;
    border-radius: 4px;
    transition: width 0.3s ease;
  }
</style>
</head>
<body>
  <h2>Krunker Civilian Client</h2>
  <div id="status">Checking for updates...</div>
  <div class="progress-container">
    <div class="progress-bar" id="progressBar"></div>
  </div>
</body>
</html>`,wt="data:text/html;charset=utf-8,"+encodeURIComponent(mt);function ft(){const a=new i.BrowserWindow({width:450,height:180,resizable:!1,alwaysOnTop:!0,backgroundColor:"#1a1a2e",autoHideMenuBar:!0,title:"Krunker Civilian Client - Update",webPreferences:{nodeIntegration:!1,contextIsolation:!0,sandbox:!0}});a.removeMenu(),a.loadURL(wt);function e(t,A){a.isDestroyed()||a.webContents.executeJavaScript(`(() => {
        const s = document.getElementById('status');
        const p = document.getElementById('progressBar');
        if (s) s.textContent = ${JSON.stringify(t)};
        if (p && typeof ${JSON.stringify(A)} === 'number') p.style.width = ${JSON.stringify(A)} + '%';
      })()`).catch(()=>{})}return{window:a,sendProgress:e}}const Ct="1477679025248800982",Bt=0,Ae=1,Dt=2,ue=5e3,kt=3e4;function It(a){return process.platform==="win32"?`\\\\?\\pipe\\discord-ipc-${a}`:`${process.env.XDG_RUNTIME_DIR||process.env.TMPDIR||process.env.TMP||process.env.TEMP||"/tmp"}/discord-ipc-${a}`}function ie(a,e){const t=JSON.stringify(e),A=Buffer.from(t),o=Buffer.alloc(8);return o.writeUInt32LE(a,0),o.writeUInt32LE(A.length,4),Buffer.concat([o,A])}class Qt{socket=null;connected=!1;reconnectTimer=null;lastUpdate=0;nonce=0;destroyed=!1;recvBuf=Buffer.alloc(0);pendingActivity=null;flushTimer=null;get isConnected(){return this.connected}connect(){this.destroyed||this.tryConnect(0)}tryConnect(e){if(this.destroyed||e>9){this.scheduleReconnect();return}const t=It(e),A=new ve.Socket;let o=!1;const r=()=>{o||(o=!0,A.destroy(),this.tryConnect(e+1))};A.once("error",r),A.connect(t,()=>{if(o||this.destroyed){A.destroy();return}o=!0,this.socket=A,this.recvBuf=Buffer.alloc(0),A.removeListener("error",r),A.on("error",g=>{p.warn("[KCC-Discord] Socket error:",g.message),this.handleDisconnect()}),A.on("close",()=>{this.handleDisconnect()}),A.on("data",g=>{this.onData(g)});const d=ie(Bt,{v:1,client_id:Ct});A.write(d)}),A.setTimeout(5e3,r)}onData(e){for(this.recvBuf=Buffer.concat([this.recvBuf,e]);this.recvBuf.length>=8;){const t=this.recvBuf.readUInt32LE(0),A=this.recvBuf.readUInt32LE(4);if(this.recvBuf.length<8+A)break;const o=this.recvBuf.slice(8,8+A);this.recvBuf=this.recvBuf.slice(8+A);try{const r=JSON.parse(o.toString());this.handleMessage(t,r)}catch{}}}handleMessage(e,t){e===Ae?t.cmd==="DISPATCH"&&t.evt==="READY"&&(this.connected=!0,p.log("[KCC-Discord] Connected to Discord"),this.pendingActivity&&(this.sendActivity(this.pendingActivity),this.pendingActivity=null)):e===Dt&&(p.warn("[KCC-Discord] Discord closed connection:",t.message||""),this.handleDisconnect())}handleDisconnect(){!this.connected&&!this.socket||(this.connected=!1,this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.socket&&(this.socket.destroy(),this.socket=null),this.recvBuf=Buffer.alloc(0),p.log("[KCC-Discord] Disconnected"),this.scheduleReconnect())}scheduleReconnect(){this.destroyed||this.reconnectTimer||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.connected&&this.tryConnect(0)},kt))}setActivity(e){if(this.destroyed||(this.pendingActivity=e,!this.connected||!this.socket))return;const A=Date.now()-this.lastUpdate;if(A<ue){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=null,this.pendingActivity&&this.connected&&this.socket&&(this.sendActivity(this.pendingActivity),this.pendingActivity=null)},ue-A));return}this.sendActivity(e),this.pendingActivity=null}sendActivity(e){if(!this.socket||this.destroyed)return;this.lastUpdate=Date.now();const t={};e.details&&(t.details=e.details),e.state&&(t.state=e.state),e.startTimestamp&&(t.timestamps={start:e.startTimestamp}),e.largeImageKey&&(t.assets={large_image:e.largeImageKey,large_text:e.largeImageText||"Krunker Civilian Client"});const A=ie(Ae,{cmd:"SET_ACTIVITY",args:{pid:process.pid,activity:t},nonce:String(++this.nonce)});try{this.socket.write(A)}catch(o){p.warn("[KCC-Discord] Write error:",o.message)}}clearActivity(){if(!this.connected||!this.socket||this.destroyed)return;const e=ie(Ae,{cmd:"SET_ACTIVITY",args:{pid:process.pid,activity:null},nonce:String(++this.nonce)});try{this.socket.write(e)}catch{}}disconnect(){if(this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.socket){try{this.clearActivity()}catch{}this.socket.destroy(),this.socket=null}this.connected=!1,this.recvBuf=Buffer.alloc(0)}}function bt(a){const e=[{id:"disabled",label:"Disabled"}],t=q.join(a,"themes");try{const A=u.readdirSync(t);for(const o of A)q.extname(o).toLowerCase()===".css"&&e.push({id:`user:${o}`,label:q.basename(o,".css")})}catch{}return e}function me(a,e){if(a==="disabled"||!a)return"";const t="user:";if(!a.startsWith(t))return"";const A=q.basename(a.slice(t.length));if(!A)return"";try{return u.readFileSync(q.join(e,"themes",A),"utf-8")}catch{return""}}const Te=new Set([".png",".jpg",".jpeg",".gif",".webp"]);function St(a){const e=[{id:"disabled",label:"Disabled (Default)"},{id:"swap:random",label:"Random (from backgrounds/)"}],t=q.join(a,"backgrounds");try{const A=u.readdirSync(t);for(const o of A)Te.has(q.extname(o).toLowerCase())&&e.push({id:`swap:${o}`,label:o})}catch{}return e}function Tt(a){switch(a.toLowerCase()){case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";default:return"image/png"}}function Et(a){const e=q.join(a,"backgrounds");try{return u.readdirSync(e).filter(t=>Te.has(q.extname(t).toLowerCase()))}catch{return[]}}function we(a){const e=u.readFileSync(a);return`data:${Tt(q.extname(a))};base64,${e.toString("base64")}`}function fe(a,e,t){let A="";if(e)try{new URL(e),A=`url(${e})`}catch{}if(!A&&a&&a!=="disabled"){const o=q.join(t,"backgrounds");if(a==="swap:random"){const r=Et(t);if(r.length>0){const d=r[Math.floor(Math.random()*r.length)];try{A=`url(${we(q.join(o,d))})`}catch{}}}else if(a.startsWith("swap:")){const r=q.basename(a.slice(5));if(!r)return"";try{A=`url(${we(q.join(o,r))})`}catch{}}}return A?`
#instructionHolder[style^="display: block"] {
    background-image: initial !important;
}
#instructionHolder {
    background-image: ${A} !important;
    background-size: cover !important;
    background-position: center !important;
}
#instructions {
    display: block;
    visibility: hidden;
}`:""}const Gt=`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  ${be}
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: var(--kpc-surface-dialog);
    color: var(--kpc-text-primary);
    height: 40px;
    overflow: hidden;
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 0 6px;
    user-select: none;
    -webkit-app-region: no-drag;
  }

  /* ── Shared pill style for Game btn, tabs, and New Tab btn ── */
  .bar-pill {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    border: 1px solid var(--kpc-toggle-off);
    border-radius: 6px;
    padding: 4px 10px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 500;
    transition: background 0.12s, border-color 0.12s;
    background: var(--kpc-surface-card);
    color: var(--kpc-text-secondary);
  }
  .bar-pill:hover {
    background: var(--kpc-surface-input);
    border-color: rgba(255,255,255,0.2);
  }

  /* ── Game button (green accent) ── */
  #gameBtn {
    background: rgba(76, 175, 80, 0.12);
    color: var(--kpc-green);
    border-color: rgba(76, 175, 80, 0.5);
    font-weight: 600;
  }
  #gameBtn:hover {
    background: rgba(76, 175, 80, 0.25);
    border-color: var(--kpc-green);
  }

  /* ── Tab strip ── */
  #tabStrip {
    flex: 1;
    display: flex;
    gap: 4px;
    overflow-x: auto;
    overflow-y: hidden;
    align-items: center;
    height: 100%;
    padding: 4px 0;
    scrollbar-width: none;
  }
  #tabStrip::-webkit-scrollbar { display: none; }

  /* ── Tab pills ── */
  .tab {
    position: relative;
    gap: 6px;
    max-width: 200px;
    min-width: 60px;
    height: 28px;
  }
  .tab.dragging {
    opacity: 0.4;
  }
  .tab.drop-before::before {
    content: '';
    position: absolute;
    left: -3px;
    top: 2px;
    bottom: 2px;
    width: 2px;
    background: var(--kpc-green);
    border-radius: 1px;
  }
  .tab.drop-after::after {
    content: '';
    position: absolute;
    right: -3px;
    top: 2px;
    bottom: 2px;
    width: 2px;
    background: var(--kpc-green);
    border-radius: 1px;
  }
  .tab.active {
    background: rgba(76, 175, 80, 0.12);
    border-color: rgba(76, 175, 80, 0.5);
    color: var(--kpc-text-primary);
  }
  .tab.active:hover {
    background: rgba(76, 175, 80, 0.2);
    border-color: var(--kpc-green);
  }

  .tab-title {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .tab-spinner {
    width: 10px;
    height: 10px;
    border: 1.5px solid var(--kpc-border-medium);
    border-top-color: var(--kpc-green);
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
    flex-shrink: 0;
    display: none;
  }
  .tab.loading .tab-spinner { display: block; }
  @keyframes spin { to { transform: rotate(360deg); } }

  .tab-close {
    flex-shrink: 0;
    width: 16px;
    height: 16px;
    line-height: 15px;
    text-align: center;
    border-radius: 3px;
    font-size: 13px;
    color: var(--kpc-text-dim);
    transition: background 0.1s, color 0.1s;
  }
  .tab-close:hover {
    background: var(--kpc-toggle-off);
    color: #fff;
  }

  /* ── New Tab button ── */
  #newTabBtn {
    width: 28px;
    height: 28px;
    justify-content: center;
    font-size: 16px;
    font-weight: 400;
    color: var(--kpc-text-faint);
    padding: 0;
    border-style: dashed;
  }
  #newTabBtn:hover {
    color: var(--kpc-text-primary);
  }
</style>
</head>
<body>
  <button id="gameBtn" class="bar-pill">Game</button>
  <div id="tabStrip"></div>
  <button id="newTabBtn" class="bar-pill" title="New Tab (Ctrl+T)">+</button>
<script>
  const { ipcRenderer } = require('electron');
  const strip = document.getElementById('tabStrip');

  document.getElementById('gameBtn').addEventListener('click', () => {
    ipcRenderer.send('tab-back-to-game');
  });

  document.getElementById('newTabBtn').addEventListener('click', () => {
    ipcRenderer.send('tab-new');
  });

  /* ── Drag state ── */
  let dragId = null;
  let dragStartX = 0;
  let dragging = false;
  const DRAG_THRESHOLD = 5;

  function clearDropIndicators() {
    strip.querySelectorAll('.drop-before,.drop-after').forEach(
      el => el.classList.remove('drop-before', 'drop-after')
    );
  }

  function getDropTarget(clientX) {
    const tabs = Array.from(strip.querySelectorAll('.tab'));
    for (const tab of tabs) {
      if (Number(tab.dataset.id) === dragId) continue;
      const r = tab.getBoundingClientRect();
      const mid = r.left + r.width / 2;
      if (clientX < mid) return { id: Number(tab.dataset.id), side: 'before', el: tab };
    }
    const last = tabs[tabs.length - 1];
    if (last && Number(last.dataset.id) !== dragId) {
      return { id: Number(last.dataset.id), side: 'after', el: last };
    }
    return null;
  }

  document.addEventListener('mousemove', (e) => {
    if (dragId === null) return;
    if (!dragging && Math.abs(e.clientX - dragStartX) >= DRAG_THRESHOLD) {
      dragging = true;
      const el = strip.querySelector('.tab[data-id="' + dragId + '"]');
      if (el) el.classList.add('dragging');
    }
    if (!dragging) return;
    clearDropIndicators();
    const target = getDropTarget(e.clientX);
    if (target) target.el.classList.add(target.side === 'before' ? 'drop-before' : 'drop-after');
  });

  document.addEventListener('mouseup', (e) => {
    if (dragId === null) return;
    const wasDragging = dragging;
    const srcId = dragId;
    clearDropIndicators();
    const dragEl = strip.querySelector('.tab.dragging');
    if (dragEl) dragEl.classList.remove('dragging');
    dragId = null;
    dragging = false;

    if (wasDragging) {
      const target = getDropTarget(e.clientX);
      if (target) {
        ipcRenderer.send('tab-reorder', srcId, target.id, target.side);
      }
    }
  });

  ipcRenderer.on('tabs-update', (_e, tabs) => {
    strip.innerHTML = '';
    for (const t of tabs) {
      const el = document.createElement('div');
      el.className = 'bar-pill tab' + (t.active ? ' active' : '') + (t.loading ? ' loading' : '');
      el.dataset.id = String(t.id);

      const spinner = document.createElement('div');
      spinner.className = 'tab-spinner';
      el.appendChild(spinner);

      const title = document.createElement('span');
      title.className = 'tab-title';
      title.textContent = t.title || 'Loading...';
      title.title = t.title || '';
      el.appendChild(title);

      const close = document.createElement('span');
      close.className = 'tab-close';
      close.textContent = '\\u00d7';
      close.addEventListener('click', (ev) => {
        ev.stopPropagation();
        ipcRenderer.send('tab-close', t.id);
      });
      el.appendChild(close);

      el.addEventListener('mousedown', (ev) => {
        if (ev.target.classList.contains('tab-close')) return;
        dragId = t.id;
        dragStartX = ev.clientX;
        dragging = false;
      });

      el.addEventListener('click', () => {
        if (!dragging) ipcRenderer.send('tab-switch', t.id);
      });

      strip.appendChild(el);
    }

    const activeEl = strip.querySelector('.tab.active');
    if (activeEl) activeEl.scrollIntoView({ inline: 'nearest', block: 'nearest' });
  });
<\/script>
</body>
</html>`,Vt="data:text/html;charset=utf-8,"+encodeURIComponent(Gt),Ce="https://krunker.io/social.html",ae=40,Mt=20;class j{tabs=[];activeTabId=null;tabBarView;containerView;tabWindow=null;visible=!1;nextId=1;mode;mainWin;ses;preloadPath;isGameURL;titlePolls=new Map;recentlyClosed=[];getTabWindowState;saveTabWindowState;getSavedTabs;saveTabs;isRememberEnabled;tabSaveTimer=null;restoredTabs=!1;constructor(e,t,A,o,r,d,g,m,C,c){this.mainWin=e,this.ses=t,this.preloadPath=A,this.mode=o,this.isGameURL=r,this.getTabWindowState=d,this.saveTabWindowState=g,this.getSavedTabs=m,this.saveTabs=C,this.isRememberEnabled=c,this.tabBarView=new i.WebContentsView({webPreferences:{nodeIntegration:!0,contextIsolation:!1,sandbox:!1}}),this.tabBarView.webContents.loadURL(Vt),this.containerView=new i.View,this.containerView.addChildView(this.tabBarView),this.tabBarView.webContents.on("before-input-event",(w,B)=>{B.type==="keyDown"&&this.handleTabShortcut(w,B)}),o==="same"&&this.initSameWindowMode(),this.registerIPC()}initSameWindowMode(){this.mainWin.contentView.addChildView(this.containerView),this.containerView.setVisible(!1),this.visible=!1,this.mainWin.on("resize",()=>this.updateLayout())}ensureTabWindow(){if(this.tabWindow&&!this.tabWindow.isDestroyed())return;const e=this.getTabWindowState();this.tabWindow=new i.BrowserWindow({width:e.width,height:e.height,x:e.x,y:e.y,frame:!0,backgroundColor:"#000000",autoHideMenuBar:!0,title:"KCC - Tabs",show:!1,webPreferences:{nodeIntegration:!1,contextIsolation:!0,sandbox:!0}}),this.tabWindow.removeMenu(),e.maximized&&this.tabWindow.maximize(),this.tabWindow.contentView.addChildView(this.containerView),this.containerView.setVisible(!0),this.tabWindow.on("resize",()=>{this.updateLayout(),this.debounceSaveTabWindow()}),this.tabWindow.on("move",()=>this.debounceSaveTabWindow()),this.tabWindow.on("close",()=>{if(this.tabSaveTimer&&clearTimeout(this.tabSaveTimer),this.tabWindow&&!this.tabWindow.isDestroyed()){const t=this.tabWindow.getBounds();this.saveTabWindowState({width:t.width,height:t.height,x:t.x,y:t.y,maximized:this.tabWindow.isMaximized()})}}),this.tabWindow.on("closed",()=>{this.destroyAllTabs(),this.tabWindow=null}),this.tabWindow.show()}debounceSaveTabWindow(){this.tabSaveTimer&&clearTimeout(this.tabSaveTimer),this.tabSaveTimer=setTimeout(()=>{if(!this.tabWindow||this.tabWindow.isDestroyed())return;const e=this.tabWindow.getBounds();this.saveTabWindowState({width:e.width,height:e.height,x:e.x,y:e.y,maximized:this.tabWindow.isMaximized()})},1e3)}registerIPC(){i.ipcMain.on("tab-switch",(e,t)=>this.switchToTab(t)),i.ipcMain.on("tab-close",(e,t)=>this.closeTab(t)),i.ipcMain.on("tab-new",()=>this.openTab(Ce)),i.ipcMain.on("tab-reorder",(e,t,A,o)=>{this.reorderTab(t,A,o)}),i.ipcMain.on("tab-back-to-game",()=>{this.mode==="same"?this.hideTabs():this.mainWin.focus()})}openTab(e){if(!this.restoredTabs){this.restoredTabs=!0;const t=this.isRememberEnabled()?this.getSavedTabs():[];if(this.saveTabs([]),t.length>0){for(const o of t)this.openSingleTab(o);const A=this.tabs.find(o=>o.url===e);if(A)return this.switchToTab(A.id),this.showTabs(),A.id}}return this.openSingleTab(e)}openSingleTab(e){if(this.tabs.length>=Mt){const r=this.tabs.find(d=>d.url===e);return r?(this.switchToTab(r.id),r.id):(p.warn("[KCC-Tabs] Tab limit reached, ignoring openTab"),-1)}const t=this.nextId++,A=this.createTabView(t),o={id:t,view:A,title:this.titleFromUrl(e),url:e,loading:!0};return this.tabs.push(o),this.mode==="new"&&this.ensureTabWindow(),this.switchToTab(t),this.showTabs(),A.webContents.loadURL(e),t}createTabView(e){const t=new i.WebContentsView({webPreferences:{preload:this.preloadPath,session:this.ses,contextIsolation:!1,nodeIntegration:!1,sandbox:!0,spellcheck:!1}}),A=t.webContents;return A.on("did-finish-load",()=>{A.insertCSS(Se).catch(()=>{}),A.send("main_did-finish-load-tab"),i.ipcMain.emit("throttle-state",{sender:A},"menu"),this.updateTabInfo(e,{loading:!1}),this.startTitleWatcher(e,A)}),A.on("did-start-loading",()=>{this.updateTabInfo(e,{loading:!0})}),A.on("did-stop-loading",()=>{this.updateTabInfo(e,{loading:!1})}),A.on("page-title-updated",(o,r)=>{this.isGenericTitle(r)||this.updateTabInfo(e,{title:r})}),A.on("did-navigate",(o,r)=>{this.updateTabInfo(e,{url:r,title:this.titleFromUrl(r)})}),A.setWindowOpenHandler(({url:o})=>(o.includes("krunker.io")?this.isGameURL(o)?(this.mainWin.loadURL(o),this.mode==="same"?this.hideTabs():this.mainWin.focus()):setImmediate(()=>this.openTab(o)):setImmediate(()=>i.shell.openExternal(o)),{action:"deny"})),A.on("will-navigate",(o,r)=>{r.includes("krunker.io")&&this.isGameURL(r)&&(o.preventDefault(),this.mainWin.loadURL(r),this.mode==="same"?this.hideTabs():this.mainWin.focus())}),A.on("context-menu",(o,r)=>{if(!r.linkURL)return;const d=[];r.linkURL.includes("krunker.io")&&!this.isGameURL(r.linkURL)&&d.push({label:"Open in New Tab",click:()=>this.openTab(r.linkURL)}),d.push({label:"Copy Link",click:()=>i.clipboard.writeText(r.linkURL)}),r.linkURL.includes("krunker.io")||d.push({label:"Open in Browser",click:()=>i.shell.openExternal(r.linkURL)}),d.length&&i.Menu.buildFromTemplate(d).popup()}),A.on("before-input-event",(o,r)=>{r.type==="keyDown"&&(this.handleTabShortcut(o,r)||r.key==="F12"&&!r.control&&!r.shift&&!r.alt&&(A.toggleDevTools(),o.preventDefault()))}),t}switchToTab(e){const t=this.tabs.find(A=>A.id===e);if(t){if(this.activeTabId!==null&&this.activeTabId!==e){const A=this.tabs.find(o=>o.id===this.activeTabId);A&&(this.containerView.removeChildView(A.view),this.freezeTab(A))}this.activeTabId=e,this.unfreezeTab(t),this.containerView.addChildView(t.view),this.updateLayout(),this.broadcastTabState()}}freezeTab(e){const t=e.view.webContents;if(!t.isDestroyed()){this.stopTitleWatcher(e.id);try{t.debugger.attach("1.3")}catch{}t.debugger.sendCommand("Page.setWebLifecycleState",{state:"frozen"}).catch(()=>{})}}unfreezeTab(e){const t=e.view.webContents;t.isDestroyed()||t.debugger.sendCommand("Page.setWebLifecycleState",{state:"active"}).catch(()=>{}).finally(()=>{try{t.debugger.detach()}catch{}t.isDestroyed()||this.startTitleWatcher(e.id,t)})}closeTab(e){const t=this.tabs.findIndex(o=>o.id===e);if(t===-1)return;const A=this.tabs[t];if(this.activeTabId===e&&(this.containerView.removeChildView(A.view),this.activeTabId=null),this.recentlyClosed.push({url:A.url,title:A.title}),this.recentlyClosed.length>10&&this.recentlyClosed.shift(),this.stopTitleWatcher(e),A.view.webContents.close(),this.tabs.splice(t,1),this.tabs.length>0){const o=Math.min(t,this.tabs.length-1);this.switchToTab(this.tabs[o].id)}else this.mode==="same"?this.hideTabs():this.tabWindow&&!this.tabWindow.isDestroyed()&&(this.tabWindow.contentView.removeChildView(this.containerView),this.tabWindow.close());this.broadcastTabState()}showTabs(){this.mode==="same"?(this.containerView.setVisible(!0),this.visible=!0,this.updateLayout()):(this.ensureTabWindow(),this.tabWindow&&!this.tabWindow.isDestroyed()&&(this.tabWindow.show(),this.tabWindow.focus()),this.visible=!0)}hideTabs(){this.mode==="same"?(this.containerView.setVisible(!1),this.visible=!1,this.mainWin.focus()):(this.mainWin.focus(),this.visible=!1)}nextTab(){if(this.tabs.length<2||this.activeTabId===null)return;const t=(this.tabs.findIndex(A=>A.id===this.activeTabId)+1)%this.tabs.length;this.switchToTab(this.tabs[t].id)}prevTab(){if(this.tabs.length<2||this.activeTabId===null)return;const t=(this.tabs.findIndex(A=>A.id===this.activeTabId)-1+this.tabs.length)%this.tabs.length;this.switchToTab(this.tabs[t].id)}closeCurrentTab(){this.activeTabId!==null&&this.closeTab(this.activeTabId)}reorderTab(e,t,A){const o=this.tabs.findIndex(m=>m.id===e),r=this.tabs.findIndex(m=>m.id===t);if(o===-1||r===-1||o===r)return;const[d]=this.tabs.splice(o,1);let g=this.tabs.findIndex(m=>m.id===t);A==="after"&&g++,this.tabs.splice(g,0,d),this.broadcastTabState()}switchToTabByIndex(e){this.tabs.length!==0&&((e<0||e>=this.tabs.length)&&(e=this.tabs.length-1),this.switchToTab(this.tabs[e].id))}reopenTab(){const e=this.recentlyClosed.pop();e&&this.openTab(e.url)}handleTabShortcut(e,t){return t.key==="Escape"&&!t.control&&!t.shift&&!t.alt?(this.mode==="same"?this.hideTabs():this.mainWin.focus(),e.preventDefault(),!0):t.key==="w"&&t.control&&!t.shift&&!t.alt?(this.closeCurrentTab(),e.preventDefault(),!0):t.key==="Tab"&&t.control&&!t.shift&&!t.alt?(this.nextTab(),e.preventDefault(),!0):t.key==="Tab"&&t.control&&t.shift&&!t.alt?(this.prevTab(),e.preventDefault(),!0):t.key==="t"&&t.control&&!t.shift&&!t.alt?(this.openTab(Ce),e.preventDefault(),!0):t.key==="T"&&t.control&&t.shift&&!t.alt?(this.reopenTab(),e.preventDefault(),!0):t.key>="1"&&t.key<="8"&&t.control&&!t.shift&&!t.alt?(this.switchToTabByIndex(parseInt(t.key)-1),e.preventDefault(),!0):t.key==="9"&&t.control&&!t.shift&&!t.alt?(this.switchToTabByIndex(-1),e.preventDefault(),!0):!1}destroyAll(){if(this.destroyAllTabs(),i.ipcMain.removeAllListeners("tab-switch"),i.ipcMain.removeAllListeners("tab-close"),i.ipcMain.removeAllListeners("tab-new"),i.ipcMain.removeAllListeners("tab-reorder"),i.ipcMain.removeAllListeners("tab-back-to-game"),this.tabWindow&&!this.tabWindow.isDestroyed()&&(this.tabWindow.contentView.removeChildView(this.containerView),this.tabWindow.close(),this.tabWindow=null),this.mode==="same")try{this.mainWin.contentView.removeChildView(this.containerView)}catch{}}destroyAllTabs(){this.tabs.length>0&&this.isRememberEnabled()&&(this.saveTabs(this.tabs.map(e=>e.url)),this.restoredTabs=!1);for(const e of this.tabs)this.stopTitleWatcher(e.id),this.activeTabId===e.id&&this.containerView.removeChildView(e.view),e.view.webContents.isDestroyed()||e.view.webContents.close();this.tabs=[],this.activeTabId=null,this.broadcastTabState()}updateLayout(){let e;if(this.mode==="same"){const[t,A]=this.mainWin.getContentSize();e={width:t,height:A},this.containerView.setBounds({x:0,y:0,width:t,height:A})}else if(this.tabWindow&&!this.tabWindow.isDestroyed()){const[t,A]=this.tabWindow.getContentSize();e={width:t,height:A},this.containerView.setBounds({x:0,y:0,width:t,height:A})}else return;if(this.tabBarView.setBounds({x:0,y:0,width:e.width,height:ae}),this.activeTabId!==null){const t=this.tabs.find(A=>A.id===this.activeTabId);t&&t.view.setBounds({x:0,y:ae,width:e.width,height:e.height-ae})}}updateTabInfo(e,t){const A=this.tabs.find(o=>o.id===e);A&&(t.title!==void 0&&(A.title=t.title),t.url!==void 0&&(A.url=t.url),t.loading!==void 0&&(A.loading=t.loading),this.broadcastTabState())}broadcastTabState(){if(this.tabBarView.webContents.isDestroyed())return;const e=this.tabs.map(t=>({id:t.id,title:t.title,active:t.id===this.activeTabId,loading:t.loading}));this.tabBarView.webContents.send("tabs-update",e)}static GENERIC_TITLES=new Set(["krunker hub","krunker","krunker.io","","hub","social","profile","new tab","loading..."]);isGenericTitle(e){return j.GENERIC_TITLES.has(e.toLowerCase().trim())}startTitleWatcher(e,t){const A=this.titlePolls.get(e);A&&clearInterval(A);let o="",r="";const d=setInterval(()=>{if(t.isDestroyed()){clearInterval(d),this.titlePolls.delete(e);return}t.executeJavaScript(`(function() {
                    var url = window.location.href;
                    var title = '';
                    var ph = document.getElementById('profileHolder');
                    if (ph && ph.style.display === 'block') {
                        var ns = document.getElementById('nameSwitch');
                        if (ns && ns.innerText) title = ns.innerText;
                    }
                    return JSON.stringify({ url: url, dom: title });
                })()`).then(g=>{const{url:m,dom:C}=JSON.parse(g);if(m===o&&C===r)return;o=m,r=C;const c=this.tabs.find(w=>w.id===e);if(c){if(C){c.title!==C?this.updateTabInfo(e,{url:m,title:C}):c.url!==m&&this.updateTabInfo(e,{url:m});return}c.url!==m&&this.updateTabInfo(e,{url:m,title:this.titleFromUrl(m)})}}).catch(()=>{})},1e3);this.titlePolls.set(e,d)}stopTitleWatcher(e){const t=this.titlePolls.get(e);t&&(clearInterval(t),this.titlePolls.delete(e))}titleFromUrl(e){try{const t=new URL(e),A=t.searchParams.get("p"),o=t.searchParams.get("q");if(o)return o;if(A)return{profile:"Profile",leaders:"Leaderboard",games:"Games",clans:"Clans",skins:"Skins",mods:"Mods",maps:"Maps",editor:"Editor",market:"Market",itemsales:"Market Item",inventory:"Inventory",settings:"Settings",feed:"Hub"}[A]||A.charAt(0).toUpperCase()+A.slice(1);const r=t.pathname.replace(/\.html$/,"").replace(/^\//,"");return r==="social"?"Hub":r?r.charAt(0).toUpperCase()+r.slice(1):"New Tab"}catch{return"New Tab"}}}const yt="SUQzBAAAAAABVFRJVDIAAAAvAAADZmFjZWl0IGFjY2VwdCBzb3VuZCBlcGljIC04OTYyNDA1MDE5ODIxNzAxMzY4AFRYWFgAAABAAAADY29tbWVudABmcmU6YWMgLSBmcmVlIGF1ZGlvIGNvbnZlcnRlciA8aHR0cHM6Ly93d3cuZnJlYWMub3JnLz4AVFNTRQAAAA8AAANMYXZmNTcuODMuMTAwAENIQVAAAAAkAABjaDAAAAAAAAAAHmD//////////1RJVDIAAAAGAAADY2hwMAAAAAAAAAAAAAAA//tQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAEsAAHqmwADBggLDhATFRgaHR8iJScqLC8xNDY5PD5BQ0ZIS01QU1VYWl1fYmRnamxvcXR2eXt+gYOGiIuNkJKVmJqdn6Kkp6msr7G0trm7vsDDxsjLzdDS1dfa3d/i5Ofp7O7x9Pb5+/4AAAAATGF2YzU3LjEwAAAAAAAAAAAAAAAAJAPAAAAAAAAB6psnMrNeAAAAAAAAAAAAAAAAAAAAAP/7kGQAD/AAAGkAAAAIAAANIAAAAQAAAaQAAAAgAAA0gAAABExBTUUzLjEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV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qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";let Y=null;const xt="wss://gamefrontend.svc.krunker.io/v1/matchmaking/queue",Ft={sandstorm_v3:{number:2,image:"https://assets.krunker.io/img/maps/map_2.png"},undergrowth:{number:4,image:"https://assets.krunker.io/img/maps/map_4.png"},industry:{number:11,image:"https://assets.krunker.io/img/maps/map_11.png"},site:{number:14,image:"https://assets.krunker.io/img/maps/map_14.png"},bureau:{number:17,image:"https://assets.krunker.io/img/maps/map_17.png"},burg_new:{number:0,image:"https://assets.krunker.io/img/maps/map_0.png"},eterno_sim:{number:39,image:"https://assets.krunker.io/img/maps/map_39.png"}},Ee={na:"North America",eu:"Europe",as:"Asia"},Yt=`
* { user-select: none; margin: 0; padding: 0; box-sizing: border-box; }
body {
  font-family: "Trebuchet MS", sans-serif;
  background: #0d0d0d;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #e0e0e0;
  overflow: hidden;
}
.queuer-container {
  position: relative;
  background: #1a1a1a;
  padding: 40px 52px;
  max-width: 1000px;
  width: 90vw;
  border: 2px solid #2a2a2a;
  border-top: 3px solid #06b6d4;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.7);
  border-radius: 4px;
}
.main-content { display: flex; align-items: center; gap: 56px; }
.left-section { flex: 1; display: flex; flex-direction: column; gap: 24px; }
.status-area {
  display: flex; align-items: center; gap: 14px;
  position: relative; padding-left: 18px;
}
.status-area::before {
  content: ""; position: absolute; left: 0;
  width: 8px; height: 8px; background: #666;
  border-radius: 50%; transition: background 0.3s ease;
}
.status-area.active::before {
  background: #06b6d4;
  box-shadow: 0 0 12px rgba(6, 182, 212, 0.6);
}
#queueStatus {
  font-size: 14px; font-weight: 600; color: #666;
  text-transform: uppercase; letter-spacing: 1px;
  transition: color 0.3s ease;
}
#queueStatus.active { color: #06b6d4; }
.timer-display {
  font-size: 52px; font-weight: 700; color: #fff;
  font-variant-numeric: tabular-nums; letter-spacing: 0.5px;
  padding: 12px 16px; background: #222;
  border-left: 3px solid #06b6d4; border-radius: 2px;
}
.region-controls { display: flex; gap: 12px; }
.region-option { position: relative; }
.region-option input { display: none; }
.region-option label {
  display: block; padding: 12px 24px; background: #222;
  border: 2px solid #2d2d2d; border-radius: 4px;
  color: #888; font-size: 16px; font-weight: 600;
  text-transform: uppercase; letter-spacing: 0.5px;
  cursor: pointer; transition: all 0.2s ease;
}
.region-option label:hover { background: #2a2a2a; border-color: #3a3a3a; }
.region-option input:checked + label {
  background: rgba(6, 182, 212, 0.1);
  border-color: #06b6d4; color: #06b6d4;
}
.divider { width: 1px; height: 120px; background: #2a2a2a; }
.right-section { display: flex; flex-direction: column; gap: 14px; }
.btn {
  padding: 16px 42px; border: 2px solid transparent;
  font-size: 20px; font-weight: 600; cursor: pointer;
  transition: all 0.2s ease; font-family: "Trebuchet MS", sans-serif;
  text-transform: uppercase; letter-spacing: 1px; border-radius: 4px;
}
.btn:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-secondary { background: #222; color: #999; border-color: #2a2a2a; }
.btn-secondary:hover:not(:disabled) { background: #2a2a2a; border-color: #3a3a3a; }
.btn-primary { background: #06b6d4; color: #fff; border-color: #06b6d4; }
.btn-primary:hover:not(:disabled) { background: #0ea5ca; border-color: #0ea5ca; }
.btn-primary:active:not(:disabled) { transform: scale(0.98); }
.btn-primary.in-queue { background: #222; border-color: #06b6d4; color: #06b6d4; }
.btn-primary.in-queue:hover:not(:disabled) { background: rgba(6, 182, 212, 0.1); }
.overlay {
  position: fixed; top: 0; left: 0; width: 100%; height: 100%;
  background: rgba(0, 0, 0, 0.9); display: flex;
  align-items: center; justify-content: center;
  opacity: 0; visibility: hidden; transition: all 0.3s ease; z-index: 1000;
}
.overlay.active { opacity: 1; visibility: visible; }
.popup {
  background: #1a1a1a; border: 2px solid #2a2a2a;
  border-top: 3px solid #06b6d4; max-width: 560px; width: 90vw;
  box-shadow: 0 12px 48px rgba(0, 0, 0, 0.8);
  text-align: center; transform: scale(0.95);
  transition: transform 0.3s ease; border-radius: 4px;
}
.overlay.active .popup { transform: scale(1); }
.popup h2 {
  margin-top: 12px; font-size: 32px; font-weight: 700;
  color: #06b6d4; text-transform: uppercase; letter-spacing: 1.5px;
}
.popup-content { margin: 20px 0; }
.popup-content p {
  font-size: 15px; color: #888; margin-bottom: 12px;
  text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600;
}
.region-found {
  font-size: 18px; font-weight: 700; color: #fff;
  text-transform: uppercase; letter-spacing: 1px;
  display: inline-block; padding: 12px 24px;
  background: rgba(6, 182, 212, 0.15);
  border: 2px solid #06b6d4; border-radius: 4px;
}
.countdown-large {
  font-size: 48px; font-weight: 700; color: #06b6d4;
  margin: 16px 0; font-variant-numeric: tabular-nums; line-height: 1;
}
#matchFoundMessage {
  margin-top: 12px; font-size: 20px; color: #fff;
  text-align: center; width: 400px; margin-left: auto; margin-right: auto;
}
#closeButton {
  position: absolute; right: 0; top: 0;
  margin: 10px 20px 0 0; font-size: 20px; cursor: pointer;
}
`;function vt(){const a=[];for(const[e,t]of Object.entries(Ft))a.push(`${JSON.stringify(e)}: { number: ${t.number}, image: ${JSON.stringify(t.image)} }`);return`{ ${a.join(", ")} }`}function Kt(){return JSON.stringify(Ee)}function Ut(){return Object.entries(Ee).map(([a,e])=>{const t=a==="as"?"asia":a;return`<div class="region-option"><input type="checkbox" id="${t}" value="${a}"><label for="${t}">${e==="North America"?"NA":e==="Europe"?"EU":"Asia"}</label></div>`}).join(`
`)}function Nt(a,e,t){return`
let isQueued = false;
let queueStartTime = null;
let queueInterval = null;
let queueConnection = null;
let countdownInterval = null;
let isConnecting = false;
let audioContext = null;
let notificationBuffer = null;
let currentSource = null;
let audioInitialized = false;
const selectedMaps = new Set();

const WS_URL = ${JSON.stringify(xt)};
const INIT_TOKEN = ${JSON.stringify(a)};
const INIT_REGION = ${JSON.stringify(e)};
const INIT_ALL_REGIONS = ${JSON.stringify(t)};
const maps = ${vt()};
const regions = ${Kt()};

const queueStatus = document.getElementById('queueStatus');
const statusArea = document.getElementById('statusArea');
const queueTimerDisplay = document.getElementById('queueTimerDisplay');
const regionCheckboxes = document.getElementById('regionCheckboxes');
const matchPopupOverlay = document.getElementById('matchPopupOverlay');
const countdownTimer = document.getElementById('countDownTimer');
const foundRegion = document.getElementById('foundRegion');
const queueButton = document.getElementById('queueButton');
const closeButton = document.getElementById('closeButton');

const base64String = ${JSON.stringify(yt)};

function saveSettings() {
    const selectedRegions = Array.from(document.querySelectorAll('#regionCheckboxes input:checked')).map(el => el.value);
    localStorage.setItem('queue_selectedRegions', JSON.stringify(selectedRegions));
}

function loadSettings() {
    const savedRegions = localStorage.getItem('queue_selectedRegions');
    if (savedRegions) {
        for (const regionId of JSON.parse(savedRegions)) {
            const checkbox = document.getElementById(regionId === 'as' ? 'asia' : regionId);
            if (checkbox) checkbox.checked = true;
        }
    } else if (INIT_REGION) {
        const checkbox = document.getElementById(INIT_REGION === 'as' ? 'asia' : INIT_REGION);
        if (checkbox) checkbox.checked = true;
        if (INIT_ALL_REGIONS) {
            for (const el of document.querySelectorAll('#regionCheckboxes input')) el.checked = true;
        }
    }
}

const base64ToArrayBuffer = (b64) => {
    const bin = atob(b64);
    const bytes = new Uint8Array(bin.length);
    for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
    return bytes.buffer;
};

async function initializeAudio() {
    audioContext = new AudioContext();
    if (audioContext.state === 'suspended') await audioContext.resume();
    const arrayBuffer = base64ToArrayBuffer(base64String);
    notificationBuffer = await audioContext.decodeAudioData(arrayBuffer);
    audioInitialized = true;
}

function playNotificationSound() {
    if (!notificationBuffer || !audioContext) return;
    try {
        const source = audioContext.createBufferSource();
        source.buffer = notificationBuffer;
        source.connect(audioContext.destination);
        source.start(0);
        currentSource = source;
    } catch (e) { console.error('Audio play error:', e); }
}

function stopNotificationSound() {
    if (currentSource) {
        try { currentSource.stop(); currentSource.disconnect(); } catch {}
        currentSource = null;
    }
}

function formatTime(seconds) {
    const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
    const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
    const s = String(Math.floor(seconds % 60)).padStart(2, '0');
    return h + ':' + m + ':' + s;
}

function updateCooldownTimer(ms) {
    const endTime = Date.now() + ms;
    function updateDisplay() {
        const remaining = Math.ceil((endTime - Date.now()) / 1000);
        if (remaining <= 0) {
            queueStatus.textContent = 'Ready';
            queueStatus.classList.remove('active');
            statusArea.classList.remove('active');
            queueButton.disabled = false;
            return;
        }
        queueStatus.textContent = 'Cooldown: ' + formatTime(remaining);
        queueButton.disabled = true;
        setTimeout(updateDisplay, 1000);
    }
    updateDisplay();
}

function updateQueueTimer() {
    if (queueStartTime) {
        const elapsed = Math.floor((Date.now() - queueStartTime) / 1000);
        queueTimerDisplay.textContent = formatTime(elapsed);
    }
}

function startQueue() {
    const selectedRegions = Array.from(document.querySelectorAll('#regionCheckboxes input:checked')).map(el => el.value);

    if (selectedRegions.length === 0) {
        queueStatus.textContent = 'Select at least one region';
        queueButton.disabled = false;
        isConnecting = false;
        return;
    }
    if (selectedMaps.size === 0) {
        queueStatus.textContent = 'Select at least one map';
        queueButton.disabled = false;
        isConnecting = false;
        return;
    }

    const wsUrl = WS_URL + '?token=' + INIT_TOKEN + '&maps=' + Array.from(selectedMaps).join(',') + '&regions=' + selectedRegions.join(',');

    try {
        queueConnection = new WebSocket(wsUrl);
    } catch (error) {
        console.error('WebSocket creation error:', error);
        queueStatus.textContent = 'Connection failed';
        queueButton.disabled = false;
        isConnecting = false;
        return;
    }

    queueConnection.onerror = (error) => {
        console.error('queueConnection error:', error);
        queueStatus.textContent = 'Connection error';
        queueStatus.classList.remove('active');
        statusArea.classList.remove('active');
        isQueued = false;
        isConnecting = false;
        queueButton.disabled = false;
    };

    queueConnection.onopen = () => {
        isQueued = true;
        isConnecting = false;
        queueStartTime = Date.now();
        queueButton.textContent = 'Leave Queue';
        queueButton.classList.add('in-queue');
        queueStatus.textContent = 'In queue';
        queueStatus.classList.add('active');
        statusArea.classList.add('active');
        updateQueueTimer();
        queueInterval = setInterval(updateQueueTimer, 1000);
        queueButton.disabled = false;
    };

    queueConnection.onmessage = (event) => {
        const data = JSON.parse(event.data);
        switch (data.type) {
            case 'QUEUE_STATUS':
                if (data.payload.status === 'MATCHED')
                    matchFound(data.payload.assignment.extensions.map.trim(), data.payload.assignment.extensions.region);
                break;
            case 'ERROR':
                if (data.payload.code === 'COOLDOWN') {
                    queueConnection.close();
                    isQueued = false;
                    isConnecting = false;
                    queueButton.disabled = false;
                    updateCooldownTimer(data.payload.payload.cooldown);
                }
                break;
            case 'INTERNAL_ERROR':
                queueConnection.close();
                isQueued = false;
                isConnecting = false;
                queueButton.disabled = false;
                break;
        }
    };

    queueConnection.onclose = () => {
        isQueued = false;
        isConnecting = false;
        clearInterval(queueInterval);
        queueButton.textContent = 'Start Queue';
        queueButton.classList.remove('in-queue');
        queueStatus.textContent = 'Ready';
        queueStatus.classList.remove('active');
        statusArea.classList.remove('active');
        queueTimerDisplay.textContent = '00:00:00';
        queueButton.disabled = false;
    };
}

function matchFound(map, region) {
    playNotificationSound();
    matchPopupOverlay.classList.add('active');
    region = region.slice(2);
    const regionName = regions[region] || region;
    let foundMapName = 'unknown';
    for (const [mapName, mapData] of Object.entries(maps)) {
        if (mapData.number === parseInt(map, 10)) { foundMapName = mapName; break; }
    }
    foundRegion.textContent = regionName + ', ' + foundMapName;

    const duration = 60;
    const startTime = Date.now();
    countdownInterval = setInterval(() => {
        const elapsed = Math.floor((Date.now() - startTime) / 1000);
        const remaining = Math.max(0, duration - elapsed);
        countdownTimer.textContent = formatTime(remaining);
        if (remaining <= 0) {
            clearInterval(countdownInterval);
            matchPopupOverlay.classList.remove('active');
        }
    }, 1000);

    isQueued = false;
    isConnecting = false;
    clearInterval(queueInterval);
    queueButton.textContent = 'Start Queue';
    queueButton.classList.remove('in-queue');
    queueStatus.textContent = 'Ready';
    queueStatus.classList.remove('active');
    statusArea.classList.remove('active');
    queueTimerDisplay.textContent = '00:00:00';
    queueButton.disabled = false;
}

// Queue button
queueButton.onclick = async () => {
    if (isConnecting) return;
    queueButton.disabled = true;
    isConnecting = true;
    if (isQueued) {
        queueConnection.close();
    } else {
        if (!audioInitialized) await initializeAudio();
        startQueue();
    }
};

// Close match popup
closeButton.onclick = () => {
    matchPopupOverlay.classList.remove('active');
    stopNotificationSound();
    if (countdownInterval) clearInterval(countdownInterval);
};

// Region checkbox changes
for (const sel of regionCheckboxes.querySelectorAll('input')) {
    sel.onclick = () => {
        if (isQueued && queueConnection) queueConnection.close();
        saveSettings();
    };
}

// Init — select all maps unconditionally (ranked doesn't allow map choice)
for (const data of Object.values(maps)) selectedMaps.add(data.number);
loadSettings();
`}function Rt(a,e,t){return`<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Ranked Queue</title>
<style>${Yt}</style>
</head>
<body>
<div class="queuer-container">
  <div class="main-content">
    <div class="left-section">
      <div class="status-area" id="statusArea">
        <span id="queueStatus">Ready</span>
      </div>
      <div class="timer-display" id="queueTimerDisplay">00:00:00</div>
      <div class="region-controls" id="regionCheckboxes">
        ${Ut()}
      </div>
    </div>
    <div class="divider"></div>
    <div class="right-section">
      <button type="button" class="btn btn-primary" id="queueButton">Start Queue</button>
    </div>
  </div>
</div>
<div class="overlay" id="matchPopupOverlay">
  <div class="popup">
    <h2>Match Found</h2>
    <div class="popup-content">
      <div id="closeButton">X</div>
      <div class="region-found" id="foundRegion">Region: </div>
      <div id="matchFoundMessage">open the client and rejoin the game from the ranked menu</div>
      <div class="countdown-large" id="countDownTimer">00:00:60</div>
    </div>
  </div>
</div>
<script>${Nt(a,e,t)}<\/script>
</body>
</html>`}function Lt(a,e,t){if(Y&&!Y.isDestroyed()){Y.focus();return}const A=new i.BrowserWindow({width:850,height:350,resizable:!1,autoHideMenuBar:!0,backgroundColor:"#0d0d0d",title:"Ranked Queue",webPreferences:{nodeIntegration:!1,contextIsolation:!0,sandbox:!0}});A.removeMenu(),Y=A,A.on("closed",()=>{Y=null});const o=Rt(a,e,t);A.loadURL("data:text/html;charset=utf-8,"+encodeURIComponent(o))}const Ge=require("../../package.json").version,Ht={"us-ca-sv":"SV","jb-hnd":"TOK","de-fra":"FRA","as-mb":"MBI","au-syd":"SYD",sgp:"SIN","us-tx":"DAL","me-bhn":"BHN",brz:"BRZ","us-nj":"NY"};let N={},Be=0;function De(a){return new Promise(e=>{const A=process.platform==="win32"?["-n","1","-w","1500",a]:["-c","1","-W","2",a];O.execFile("ping",A,{timeout:3e3},(o,r)=>{if(o){e(-1);return}const d=r.match(/time[=<]([\d.]+)\s*ms/i);e(d?Math.round(parseFloat(d[1])):-1)})})}const Ve=Ue(),Pt={removeUselessFeatures:!0,gpuRasterizing:!1,helpfulFlags:!0,increaseLimits:!1,lowLatency:!1,experimentalFlags:!1},Ot={...Pt,...f.get("advanced")},Jt={fpsUnlocked:!0,...f.get("performance")};Ne(Ve,Ot,Jt);i.app.setAppUserModelId("com.krunkercivilian.client");He();const ke=["*://*.pollfish.com/*","*://www.paypalobjects.com/*","*://fran-cdn.frvr.com/*","*://c.amazon-adsystem.com/*","*://cdn.frvr.com/fran/*","*://cookiepro.com/*","*://*.cookiepro.com/*","*://www.googletagmanager.com/*","*://*.doubleclick.net/*","*://storage.googleapis.com/pollfish_production/*","*://coeus.frvr.com/*","*://apis.google.com/js/platform.js","*://imasdk.googleapis.com/*"],Wt=`
.endAHolder,
#aHider,
#adCon,
#rightABox,
#aContainer,
#topRightAdHolder,
div#aContainer,
#braveWarning,
#topRightAdHolder {
  display: none !important;
}`,jt=`
(function dismissConsent() {
  let attempts = 0;
  const timer = setInterval(() => {
    attempts++;
    const btn = document.querySelector('.fc-cta-consent, [aria-label="Consent"], .css-47sehv');
    if (btn) { btn.click(); clearInterval(timer); }
    if (attempts > 30) clearInterval(timer);
  }, 500);
})();`,Xt=`
document.addEventListener('keydown', function(e) {
  if (e.key === 'Escape' && document.pointerLockElement) {
    document.exitPointerLock();
  }
}, true);`;function Ie(a){try{const e=new URL(a);(e.protocol==="https:"||e.protocol==="http:")&&i.shell.openExternal(a)}catch{}}function M(a,e){return e?a.key===e.key&&a.control===e.ctrl&&a.shift===e.shift&&a.alt===e.alt:!1}let P=null;function zt(){return P||(P={...Qe,...f.get("keybinds")}),P}let oe=null;function x(a){oe&&clearTimeout(oe),oe=setTimeout(()=>{if(a.isDestroyed())return;const e=a.getBounds();f.set("window",{width:e.width,height:e.height,x:e.x,y:e.y,maximized:a.isMaximized(),fullscreen:a.isFullScreen()})},1e3)}i.app.whenReady().then(async()=>{p.log("[KCC] App ready"),p.log("[KCC] Minor update test — asar swap successful");const a=!!process.env.PORTABLE_EXECUTABLE_DIR,e=!!process.env.APPIMAGE,t=!i.app.isPackaged,A=process.platform==="win32"&&!a,o=!a&&!e;if(t||!A&&!o)p.log("[KCC] Skipping auto-update");else{const r=q.join(q.dirname(i.app.getPath("exe")),"resources"),d=q.join(r,"app-pending.asar");if(u.existsSync(d))try{u.unlinkSync(d)}catch{}try{p.log("[KCC] Checking for updates...");const g=await gt(Ge);if(g){p.log(`[KCC] Update available: v${g.version} (${g.updateType})`);const{window:m,sendProgress:C}=ft();let c=!1;if(m.on("closed",()=>{c=!0}),g.updateType==="minor"&&o){C(`Patch available (v${g.version})`,0);const w=q.join(r,"app-pending.asar");try{if(await qe(g.downloadUrl,w,B=>{!c&&!m.isDestroyed()&&C(`Downloading patch... ${B}%`,B)},g.sha256||void 0),!c){C("Applying patch...",100),ut(w);return}}catch(B){if(p.error("[KCC] Patch download failed:",B),u.existsSync(w))try{u.unlinkSync(w)}catch{}m.isDestroyed()||m.close()}}else if(g.updateType==="major"&&A){C(`Update available (v${g.version})`,0);const w=q.join(i.app.getPath("temp"),"kcc-update");u.existsSync(w)||u.mkdirSync(w,{recursive:!0});const B=q.join(w,`KCC-${g.version}-Setup.exe`);try{if(await qe(g.downloadUrl,B,S=>{!c&&!m.isDestroyed()&&C(`Downloading update... ${S}%`,S)},g.sha256||void 0),!c){C("Installing update...",100),qt(B);return}}catch(S){p.error("[KCC] Update download failed:",S),m.isDestroyed()||m.close()}}else p.log("[KCC] Update available but cannot auto-install on this platform"),m.isDestroyed()||m.close()}else p.log("[KCC] No updates available")}catch(g){p.error("[KCC] Update check failed:",g)}}await Zt()});async function Zt(){p.log("[KCC] Starting initialization");const a=i.session.fromPartition("persist:krunker"),e=a.getUserAgent();a.setUserAgent(e.replace(/\s*krunker-civilian-client\/\S+/i,"")),Pe(a);const t=f.get("swapper"),A=t.path||q.join(i.app.getPath("userData"),"Krunker Civilian Client","swapper");for(const s of["themes","backgrounds"]){const n=q.join(A,s);u.existsSync(n)||u.mkdirSync(n,{recursive:!0})}const o=t.enabled?new Oe(A):null;p.log(`[KCC] Resource swapper: ${o?"enabled":"disabled"} (${A})`);const r=f.get("userscripts")||{enabled:!0,path:""},d=r.path||q.join(i.app.getPath("userData"),"Krunker Civilian Client"),g=r.enabled?new Je(d):null;p.log(`[KCC] Userscripts: ${g?"enabled":"disabled"} (${d})`);const m=o?[...ke,"*://*.krunker.io/*"]:[...ke];a.webRequest.onBeforeRequest({urls:m},(s,n)=>{if(o){const l=o.getRedirect(s.url);if(l)return n({redirectURL:l})}try{if(new URL(s.url).hostname.endsWith("krunker.io"))return n({})}catch{}n({cancel:!0})}),o&&o.waitForReady().then(()=>{p.log(`[KCC] Swapper ready: ${o.patterns.length} pattern(s)`)}),o&&a.webRequest.onHeadersReceived(({responseHeaders:s},n)=>{if(!s)return n({});for(const l in s){const h=l.toLowerCase();if(h==="access-control-allow-credentials"&&s[l][0]==="true")return n({responseHeaders:s});if(h==="access-control-allow-origin"){delete s[l];break}}return n({responseHeaders:{...s,"access-control-allow-origin":["*"]}})});const C=f.get("window"),c=new i.BrowserWindow({width:C.width,height:C.height,x:C.x,y:C.y,frame:!0,backgroundColor:"#000000",webPreferences:{preload:q.join(__dirname,"..","preload","index.js"),session:a,contextIsolation:!1,nodeIntegration:!1,sandbox:!0,spellcheck:!1,backgroundThrottling:!1}});C.fullscreen?c.setFullScreen(!0):C.maximized&&c.maximize(),i.Menu.setApplicationMenu(null);let w=null;if((f.get("discord")||{enabled:!1}).enabled&&(w=new Qt,w.connect(),p.log("[KCC] Discord Rich Presence enabled")),process.platform==="win32"){const s={High:-14,"Above Normal":-7,"Below Normal":7,Low:19},n=f.get("performance")?.processPriority||"Normal",l=s[n];if(l!==void 0){try{de.setPriority(process.pid,l)}catch{}setInterval(()=>{for(const h of i.app.getAppMetrics())if(h.pid!==process.pid)try{de.setPriority(h.pid,l)}catch{}},1e3),p.log(`[KCC] Process priority set to ${n}`)}}const B=new WeakSet;function S(s,n){const l=Math.max(1,Math.min(3,n));try{B.has(s)||(s.debugger.attach("1.3"),B.add(s)),s.debugger.sendCommand("Emulation.setCPUThrottlingRate",{rate:l})}catch{}}let I=!1;i.ipcMain.on("keybind-capture",(s,n)=>{I=n}),c.webContents.on("before-input-event",(s,n)=>{if(n.type!=="keyDown"||I)return;const l=zt();if(M(n,l.reload))c.reload(),s.preventDefault();else if(M(n,l.newMatch)){const h=f.get("matchmaker");h.enabled?c.webContents.send("matchmaker-find",{...h,cancelKey:l.matchmakerCancel}):c.loadURL("https://krunker.io"),s.preventDefault()}else if(M(n,l.joinFromClipboard)){const h=i.clipboard.readText();try{const Q=new URL(h);Q.protocol==="https:"&&Q.hostname.endsWith("krunker.io")&&c.loadURL(h)}catch{}s.preventDefault()}else if(M(n,l.copyGameLink))i.clipboard.writeText(c.webContents.getURL()),s.preventDefault();else if(M(n,l.devTools))c.webContents.toggleDevTools(),s.preventDefault();else if(M(n,l.matchmaker)){const h=f.get("matchmaker");h.enabled?c.webContents.send("matchmaker-find",{...h,cancelKey:l.matchmakerCancel}):c.loadURL("https://krunker.io"),s.preventDefault()}else M(n,l.fullscreenToggle)?(c.setFullScreen(!c.isFullScreen()),s.preventDefault()):n.key==="t"&&n.control&&!n.shift&&!n.alt?(G.openTab("https://krunker.io/social.html"),s.preventDefault()):n.key==="T"&&n.control&&n.shift&&!n.alt&&(G.reopenTab(),s.preventDefault())}),c.on("resize",()=>x(c)),c.on("move",()=>x(c)),c.on("maximize",()=>x(c)),c.on("unmaximize",()=>x(c)),c.on("enter-full-screen",()=>x(c)),c.on("leave-full-screen",()=>x(c));const D=["/",""];function E(s){try{const n=new URL(s);return n.hostname.includes("krunker.io")?D.includes(n.pathname):!1}catch{return!1}}const Me={lastServer:"",socialTabBehaviour:"New Window"};let K=null;function ye(){return K||(K={...Me,...f.get("game")}),K}const se=q.join(__dirname,"..","preload","index.js");let U=ye().socialTabBehaviour==="Same Window"?"same":"new",ce=[],G=new j(c,a,se,U,E,()=>f.get("tabWindow"),s=>f.set("tabWindow",s),()=>ce,s=>{ce=s},()=>f.get("game.rememberTabs")??!1);c.webContents.on("will-navigate",(s,n)=>{try{const l=new URL(n);if(l.protocol!=="https:"&&l.protocol!=="http:"){s.preventDefault();return}}catch{s.preventDefault();return}n.includes("krunker.io")&&!E(n)&&(s.preventDefault(),G.openTab(n))}),c.webContents.setWindowOpenHandler(({url:s})=>(s.includes("krunker.io")?E(s)?c.loadURL(s):setImmediate(()=>G.openTab(s)):setImmediate(()=>Ie(s)),{action:"deny"})),c.webContents.on("context-menu",(s,n)=>{if(!n.linkURL)return;const l=[];n.linkURL.includes("krunker.io")&&!E(n.linkURL)&&l.push({label:"Open in New Tab",click:()=>G.openTab(n.linkURL)}),l.push({label:"Copy Link",click:()=>i.clipboard.writeText(n.linkURL)}),n.linkURL.includes("krunker.io")||l.push({label:"Open in Browser",click:()=>Ie(n.linkURL)}),l.length&&i.Menu.buildFromTemplate(l).popup()}),c.webContents.on("did-finish-load",()=>{p.log(`[KCC] Page loaded: ${c.webContents.getURL()}`),o&&o.rescan().catch(()=>{});const s=[c.webContents.insertCSS(Wt),c.webContents.insertCSS(Se)],n=f.get("ui"),l=n?.cssTheme||"disabled",h=me(l,A);if(p.log(`[KCC] CSS theme: id=${l}, css=${h?h.length+" chars":"none"}`),h){const k=Buffer.from(h).toString("base64");c.webContents.executeJavaScript(`(() => {
        const s = document.createElement('style');
        s.id = 'kcc-user-theme';
        s.textContent = atob('${k}');
        document.head.appendChild(s);
      })()`).catch(b=>p.warn("[KCC] Theme inject failed:",b))}const Q=fe(n?.loadingTheme||"disabled",n?.backgroundUrl||"",A);Q&&s.push(c.webContents.insertCSS(Q)),Promise.all(s).catch(()=>{});const T=f.get("performance");S(c.webContents,T?.cpuThrottleMenu??1.5),c.webContents.executeJavaScript(Xt).catch(k=>p.warn("[KCC] Pointerlock fix inject failed:",k)),c.webContents.executeJavaScript(jt).catch(k=>p.warn("[KCC] Consent dismiss inject failed:",k)),c.webContents.send("main_did-finish-load")});const X=new Set(["window","performance","game","swapper","matchmaker","keybinds","userscripts","ui","discord","translator","advanced","accounts","tabWindow"]);i.ipcMain.handle("get-version",()=>Ge),i.ipcMain.handle("get-platform",()=>Ve),i.ipcMain.handle("get-config",(s,n)=>{if(X.has(n))return f.get(n)}),i.ipcMain.handle("get-all-config",(s,n)=>{const l={};for(const h of n)X.has(h)&&(l[h]=f.get(h));return l});let z=null;const Z=new Map;i.ipcMain.handle("set-config",(s,n,l)=>{if(X.has(n)){if(n==="keybinds"){f.set(n,l),P=null;return}if(n==="game"){K=null;const h=l;if(h?.socialTabBehaviour){const Q=h.socialTabBehaviour==="Same Window"?"same":"new";Q!==U&&(G.destroyAll(),U=Q,G=new j(c,a,se,U,E,()=>f.get("tabWindow"),T=>f.set("tabWindow",T)))}}Z.set(n,l),z||(z=setTimeout(()=>{for(const[h,Q]of Z)f.set(h,Q);Z.clear(),z=null},300))}}),i.ipcMain.handle("window-minimize",()=>c.minimize()),i.ipcMain.handle("window-maximize",()=>{c.isMaximized()?c.unmaximize():c.maximize()}),i.ipcMain.handle("window-close",()=>c.close()),i.ipcMain.handle("window-is-maximized",()=>c.isMaximized()),i.ipcMain.handle("toggle-devtools",()=>c.webContents.toggleDevTools()),i.ipcMain.handle("inject-game-click",()=>{const[s,n]=c.getContentSize(),l=Math.round(s/2),h=Math.round(n/2);c.webContents.sendInputEvent({type:"mouseDown",x:l,y:h,button:"left",clickCount:1}),c.webContents.sendInputEvent({type:"mouseUp",x:l,y:h,button:"left",clickCount:1})}),i.ipcMain.handle("get-swap-dir",()=>A),i.ipcMain.handle("open-swap-folder",()=>i.shell.openPath(A)),i.ipcMain.handle("open-themes-folder",()=>i.shell.openPath(q.join(A,"themes"))),i.ipcMain.handle("open-backgrounds-folder",()=>i.shell.openPath(q.join(A,"backgrounds"))),i.ipcMain.handle("ping-regions",async()=>{if(Object.keys(N).length>0&&Date.now()-Be<6e4)return N;try{const s=await new Promise((T,k)=>{F.get("https://matchmaker.krunker.io/ping-list?hostname=krunker.io",b=>{let V="";b.on("data",y=>{V+=y}),b.on("end",()=>T(V)),b.on("error",k)}).on("error",k)}),n=JSON.parse(s),l={};async function h(T){const k=await De(T);if(k>=0)return k;const b=await De(T);return b>=0?b:-1}const Q=Object.entries(n).map(async([T,k])=>{const b=Ht[T]??T,V=k.split(":")[0],y=await h(V);y>=0&&(l[b]=y)});return await Promise.allSettled(Q),N=l,Be=Date.now(),l}catch(s){return p.error("[KCC] Ping regions error:",s),N}}),i.ipcMain.on("open-ranked-queue",(s,n,l,h)=>{Lt(n,l,h)}),i.ipcMain.on("discord-update",(s,n)=>{w?.setActivity(n)}),i.ipcMain.on("verbose-log",(s,n,...l)=>{n==="error"?p.error(...l):n==="warn"?p.warn(...l):p.log(...l)}),i.ipcMain.on("throttle-state",(s,n)=>{const l=f.get("performance"),h=n==="game"?l?.cpuThrottleGame??1:l?.cpuThrottleMenu??1.5;S(c.webContents,h)}),i.ipcMain.handle("list-themes",()=>bt(A)),i.ipcMain.handle("get-theme-css",(s,n)=>me(n,A)),i.ipcMain.handle("list-loading-themes",()=>St(A)),i.ipcMain.handle("get-loading-screen-css",(s,n,l)=>fe(n,l,A)),i.ipcMain.handle("changelog-fetch",async(s,n)=>{const l=n.startsWith("v")?n:`v${n}`;try{const h=await new Promise((T,k)=>{F.get(`https://api.github.com/repos/bigjakk/Krunker-Civilian-Client/releases/tags/${l}`,{headers:{"User-Agent":"KCC"}},b=>{let V="";b.on("data",y=>{V+=y}),b.on("end",()=>T(V)),b.on("error",k)}).on("error",k)});return JSON.parse(h).body||""}catch{return""}}),i.ipcMain.handle("userscripts-get-dir",()=>g?g.dir:""),i.ipcMain.handle("userscripts-open-folder",()=>{g&&i.shell.openPath(g.dir)}),i.ipcMain.handle("userscripts-scan",async()=>{if(!g)return{scripts:[],tracker:{}};const s=await g.scanScripts(),n=await g.loadTracker(s);return{scripts:s,tracker:n}}),i.ipcMain.handle("userscripts-set-tracker",(s,n)=>{g&&g.saveTracker(n)}),i.ipcMain.handle("userscripts-load-prefs",(s,n)=>g?g.loadScriptPrefs(n):{}),i.ipcMain.handle("userscripts-save-prefs",(s,n,l)=>{g&&g.saveScriptPrefs(n,l)}),i.ipcMain.handle("open-electron-log",()=>{i.shell.openPath(at())}),i.ipcMain.handle("reset-swapper",async()=>{try{const s=await u.promises.readdir(A,{withFileTypes:!0});for(const n of s)await u.promises.rm(q.join(A,n.name),{recursive:!0,force:!0});return!0}catch(s){return p.error("[KCC] Reset swapper failed:",s),!1}}),i.ipcMain.handle("restart-client",()=>{i.app.relaunch(),i.app.quit()}),i.ipcMain.handle("reset-options",()=>{f.clear(),i.app.relaunch(),i.app.quit()}),i.ipcMain.handle("delete-all-data",async()=>{f.clear();const s=i.app.getPath("userData");try{await u.promises.rm(q.join(s,"logs"),{recursive:!0,force:!0})}catch(n){p.warn("[KCC] Partial data deletion failed (non-fatal):",n)}i.app.relaunch(),i.app.quit()});const _=i.safeStorage.isEncryptionAvailable();_||p.warn("[KCC] safeStorage encryption not available — account passwords will use base64 fallback");function le(s){return _?i.safeStorage.encryptString(s).toString("base64"):Buffer.from(s).toString("base64")}function pe(s){return _?i.safeStorage.decryptString(Buffer.from(s,"base64")):Buffer.from(s,"base64").toString()}i.ipcMain.handle("alt-list",()=>(f.get("accounts")||[]).map(n=>({label:n.label}))),i.ipcMain.handle("alt-save",(s,n)=>{const l=f.get("accounts")||[],h={label:n.label,username:le(n.username),password:le(n.password)};return l.push(h),f.set("accounts",l),{success:!0,index:l.length-1}}),i.ipcMain.handle("alt-get-credentials",(s,n)=>{const l=f.get("accounts")||[];if(n<0||n>=l.length)return null;const h=l[n];try{return{username:pe(h.username),password:pe(h.password)}}catch(Q){return p.error("[KCC] Failed to decrypt account credentials:",Q),null}}),i.ipcMain.handle("alt-remove",(s,n)=>{const l=f.get("accounts")||[];return n<0||n>=l.length?{success:!1}:(l.splice(n,1),f.set("accounts",l),{success:!0})}),i.ipcMain.handle("alt-rename",(s,n,l)=>{const h=f.get("accounts")||[];return n<0||n>=h.length?{success:!1}:(h[n].label=l,f.set("accounts",h),{success:!0})}),c.on("close",()=>{c.webContents.setAudioMuted(!0),c.webContents.stop()}),i.app.on("will-quit",()=>{w?.disconnect(),p.log("[KCC] Shutting down"),ot()}),p.log("[KCC] Initialization complete — loading game"),c.loadURL("https://krunker.io")}i.app.on("window-all-closed",()=>{i.app.quit()});
"use strict";const c=require("electron"),St={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function b(e){return e.replace(/[&<>"']/g,n=>St[n])}const Xe="kpc-animationBlock",Et=".death-ui-bottom, .death-ui-bottom-empty { animation: none !important; transition: none !important; }";function Fe(e){let n=document.getElementById(Xe);e?n||(n=document.createElement("style"),n.id=Xe,n.textContent=Et,document.head.appendChild(n)):n&&n.remove()}const Je="kpc-menuTimer",xt=`
#uiBase.onMenu #spectateUI { display: block !important; }
#uiBase.onCompMenu.onMenu #specTimer,
#uiBase.onMenu #specGMessage,
#uiBase.onMenu #spec1,
#uiBase.onMenu #specGameInfo,
#uiBase.onMenu #spec0,
#uiBase.onMenu #specControlHolder,
#uiBase.onMenu #specNames { display: none !important; }
#uiBase.onMenu #spectateHUD {
  box-sizing: border-box; display: flex !important; justify-content: center;
  height: 0.5rem; white-space: nowrap; width: max-content;
  position: fixed; top: calc(50% + 140px);
}
#uiBase.onMenu #spectateHUD #specGMessage { top: 0; }
#uiBase.onMenu #spectateUI > #spectateHUD { z-index: 1; transform: unset; }
#uiBase.onMenu .spectateInfo {
  position: fixed; top: calc(50% + 80px); left: 50%; transform: translate(-50%, -50%);
}
#uiBase.onMenu #spectateUI div .spectateInfo #specTimer {
  background-color: transparent; padding: 25px; font-size: 42px; border-radius: 0.5em;
}
#uiBase.onMenu #specKPDContr { display: none; }
#uiBase.onMenu #spectateUI div#specStats {
  position: absolute; top: calc(50% + 13em); left: 50%; transform: translateX(-50%); z-index: 1;
}
#uiBase.onMenu #spectateUI div#specStats:before {
  content: "Spectating"; position: absolute; bottom: 100%; left: 50%;
  transform: translateX(-50%); font-size: 1.2em; padding-bottom: 0.5em;
}
`;function _e(e){let n=document.getElementById(Je);e?n||(n=document.createElement("style"),n.id=Je,n.textContent=xt,document.head.appendChild(n)):n&&n.remove()}const Lt=["Free for All","Team Deathmatch","Hardpoint","Capture the Flag","Parkour","Hide & Seek","Infected","Race","Last Man Standing","Simon Says","Gun Game","Prop Hunt","Boss Hunt","Classic FFA","Deposit","Stalker","King of the Hill","One in the Chamber","Trade","Kill Confirmed","Defuse","Sharp Shooter","Traitor","Raid","Blitz","Domination","Squad Deathmatch","Kranked FFA","Team Defender","Deposit FFA","Chaos Snipers","Bighead FFA"],Tt=["Free for All","Team Deathmatch","Hardpoint","Capture the Flag","Parkour","Gun Game","Classic FFA","Deposit","Kill Confirmed","Sharp Shooter","Domination","Kranked FFA","Team Defender","Deposit FFA","Chaos Snipers","Bighead FFA"],Mt=["SV","TOK","FRA","MBI","SYD","SIN","DAL","BHN","BRZ","NY"],st={SV:"Silicon Valley",TOK:"Tokyo",FRA:"Frankfurt",MBI:"Mumbai",SYD:"Sydney",SIN:"Singapore",DAL:"Dallas",BHN:"Bahrain",BRZ:"Brazil",NY:"New York"},It={SkyTemple:"Sky Temple",Krunk_Plaza:"Krunk Plaza",Old_Burg:"Old Burg","Soul Sanctum":"Soul Sanctum","Slide Moonlight":"Slide Moonlight","Eterno Sim":"Eterno Sim"},Rt=["Burg","Littletown","Sandstorm","Subzero","Undergrowth","Freight","Lostworld","Citadel","Oasis","Kanji","Industry","Lumber","Evacuation","Site","SkyTemple","Lagoon","Tropicano","Habitat","Atomic","Old_Burg","Throwback","Clockwork","Bazaar","Erupt","HQ","Lush","Vivo","Slide Moonlight","Eterno Sim"],Bt=4,Ze=2e3,Be=80,At=20,Pt=300,Nt=800;function Ht(e,n){return document.activeElement?.tagName==="INPUT"?!1:n.key===e.key&&n.shiftKey===e.shift&&n.altKey===e.alt&&n.ctrlKey===e.ctrl}const Dt="matchmakerPopupContainer",A=document.createElement("div");A.id=Dt;const it=document.createElement("div");it.id="matchmakerPopupTitle";A.appendChild(it);const ot=document.createElement("div");ot.id="matchmakerPopupDescription";A.appendChild(ot);const $e=document.createElement("div");$e.id="matchmakerPopupOptions";const ee=document.createElement("div");ee.id="matchmakerCancelButton";ee.className="matchmakerPopupButton bigShadowT";ee.textContent="Cancel";ee.setAttribute("onmouseenter","playTick()");ee.addEventListener("click",()=>{const e=window;typeof e.playSelect=="function"&&e.playSelect(),q()});$e.appendChild(ee);A.appendChild($e);const te=document.createElement("div");te.id="matchmakerSearchContainer";const J=document.createElement("div");J.id="matchmakerSearchStatus";te.appendChild(J);const D=document.createElement("div");D.id="matchmakerSearchFeed";te.appendChild(D);const Z=document.createElement("div");Z.id="matchmakerSearchCounter";te.appendChild(Z);const he=document.createElement("div");he.id="matchmakerSearchCancel";he.textContent="Cancel";he.setAttribute("onmouseenter","playTick()");he.addEventListener("click",()=>ct());te.appendChild(he);A.appendChild(te);let rt=[],Oe=!0,lt={key:"Escape",ctrl:!1,shift:!1,alt:!1},U=!1;function ct(){U=!0;const e=window;typeof e.playSelect=="function"&&e.playSelect(),q()}async function Ft(e){try{const t=await(await fetch(`https://matchmaker.krunker.io/game-list?hostname=${window.location.hostname}`)).json(),a=new Map;for(const s of t.games)a.set(s[0],{players:s[2],limit:s[3]});const i=[e,...rt.filter(s=>s.gameID!==e).map(s=>s.gameID)];for(const s of i){const o=a.get(s);if(o&&o.players<o.limit){q(),window.location.href=`https://krunker.io/?game=${s}`;return}}q(),Oe&&typeof window.openServerWindow=="function"&&window.openServerWindow(0)}catch{q(),window.location.href=`https://krunker.io/?game=${e}`}}function q(){document.removeEventListener("keydown",dt,!0),A.parentNode&&A.remove(),A.classList.remove("searching")}function dt(e){document.pointerLockElement||Ht(lt,e)&&(e.preventDefault(),e.stopPropagation(),ct())}function _t(){U=!1,A.classList.add("searching"),A.style.backgroundImage="none",J.textContent="Connecting...",D.innerHTML="",Z.textContent="",document.addEventListener("keydown",dt,!0);const e=document.getElementById("uiBase");e&&e.appendChild(A)}function Ot(e){const n=document.createElement("div");n.className=`mm-feed-entry ${e.passesFilter?"mm-pass":"mm-fail"}`;const t=document.createElement("span");t.className="mm-feed-region",t.textContent=e.region;const a=document.createElement("span");a.className="mm-feed-map",a.textContent=e.map;const i=document.createElement("span");return i.className="mm-feed-players",i.textContent=`${e.playerCount}/${e.playerLimit}`,n.appendChild(t),n.appendChild(a),n.appendChild(i),n}async function Kt(e){if(e.length===0)return;J.textContent="Scanning lobbies...";const n=e.length,t=Math.floor(Ze/Be),a=n>t?n/t:1,i=n>t?Be:Math.max(At,Math.min(Be,Ze/n));for(let s=0;s<n;s+=a){if(U)return;const o=Math.min(Math.floor(s),n-1),r=Ot(e[o]);for(D.appendChild(r);D.children.length>Bt;)D.removeChild(D.firstChild);Z.textContent=`Checked: ${o+1} / ${n} lobbies`,await new Promise(l=>setTimeout(l,i))}Z.textContent=`Checked: ${n} / ${n} lobbies`,U||await new Promise(s=>setTimeout(s,Pt))}async function Ut(e){const t=await(await fetch(`https://matchmaker.krunker.io/game-list?hostname=${window.location.hostname}`)).json(),a=[],i=[];for(const s of t.games){const o=s[0],r=o.split(":")[0],l=s[2],d=s[3],f=s[4].i,p=Lt[s[4].g]??"Unknown Gamemode",h=s[5];let v=!0;(e.regions.length>0&&!e.regions.includes(r)||e.gamemodes.length>0&&!e.gamemodes.includes(p)||e.maps.length>0&&!e.maps.includes(f)||l<e.minPlayers||l>e.maxPlayers||h<e.minRemainingTime||l===d||window.location.href.includes(o))&&(v=!1);const u={gameID:o,region:r,playerCount:l,playerLimit:d,map:f,gamemode:p,remainingTime:h,passesFilter:v};a.push(u),v&&i.push(u)}return{all:a,filtered:i}}function qt(e,n,t){return e.sort((a,i)=>{if(t)return a.playerCount!==i.playerCount?i.playerCount-a.playerCount:(n[a.region]??999)-(n[i.region]??999);const s=n[a.region]??999,o=n[i.region]??999;return s!==o?s-o:i.playerCount-a.playerCount})}async function zt(e,n){Oe=e.openServerBrowser,lt=e.cancelKey,U=!0,q(),_t(),n?.log("[KCC-MM] Fetching game list + pings...");let t,a,i;try{const[s,o]=await Promise.all([Ut(e),c.ipcRenderer.invoke("ping-regions").catch(()=>({}))]);t=s.all,a=s.filtered,i=o}catch{U||(J.textContent="Failed to fetch lobbies",await new Promise(s=>setTimeout(s,2e3)),q());return}if(!U&&(n?.log("[KCC-MM]",a.length,"/",t.length,"games passed filters"),a.length>0&&qt(a,i,e.sortByPlayers),rt=a,Kt(t),await new Promise(s=>setTimeout(s,Nt)),!U))if(a.length>0){const s=a[0],o=i[s.region]??999,r=a.filter(p=>{const h=i[p.region]??999;return Math.abs(h-o)<=20&&s.playerCount-p.playerCount<=2}),l=r[Math.floor(Math.random()*r.length)];n?.log("[KCC-MM] Best match:",l.gameID,l.region,l.map,`(${i[l.region]??"?"}ms, pool: ${r.length})`);const d=st[l.region]??l.region;J.textContent="Lobby Found!",D.innerHTML="";const f=document.createElement("div");f.className="mm-feed-entry mm-pass",f.style.cssText="font-size:1.1em;justify-content:center;",f.innerHTML=`<span class="mm-feed-region">${b(l.region)}</span><span class="mm-feed-map">${b(l.map)}</span><span class="mm-feed-players">${l.playerCount}/${l.playerLimit}</span>`,D.appendChild(f),Z.textContent=`${l.gamemode} · ${d} · ${i[l.region]??"?"}ms`,await new Promise(p=>setTimeout(p,1200)),await Ft(l.gameID)}else n?.log("[KCC-MM] No matching games found"),q(),Oe&&typeof window.openServerWindow=="function"&&window.openServerWindow(0)}const O=[],Ae=new Map;function Gt(e){const n={name:"",author:"",version:"",desc:"",src:"",license:"",runAt:"document-end",priority:0},t=e.match(/\/\/\s*==UserScript==/),a=e.match(/\/\/\s*==\/UserScript==/);if(!t||!a)return n;const i=e.substring(t.index+t[0].length,a.index);for(const s of i.split(`
`)){const o=s.match(/\/\/\s*@(\S+)\s+(.*)/);if(!o)continue;const[,r,l]=o,d=l.trim();switch(r){case"name":n.name=d;break;case"author":n.author=d;break;case"version":n.version=d;break;case"desc":case"description":n.desc=d;break;case"src":n.src=d;break;case"license":n.license=d;break;case"run-at":d==="document-start"?n.runAt="document-start":n.runAt="document-end";break;case"priority":n.priority=parseInt(d,10)||0;break}}return n}function $t(e,n,t){const a=Ae.get(n);if(t){if(a)return;const i=c.webFrame.insertCSS(e);Ae.set(n,i)}else{if(!a)return;c.webFrame.removeInsertedCSS(a),Ae.delete(n)}}function Ke(e,n){if(e.executed)return;const t={_console:n,_css(a,i,s){$t(a,e.filename+":"+i,s)},unload:null,settings:null};try{const a=`
      if (document.readyState !== 'loading') {
        const _origAdd = EventTarget.prototype.addEventListener;
        EventTarget.prototype.addEventListener = function(type, fn, opts) {
          if ((this === window || this === document) && type === 'DOMContentLoaded') {
            Promise.resolve().then(() => fn.call(this, new Event('DOMContentLoaded')));
            return;
          }
          return _origAdd.call(this, type, fn, opts);
        };
        try { ${e.content}
 } finally { EventTarget.prototype.addEventListener = _origAdd; }
      } else { ${e.content}
 }`;new Function(a).apply(t)===t?(e.unload=typeof t.unload=="function"?t.unload:null,e.settings=t.settings):(e.unload=null,e.settings=null),e.executed=!0,n.log("[KCC] Userscript executed:",e.meta.name||e.filename)}catch(a){n.error("[KCC] Userscript error in",e.filename,":",a)}}async function Ue(e){if(!e.settings)return;const n=await c.ipcRenderer.invoke("userscripts-load-prefs",e.filename);for(const t of Object.keys(e.settings))if(t in n){const a=e.settings[t];if(a.value=n[t],typeof a.changed=="function")try{a.changed(a.value)}catch{}}}function jt(){return O}async function Wt(e){const{scripts:n,tracker:t}=await c.ipcRenderer.invoke("userscripts-scan");if(!n||n.length===0){e.log("[KCC] No userscripts found");return}for(const i of n){const s=Gt(i.content);O.push({filename:i.filename,content:i.content,meta:s,enabled:t[i.filename]===!0,executed:!1,unload:null,settings:null})}O.sort((i,s)=>s.meta.priority-i.meta.priority);for(const i of O)i.enabled&&i.meta.runAt==="document-start"&&(Ke(i,e),await Ue(i));const a=()=>{for(const i of O)i.enabled&&i.meta.runAt==="document-end"&&!i.executed&&(Ke(i,e),Ue(i))};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a,{once:!0}):a(),e.log("[KCC] Userscripts initialized:",O.length,"scripts loaded")}function Qt(e,n,t){const a=O.find(s=>s.filename===e);if(!a)return{needsReload:!1};a.enabled=n;const i={};for(const s of O)i[s.filename]=s.enabled;if(c.ipcRenderer.invoke("userscripts-set-tracker",i),n)return a.executed?{needsReload:!1}:(Ke(a,t),Ue(a),{needsReload:!1});if(a.unload&&a.executed){try{a.unload(),t.log("[KCC] Userscript unloaded:",a.meta.name||a.filename)}catch(s){t.error("[KCC] Userscript unload error:",s)}return a.executed=!1,a.unload=null,a.settings=null,{needsReload:!1}}return{needsReload:a.executed}}const ye={enabled:!0,targetLanguage:"en",showLanguageTag:!0};let G,F={...ye},$=null,K=null;const je="kccTL_",ut=600*1e3;function Vt(e){try{const n=sessionStorage.getItem(je+e.toLowerCase().trim());if(!n)return null;const t=JSON.parse(n);return Date.now()-t.ts>ut?null:t}catch{return null}}function Yt(e,n,t){try{const a={t:n,l:t,ts:Date.now()};sessionStorage.setItem(je+e.toLowerCase().trim(),JSON.stringify(a))}catch{}}const Xt=new Set(["hi","hey","hello","yo","sup","bye","cya","gn","gm","yes","no","yep","yea","yeah","nah","nope","ok","okay","kk","lol","lmao","lmfao","rofl","omg","omfg","wtf","wth","bruh","bro","dude","man","brb","afk","gtg","g2g","smh","tbh","imo","imho","ngl","fr","frfr","fax","idk","idc","idgaf","nvm","stfu","pls","plz","thx","ty","tysm","np","yw","mb","sry","sorry","bet","cap","nocap","sus","mid","based","cringe","ratio","rip","oof","uwu","owo","xd","xdd","xddd","lel","kek","damn","dang","boi","fam","goat","goated","lit","vibe","vibes","lowkey","highkey","deadass","nice","cool","sick","fire","trash","ass","toxic","wow","whoa","wha","huh","wat","wut","hmm","gg","ggwp","ggez","wp","ez","gl","hf","glhf","nt","ns","gj","mvp","clutch","ace","carry","noob","newb","n00b","bot","tryhard","sweat","sweaty","hack","hacks","hacker","hax","cheater","cheats","lag","laggy","ping","fps","dc","disconnect","nerf","buff","op","broken","meta","spam","camp","camper","aim","aimbot","wh","wallhack","esp","rush","push","rotate","flank","peek","hold","one","low","dead","down","res","revive","w","l","dub","win","loss","f","ggs","kr","ak","smg","sniper","shotty","rev","semi","crossy","famas","rpg","lmg","deagle","comp","pub","pubs","ranked","nuke","nuked","nuking","kpd","bhop","bhopping","slidehopping","slidehop","krunker","krunky","yendis","krunkitis","contra","relic","unob","unobtainable","spin","market","trade","gift","drop","drops","skin","skins","clan","verified","lvl","level","trig","trigger","runner","det","detective","vince","bowman","spray","agent","rocketeer","streamer","ttv",":)",":(",":d",":p",":o","<3"]),Jt=new Set(["so","cy","ht","hmn","ceb","haw","la","mg","mi","ny","sm","st","su","sw","tl","yo","zu","sn","ig","rw","co","fy","gd","lb","mt","eo"]);let W=new Map;const pt=3,Zt=3,en=15;let Pe=0;const tn=3,nn=15,j=[];function mt(e){Pe<tn?(Pe++,e().finally(()=>{Pe--,j.length>0&&j.shift()()})):(j.length>=nn&&j.shift(),j.push(()=>mt(e)))}const an=300*1e3;let de=null;function sn(){de||(de=setInterval(()=>{W=new Map;const e=Date.now(),n=[];for(let t=0;t<sessionStorage.length;t++){const a=sessionStorage.key(t);if(a?.startsWith(je))try{const i=JSON.parse(sessionStorage.getItem(a)||"");e-i.ts>ut&&n.push(a)}catch{n.push(a)}}for(const t of n)sessionStorage.removeItem(t)},an))}function on(){de&&(clearInterval(de),de=null)}const rn=["joined the game","left the game","has been kicked","has been banned","vote to kick","press f1","connecting","connected","was arrested","started a vote","was kicked","was banned"];function ln(e){return/^[\x00-\x7F\u00C0-\u024F\u1E00-\u1EFF\s\d.,!?;:'"()\-/@#$%^&*+=~`[\]{}|\\<>]+$/u.test(e)}function cn(e){const n=e.trim();if(n.length<2)return!1;const t=n.replace(/[^a-zA-Z0-9\s]/g,"").toLowerCase().split(/\s+/).filter(i=>i.length>0);if(t.length===0||t.every(i=>Xt.has(i)))return!1;const a=n.toLowerCase();return(W.get(a)??0)>=pt?!1:ln(n)?!(t.length<Zt&&!/[À-ÿ]/.test(n)):!0}function dn(e){const n=e.textContent?.trim();if(!n||n.length<2||e.querySelector("img")||n.startsWith("/"))return null;const t=n.toLowerCase();if(rn.some(i=>t.includes(i)))return null;const a=n.indexOf(":");if(a>0&&a<25){const i=n.substring(0,a+1),s=n.substring(a+1).trim();return s.length>=2?{message:s,username:i}:null}return{message:n,username:""}}async function un(e){const n=Vt(e);if(n)return{translation:n.t,srcLang:n.l};try{const t=new AbortController,a=setTimeout(()=>t.abort(),5e3),i="https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl="+F.targetLanguage+"&dt=t&q="+encodeURIComponent(e),s=await fetch(i,{signal:t.signal});if(clearTimeout(a),!s.ok)return G.warn("[KCC-TL] HTTP",s.status),null;const o=await s.json();if(!o?.[0]?.[0])return null;const r=o[0].map(p=>p[0]).join(""),l=o[2]||"unknown";if(l===F.targetLanguage)return null;const d=p=>p.toLowerCase().replace(/[^a-z0-9]/g,"");if(d(r)===d(e))return null;if(e.length<en&&Jt.has(l)){const p=e.toLowerCase().trim();return W.set(p,(W.get(p)??0)+1),null}if(e.trim().split(/\s+/).length<=2){const p=e.toLowerCase().trim(),h=(W.get(p)??0)+1;if(W.set(p,h),h>=pt)return null}return Yt(e,r,l),{translation:r,srcLang:l}}catch(t){return t.name!=="AbortError"&&G.warn("[KCC-TL] Error:",t.message),null}}function pn(e,n,t,a){const i=document.createElement("div");i.className="kcc-translation";const s=F.showLanguageTag&&a!=="unknown"?" ["+a.toUpperCase()+"]":"";i.textContent="🌐 "+(n?n+" ":"")+t+s,e.appendChild(i)}function mn(e){if(e.hasAttribute("data-kpc-translated"))return;e.setAttribute("data-kpc-translated","1");const n=dn(e);if(!n||!cn(n.message))return;const{message:t,username:a}=n;mt(async()=>{if(!e.isConnected)return;const i=await un(t);i&&e.isConnected&&pn(e,a,i.translation,i.srcLang)})}function ft(){if($)return;let e=0;K=setInterval(()=>{e++;const n=document.getElementById("chatList");if(!n){e>60&&(clearInterval(K),K=null,G.warn("[KCC-TL] #chatList not found after 30s, giving up"));return}clearInterval(K),K=null,$=new MutationObserver(t=>{for(const a of t)for(const i of a.addedNodes)i.nodeType===1&&mn(i)}),$.observe(n,{childList:!0}),sn(),G.log("[KCC-TL] Chat observer active")},500)}function fn(){K&&(clearInterval(K),K=null),$&&($.disconnect(),$=null),on(),j.length=0}function gn(e,n){if(G=e,F={enabled:n.enabled??ye.enabled,targetLanguage:n.targetLanguage??ye.targetLanguage,showLanguageTag:n.showLanguageTag??ye.showLanguageTag},!F.enabled){G.log("[KCC-TL] Translator disabled");return}G.log("[KCC-TL] Initializing (target: "+F.targetLanguage+")"),ft()}function Ne(e){e.enabled!==void 0&&(F.enabled=e.enabled,e.enabled&&!$&&ft(),e.enabled||fn()),e.targetLanguage!==void 0&&(F.targetLanguage=e.targetLanguage),e.showLanguageTag!==void 0&&(F.showLanguageTag=e.showLanguageTag)}const hn=new Set(["Team Deathmatch","Hardpoint","Capture the Flag","Hide & Seek","Infected","Last Man Standing","Simon Says","Prop Hunt","Boss Hunt","Deposit","Stalker","Kill Confirmed","Defuse","Traitor","Blitz","Domination","Squad Deathmatch","Team Defender"]);let E=null,ue=null,we=0,We=!1,He=!1,ce=!1,gt=null;const vn=30;function et(e){return e.nodeType===1&&e.id?.startsWith("chatMsg_")}function kn(){const e=document.getElementById("gameModeLabel")||document.getElementById("subGameMode");return e?hn.has(e.textContent?.trim()||""):!1}function yn(e){if(we>0&&E&&ue){const n=[];for(const t of e){if(He)break;for(const a of t.removedNodes)et(a)&&n.push(a)}if(n.length>0){He=!0,ue.disconnect();const t=E.firstChild;for(const a of n)E.insertBefore(a,t);for(;E.children.length>we;)E.removeChild(E.firstChild);ue.observe(E,{childList:!0}),He=!1}}if(We){const n=kn();for(const t of e)for(const a of t.addedNodes){if(!et(a))continue;const i=a.querySelector(".chatMsg");if(!i)continue;if(i.textContent?.includes("Text & Voice Chat")){a.remove();continue}if(!n||!i.innerHTML.includes("‮:")||!a.dataset.tab)continue;const s=a.dataset.tab==="1",o=document.createElement("div");o.style.cssText="float:left; margin-right:4px; font-weight:bold;",o.style.color=s?"#00FF00":"#FF0000",o.textContent=s?"[T]":"[M]",i.insertBefore(o,i.firstChild)}}E&&!ce&&(E.scrollTop=E.scrollHeight)}function bn(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=vn}function Cn(){if(!E)return;const e=bn(E);ce&&e?(ce=!1,E.classList.remove("kpc-chat-paused")):!ce&&!e&&(ce=!0,E.classList.add("kpc-chat-paused"))}function tt(){return E=document.getElementById("chatList"),E?(ue=new MutationObserver(yn),ue.observe(E,{childList:!0}),E.addEventListener("scroll",Cn,{passive:!0}),gt?.log("[KCC-Chat] Observer attached to #chatList"),!0):!1}function wn(e,n){if(gt=n??null,We=e.betterChat,we=e.chatHistorySize,tt())return;let t=0;const a=setInterval(()=>{(++t>120||tt())&&clearInterval(a)},500)}function Sn(e){We=e}function En(e){we=e}let Se=null,_=null,Q=null,be=0,V=null,Y=null;function xn(){const e=document.querySelectorAll("#tScoreC1, #tScoreC2");for(const n of e){if(n.className.includes("you"))continue;const t=n.nextElementSibling;if(!t)continue;const a=parseInt(t.textContent||"0",10);a>be&&Q&&(Q.textContent=String((a-be)/10),V&&clearTimeout(V),V=setTimeout(()=>{Q&&(Q.textContent="0"),V=null},1600)),be=a}}function Ln(){const e=document.querySelector(".topRightCounters");if(!e||_)return;_=document.createElement("div"),_.className="statIcon kpc-hp-counter",_.innerHTML='<div class="greyInner" style="display:flex"><span style="color:white;font-size:15px;margin-right:4px;">on</span><span class="pointVal">0</span></div>',Q=_.querySelector(".pointVal"),e.appendChild(_);const n=document.getElementById("teamScores");n&&(Se=new MutationObserver(xn),Se.observe(n,{childList:!0,subtree:!0}))}function Tn(){Y=setInterval(()=>{document.querySelector(".cmpTmHed")&&(Y&&(clearInterval(Y),Y=null),Ln())},2e3)}function Mn(){clearInterval(Y),Y=null,Se?.disconnect(),Se=null,_?.remove(),_=null,clearTimeout(V),V=null,Q=null,be=0}function ht(){Tn()}function In(){Mn()}const z=[{rank:"Unranked",elo:null,color:"#FFFFFF",image:"rank_unranked.svg"},{rank:"Bronze 1",elo:0,color:"#CD7F32",image:"rank_bronze.svg"},{rank:"Bronze 2",elo:200,color:"#CD7F32",image:"rank_bronze.svg"},{rank:"Bronze 3",elo:400,color:"#CD7F32",image:"rank_bronze.svg"},{rank:"Silver 1",elo:700,color:"#C0C0C0",image:"rank_silver.svg"},{rank:"Silver 2",elo:900,color:"#C0C0C0",image:"rank_silver.svg"},{rank:"Silver 3",elo:1100,color:"#C0C0C0",image:"rank_silver.svg"},{rank:"Gold 1",elo:1300,color:"#FFD700",image:"rank_gold.svg"},{rank:"Gold 2",elo:1600,color:"#FFD700",image:"rank_gold.svg"},{rank:"Gold 3",elo:2e3,color:"#FFD700",image:"rank_gold.svg"},{rank:"Platinum",elo:2300,color:"#4B69FF",image:"rank_platinum.svg"},{rank:"Diamond",elo:3e3,color:"#4B69FF",image:"rank_diamond.svg"},{rank:"Master",elo:3300,color:"#EE7032",image:"rank_master.svg"},{rank:"Kracked",elo:4700,color:"#FF0000",image:"rank_kracked.svg"}],qe="https://assets.krunker.io/img/ranked/ranks/";function Rn(e){let n=0;for(let o=z.length-1;o>=0;o--)if(z[o].elo!==null&&e>=z[o].elo){n=o;break}const t=z[n],a=z[n+1]||t,i=n===z.length-1;let s=0;return!i&&t.elo!==null&&a.elo!==null?s=Math.min(100,Math.max(0,(e-t.elo)/(a.elo-t.elo)*100)):i&&(s=100),{current:t,next:a,progress:s,isMax:i}}function Bn(){if(document.getElementById("kpc-rank-overlay"))return;const e=document.createElement("div");e.id="kpc-rank-overlay",e.addEventListener("mousedown",t=>{t.target===e&&e.remove()});let n="";for(const t of z)n+=`<div class="kpc-rank-grid-item">
            <img src="${qe}${t.image}" loading="lazy">
            <div><div class="kpc-rank-name" style="color:${t.color}">${t.rank}</div>
            <div class="kpc-rank-elo">${t.elo!==null?t.elo+"+":"Placement"}</div></div></div>`;e.innerHTML=`<div class="kpc-rank-popup">
        <div class="kpc-rank-popup-header"><h2>Rank Distribution</h2>
        <div class="kpc-rank-popup-close" id="kpc-rank-close">✕</div></div>
        <div class="kpc-rank-grid">${n}</div></div>`,document.body.appendChild(e),document.getElementById("kpc-rank-close")?.addEventListener("click",()=>e.remove())}function An(e){if(e.querySelector("#kpc-elo-tracker"))return;const n=e.querySelectorAll(".quick-stat-value");if(!n.length)return;const t=Number(n[0].textContent);if(isNaN(t))return;const a=Rn(t),i=document.createElement("div");i.id="kpc-elo-tracker";const s=a.isMax?"":`<div class="kpc-rank-container"><img src="${qe}${a.next.image}" class="kpc-elo-rank-img"><span>${a.next.rank}</span></div>`,o=a.isMax?`${t}`:`${t} / ${a.next.elo}`;i.innerHTML=`<div class="kpc-elo-info-row">
        <div class="kpc-rank-container"><img src="${qe}${a.current.image}" class="kpc-elo-rank-img"><span>${a.current.rank}</span></div>
        <div class="kpc-elo-bar-bg"><div class="kpc-elo-bar-fill" style="width:${a.progress}%"></div>
        <div class="kpc-elo-bar-text">${o}</div></div>${s}</div>`;const r=e.querySelector(".quick-stats");r?e.insertBefore(i,r):e.appendChild(i)}function Pn(e){if(e.querySelector("#kpc-rank-list-btn"))return;const n=document.createElement("div");n.id="kpc-rank-list-btn",n.innerHTML='<span class="material-icons" style="font-size:16px;vertical-align:middle;margin-right:4px;">list</span> Ranks',n.addEventListener("click",Bn),getComputedStyle(e).position==="static"&&(e.style.position="relative"),e.appendChild(n)}function nt(){const e=document.querySelector(".rank-card"),n=document.querySelector(".rank-and-stats");e&&n&&(An(n),Pn(e))}function Nn(){const e=document.querySelector(".footer-controls");if(!e||e.querySelector("#kpc-ranked-queue-btn"))return;const n=document.createElement("button");n.id="kpc-ranked-queue-btn",n.className="kpc-ranked-queue-btn",n.innerHTML='<span class="material-icons" style="font-size:20px;vertical-align:middle;">open_in_new</span>',n.title="Open External Queue",n.addEventListener("click",()=>{let a=localStorage.getItem("__FRVR_auth_access_token")||"";a=a.replace(/"/g,"").replace(/\//g,"");const i=document.querySelector(".region-indicator");let s="na";if(i){const l=(i.textContent||"").split(": "),d=l[1]||l[0];d.includes("Europe")?s="eu":d.includes("Asia")&&(s="as")}const o=localStorage.getItem("s_rankedAllRegions")==="true";c.ipcRenderer.send("open-ranked-queue",a,s,o)});const t=e.lastElementChild;t?e.insertBefore(n,t):e.appendChild(n)}function Hn(){let e=0;const n=setInterval(()=>{const t=window.openRankedMenu;if(t&&!t.__kpcRankPatched){clearInterval(n);let a=null,i=null;const s=function(...o){t.apply(this,o);const r=document.querySelector(".rankedMenuModal");r&&(a=new MutationObserver(nt),a.observe(r,{childList:!0,subtree:!0}),nt(),Nn(),i=setInterval(()=>{document.querySelector(".rankedMenuModal")||(a&&(a.disconnect(),a=null),i&&(clearInterval(i),i=null))},5e3))};s.__kpcRankPatched=!0,window.openRankedMenu=s}else++e>75&&clearInterval(n)},200)}function Dn(e,n){const t=e.split(".").map(Number),a=n.split(".").map(Number),i=Math.max(t.length,a.length);for(let s=0;s<i;s++){const o=t[s]||0,r=a[s]||0;if(o<r)return!0;if(o>r)return!1}return!1}function Fn(e){try{const n=new URL(e);if(n.protocol==="https:"||n.protocol==="http:")return b(e)}catch{}return"#"}function _n(e){const a=b(e).replace(/### (.+)/g,"<h3>$1</h3>").replace(/## (.+)/g,"<h2>$1</h2>").replace(/# (.+)/g,"<h1>$1</h1>").replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>").replace(/\*(.+?)\*/g,"<em>$1</em>").replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,r,l)=>`<a href="${Fn(l)}" target="_blank">${r}</a>`).split(`
`);let i=!1;const s=[];for(const o of a)o.trimStart().startsWith("- ")?(i||(s.push("<ul>"),i=!0),s.push("<li>"+o.trimStart().slice(2)+"</li>")):(i&&(s.push("</ul>"),i=!1),s.push(o));return i&&s.push("</ul>"),s.join(`
`).replace(/\n\n/g,"<br><br>").replace(/\n/g,"<br>")}function On(e,n){const t=document.createElement("div");t.id="kpc-changelog-host";const a=t.attachShadow({mode:"closed"}),i=document.createElement("style");i.textContent=`
        .overlay {
            position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
            background: rgba(0,0,0,0.75); z-index: 99998;
            display: flex; justify-content: center; align-items: center;
            font-family: 'Segoe UI', sans-serif; color: #e0e0e0;
        }
        .modal {
            background: #1a1a2e; border-radius: 12px; padding: 24px;
            min-width: 400px; max-width: 600px; max-height: 70vh;
            display: flex; flex-direction: column; box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        .header {
            display: flex; justify-content: space-between; align-items: center;
            margin-bottom: 16px;
        }
        .header h2 { margin: 0; font-size: 1.4rem; color: #fff; }
        .close-btn {
            background: none; border: none; color: #888; font-size: 1.5rem;
            cursor: pointer; padding: 4px 8px; border-radius: 4px;
        }
        .close-btn:hover { color: #fff; background: rgba(255,255,255,0.1); }
        .body {
            overflow-y: auto; flex: 1; line-height: 1.6;
        }
        .body h1 { font-size: 1.3rem; color: #fff; margin: 12px 0 6px; }
        .body h2 { font-size: 1.15rem; color: #fff; margin: 10px 0 6px; }
        .body h3 { font-size: 1rem; color: #ccc; margin: 8px 0 4px; }
        .body ul { padding-left: 20px; margin: 6px 0; }
        .body li { margin: 3px 0; }
        .body a { color: #6ea8fe; }
        .body strong { color: #fff; }
    `;const s=document.createElement("div");s.className="overlay",s.addEventListener("click",f=>{f.target===s&&t.remove()});const o=document.createElement("div");o.className="modal";const r=document.createElement("div");r.className="header",r.innerHTML=`<h2>What's New in v${b(e)}</h2>`;const l=document.createElement("button");l.className="close-btn",l.textContent="✕",l.addEventListener("click",()=>t.remove()),r.appendChild(l);const d=document.createElement("div");d.className="body",d.innerHTML=_n(n),o.appendChild(r),o.appendChild(d),s.appendChild(o),a.appendChild(i),a.appendChild(s),document.body.appendChild(t)}async function Kn(e,n){if(!(n&&!Dn(n,e))){c.ipcRenderer.invoke("set-config","ui",{...await c.ipcRenderer.invoke("get-config","ui"),lastSeenVersion:e});try{const t=await c.ipcRenderer.invoke("changelog-fetch",e);t&&On(e,t)}catch{}}}let Qe=!1;const B={log:(...e)=>{console.log(...e),Qe&&c.ipcRenderer.send("verbose-log","log",...e)},warn:(...e)=>{console.warn(...e),c.ipcRenderer.send("verbose-log","warn",...e)},error:(...e)=>{console.error(...e),c.ipcRenderer.send("verbose-log","error",...e)}};B.log("[KCC] Preload script loaded");const vt='<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="M12 12.5ZM3.425 20.5Q2.9 20.5 2.65 20.05Q2.4 19.6 2.65 19.15L11.2 4.35Q11.475 3.9 12 3.9Q12.525 3.9 12.8 4.35L21.35 19.15Q21.6 19.6 21.35 20.05Q21.1 20.5 20.575 20.5ZM12 10.2Q11.675 10.2 11.463 10.412Q11.25 10.625 11.25 10.95V14.45Q11.25 14.75 11.463 14.975Q11.675 15.2 12 15.2Q12.325 15.2 12.538 14.975Q12.75 14.75 12.75 14.45V10.95Q12.75 10.625 12.538 10.412Q12.325 10.2 12 10.2ZM12 17.8Q12.35 17.8 12.575 17.575Q12.8 17.35 12.8 17Q12.8 16.65 12.575 16.425Q12.35 16.2 12 16.2Q11.65 16.2 11.425 16.425Q11.2 16.65 11.2 17Q11.2 17.35 11.425 17.575Q11.65 17.8 12 17.8ZM4.45 19H19.55L12 6Z"/></svg>',Un='<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M12 6v1.79c0 .45.54.67.85.35l2.79-2.79c.2-.2.2-.51 0-.71l-2.79-2.79c-.31-.31-.85-.09-.85.36V4c-4.42 0-8 3.58-8 8 0 1.04.2 2.04.57 2.95.27.67 1.13.85 1.64.34.27-.27.38-.68.23-1.04C6.15 13.56 6 12.79 6 12c0-3.31 2.69-6 6-6zm5.79 2.71c-.27.27-.38.69-.23 1.04.28.7.44 1.46.44 2.25 0 3.31-2.69 6-6 6v-1.79c0-.45-.54-.67-.85-.35l-2.79 2.79c-.2.2-.2.51 0 .71l2.79 2.79c.31.31.85.09.85-.35V20c4.42 0 8-3.58 8-8 0-1.04-.2-2.04-.57-2.95-.27-.67-1.13-.85-1.64-.34z"/></svg>',qn=["This setting is safe/standard","Proceed with caution","This setting is not recommended","This setting is experimental","This setting is experimental and unstable. Use at your own risk."];let fe=0,M=null;function zn(e){return'<span class="desc-icon" title="'+e+'">'+vt+"</span>"}function Ee(e){return'<span class="desc-icon '+e+'" title="'+(e==="instant"?"Applies instantly! (No refresh of page required)":"Refresh page to see changes")+'">'+Un+"</span>"}function Gn(){return'<span class="desc-icon restart-icon" title="Requires client restart">'+vt+"</span>"}function Le(e,n,t,a){return e>0?zn(qn[e]):n?Ee("instant"):t?Ee("refresh-icon"):a?Gn():""}function I(e){const n=e==="restart"?2:1;n>fe&&(fe=n),$n()}function $n(){if(fe===0){M&&(M.remove(),M=null);return}if(M)try{M.remove()}catch{}M=document.createElement("div"),M.className="kpc-holder-update refresh-popup",fe===2?M.innerHTML='<span class="restart-msg">Restart client fully to see changes</span>':M.innerHTML='<span class="reload-msg">'+Ee("refresh-icon")+"Reload page with <code>F5</code> or <code>CTRL + R</code> to see changes</span>",document.body.appendChild(M)}window.OffCliV=!0;window.kpc={platform:{getInfo:()=>c.ipcRenderer.invoke("get-platform")},config:{get:e=>c.ipcRenderer.invoke("get-config",e),getAll:e=>c.ipcRenderer.invoke("get-all-config",e),set:(e,n)=>c.ipcRenderer.invoke("set-config",e,n)},window:{minimize:()=>c.ipcRenderer.invoke("window-minimize"),maximize:()=>c.ipcRenderer.invoke("window-maximize"),close:()=>c.ipcRenderer.invoke("window-close"),isMaximized:()=>c.ipcRenderer.invoke("window-is-maximized")},dev:{toggleDevTools:()=>c.ipcRenderer.invoke("toggle-devtools")},swapper:{openFolder:()=>c.ipcRenderer.invoke("open-swap-folder"),getPath:()=>c.ipcRenderer.invoke("get-swap-dir")},userscripts:{openFolder:()=>c.ipcRenderer.invoke("userscripts-open-folder"),getPath:()=>c.ipcRenderer.invoke("userscripts-get-dir")}};function xe(e){return(e.shift?"Shift+":"")+(e.ctrl?"Ctrl+":"")+(e.alt?"Alt+":"")+e.key.toUpperCase()}let pe=null;const ge=document.createElement("div");ge.className="kpc-keybind-overlay";const ne=document.createElement("div");ne.className="kpc-keybind-dialog";const Ve=document.createElement("div");Ve.className="kpc-keybind-dialog-title";const Ye=document.createElement("div");Ye.className="kpc-keybind-dialog-sub";Ye.innerHTML="Press any key. Press <code>Shift+Escape</code> to cancel.";const ve=document.createElement("div");ve.className="kpc-keybind-dialog-modifiers";const ae=document.createElement("div");ae.className="kpc-keybind-modifier";ae.textContent="Shift";const se=document.createElement("div");se.className="kpc-keybind-modifier";se.textContent="Control";const ie=document.createElement("div");ie.className="kpc-keybind-modifier";ie.textContent="Alt";const Te=document.createElement("div");Te.className="kpc-keybind-dialog-cancel";Te.textContent="Cancel";Te.addEventListener("click",Ce);ve.appendChild(ae);ve.appendChild(se);ve.appendChild(ie);ne.appendChild(Te);ne.appendChild(Ve);ne.appendChild(Ye);ne.appendChild(ve);ge.appendChild(ne);function Ce(){ae.classList.remove("active"),se.classList.remove("active"),ie.classList.remove("active"),document.removeEventListener("keydown",kt,!0),document.removeEventListener("keyup",yt,!0),ge.parentNode&&ge.remove(),pe=null,c.ipcRenderer.send("keybind-capture",!1)}function kt(e){e.stopImmediatePropagation(),e.preventDefault(),e.key==="Control"?se.classList.add("active"):e.key==="Shift"?ae.classList.add("active"):e.key==="Alt"&&ie.classList.add("active")}function yt(e){if(e.stopImmediatePropagation(),e.preventDefault(),!pe)return;if(e.key==="Escape"&&e.shiftKey){Ce();return}if(e.key==="Shift"||e.key==="Control"||e.key==="Alt"){const t={key:e.key,ctrl:!1,shift:!1,alt:!1};pe.resolve(t),Ce();return}const n={key:e.key,ctrl:e.ctrlKey,shift:e.shiftKey,alt:e.altKey};pe.resolve(n),Ce()}function bt(e){return new Promise(n=>{pe={resolve:n},Ve.textContent="Edit Keybind: "+e,ae.classList.remove("active"),se.classList.remove("active"),ie.classList.remove("active"),c.ipcRenderer.send("keybind-capture",!0),document.addEventListener("keydown",kt,!0),document.addEventListener("keyup",yt,!0),document.body.appendChild(ge)})}function ze(e,n,t,a,i,s){const r=document.createElement("div");r.className="setting settName safety-0 keybind",r.innerHTML=Le(0,s)+'<span class="setting-title">'+b(e)+'</span><span class="keyIcon kpc-keyIcon">'+b(xe(t))+'</span><div class="setting-desc-new">'+b(n)+"</div>";const l=r.querySelector(".kpc-keyIcon");return l.addEventListener("click",()=>{bt(e).then(d=>{l.textContent=xe(d),a(d)})}),r}function w(e){const n=e.safety||0,t=document.createElement("div");if(t.className="setting settName safety-"+n+" bool",t.innerHTML=Le(n,e.instant,e.refreshOnly,e.restart)+'<span class="setting-title">'+b(e.label)+'</span><label class="switch"><input type="checkbox" class="s-update"'+(e.checked?" checked":"")+(e.disabled?" disabled":"")+'><div class="slider round"></div></label><div class="setting-desc-new">'+b(e.desc)+"</div>",!e.disabled){const a=t.querySelector('input[type="checkbox"]');a.addEventListener("change",()=>{e.onChange(a.checked),e.restart?I("restart"):e.refreshOnly&&I("refresh")})}return t}function Me(e){const n=e.safety||0,t=document.createElement("div");t.className="setting settName safety-"+n+" sel",t.innerHTML=Le(n,e.instant,e.refreshOnly,e.restart)+'<span class="setting-title">'+b(e.label)+'</span><div class="setting-desc-new">'+b(e.desc)+"</div>";const a=document.createElement("select");a.className="s-update inputGrey2";for(const i of e.options){const s=document.createElement("option");s.value=i.value,s.textContent=i.label,i.value===e.value&&(s.selected=!0),a.appendChild(s)}return a.addEventListener("change",()=>{e.onChange(a.value),e.restart?I("restart"):e.refreshOnly&&I("refresh")}),t.appendChild(a),t}function X(e){const n=e.safety||0,t=e.step||1,a=t<1?parseFloat:parseInt,i=document.createElement("div");i.className="setting settName safety-"+n+" num",i.innerHTML=Le(n,e.instant,e.refreshOnly,e.restart)+'<span class="setting-title">'+b(e.label)+'</span><span class="setting-input-wrapper"><div class="slidecontainer"><input type="range" class="sliderM s-update-secondary" min="'+e.min+'" max="'+e.max+'" step="'+t+'" value="'+e.value+'"></div><input type="number" class="rb-input s-update sliderVal" min="'+e.min+'" max="'+e.max+'" step="'+t+'" value="'+e.value+'"></span><div class="setting-desc-new">'+b(e.desc)+"</div>";const s=i.querySelector('input[type="range"]'),o=i.querySelector('input[type="number"]');return s.addEventListener("input",()=>{o.value=s.value}),s.addEventListener("change",()=>{const r=Math.max(e.min,Math.min(e.max,a(s.value)||0));s.value=String(r),o.value=String(r),e.onChange(r),e.restart?I("restart"):e.refreshOnly&&I("refresh")}),o.addEventListener("change",()=>{const r=Math.max(e.min,Math.min(e.max,a(o.value)||0));o.value=String(r),s.value=String(r),e.onChange(r),e.restart?I("restart"):e.refreshOnly&&I("refresh")}),i}function De(e){const n=document.createElement("div");n.className="setting settName safety-0 multisel",n.innerHTML='<span class="setting-title">'+b(e.header)+"</span>";const t=document.createElement("div");t.className="kpc-multisel-parent";for(const a of e.items){const i=document.createElement("label");i.className="hostOpt",i.innerHTML='<span class="optName">'+b(a.label)+'</span><input type="checkbox"'+(e.selected.includes(a.value)?" checked":"")+'><div class="optCheck"></div>';const s=i.querySelector("input");s.addEventListener("change",()=>{if(s.checked)e.selected.includes(a.value)||e.selected.push(a.value);else{const o=e.selected.indexOf(a.value);o>=0&&e.selected.splice(o,1)}e.onChange(e.selected)}),t.appendChild(i)}return n.appendChild(t),n}let ke=null;function jn(){function e(i){ke=new MutationObserver(()=>{const s=i.textContent;if(!s)return;const o=s.match(/(\d+)/);if(!o)return;const r=parseInt(o[1])*2;ke.disconnect(),i.textContent=s.replace(o[1],String(r)),ke.observe(i,{childList:!0,characterData:!0,subtree:!0})}),ke.observe(i,{childList:!0,characterData:!0,subtree:!0})}const n=document.getElementById("pingText");if(n){e(n);return}let t=0;const a=setInterval(()=>{if(++t>60){clearInterval(a);return}const i=document.getElementById("pingText");i&&(clearInterval(a),e(i))},500)}function Wn(){const e=window;let n=0;const t=setInterval(()=>{const a=e.windows?.[22]?.genList;if(a&&!a.__kpcPingPatched){clearInterval(t);const i=function(){const s=a.call(this),r=new DOMParser().parseFromString(s,"text/html");for(const l of r.querySelectorAll(".pListPing.material-icons")){const d=l.getAttribute("title");l.classList.remove("pListPing","material-icons"),l.removeAttribute("title"),l.textContent=d?d+" ":"N/A "}return r.body.innerHTML};i.__kpcPingPatched=!0,e.windows[22].genList=i}else++n>75&&clearInterval(t)},200)}function Qn(){const e=window,n=e.windows[0];let t=n.tabIndex;function a(){const l=n.tabs[n.settingType];return l&&t===l.length-1}function i(){a()&&re()}const s=e.showWindow.bind(e),o=n.changeTab.bind(n),r=n.searchList.bind(n);e.showWindow=(...l)=>{const d=s(...l);if(l[0]===1){n.settingType==="basic"&&n.toggleType({checked:!0});const f=document.querySelector(".advancedSwitch input#typeBtn");f&&(f.disabled=!0,f.nextElementSibling&&f.nextElementSibling.setAttribute("title","Client auto-enables advanced settings mode"));const h=document.getElementById("settSearch")?.value?.trim()??"";h.length>0?re(h):a()&&re()}return d},n.changeTab=(...l)=>{const d=o(...l);return t=n.tabIndex,i(),d},n.searchList=(...l)=>{const d=r(...l),p=document.getElementById("settSearch")?.value?.trim()??"";if(p.length>0)re(p);else{const h=document.querySelector("#settHolder .kpc-settings");h&&!a()?h.remove():a()&&re()}return d},i()}function R(e,n){const t=document.createElement("div"),a=document.createElement("div");a.className="setHed",a.innerHTML='<span class="material-icons plusOrMinus">'+(n?"keyboard_arrow_right":"keyboard_arrow_down")+"</span>"+e;const i=document.createElement("div");return i.className="setBodH"+(n?" setting-category-collapsed":""),a.addEventListener("click",()=>{const s=i.classList.toggle("setting-category-collapsed"),o=a.querySelector(".plusOrMinus");o&&(o.textContent=s?"keyboard_arrow_right":"keyboard_arrow_down")}),t.appendChild(a),t.appendChild(i),{section:t,body:i}}function Vn(e,n,t,a){const s={...{lastServer:"",socialTabBehaviour:"New Window",rememberTabs:!1},...n};e.appendChild(Me({label:"Social/Hub Tab Behaviour",desc:"How social, market, and editor pages open when clicked",options:[{value:"New Window",label:"Tabs (Separate Window)"},{value:"Same Window",label:"Tabs (Overlay Game)"}],value:s.socialTabBehaviour,instant:!0,onChange:d=>{s.socialTabBehaviour=d,c.ipcRenderer.invoke("set-config","game",s)}})),e.appendChild(w({label:"Remember Tabs",desc:"Restore your open tabs when you reopen the social/hub window",checked:s.rememberTabs,instant:!0,onChange:d=>{s.rememberTabs=d,c.ipcRenderer.invoke("set-config","game",s)}}));const r={...{showExitButton:!0,deathscreenAnimation:!1,hideMenuPopups:!1},...t};function l(){c.ipcRenderer.invoke("set-config","ui",r)}e.appendChild(w({label:"Show Exit Button",desc:"Show the exit button in the game sidebar",checked:r.showExitButton,instant:!0,onChange:d=>{r.showExitButton=d,l();const f=document.getElementById("clientExit");f&&(f.style.display=d?"flex":"none")}})),e.appendChild(w({label:"Join as Spectator",desc:"Automatically enable spectate mode when joining a game",checked:s.joinAsSpectator,instant:!0,onChange:d=>{s.joinAsSpectator=d,c.ipcRenderer.invoke("set-config","game",s)}})),e.appendChild(w({label:"Show Changelog",desc:"Show release notes popup when the client updates",checked:r.showChangelog??!0,instant:!0,onChange:d=>{r.showChangelog=d,l()}})),e.appendChild(ze("Toggle Fullscreen","Fullscreen the game window (default F11)",a.binds.fullscreenToggle,d=>{a.binds.fullscreenToggle=d,a.saveBinds()},void 0,!0))}function Yn(e,n,t,a){const i={rawInput:!0,showPing:!0,hpEnemyCounter:!0,...n},s={deathscreenAnimation:!1,hideMenuPopups:!1,menuTimer:!0,doublePing:!0,...t};function o(){c.ipcRenderer.invoke("set-config","game",i)}function r(){c.ipcRenderer.invoke("set-config","ui",s)}a.isWindows&&e.appendChild(w({label:"Raw Input",desc:"Bypass OS mouse acceleration for direct 1:1 sensor input (Windows only)",checked:i.rawInput??!0,refreshOnly:!0,onChange:l=>{i.rawInput=l,o()}})),e.appendChild(w({label:"Show Ping in Player List",desc:"Replace the ping icon with numeric millisecond values in the player list",checked:i.showPing??!0,refreshOnly:!0,onChange:l=>{i.showPing=l,o()}})),e.appendChild(w({label:"Double Ping Display",desc:"Show the real ping value (Krunker displays half the actual latency)",checked:s.doublePing??!0,refreshOnly:!0,onChange:l=>{s.doublePing=l,r()}})),e.appendChild(w({label:"Hardpoint Enemy Counter",desc:"Show enemy capture points in Hardpoint mode",checked:i.hpEnemyCounter??!0,refreshOnly:!0,onChange:l=>{i.hpEnemyCounter=l,o(),l?ht():In()}})),e.appendChild(w({label:"Block Death Screen Animation",desc:"Disable the slide-in animation on the death screen",checked:s.deathscreenAnimation,instant:!0,onChange:l=>{s.deathscreenAnimation=l,r(),Fe(l)}})),e.appendChild(w({label:"Hide Menu Popups",desc:"Hide promotional notifications, offers, and streams on the main menu",checked:s.hideMenuPopups,instant:!0,onChange:l=>{s.hideMenuPopups=l,r(),l?Ge():la()}})),e.appendChild(w({label:"Menu Timer",desc:"Show the game/spectate timer on the menu screen",checked:s.menuTimer??!0,instant:!0,onChange:l=>{s.menuTimer=l,r(),_e(l)}})),s.deathscreenAnimation&&Fe(!0),(s.menuTimer??!0)&&_e(!0),s.hideMenuPopups&&Ge()}function Xn(e,n,t){const a={fpsUnlocked:!0,cpuThrottleGame:1,cpuThrottleMenu:1.5,processPriority:"Normal",...n};function i(){c.ipcRenderer.invoke("set-config","performance",a)}e.appendChild(w({label:"Unlimited FPS",desc:"Uncap the frame rate (requires restart)",checked:a.fpsUnlocked,restart:!0,onChange:s=>{a.fpsUnlocked=s,i()}})),e.appendChild(X({label:"CPU Throttle (Game)",desc:"CPU throttle rate during gameplay (1 = no throttle, 3 = heavy throttle)",min:1,max:3,step:.01,value:a.cpuThrottleGame,instant:!0,safety:2,onChange:s=>{a.cpuThrottleGame=s,i()}})),e.appendChild(X({label:"CPU Throttle (Menu)",desc:"CPU throttle rate on menu screens (1 = no throttle, 3 = heavy throttle)",min:1,max:3,step:.01,value:a.cpuThrottleMenu,instant:!0,safety:1,onChange:s=>{a.cpuThrottleMenu=s,i()}})),t&&e.appendChild(Me({label:"Process Priority",desc:"OS-level process priority for the client (Windows only)",options:[{value:"Normal",label:"Normal"},{value:"Above Normal",label:"Above Normal"},{value:"High",label:"High"},{value:"Below Normal",label:"Below Normal"},{value:"Low",label:"Low"}],value:a.processPriority,restart:!0,safety:2,onChange:s=>{a.processPriority=s,i()}}))}function Jn(e,n){const t=n?n.enabled:!0;e.appendChild(w({label:"Resource Swapper",desc:"Replace game textures, sounds, and models with local files",checked:t,restart:!0,onChange:s=>{c.ipcRenderer.invoke("get-config","swapper").then(o=>{c.ipcRenderer.invoke("set-config","swapper",{enabled:s,path:o?o.path:""})})}}));const a=document.createElement("div");a.className="setting settName safety-0 has-button",a.innerHTML='<span class="setting-title">Swapper Folder</span><div class="setting-desc-new">Place replacement assets here (textures/, sound/, models/)</div>';const i=document.createElement("div");i.className="settingsBtn",i.title="Open Folder",i.innerHTML='<span class="material-icons">folder</span> Swapper',i.addEventListener("click",()=>c.ipcRenderer.invoke("open-swap-folder")),a.appendChild(i),e.appendChild(a)}function Zn(e,n){const t={cssTheme:"disabled",loadingTheme:"disabled",backgroundUrl:"",...n};function a(){c.ipcRenderer.invoke("set-config","ui",t)}const i=document.createElement("div");i.className="setting settName safety-0 sel has-button",i.innerHTML='<span class="setting-title">CSS Theme</span><div class="setting-desc-new">Load a custom CSS theme from swap/themes/</div>';const s=document.createElement("select");s.className="s-update inputGrey2",s.innerHTML='<option value="disabled">Loading...</option>',i.appendChild(s);const o=document.createElement("div");o.className="settingsBtn",o.title="Open Themes Folder",o.innerHTML='<span class="material-icons">folder</span>',o.addEventListener("click",()=>c.ipcRenderer.invoke("open-themes-folder")),i.appendChild(o),e.appendChild(i),c.ipcRenderer.invoke("list-themes").then(h=>{s.innerHTML="";for(const v of h){const u=document.createElement("option");u.value=v.id,u.textContent=v.label,v.id===t.cssTheme&&(u.selected=!0),s.appendChild(u)}}),s.addEventListener("change",()=>{t.cssTheme=s.value,a(),I("refresh")});const r=document.createElement("div");r.className="setting settName safety-0 sel has-button",r.innerHTML='<span class="setting-title">Loading Background</span><div class="setting-desc-new">Custom background image for the loading screen (swap/backgrounds/)</div>';const l=document.createElement("select");l.className="s-update inputGrey2",l.innerHTML='<option value="disabled">Loading...</option>',r.appendChild(l);const d=document.createElement("div");d.className="settingsBtn",d.title="Open Backgrounds Folder",d.innerHTML='<span class="material-icons">folder</span>',d.addEventListener("click",()=>c.ipcRenderer.invoke("open-backgrounds-folder")),r.appendChild(d),e.appendChild(r),c.ipcRenderer.invoke("list-loading-themes").then(h=>{l.innerHTML="";for(const v of h){const u=document.createElement("option");u.value=v.id,u.textContent=v.label,v.id===t.loadingTheme&&(u.selected=!0),l.appendChild(u)}}),l.addEventListener("change",()=>{t.loadingTheme=l.value,a(),I("refresh")});const f=document.createElement("div");f.className="setting settName safety-0",f.innerHTML=Ee("refresh-icon")+'<span class="setting-title">Background URL</span><div class="setting-desc-new">Direct image URL for loading screen (overrides dropdown above)</div>';const p=document.createElement("input");p.type="text",p.className="inputGrey2",p.placeholder="https://example.com/image.png",p.value=t.backgroundUrl||"",p.style.width="300px",p.addEventListener("change",()=>{t.backgroundUrl=p.value.trim(),a(),I("refresh")}),f.appendChild(p),e.appendChild(f)}function ea(e,n,t){const a=n||{enabled:!0,regions:[],gamemodes:[],minPlayers:1,maxPlayers:6,minRemainingTime:120,openServerBrowser:!0,sortByPlayers:!1};function i(){c.ipcRenderer.invoke("set-config","matchmaker",a)}e.appendChild(w({label:"Custom Matchmaker",desc:"Use the matchmaker hotkey to find a game matching your criteria",checked:a.enabled,instant:!0,onChange:s=>{a.enabled=s,i()}})),e.appendChild(w({label:"Open Server Browser on Cancel",desc:"Opens the server browser when no game is found and you cancel",checked:a.openServerBrowser,instant:!0,onChange:s=>{a.openServerBrowser=s,i()}})),e.appendChild(w({label:"Prioritize Player Count",desc:"Sort results by most players first, then by ping (default is ping first)",checked:a.sortByPlayers??!1,instant:!0,onChange:s=>{a.sortByPlayers=s,i()}})),e.appendChild(ze("Matchmaker Hotkey","Key to trigger the custom matchmaker",t.binds.matchmaker,s=>{t.binds.matchmaker=s,t.saveBinds()},void 0,!0)),e.appendChild(ze("Matchmaker Cancel","Key to dismiss the matchmaker popup",t.binds.matchmakerCancel,s=>{t.binds.matchmakerCancel=s,t.saveBinds()},void 0,!0)),e.appendChild(X({label:"Min Players",desc:"Minimum player count in lobby (0-7)",min:0,max:7,value:a.minPlayers,instant:!0,onChange:s=>{a.minPlayers=s,i()}})),e.appendChild(X({label:"Max Players",desc:"Maximum player count in lobby (0-7)",min:0,max:7,value:a.maxPlayers,instant:!0,onChange:s=>{a.maxPlayers=s,i()}})),e.appendChild(X({label:"Min Remaining Time",desc:"Minimum seconds remaining in match (0-480)",min:0,max:480,value:a.minRemainingTime,instant:!0,onChange:s=>{a.minRemainingTime=s,i()}})),e.appendChild(De({header:"Regions (none selected = all)",items:Mt.map(s=>({value:s,label:st[s]||s})),selected:a.regions,onChange:()=>i()})),e.appendChild(De({header:"Gamemodes (none selected = all)",items:Tt.map(s=>({value:s,label:s})),selected:a.gamemodes,onChange:()=>i()})),a.maps||(a.maps=[]),e.appendChild(De({header:"Maps (none selected = all)",items:Rt.map(s=>({value:s,label:It[s]||s})),selected:a.maps,onChange:()=>i()}))}function ta(e,n){const t={enabled:!1,...n};e.appendChild(w({label:"Discord Rich Presence",desc:"Show game activity in your Discord profile",checked:t.enabled,restart:!0,onChange:a=>{t.enabled=a,c.ipcRenderer.invoke("set-config","discord",t)}}))}function Ct(e){const n=window;if(typeof n.loginOrRegister!="function")return;function t(){n.loginOrRegister(),queueMicrotask(()=>{const a=document.querySelector(".auth-toggle-btn");a&&a.textContent?.includes("username")&&a.click(),queueMicrotask(()=>{const i=document.querySelector("#accName"),s=document.querySelector("#accPass");if(!i||!s)return;i.value=e.username,s.value=e.password,i.dispatchEvent(new Event("input",{bubbles:!0})),s.dispatchEvent(new Event("input",{bubbles:!0}));const o=document.querySelector(".io-button");o&&o.click()})})}typeof n.logoutAcc=="function"?(n.logoutAcc(),setTimeout(t,500)):t()}function na(e,n){const t=n||[],a=document.createElement("div");a.className="setting settName safety-0 has-button",a.innerHTML='<span class="setting-title">Add Account</span><button class="kpc-acc-save" style="margin-left:auto;padding:4px 14px;border:none;border-radius:4px;cursor:pointer;font-size:12px;font-family:inherit;background:var(--kpc-accent);color:#fff;">+ Add</button><div class="setting-desc-new">Save a Krunker account for quick switching</div>',e.appendChild(a);const i=document.createElement("div");i.className="kpc-acc-form",i.style.display="none",i.innerHTML='<input type="text" placeholder="Label (e.g. Main, Alt1)" class="kpc-acc-label"><input type="text" placeholder="Krunker Username" class="kpc-acc-user"><input type="password" placeholder="Krunker Password" class="kpc-acc-pass"><div class="kpc-acc-form-buttons"><button class="kpc-acc-save">Save</button><button class="kpc-acc-cancel">Cancel</button></div>',e.appendChild(i);const s=i.querySelector(".kpc-acc-label"),o=i.querySelector(".kpc-acc-user"),r=i.querySelector(".kpc-acc-pass");i.querySelectorAll("input").forEach(f=>{f.addEventListener("keydown",p=>p.stopPropagation())}),a.querySelector("button").addEventListener("click",()=>{i.style.display=i.style.display==="none"?"":"none"}),i.querySelector(".kpc-acc-cancel").addEventListener("click",()=>{i.style.display="none"});const l=document.createElement("div");e.appendChild(l);function d(){if(l.innerHTML="",t.length===0){l.innerHTML='<div class="kpc-acc-empty">No saved accounts</div>';return}t.forEach((f,p)=>{const h=document.createElement("div");h.className="kpc-acc-item",h.innerHTML='<div class="kpc-acc-item-info"><span class="kpc-acc-item-label">'+b(f.label)+'</span></div><div class="kpc-acc-item-actions"><button class="kpc-acc-switch">Switch</button><button class="kpc-acc-delete">Delete</button></div>',h.querySelector(".kpc-acc-switch").addEventListener("click",()=>{c.ipcRenderer.invoke("alt-get-credentials",p).then(v=>{v&&Ct(v)})}),h.querySelector(".kpc-acc-delete").addEventListener("click",()=>{c.ipcRenderer.invoke("alt-remove",p).then(()=>{t.splice(p,1),d()})}),l.appendChild(h)})}d(),i.querySelector(".kpc-acc-save").addEventListener("click",()=>{const f=s.value.trim(),p=o.value.trim(),h=r.value;if(!f||!p||!h)return;const v={label:f,username:p,password:h};c.ipcRenderer.invoke("alt-save",v).then(()=>{t.push({label:f}),s.value="",o.value="",r.value="",i.style.display="none",d()})})}function aa(e,n,t){const a={betterChat:!0,chatHistorySize:200,...n};function i(){c.ipcRenderer.invoke("set-config","game",a)}e.appendChild(w({label:"Better Chat",desc:"Merge team and all-chat with colored [T]/[M] prefixes",checked:a.betterChat,instant:!0,onChange:r=>{a.betterChat=r,i(),Sn(r)}})),e.appendChild(X({label:"Chat History Size",desc:"Maximum chat messages to keep (0 to disable history preservation)",min:0,max:1e3,value:a.chatHistorySize,instant:!0,onChange:r=>{a.chatHistorySize=r,i(),En(r)}}));const s={enabled:!0,targetLanguage:"en",showLanguageTag:!0,...t};function o(){c.ipcRenderer.invoke("set-config","translator",s)}e.appendChild(w({label:"Chat Translator",desc:"Automatically translate non-English chat messages",checked:s.enabled,instant:!0,onChange:r=>{s.enabled=r,o(),Ne({enabled:r})}})),e.appendChild(Me({label:"Target Language",desc:"Language to translate messages into",instant:!0,options:[{value:"en",label:"English"},{value:"es",label:"Spanish"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"pt",label:"Portuguese"},{value:"ru",label:"Russian"},{value:"ja",label:"Japanese"},{value:"ko",label:"Korean"},{value:"zh",label:"Chinese"},{value:"ar",label:"Arabic"},{value:"hi",label:"Hindi"},{value:"tr",label:"Turkish"},{value:"pl",label:"Polish"},{value:"it",label:"Italian"},{value:"nl",label:"Dutch"}],value:s.targetLanguage,onChange:r=>{s.targetLanguage=r,o(),Ne({targetLanguage:r})}})),e.appendChild(w({label:"Show Language Tag",desc:"Show detected language code before translations (e.g. [FR])",checked:s.showLanguageTag,instant:!0,onChange:r=>{s.showLanguageTag=r,o(),Ne({showLanguageTag:r})}}))}function sa(e,n,t){const i={...{removeUselessFeatures:!0,gpuRasterizing:!1,helpfulFlags:!0,increaseLimits:!1,lowLatency:!1,experimentalFlags:!1,angleBackend:"default",verboseLogging:!1},...n};function s(){c.ipcRenderer.invoke("set-config","advanced",i)}const o=t?[{value:"default",label:"Default (D3D11)"},{value:"gl",label:"OpenGL"},{value:"d3d9",label:"Direct3D 9"},{value:"d3d11",label:"Direct3D 11"},{value:"d3d11on12",label:"D3D11on12"},{value:"vulkan",label:"Vulkan"}]:[{value:"default",label:"Default"},{value:"gl",label:"OpenGL"},{value:"vulkan",label:"Vulkan"}];e.appendChild(Me({label:"ANGLE Backend",desc:"Graphics API used for WebGL rendering",options:o,value:i.angleBackend,restart:!0,onChange:l=>{i.angleBackend=l,s()}}));const r=[{key:"removeUselessFeatures",label:"Remove Useless Features",desc:"Disables crash reporting, metrics, print preview, and other unused Chromium features",safety:1},{key:"gpuRasterizing",label:"GPU Rasterization",desc:"Force GPU rasterization and out-of-process rasterization",safety:2},{key:"helpfulFlags",label:"Useful Flags",desc:"Enables WebGL, JS harmony, V8 features, background throttle prevention, and autoplay bypass",safety:3},{key:"increaseLimits",label:"Increase Limits",desc:"Raises renderer process, WebGL context, and WebRTC CPU limits; ignores GPU blocklist",safety:4},{key:"lowLatency",label:"Low Latency Flags",desc:"Enables high-resolution timer, QUIC protocol, and high-performance GPU",safety:4},{key:"experimentalFlags",label:"Experimental Flags",desc:"Enables accelerated video decode, native GPU memory buffers, high DPI support, and disables pings/proxy",safety:4}];for(const l of r)e.appendChild(w({label:l.label,desc:l.desc,checked:!!i[l.key],restart:!0,safety:l.safety,onChange:d=>{i[l.key]=d,s()}}));e.appendChild(w({label:"Verbose Logging",desc:"Forward all preload console output to the Electron log file",checked:i.verboseLogging,instant:!0,onChange:l=>{i.verboseLogging=l,s(),Qe=l}}))}function ia(e,n,t){const a=t.toLowerCase(),i=Array.from(e.children).filter(o=>o.querySelector(".setHed"));i.forEach(o=>{const r=o.querySelector(".setHed")?.textContent?.toLowerCase()||"",l=o.querySelector(".setBodH");if(!l){o.style.display="none";return}if(r.includes(a)){l.classList.remove("setting-category-collapsed");return}let d=0;Array.from(l.children).forEach(f=>{const p=f;(p.textContent?.toLowerCase()||"").includes(a)?(p.style.display="",d++):p.style.display="none"}),d===0?o.style.display="none":l.classList.remove("setting-category-collapsed")}),i.find(o=>o.style.display!=="none")&&Array.from(n.children).forEach(o=>{o.textContent?.toLowerCase().includes("no settings")&&o.remove()})}function re(e){const n=document.getElementById("settHolder");if(!n)return;if(fe=0,M&&(M.remove(),M=null),e){const m=n.querySelector(".kpc-settings");m&&m.remove()}else for(;n.firstChild;)n.removeChild(n.firstChild);const t=document.createElement("div");t.className="kpc-settings";const a=document.createElement("div");a.className="kpc-action-grid";const i=[{label:"Open Resource Swapper",color:"kpc-ab-pink",action:()=>c.ipcRenderer.invoke("open-swap-folder")},{label:"Reset Resource Swapper",color:"kpc-ab-pink",action:()=>{confirm("Reset resource swapper? This will delete all files in the swapper folder.")&&c.ipcRenderer.invoke("reset-swapper")}},{label:"Open Electron Logs",color:"kpc-ab-red",action:()=>c.ipcRenderer.invoke("open-electron-log")},{label:"Restart Client",color:"kpc-ab-orange",full:!0,action:()=>c.ipcRenderer.invoke("restart-client")},{label:"Reset Options",color:"kpc-ab-red",action:()=>{confirm("Reset all settings to defaults? The client will restart.")&&c.ipcRenderer.invoke("reset-options")}},{label:"Delete All Data",color:"kpc-ab-red",action:()=>{confirm("Delete all data (config, logs)? Scripts are preserved. The client will restart.")&&c.ipcRenderer.invoke("delete-all-data")}}];for(const m of i){const k=document.createElement("button");k.className="kpc-action-btn "+m.color+(m.full?" full":""),k.textContent=m.label,k.addEventListener("click",m.action),a.appendChild(k)}t.appendChild(a);const s=R("General");t.appendChild(s.section);const o=R("Game");t.appendChild(o.section);const r=R("Performance");t.appendChild(r.section);const l=R("Swapper");t.appendChild(l.section);const d=R("Appearance");t.appendChild(d.section);const f=R("Matchmaker");t.appendChild(f.section);const p=R("Chat");t.appendChild(p.section);const h=R("Discord");t.appendChild(h.section);const v=R("Accounts",!0);t.appendChild(v.section);const u=R("Advanced");t.appendChild(u.section);const y=R("Userscripts");t.appendChild(y.section),Promise.all([c.ipcRenderer.invoke("get-all-config",["swapper","matchmaker","keybinds","advanced","game","ui","discord","translator","accounts","performance"]),c.ipcRenderer.invoke("get-platform")]).then(([m,k])=>{const g=m.swapper,x=m.matchmaker,L=m.keybinds,N=m.advanced,S=m.game,C=m.ui,P=m.discord,T=m.translator,oe={...{matchmaker:{key:"F6",ctrl:!1,shift:!1,alt:!1},matchmakerCancel:{key:"Escape",ctrl:!1,shift:!1,alt:!1},fullscreenToggle:{key:"F11",ctrl:!1,shift:!1,alt:!1}},...L},Ie=k&&k.isWindows,Re={binds:oe,saveBinds:()=>c.ipcRenderer.invoke("set-config","keybinds",oe),isWindows:Ie};Vn(s.body,S,C,Re),Yn(o.body,S,C,Re),Xn(r.body,m.performance,Ie),Jn(l.body,g),Zn(d.body,C),ea(f.body,x,Re),aa(p.body,S,T),ta(h.body,P),na(v.body,m.accounts),sa(u.body,N,Ie),oa(y.body),e&&ia(t,n,e),n.appendChild(t)}).catch(m=>{console.error("[KCC] Settings render error:",m)})}function oa(e){c.ipcRenderer.invoke("get-config","userscripts").then(n=>{const t=n||{enabled:!0,path:""};e.appendChild(w({label:"Userscripts",desc:"Load custom scripts from the scripts folder",checked:t.enabled,restart:!0,onChange:o=>{t.enabled=o,c.ipcRenderer.invoke("set-config","userscripts",t)}}));const a=document.createElement("div");a.className="setting settName safety-0 has-button",a.innerHTML='<span class="setting-title">Scripts Folder</span><div class="setting-desc-new">Place .js userscript files here</div>';const i=document.createElement("div");i.className="settingsBtn",i.title="Open Folder",i.innerHTML='<span class="material-icons">folder</span> Scripts',i.addEventListener("click",()=>c.ipcRenderer.invoke("userscripts-open-folder")),a.appendChild(i),e.appendChild(a);const s=jt();if(s.length===0){const o=document.createElement("div");o.className="setting settName safety-0",o.innerHTML='<div class="setting-desc-new">No userscripts found. Place .js files in the scripts folder and reload.</div>',e.appendChild(o);return}for(const o of s){const r=document.createElement("div");r.className="setting settName safety-0 bool";const l=b(o.meta.name||o.filename),d=[];o.meta.author&&d.push("by "+b(o.meta.author)),o.meta.version&&d.push("v"+b(o.meta.version));const f=d.length>0?'<span class="kpc-us-meta">'+d.join(" &middot; ")+"</span>":"",p=b(o.meta.desc||"");r.innerHTML='<span class="setting-title">'+l+'</span><label class="switch"><input type="checkbox" class="s-update"'+(o.enabled?" checked":"")+'><div class="slider round"></div></label><div class="setting-desc-new">'+p+(f?"<br>"+f:"")+"</div>",e.appendChild(r);const h=r.querySelector('input[type="checkbox"]'),v=document.createElement("div");v.className="kpc-us-settings",e.appendChild(v),o.enabled&&o.settings&&at(o,v),h.addEventListener("change",()=>{const{needsReload:u}=Qt(o.filename,h.checked,B);v.innerHTML="",h.checked&&o.settings&&at(o,v),u&&I("refresh")})}})}function at(e,n){if(e.settings)for(const[,t]of Object.entries(e.settings)){const a=t.type==="bool"?"bool":t.type==="sel"?"sel":t.type==="num"?"num":t.type==="keybind"?"keybind":"",i=document.createElement("div");switch(i.className="setting settName safety-0"+(a?" "+a:""),i.innerHTML='<span class="setting-title">'+b(t.title)+"</span>"+(t.desc?'<div class="setting-desc-new">'+b(t.desc)+"</div>":""),t.type){case"bool":{const s=document.createElement("label");s.className="switch",s.innerHTML='<input type="checkbox" class="s-update"'+(t.value?" checked":"")+'><div class="slider round"></div>',i.appendChild(s);const o=s.querySelector("input");o.addEventListener("change",()=>{t.value=o.checked,typeof t.changed=="function"&&t.changed(t.value),le(e)});break}case"num":{const s=document.createElement("input");s.type="number",s.className="rb-input s-update sliderVal",s.value=String(t.value),t.min!==void 0&&(s.min=String(t.min)),t.max!==void 0&&(s.max=String(t.max)),t.step!==void 0&&(s.step=String(t.step)),i.appendChild(s),s.addEventListener("change",()=>{t.value=parseFloat(s.value)||0,typeof t.changed=="function"&&t.changed(t.value),le(e)});break}case"sel":{const s=document.createElement("select");if(s.className="s-update inputGrey2",t.opts)for(const o of t.opts){const r=document.createElement("option");r.value=String(o),r.textContent=String(o),String(o)===String(t.value)&&(r.selected=!0),s.appendChild(r)}i.appendChild(s),s.addEventListener("change",()=>{t.value=s.value,typeof t.changed=="function"&&t.changed(t.value),le(e)});break}case"color":{const s=document.createElement("input");s.type="color",s.className="kpc-color-input",s.value=String(t.value)||"#ffffff",i.appendChild(s),s.addEventListener("input",()=>{t.value=s.value,typeof t.changed=="function"&&t.changed(t.value),le(e)});break}case"keybind":{const s=t.value,o=document.createElement("span");o.className="keyIcon kpc-keyIcon",o.textContent=xe(s),o.addEventListener("click",()=>{bt(t.title).then(r=>{t.value=r,o.textContent=xe(r),typeof t.changed=="function"&&t.changed(t.value),le(e)})}),i.appendChild(o);break}}n.appendChild(i)}}function le(e){if(!e.settings)return;const n={};for(const[t,a]of Object.entries(e.settings))n[t]=a.value;c.ipcRenderer.invoke("userscripts-save-prefs",e.filename,n)}let me=null;const ra="#leftTabsHolder > .youNewDiv:not(#battlepassAd), .webpush-container, #homeStoreAd, #streamContainerNew, #bundlePop, #genericPop.claimPop, #newsHolder, #streamContainer { display: none !important; }",wt=["homeStoreAd","streamContainerNew"];function Ge(){if(me)return;if(!document.getElementById("kpc-hideMenuPopups")){const n=document.createElement("style");n.id="kpc-hideMenuPopups",n.textContent=ra,document.head.appendChild(n)}const e=window;me=setInterval(()=>{for(const a of wt){const i=document.getElementById(a);i&&i.style.display!=="none"&&(i.style.display="none")}const n=document.getElementById("bundlePop");n&&n.children.length>0&&n.style.display!=="none"&&typeof e.clearPops=="function"&&e.clearPops();const t=document.getElementById("genericPop");t&&t.classList.contains("claimPop")&&t.style.display!=="none"&&typeof e.clearPops=="function"&&e.clearPops()},1e3)}function la(){me&&(clearInterval(me),me=null);const e=document.getElementById("kpc-hideMenuPopups");e&&e.remove();for(const n of wt){const t=document.getElementById(n);t&&(t.style.display="")}}c.ipcRenderer.on("matchmaker-find",(e,n)=>{zt(n,B).catch(t=>B.error("[KCC] Matchmaker error:",t))});c.ipcRenderer.on("main_did-finish-load",()=>{B.log("[KCC] did-finish-load received, waiting to hook settings...");const e=window.location.pathname==="/"||window.location.pathname==="";window.closeClient=()=>window.close(),Promise.all([c.ipcRenderer.invoke("get-all-config",["ui","userscripts","game","translator","keybinds","discord","advanced","performance"]),c.ipcRenderer.invoke("get-platform"),c.ipcRenderer.invoke("get-version")]).then(([t,a,i])=>{const s=t.ui,o=t.userscripts,r=t.game,l=t.translator,d=t.discord;Qe=t.advanced?.verboseLogging??!1;const p=s?s.showExitButton!==!1:!0,h=()=>{const u=document.getElementById("clientExit");return u?(u.style.display=p?"flex":"none",!0):!1};if(!h()){let u=0;const y=setInterval(()=>{(h()||++u>30)&&clearInterval(y)},500)}if(s?.deathscreenAnimation&&Fe(!0),s?.hideMenuPopups&&Ge(),(s?.menuTimer??!0)&&_e(!0),e&&(s?.doublePing??!0)&&jn(),e&&(r?.showPing??!0)&&Wn(),e&&process.platform==="win32"&&(r?.rawInput??!0)){const u=HTMLCanvasElement.prototype.requestPointerLock;HTMLCanvasElement.prototype.requestPointerLock=function(y){const m=u.call(this,{...y,unadjustedMovement:!0});return m&&typeof m.catch=="function"?m.catch(()=>u.call(this,y)):m}}if(e&&wn({betterChat:r?.betterChat??!0,chatHistorySize:r?.chatHistorySize??200},B),e&&(r?.hpEnemyCounter??!0)&&ht(),e&&Hn(),e){let u=!1;setInterval(()=>{const y=document.getElementById("uiBase"),m=!!y&&y.className!=="onMenu"&&y.className!=="";m!==u&&(u=m,c.ipcRenderer.send("throttle-state",u?"game":"menu"))},2e3)}if(e&&(s?.showChangelog??!0)&&Kn(i,s?.lastSeenVersion||""),e){const u=()=>Array.from(document.querySelectorAll(".bpClaimB")).filter(y=>y.offsetParent!==null&&y.textContent?.trim()==="Claim");setInterval(()=>{const y=document.querySelector(".bpBotH");if(!y||y.offsetParent===null)return;const m=document.getElementById("claimAllBtn");if(m){u().length>0?(m.textContent="Claim All",m.classList.remove("disabled")):(m.textContent="Nothing to Claim",m.classList.add("disabled"));return}const k=u(),g=document.createElement("div");g.className="bpBtn skip",g.id="claimAllBtn",g.style.cssText="margin-left: 8px; cursor: pointer; background: #4CAF50;",k.length>0?g.textContent="Claim All":(g.textContent="Nothing to Claim",g.classList.add("disabled")),g.addEventListener("click",async()=>{if(g.classList.contains("disabled"))return;window.playSelect?.(.1);const x=u();if(x.length===0)return;g.textContent="Claiming...",g.classList.add("disabled");for(const N of x)N.click(),await new Promise(S=>setTimeout(S,200));const L=u();g.textContent=L.length>0?"Claim All":"Nothing to Claim",g.classList.toggle("disabled",L.length===0)}),y.appendChild(g)},500)}if((o?o.enabled:!0)&&Wt(B).catch(u=>B.error("[KCC] Userscript init error:",u)),e&&r?.joinAsSpectator){let u=0;const y=setInterval(()=>{if(++u>300){clearInterval(y);return}const m=document.getElementById("uiBase");if(!(!m||m.className===""))if(m.className==="onMenu"){const k=document.querySelector("#spectButton input");k&&!k.checked&&window.setSpect(1),clearInterval(y)}else clearInterval(y)},100)}if(e){const u={enabled:!0,targetLanguage:"en",showLanguageTag:!0,...l};gn(B,u)}if(e&&d?.enabled){let u=function(){let g,x="",L;const N=window,S=N.spectating;let C=null;if(typeof N.getGameActivity=="function")try{C=N.getGameActivity()}catch{}if(S)g="Spectating",C?.map&&(x=C.map);else{const P=document.getElementById("uiBase");if(P&&P.className==="onMenu")g="In Menus";else{if(C?.mode&&C?.map?g=C.mode+" on "+C.map:g=document.getElementById("mapInfo")?.textContent||"Playing Krunker",C?.class?.name)x=C.class.name;else{const T=document.getElementById("menuClassName");T?.textContent&&(x=T.textContent)}L=k}}(g!==y||x!==m)&&(L&&y!==g&&(k=Math.floor(Date.now()/1e3),L=k),y=g,m=x,c.ipcRenderer.send("discord-update",{details:g,state:x||void 0,startTimestamp:L,largeImageKey:"krunker",largeImageText:"Krunker Civilian Client"}))},y="",m="",k=Math.floor(Date.now()/1e3);u(),setInterval(u,5e3),document.addEventListener("pointerlockchange",u)}e&&c.ipcRenderer.invoke("alt-list").then(()=>{const u=document.createElement("div");u.id="kpcAltBtn",u.className="menuItem",u.setAttribute("onmouseenter","playTick()"),u.innerHTML='<span class="material-icons-outlined menBtnIcn" style="color:#4fc3f7">people</span><div class="menuItemTitle" style="font-size:13px">Accounts</div>';function y(){const k=document.getElementById("windowHolder"),g=document.getElementById("menuWindow"),x=document.getElementById("windowHeader");if(!k||!g||!x)return;if(k.style.display!=="none"&&x.innerText==="Alt Manager"){k.style.display="none";return}k.className="popupWin",k.style.display="block",g.classList.value="dark",g.style.cssText="width:800px;max-height:calc(100% - 330px);overflow-y:auto;top:50%;transform:translate(-50%,-50%);",x.innerText="Alt Manager";function L(){c.ipcRenderer.invoke("alt-list").then(S=>{let C='<div style="font-size:30px;text-align:center;margin:3px;font-weight:700;color:#fff;">Alt Manager</div><hr style="color:rgba(28,28,28,.5);"><div class="button buttonPI lgn" id="kpcAltAddBtn" style="text-align:center;width:98%;margin:3px;padding-top:5px;padding-bottom:13px;">Add Account</div><div class="amHolder" style="display:flex;flex-direction:column;justify-content:center;">';!S||S.length===0?C+='<div style="color:rgba(255,255,255,0.4);text-align:center;padding:20px 0;font-size:18px;">No saved accounts</div>':S.forEach((T,H)=>{C+='<div class="amAccName" style="display:flex;justify-content:flex-end;align-items:center;padding:4px 0;"><span style="margin-right:auto;color:#fff;font-size:18px;">'+b(T.label)+'</span><div class="button buttonG lgn kpc-alt-login" data-idx="'+H+'" style="width:70px;margin-right:0;padding-top:3px;padding-bottom:15px;transform:scale(0.75);"><span class="material-icons" style="vertical-align:bottom;color:#fff;font-size:30px;margin-bottom:-1px;">login</span></div><div class="verticalSeparator" style="height:35px;background:rgba(28,28,28,.3);"></div><div class="button buttonR lgn kpc-alt-del" data-idx="'+H+'" style="width:70px;margin-right:0;padding-top:3px;padding-bottom:15px;transform:scale(0.75);"><span class="material-icons" style="vertical-align:bottom;color:#fff;font-size:30px;margin-bottom:-1px;">delete</span></div></div>'}),C+="</div>",g.innerHTML=C;const P=document.getElementById("kpcAltAddBtn");P&&P.addEventListener("click",N),g.querySelectorAll(".kpc-alt-login").forEach(T=>{T.addEventListener("click",()=>{const H=parseInt(T.dataset.idx||"0",10);S[H]&&(k.style.display="none",c.ipcRenderer.invoke("alt-get-credentials",H).then(oe=>{oe&&Ct(oe)}))})}),g.querySelectorAll(".kpc-alt-del").forEach(T=>{T.addEventListener("click",()=>{const H=parseInt(T.dataset.idx||"0",10);confirm('Delete account "'+(S[H]?.label||"")+'"?')&&c.ipcRenderer.invoke("alt-remove",H).then(()=>L())})})})}function N(){g.innerHTML='<div class="setBodH" style="padding:20px;"><div style="font-size:25px;text-align:center;margin-bottom:15px;color:#fff;">Add Account</div><input class="accountInput" id="kpcAltLabel" type="text" placeholder="Label (e.g. Main, Alt1)" style="width:100%;margin-bottom:8px;"><input class="accountInput" id="kpcAltUser" type="text" placeholder="Krunker Username" style="width:100%;margin-bottom:8px;"><input class="accountInput" id="kpcAltPass" type="password" placeholder="Krunker Password" style="width:100%;margin-bottom:15px;"><div style="display:flex;gap:8px;"><div class="button buttonG lgn" id="kpcAltSaveBtn" style="flex:1;text-align:center;padding-top:5px;padding-bottom:13px;">Add Account</div><div class="button buttonR lgn" id="kpcAltBackBtn" style="width:120px;text-align:center;padding-top:5px;padding-bottom:13px;">Back</div></div></div>',g.querySelectorAll("input.accountInput").forEach(S=>{S.addEventListener("keydown",C=>C.stopPropagation())}),document.getElementById("kpcAltBackBtn").addEventListener("click",L),document.getElementById("kpcAltSaveBtn").addEventListener("click",()=>{const S=document.getElementById("kpcAltLabel").value.trim(),C=document.getElementById("kpcAltUser").value.trim(),P=document.getElementById("kpcAltPass").value;!S||!C||!P||c.ipcRenderer.invoke("alt-save",{label:S,username:C,password:P}).then(()=>L())})}L()}u.addEventListener("click",k=>{k.stopPropagation(),window.playSelect?.(),y()});function m(){if(document.getElementById("kpcAltBtn"))return!0;const k=document.getElementById("menuItemContainer");if(!k)return!1;const g=document.getElementById("clientExit");return g?k.insertBefore(u,g):k.appendChild(u),!0}if(!m()){let k=0;const g=setInterval(()=>{(m()||++k>60)&&clearInterval(g)},500)}})}).catch(()=>{});const n=setInterval(()=>{const t=window;Object.hasOwn(t,"showWindow")&&typeof t.showWindow=="function"&&Object.hasOwn(t,"windows")&&Array.isArray(t.windows)&&t.windows.length>=0&&typeof t.windows[0]<"u"&&typeof t.windows[0].changeTab=="function"&&(clearInterval(n),B.log("[KCC] Settings window found, hooking..."),Qn())},500)});c.ipcRenderer.on("main_did-finish-load-tab",()=>{B.log("[KCC] Tab page loaded"),window.closeClient=()=>window.close()});
MIT License

Copyright (c) 2020 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ajv-formats

JSON Schema formats for Ajv

[![Build Status](https://travis-ci.org/ajv-validator/ajv-formats.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv-formats)
[![npm](https://img.shields.io/npm/v/ajv-formats.svg)](https://www.npmjs.com/package/ajv-formats)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)

## Usage

```javascript
// ESM/TypeScript import
import Ajv from "ajv"
import addFormats from "ajv-formats"
// Node.js require:
const Ajv = require("ajv")
const addFormats = require("ajv-formats")

const ajv = new Ajv()
addFormats(ajv)
```

## Formats

The package defines these formats:

- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
- _time_: time with optional time-zone.
- _date-time_: date-time from the same source (time-zone is mandatory).
- _duration_: duration from [RFC3339](https://tools.ietf.org/html/rfc3339#appendix-A)
- _uri_: full URI.
- _uri-reference_: URI reference, including full and relative URIs.
- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)
- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url).
- _email_: email address.
- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
- _ipv4_: IP address v4.
- _ipv6_: IP address v6.
- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.
- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122).
- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).
- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).
- _byte_: base64 encoded data according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _int32_: signed 32 bits integer according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _int64_: signed 64 bits according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _float_: float according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _double_: double according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _password_: password string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)
- _binary_: binary string according to the [openApi 3.0.0 specification](https://spec.openapis.org/oas/v3.0.0#data-types)

See regular expressions used for format validation and the sources that were used in [formats.ts](https://github.com/ajv-validator/ajv-formats/blob/master/src/formats.ts).

**Please note**: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. These formats are available in [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) plugin.

## Keywords to compare values: `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum`

These keywords allow to define minimum/maximum constraints when the format keyword defines ordering (`compare` function in format definition).

These keywords are added to ajv instance when ajv-formats is used without options or with option `keywords: true`.

These keywords apply only to strings. If the data is not a string, the validation succeeds.

The value of keywords `formatMaximum`/`formatMinimum` and `formatExclusiveMaximum`/`formatExclusiveMinimum` should be a string or [\$data reference](https://github.com/ajv-validator/ajv/blob/master/docs/validation.md#data-reference). This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` keyword is not present schema compilation will throw exception.

When these keyword are added, they also add comparison functions to formats `"date"`, `"time"` and `"date-time"`. User-defined formats also can have comparison functions. See [addFormat](https://github.com/ajv-validator/ajv/blob/master/docs/api.md#api-addformat) method.

```javascript
require("ajv-formats")(ajv)

const schema = {
  type: "string",
  format: "date",
  formatMinimum: "2016-02-06",
  formatExclusiveMaximum: "2016-12-27",
}

const validDataList = ["2016-02-06", "2016-12-26"]

const invalidDataList = ["2016-02-05", "2016-12-27", "abc"]
```

## Options

Options can be passed via the second parameter. Options value can be

1. The list of format names that will be added to ajv instance:

```javascript
addFormats(ajv, ["date", "time"])
```

**Please note**: when ajv encounters an undefined format it throws exception (unless ajv instance was configured with `strict: false` option). To allow specific undefined formats they have to be passed to ajv instance via `formats` option with `true` value:

```javascript
const ajv = new Ajv((formats: {date: true, time: true})) // to ignore "date" and "time" formats in schemas.
```

2. Format validation mode (default is `"full"`) with optional list of format names and `keywords` option to add additional format comparison keywords:

```javascript
addFormats(ajv, {mode: "fast"})
```

or

```javascript
addFormats(ajv, {mode: "fast", formats: ["date", "time"], keywords: true})
```

In `"fast"` mode the following formats are simplified: `"date"`, `"time"`, `"date-time"`, `"uri"`, `"uri-reference"`, `"email"`. For example `"date"`, `"time"` and `"date-time"` do not validate ranges in `"fast"` mode, only string structure, and other formats have simplified regular expressions.

## Tests

```bash
npm install
git submodule update --init
npm test
```

## License

[MIT](https://github.com/ajv-validator/ajv-formats/blob/master/LICENSE)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
function fmtDef(validate, compare) {
    return { validate, compare };
}
exports.fullFormats = {
    // date: http://tools.ietf.org/html/rfc3339#section-5.6
    date: fmtDef(date, compareDate),
    // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
    time: fmtDef(time, compareTime),
    "date-time": fmtDef(date_time, compareDateTime),
    // duration: https://tools.ietf.org/html/rfc3339#appendix-A
    duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(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*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
    // uri-template: https://tools.ietf.org/html/rfc6570
    "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
    // For the source: https://gist.github.com/dperini/729294
    // For test cases: https://mathiasbynens.be/demo/url-regex
    url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
    email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
    hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
    // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
    ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
    ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
    regex,
    // uuid: http://tools.ietf.org/html/rfc4122
    uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
    // JSON-pointer: https://tools.ietf.org/html/rfc6901
    // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
    "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
    "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
    // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
    "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
    // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
    // byte: https://github.com/miguelmota/is-base64
    byte,
    // signed 32 bit integer
    int32: { type: "number", validate: validateInt32 },
    // signed 64 bit integer
    int64: { type: "number", validate: validateInt64 },
    // C-type float
    float: { type: "number", validate: validateNumber },
    // C-type double
    double: { type: "number", validate: validateNumber },
    // hint to the UI to hide input strings
    password: true,
    // unchecked string payload
    binary: true,
};
exports.fastFormats = {
    ...exports.fullFormats,
    date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
    time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareTime),
    "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
    // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
    uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
    "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
    // email (sources from jsen validator):
    // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
    // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
    email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
};
exports.formatNames = Object.keys(exports.fullFormats);
function isLeapYear(year) {
    // https://tools.ietf.org/html/rfc3339#appendix-C
    return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function date(str) {
    // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const year = +matches[1];
    const month = +matches[2];
    const day = +matches[3];
    return (month >= 1 &&
        month <= 12 &&
        day >= 1 &&
        day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]));
}
function compareDate(d1, d2) {
    if (!(d1 && d2))
        return undefined;
    if (d1 > d2)
        return 1;
    if (d1 < d2)
        return -1;
    return 0;
}
const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
function time(str, withTimeZone) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hour = +matches[1];
    const minute = +matches[2];
    const second = +matches[3];
    const timeZone = matches[5];
    return (((hour <= 23 && minute <= 59 && second <= 59) ||
        (hour === 23 && minute === 59 && second === 60)) &&
        (!withTimeZone || timeZone !== ""));
}
function compareTime(t1, t2) {
    if (!(t1 && t2))
        return undefined;
    const a1 = TIME.exec(t1);
    const a2 = TIME.exec(t2);
    if (!(a1 && a2))
        return undefined;
    t1 = a1[1] + a1[2] + a1[3] + (a1[4] || "");
    t2 = a2[1] + a2[2] + a2[3] + (a2[4] || "");
    if (t1 > t2)
        return 1;
    if (t1 < t2)
        return -1;
    return 0;
}
const DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dateTime = str.split(DATE_TIME_SEPARATOR);
    return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1], true);
}
function compareDateTime(dt1, dt2) {
    if (!(dt1 && dt2))
        return undefined;
    const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
    const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
    const res = compareDate(d1, d2);
    if (res === undefined)
        return undefined;
    return res || compareTime(t1, t2);
}
const NOT_URI_FRAGMENT = /\/|:/;
const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
function uri(str) {
    // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
    return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
function byte(str) {
    BYTE.lastIndex = 0;
    return BYTE.test(str);
}
const MIN_INT32 = -(2 ** 31);
const MAX_INT32 = 2 ** 31 - 1;
function validateInt32(value) {
    return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
}
function validateInt64(value) {
    // JSON and javascript max Int is 2**53, so any int that passes isInteger is valid for Int64
    return Number.isInteger(value);
}
function validateNumber() {
    return true;
}
const Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
    if (Z_ANCHOR.test(str))
        return false;
    try {
        new RegExp(str);
        return true;
    }
    catch (e) {
        return false;
    }
}
//# sourceMappingURL=formats.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const formats_1 = require("./formats");
const limit_1 = require("./limit");
const codegen_1 = require("ajv/dist/compile/codegen");
const fullName = new codegen_1.Name("fullFormats");
const fastName = new codegen_1.Name("fastFormats");
const formatsPlugin = (ajv, opts = { keywords: true }) => {
    if (Array.isArray(opts)) {
        addFormats(ajv, opts, formats_1.fullFormats, fullName);
        return ajv;
    }
    const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
    const list = opts.formats || formats_1.formatNames;
    addFormats(ajv, list, formats, exportName);
    if (opts.keywords)
        limit_1.default(ajv);
    return ajv;
};
formatsPlugin.get = (name, mode = "full") => {
    const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
    const f = formats[name];
    if (!f)
        throw new Error(`Unknown format "${name}"`);
    return f;
};
function addFormats(ajv, list, fs, exportName) {
    var _a;
    var _b;
    (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : (_b.formats = codegen_1._ `require("ajv-formats/dist/formats").${exportName}`);
    for (const f of list)
        ajv.addFormat(f, fs[f]);
}
module.exports = exports = formatsPlugin;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = formatsPlugin;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatLimitDefinition = void 0;
const ajv_1 = require("ajv");
const codegen_1 = require("ajv/dist/compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => codegen_1.str `should be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => codegen_1._ `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
exports.formatLimitDefinition = {
    keyword: Object.keys(KWDs),
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self } = it;
        if (!opts.validateFormats)
            return;
        const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format");
        if (fCxt.$data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fmt = gen.const("fmt", codegen_1._ `${fmts}[${fCxt.schemaCode}]`);
            cxt.fail$data(codegen_1.or(codegen_1._ `typeof ${fmt} != "object"`, codegen_1._ `${fmt} instanceof RegExp`, codegen_1._ `typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
            const format = fCxt.schema;
            const fmtDef = self.formats[format];
            if (!fmtDef || fmtDef === true)
                return;
            if (typeof fmtDef != "object" ||
                fmtDef instanceof RegExp ||
                typeof fmtDef.compare != "function") {
                throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
            }
            const fmt = gen.scopeValue("formats", {
                key: format,
                ref: fmtDef,
                code: opts.code.formats ? codegen_1._ `${opts.code.formats}${codegen_1.getProperty(format)}` : undefined,
            });
            cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
            return codegen_1._ `${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
    },
    dependencies: ["format"],
};
const formatLimitPlugin = (ajv) => {
    ajv.addKeyword(exports.formatLimitDefinition);
    return ajv;
};
exports.default = formatLimitPlugin;
//# sourceMappingURL=limit.js.mapconst Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  required: ["foo", "bar"],
  additionalProperties: false,
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}
The MIT License (MIT)

Copyright (c) 2015-2021 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg">

&nbsp;

# Ajv JSON schema validator

The fastest JSON validator for Node.js and browser.

Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/).

[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild)
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master)
[![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-70F0F9)](https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2F8KvvURM6J38Gdq9dCuPswMOkMny0xCOJ%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAr8rPVRuMOXv6kwF2yUAap-eoVg-9ssOFCi1fIrxTUw0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion&data=%7B%22type%22%3A%22group%22%2C%22groupLinkId%22%3A%224pwLRgWHU9tlroMWHz0uOg%3D%3D%22%7D)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)

## Ajv sponsors

[<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv)

[<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)

[<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv)

## Contributing

More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation.

Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html).

## Documentation

All documentation is available on the [Ajv website](https://ajv.js.org).

Some useful site links:

- [Getting started](https://ajv.js.org/guide/getting-started.html)
- [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html)
- [API reference](https://ajv.js.org/api.html)
- [Strict mode](https://ajv.js.org/strict-mode.html)
- [Standalone validation code](https://ajv.js.org/standalone.html)
- [Security considerations](https://ajv.js.org/security.html)
- [Command line interface](https://ajv.js.org/packages/ajv-cli.html)
- [Frequently Asked Questions](https://ajv.js.org/faq.html)

## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)

Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!

Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.

Please sponsor Ajv via:

- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)
- [Ajv Open Collective](https://opencollective.com/ajv)

Thank you.

#### Open Collective sponsors

<a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a>

<a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/12/website"><img src="https://opencollective.com/ajv/organization/12/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/13/website"><img src="https://opencollective.com/ajv/organization/13/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/14/website"><img src="https://opencollective.com/ajv/organization/14/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/15/website"><img src="https://opencollective.com/ajv/organization/15/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/16/website"><img src="https://opencollective.com/ajv/organization/16/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/17/website"><img src="https://opencollective.com/ajv/organization/17/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/18/website"><img src="https://opencollective.com/ajv/organization/18/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/19/website"><img src="https://opencollective.com/ajv/organization/19/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/20/website"><img src="https://opencollective.com/ajv/organization/20/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/21/website"><img src="https://opencollective.com/ajv/organization/21/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/22/website"><img src="https://opencollective.com/ajv/organization/22/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/23/website"><img src="https://opencollective.com/ajv/organization/23/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/24/website"><img src="https://opencollective.com/ajv/organization/24/avatar.svg"></a>

## Performance

Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:

- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)

Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):

[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus/schemasafe|is-my-json-valid|djv|@cfworker/json-schema|jsonschema/=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)

## Features

- Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6):
  - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html))
  - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions:
    - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator).
    - keyword [nullable](https://ajv.js.org/json-schema.html#nullable).
  - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available)
  - support of recursive references between schemas
  - correct string lengths for strings with unicode pairs
  - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin).
  - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema)
- NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/):
  - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html))
  - meta-schema for JTD schemas
  - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema)
- supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current
- [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation
- "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors)
- [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation
- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package
- [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties)
- [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items
- [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords
- [user-defined keywords](https://ajv.js.org/guide/user-keywords.html)
- additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package
- [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords
- [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords

## Install

To install version 8:

```
npm install ajv
```

## <a name="usage"></a>Getting started

Try it in the Node.js REPL: https://runkit.com/npm/ajv

In JavaScript:

```javascript
// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv")

const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}

const schema = {
  type: "object",
  properties: {
    foo: {type: "integer"},
    bar: {type: "string"},
  },
  required: ["foo"],
  additionalProperties: false,
}

const data = {
  foo: 1,
  bar: "abc",
}

const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
```

Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html)

## Changes history

See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases)

**Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0)

[Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0)

[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0).

## Code of conduct

Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md).

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.

## Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.

## Open-source software support

Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.

## License

[MIT](./LICENSE)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const dynamic_1 = require("./vocabularies/dynamic");
const next_1 = require("./vocabularies/next");
const unevaluated_1 = require("./vocabularies/unevaluated");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
class Ajv2019 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(dynamic_1.default);
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        this.addVocabulary(next_1.default);
        this.addVocabulary(unevaluated_1.default);
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2019_09_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2019 = Ajv2019;
module.exports = exports = Ajv2019;
module.exports.Ajv2019 = Ajv2019;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2019;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2019.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;
const core_1 = require("./core");
const draft2020_1 = require("./vocabularies/draft2020");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2020_12_1 = require("./refs/json-schema-2020-12");
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
class Ajv2020 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2020_12_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2020 = Ajv2020;
module.exports = exports = Ajv2020;
module.exports.Ajv2020 = Ajv2020;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2020;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const discriminator_1 = require("./vocabularies/discriminator");
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
    _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        const metaSchema = this.opts.$data
            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
            : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=ajv.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
    constructor(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        return false;
    }
    get names() {
        return { [this.str]: 1 };
    }
}
exports.Name = Name;
class _Code extends _CodeOrName {
    constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        if (this._items.length > 1)
            return false;
        const item = this._items[0];
        return item === "" || item === '""';
    }
    get str() {
        var _a;
        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
    }
    get names() {
        var _a;
        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
            if (c instanceof Name)
                names[c.str] = (names[c.str] || 0) + 1;
            return names;
        }, {})));
    }
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
    const code = [strs[0]];
    let i = 0;
    while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
    }
    return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
    if (arg instanceof _Code)
        code.push(...arg._items);
    else if (arg instanceof Name)
        code.push(arg);
    else
        code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
        if (expr[i] === plus) {
            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
            if (res !== undefined) {
                expr.splice(i - 1, 3, res);
                continue;
            }
            expr[i++] = "+";
        }
        i++;
    }
}
function mergeExprItems(a, b) {
    if (b === '""')
        return a;
    if (a === '""')
        return b;
    if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
            return;
        if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
        return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.slice(1)}`;
    return;
}
function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null
        ? x
        : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
    return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
    return JSON.stringify(x)
        .replace(/\u2028/g, "\\u2028")
        .replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
    return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = require("./code");
const scope_1 = require("./scope");
var code_2 = require("./code");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
var scope_2 = require("./scope");
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
exports.operators = {
    GT: new code_1._Code(">"),
    GTE: new code_1._Code(">="),
    LT: new code_1._Code("<"),
    LTE: new code_1._Code("<="),
    EQ: new code_1._Code("==="),
    NEQ: new code_1._Code("!=="),
    NOT: new code_1._Code("!"),
    OR: new code_1._Code("||"),
    AND: new code_1._Code("&&"),
    ADD: new code_1._Code("+"),
};
class Node {
    optimizeNodes() {
        return this;
    }
    optimizeNames(_names, _constants) {
        return this;
    }
}
class Def extends Node {
    constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
    }
    render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (!names[this.name.str])
            return;
        if (this.rhs)
            this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
    }
}
class Assign extends Node {
    constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
    }
    render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
            return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
    }
}
class AssignOp extends Assign {
    constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
    }
    render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
    }
}
class Label extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        return `${this.label}:` + _n;
    }
}
class Break extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
    }
}
class Throw extends Node {
    constructor(error) {
        super();
        this.error = error;
    }
    render({ _n }) {
        return `throw ${this.error};` + _n;
    }
    get names() {
        return this.error.names;
    }
}
class AnyCode extends Node {
    constructor(code) {
        super();
        this.code = code;
    }
    render({ _n }) {
        return `${this.code};` + _n;
    }
    optimizeNodes() {
        return `${this.code}` ? this : undefined;
    }
    optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
    }
    get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
    }
}
class ParentNode extends Node {
    constructor(nodes = []) {
        super();
        this.nodes = nodes;
    }
    render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
    }
    optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            const n = nodes[i].optimizeNodes();
            if (Array.isArray(n))
                nodes.splice(i, 1, ...n);
            else if (n)
                nodes[i] = n;
            else
                nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    optimizeNames(names, constants) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            // iterating backwards improves 1-pass optimization
            const n = nodes[i];
            if (n.optimizeNames(names, constants))
                continue;
            subtractNames(names, n.names);
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
    }
}
class BlockNode extends ParentNode {
    render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
    }
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
    constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
    }
    render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
            code += "else " + this.else.render(opts);
        return code;
    }
    optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
            return this.nodes; // else is ignored here
        let e = this.else;
        if (e) {
            const ns = e.optimizeNodes();
            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e) {
            if (cond === false)
                return e instanceof If ? e : e.nodes;
            if (this.nodes.length)
                return this;
            return new If(not(cond), e instanceof If ? [e] : e.nodes);
        }
        if (cond === false || !this.nodes.length)
            return undefined;
        return this;
    }
    optimizeNames(names, constants) {
        var _a;
        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
            return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
            addNames(names, this.else.names);
        return names;
    }
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
    constructor(iteration) {
        super();
        this.iteration = iteration;
    }
    render(opts) {
        return `for(${this.iteration})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iteration.names);
    }
}
class ForRange extends For {
    constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
    }
    render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
    }
    get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
    }
}
class ForIter extends For {
    constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
    }
    render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iterable.names);
    }
}
class Func extends BlockNode {
    constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
    }
    render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
    }
}
Func.kind = "func";
class Return extends ParentNode {
    render(opts) {
        return "return " + super.render(opts);
    }
}
Return.kind = "return";
class Try extends BlockNode {
    render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
            code += this.catch.render(opts);
        if (this.finally)
            code += this.finally.render(opts);
        return code;
    }
    optimizeNodes() {
        var _a, _b;
        super.optimizeNodes();
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
    }
    optimizeNames(names, constants) {
        var _a, _b;
        super.optimizeNames(names, constants);
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        if (this.catch)
            addNames(names, this.catch.names);
        if (this.finally)
            addNames(names, this.finally.names);
        return names;
    }
}
class Catch extends BlockNode {
    constructor(error) {
        super();
        this.error = error;
    }
    render(opts) {
        return `catch(${this.error})` + super.render(opts);
    }
}
Catch.kind = "catch";
class Finally extends BlockNode {
    render(opts) {
        return "finally" + super.render(opts);
    }
}
Finally.kind = "finally";
class CodeGen {
    constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
    }
    toString() {
        return this._root.render(this.opts);
    }
    // returns unique name in the internal scope
    name(prefix) {
        return this._scope.name(prefix);
    }
    // reserves unique name in the external scope
    scopeName(prefix) {
        return this._extScope.name(prefix);
    }
    // reserves unique name in the external scope and assigns value to it
    scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
        vs.add(name);
        return name;
    }
    getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
    }
    // return code that assigns values in the external scope to the names that are used internally
    // (same names that were returned by gen.scopeName or gen.scopeValue)
    scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
    }
    scopeCode() {
        return this._extScope.scopeCode(this._values);
    }
    _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== undefined && constant)
            this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
    }
    // `const` declaration (`var` in es5 mode)
    const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
    }
    // `let` declaration with optional assignment (`var` in es5 mode)
    let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
    }
    // `var` declaration with optional assignment
    var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
    }
    // assignment code
    assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
    }
    // `+=` code
    add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
    }
    // appends passed SafeExpr to code or executes Block
    code(c) {
        if (typeof c == "function")
            c();
        else if (c !== code_1.nil)
            this._leafNode(new AnyCode(c));
        return this;
    }
    // returns code for object literal for the passed argument list of key-value pairs
    object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
            if (code.length > 1)
                code.push(",");
            code.push(key);
            if (key !== value || this.opts.es5) {
                code.push(":");
                (0, code_1.addCodeArg)(code, value);
            }
        }
        code.push("}");
        return new code_1._Code(code);
    }
    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
    if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
            this.code(thenBody).else().code(elseBody).endIf();
        }
        else if (thenBody) {
            this.code(thenBody).endIf();
        }
        else if (elseBody) {
            throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
    }
    // `else if` clause - invalid without `if` or after `else` clauses
    elseIf(condition) {
        return this._elseNode(new If(condition));
    }
    // `else` clause - only valid after `if` or `else if` clauses
    else() {
        return this._elseNode(new Else());
    }
    // end `if` statement (needed if gen.if was used only with condition)
    endIf() {
        return this._endBlockNode(If, Else);
    }
    _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
            this.code(forBody).endFor();
        return this;
    }
    // a generic `for` clause (or statement if `forBody` is passed)
    for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
    }
    // `for` statement for a range of values
    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
    }
    // `for-of` statement (in es5 mode replace with a normal for loop)
    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
                this.var(name, (0, code_1._) `${arr}[${i}]`);
                forBody(name);
            });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
    }
    // `for-in` statement.
    // With option `ownProperties` replaced with a `for-of` loop for object keys
    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
    }
    // end `for` loop
    endFor() {
        return this._endBlockNode(For);
    }
    // `label` statement
    label(label) {
        return this._leafNode(new Label(label));
    }
    // `break` statement
    break(label) {
        return this._leafNode(new Break(label));
    }
    // `return` statement
    return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
            throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
    }
    // `try` statement
    try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
            throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
            const error = this.name("e");
            this._currNode = node.catch = new Catch(error);
            catchCode(error);
        }
        if (finallyCode) {
            this._currNode = node.finally = new Finally();
            this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
    }
    // `throw` statement
    throw(error) {
        return this._leafNode(new Throw(error));
    }
    // start self-balancing block
    block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
            this.code(body).endBlock(nodeCount);
        return this;
    }
    // end the current self-balancing block
    endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === undefined)
            throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
    }
    // `function` heading (or definition if funcBody is passed)
    func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
            this.code(funcBody).endFunc();
        return this;
    }
    // end function definition
    endFunc() {
        return this._endBlockNode(Func);
    }
    optimize(n = 1) {
        while (n-- > 0) {
            this._root.optimizeNodes();
            this._root.optimizeNames(this._root.names, this._constants);
        }
    }
    _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
    }
    _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
    }
    _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || (N2 && n instanceof N2)) {
            this._nodes.pop();
            return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
    }
    _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
            throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
    }
    get _root() {
        return this._nodes[0];
    }
    get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
    }
    set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
    }
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
    return names;
}
function addExprNames(names, from) {
    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
    if (expr instanceof code_1.Name)
        return replaceName(expr);
    if (!canOptimize(expr))
        return expr;
    return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
            c = replaceName(c);
        if (c instanceof code_1._Code)
            items.push(...c._items);
        else
            items.push(c);
        return items;
    }, []));
    function replaceName(n) {
        const c = constants[n.str];
        if (c === undefined || names[n.str] !== 1)
            return n;
        delete names[n.str];
        return c;
    }
    function canOptimize(e) {
        return (e instanceof code_1._Code &&
            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
    }
}
function subtractNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
    return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
    return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = require("./code");
class ValueError extends Error {
    constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
    }
}
var UsedValueState;
(function (UsedValueState) {
    UsedValueState[UsedValueState["Started"] = 0] = "Started";
    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
    const: new code_1.Name("const"),
    let: new code_1.Name("let"),
    var: new code_1.Name("var"),
};
class Scope {
    constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
    }
    toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
    }
    name(prefix) {
        return new code_1.Name(this._newName(prefix));
    }
    _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
    }
    _nameGroup(prefix) {
        var _a, _b;
        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return (this._names[prefix] = { prefix, index: 0 });
    }
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
    constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
    }
    setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
    }
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
    constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
    }
    get() {
        return this._scope;
    }
    name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
    }
    value(nameOrPrefix, value) {
        var _a;
        if (value.ref === undefined)
            throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
        let vs = this._values[prefix];
        if (vs) {
            const _name = vs.get(valueKey);
            if (_name)
                return _name;
        }
        else {
            vs = this._values[prefix] = new Map();
        }
        vs.set(valueKey, name);
        const s = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s.length;
        s[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
    }
    getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
            return;
        return vs.get(keyOrRef);
    }
    scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
            if (name.scopePath === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return (0, code_1._) `${scopeName}${name.scopePath}`;
        });
    }
    scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
            if (name.value === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return name.value.code;
        }, usedValues, getCode);
    }
    _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
            const vs = values[prefix];
            if (!vs)
                continue;
            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
            vs.forEach((name) => {
                if (nameSet.has(name))
                    return;
                nameSet.set(name, UsedValueState.Started);
                let c = valueCode(name);
                if (c) {
                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
                }
                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
                }
                else {
                    throw new ValueError(name);
                }
                nameSet.set(name, UsedValueState.Completed);
            });
        }
        return code;
    }
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = require("./codegen");
const util_1 = require("./util");
const names_1 = require("./names");
exports.keywordError = {
    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
    message: ({ keyword, schemaType }) => schemaType
        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
        addError(gen, errObj);
    }
    else {
        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
    }
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    addError(gen, errObj);
    if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
    }
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
    gen.assign(names_1.default.errors, errsCount);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
    /* istanbul ignore if */
    if (errsCount === undefined)
        throw new Error("ajv implementation error");
    const err = gen.name("err");
    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
            gen.assign((0, codegen_1._) `${err}.data`, data);
        }
    });
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
    const err = gen.const("err", errObj);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
    const { gen, validateName, schemaEnv } = it;
    if (schemaEnv.$async) {
        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
        gen.return(false);
    }
}
const E = {
    keyword: new codegen_1.Name("keyword"),
    schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
    params: new codegen_1.Name("params"),
    propertyName: new codegen_1.Name("propertyName"),
    message: new codegen_1.Name("message"),
    schema: new codegen_1.Name("schema"),
    parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
    const { createErrors } = cxt.it;
    if (createErrors === false)
        return (0, codegen_1._) `{}`;
    return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
    const { gen, it } = cxt;
    const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths),
    ];
    extraErrorProps(cxt, error, keyValues);
    return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
    const instPath = instancePath
        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
        : errorPath;
    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
    if (schemaPath) {
        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
    }
    return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
    const { keyword, data, schemaValue, it } = cxt;
    const { opts, propertyName, topSchemaRef, schemaPath } = it;
    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
    if (opts.messages) {
        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
    }
    if (opts.verbose) {
        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
    }
    if (propertyName)
        keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = require("./codegen");
const validation_error_1 = require("../runtime/validation_error");
const names_1 = require("./names");
const resolve_1 = require("./resolve");
const util_1 = require("./util");
const validate_1 = require("./validate");
class SchemaEnv {
    constructor(env) {
        var _a;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
            schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
    }
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
    // TODO refactor - remove compilations
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
            ref: validation_error_1.default,
            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
        });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
            : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._) `""`,
        opts: this.opts,
        self: this,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        // gen.optimize(1)
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
        if (this.opts.code.process)
            sourceCode = this.opts.code.process(sourceCode, sch);
        // console.log("\n\n\n *** \n", sourceCode)
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
            validate.$async = true;
        if (this.opts.code.source === true) {
            validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
            const { props, items } = schemaCxt;
            validate.evaluated = {
                props: props instanceof codegen_1.Name ? undefined : props,
                items: items instanceof codegen_1.Name ? undefined : items,
                dynamicProps: props instanceof codegen_1.Name,
                dynamicItems: items instanceof codegen_1.Name,
            };
            if (validate.source)
                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
    }
    catch (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
            this.logger.error("Error compiling schema, function code:", sourceCode);
        // console.log("\n\n\n *** \n", sourceCode, this.opts)
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
    var _a;
    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
    const schOrFunc = root.refs[ref];
    if (schOrFunc)
        return schOrFunc;
    let _sch = resolve.call(this, root, ref);
    if (_sch === undefined) {
        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
        const { schemaId } = this.opts;
        if (schema)
            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === undefined)
        return;
    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
            return sch;
    }
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
    let sch;
    while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
    const p = this.opts.uriResolver.parse(ref);
    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
    }
    const id = (0, resolve_1.normalizeId)(refPath);
    const schOrRef = this.refs[id] || this.schemas[id];
    if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
            return;
        return getJsonPointer.call(this, p, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
    if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
    if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a;
    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
        return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
            return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === undefined)
            return;
        schema = partSchema;
        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
    }
    // even though resolution failed we need to return SchemaEnv to throw exception
    // so that compileAsync loads missing schema.
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
        return env;
    return undefined;
}
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const type_1 = require("../../vocabularies/jtd/type");
const parseJson_1 = require("../../runtime/parseJson");
const util_1 = require("../util");
const timestamp_1 = require("../../runtime/timestamp");
const genParse = {
    elements: parseElements,
    values: parseValues,
    discriminator: parseDiscriminator,
    properties: parseProperties,
    optionalProperties: parseProperties,
    enum: parseEnum,
    type: parseType,
    ref: parseRef,
};
function compileParser(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const parseName = gen.scopeName("parse");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
        parseName,
        char: gen.name("c"),
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.parseName = parseName;
        parserFunction(cxt);
        gen.optimize(this.opts.code.optimize);
        const parseFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
        const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
        const parse = makeParse(this.scope.get());
        this.scope.value(parseName, { ref: parse });
        sch.parse = parse;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling parser, function code:", sourceCode);
        delete sch.parse;
        delete sch.parseName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileParser;
const undef = (0, codegen_1._) `undefined`;
function parserFunction(cxt) {
    const { gen, parseName, char } = cxt;
    gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
        gen.let(names_1.default.data);
        gen.let(char);
        gen.assign((0, codegen_1._) `${parseName}.message`, undef);
        gen.assign((0, codegen_1._) `${parseName}.position`, undef);
        gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`);
        gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`);
        parseCode(cxt);
        skipWhitespace(cxt);
        gen.if(names_1.default.jsonPart, () => {
            gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
            gen.return(names_1.default.data);
        });
        gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
        jsonSyntaxError(cxt);
    });
}
function parseCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    if (form)
        parseNullable(cxt, genParse[form]);
    else
        parseEmpty(cxt);
}
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
function parseNullable(cxt, parseForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return parseForm(cxt);
    tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
}
function parseElements(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "[");
    const ix = gen.let("i", 0);
    gen.assign(data, (0, codegen_1._) `[]`);
    parseItems(cxt, "]", () => {
        const el = gen.let("el");
        parseCode({ ...cxt, schema: schema.elements, data: el });
        gen.assign((0, codegen_1._) `${data}[${ix}++]`, el);
    });
}
function parseValues(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
}
function parseItems(cxt, endToken, block) {
    tryParseItems(cxt, endToken, block);
    parseToken(cxt, endToken);
}
function tryParseItems(cxt, endToken, block) {
    const { gen } = cxt;
    gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
        block();
        tryParseToken(cxt, ",", () => gen.break(), hasItem);
    });
    function hasItem() {
        tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
    }
}
function parseKeyValue(cxt, schema) {
    const { gen } = cxt;
    const key = gen.let("key");
    parseString({ ...cxt, data: key });
    parseToken(cxt, ":");
    parsePropertyValue(cxt, key, schema);
}
function parseDiscriminator(cxt) {
    const { gen, data, schema } = cxt;
    const { discriminator, mapping } = schema;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    const startPos = gen.const("pos", names_1.default.jsonPos);
    const value = gen.let("value");
    const tag = gen.let("tag");
    tryParseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => {
            parseString({ ...cxt, data: tag });
            gen.assign((0, codegen_1._) `${data}[${key}]`, tag);
            gen.break();
        }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
        );
    });
    gen.assign(names_1.default.jsonPos, startPos);
    gen.if((0, codegen_1._) `${tag} === undefined`);
    parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`);
    for (const tagValue in mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
    }
    gen.else();
    parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`);
    gen.endIf();
}
function parseProperties(cxt) {
    const { gen, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseSchemaProperties(cxt);
}
function parseSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties, additionalProperties } = schema;
    parseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if(false);
        parseDefinedProperty(cxt, key, properties);
        parseDefinedProperty(cxt, key, optionalProperties);
        if (discriminator) {
            gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`);
            const tag = gen.let("tag");
            parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
        }
        gen.else();
        if (additionalProperties) {
            parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` });
        }
        else {
            parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`);
        }
        gen.endIf();
    });
    if (properties) {
        const hasProp = (0, code_1.hasPropFunc)(gen);
        const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`));
        gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`));
    }
}
function parseDefinedProperty(cxt, key, schemas = {}) {
    const { gen } = cxt;
    for (const prop in schemas) {
        gen.elseIf((0, codegen_1._) `${key} === ${prop}`);
        parsePropertyValue(cxt, key, schemas[prop]);
    }
}
function parsePropertyValue(cxt, key, schema) {
    parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` });
}
function parseType(cxt) {
    const { gen, schema, data, self } = cxt;
    switch (schema.type) {
        case "boolean":
            parseBoolean(cxt);
            break;
        case "string":
            parseString(cxt);
            break;
        case "timestamp": {
            parseString(cxt);
            const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
            const { allowDate, parseDate } = self.opts;
            const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`;
            const fail = parseDate
                ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`)
                : notValid;
            gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`));
            break;
        }
        case "float32":
        case "float64":
            parseNumber(cxt);
            break;
        default: {
            const t = schema.type;
            if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
                parseNumber(cxt, 16); // 2 ** 53 - max safe integer
                if (t === "uint32") {
                    gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
                }
            }
            else {
                const [min, max, maxDigits] = type_1.intRange[t];
                parseNumber(cxt, maxDigits);
                gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
            }
        }
    }
}
function parseString(cxt) {
    parseToken(cxt, '"');
    parseWith(cxt, parseJson_1.parseJsonString);
}
function parseEnum(cxt) {
    const { gen, data, schema } = cxt;
    const enumSch = schema.enum;
    parseToken(cxt, '"');
    // TODO loopEnum
    gen.if(false);
    for (const value of enumSch) {
        const valueStr = JSON.stringify(value).slice(1); // remove starting quote
        gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`);
        gen.assign(data, (0, codegen_1.str) `${value}`);
        gen.add(names_1.default.jsonPos, valueStr.length);
    }
    gen.else();
    jsonSyntaxError(cxt);
    gen.endIf();
}
function parseNumber(cxt, maxDigits) {
    const { gen } = cxt;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
}
function parseBooleanToken(bool, fail) {
    return (cxt) => {
        const { gen, data } = cxt;
        tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
    };
}
function parseRef(cxt) {
    const { gen, self, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return parseCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    partialParse(cxt, getParser(gen, sch), true);
}
function getParser(gen, sch) {
    return sch.parse
        ? gen.scopeValue("parse", { ref: sch.parse })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
}
function parseEmpty(cxt) {
    parseWith(cxt, parseJson_1.parseJson);
}
function parseWith(cxt, parseFunc, args) {
    partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args);
}
function partialParse(cxt, parseFunc, args) {
    const { gen, data } = cxt;
    gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`);
    gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`);
    gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`));
}
function parseToken(cxt, tok) {
    tryParseToken(cxt, tok, jsonSyntaxError);
}
function tryParseToken(cxt, tok, fail, success) {
    const { gen } = cxt;
    const n = tok.length;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => {
        gen.add(names_1.default.jsonPos, n);
        success === null || success === void 0 ? void 0 : success(cxt);
    }, () => fail(cxt));
}
function skipWhitespace({ gen, char: c }) {
    gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
}
function jsonSlice(len) {
    return len === 1
        ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]`
        : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
}
function jsonSyntaxError(cxt) {
    parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
}
function parsingError({ gen, parseName }, msg) {
    gen.assign((0, codegen_1._) `${parseName}.message`, msg);
    gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
    gen.return(undef);
}
//# sourceMappingURL=parse.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const util_1 = require("../util");
const quote_1 = require("../../runtime/quote");
const genSerialize = {
    elements: serializeElements,
    values: serializeValues,
    discriminator: serializeDiscriminator,
    properties: serializeProperties,
    optionalProperties: serializeProperties,
    enum: serializeString,
    type: serializeType,
    ref: serializeRef,
};
function compileSerializer(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const serializeName = gen.scopeName("serialize");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.serializeName = serializeName;
        gen.func(serializeName, names_1.default.data, false, () => {
            gen.let(names_1.default.json, (0, codegen_1.str) ``);
            serializeCode(cxt);
            gen.return(names_1.default.json);
        });
        gen.optimize(this.opts.code.optimize);
        const serializeFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
        const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
        const serialize = makeSerialize(this.scope.get());
        this.scope.value(serializeName, { ref: serialize });
        sch.serialize = serialize;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling serializer, function code:", sourceCode);
        delete sch.serialize;
        delete sch.serializeName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileSerializer;
function serializeCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return serializeForm(cxt);
    gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `[`);
    const first = gen.let("first", true);
    gen.forOf("el", data, (el) => {
        addComma(cxt, first);
        serializeCode({ ...cxt, schema: schema.elements, data: el });
    });
    gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    const first = gen.let("first", true);
    gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
    const { gen, data } = cxt;
    addComma(cxt, first);
    serializeString({ ...cxt, data: key });
    gen.add(names_1.default.json, (0, codegen_1.str) `:`);
    const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
    const { gen, schema, data } = cxt;
    const { discriminator } = schema;
    gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
    const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
    serializeString({ ...cxt, data: tag });
    gen.if(false);
    for (const tagValue in schema.mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        const sch = schema.mapping[tagValue];
        serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
    }
    gen.endIf();
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
    const { gen } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    serializeSchemaProperties(cxt);
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties } = schema;
    const props = keys(properties);
    const optProps = keys(optionalProperties);
    const allProps = allProperties(props.concat(optProps));
    let first = !discriminator;
    let firstProp;
    for (const key of props) {
        if (first)
            first = false;
        else
            gen.add(names_1.default.json, (0, codegen_1.str) `,`);
        serializeProperty(key, properties[key], keyValue(key));
    }
    if (first)
        firstProp = gen.let("first", true);
    for (const key of optProps) {
        const value = keyValue(key);
        gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => {
            addComma(cxt, firstProp);
            serializeProperty(key, optionalProperties[key], value);
        });
    }
    if (schema.additionalProperties) {
        gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)));
    }
    function keys(ps) {
        return ps ? Object.keys(ps) : [];
    }
    function allProperties(ps) {
        if (discriminator)
            ps.push(discriminator);
        if (new Set(ps).size !== ps.length) {
            throw new Error("JTD: properties/optionalProperties/disciminator overlap");
        }
        return ps;
    }
    function keyValue(key) {
        return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    }
    function serializeProperty(key, propSchema, value) {
        gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
        serializeCode({ ...cxt, schema: propSchema, data: value });
    }
    function isAdditional(key, ps) {
        return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
    }
}
function serializeType(cxt) {
    const { gen, schema, data } = cxt;
    switch (schema.type) {
        case "boolean":
            gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
            break;
        case "string":
            serializeString(cxt);
            break;
        case "timestamp":
            gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
            break;
        default:
            serializeNumber(cxt);
    }
}
function serializeString({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data, self }) {
    const condition = (0, codegen_1._) `${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`;
    if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
        gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
    }
    else {
        // specialNumbers === "null"
        gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._) `null`), () => gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`));
    }
}
function serializeRef(cxt) {
    const { gen, self, data, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return serializeCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
    return sch.serialize
        ? gen.scopeValue("serialize", { ref: sch.serialize })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
    if (first) {
        gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
    }
    else {
        gen.add(names_1.default.json, (0, codegen_1.str) `,`);
    }
}
//# sourceMappingURL=serialize.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jtdForms = void 0;
exports.jtdForms = [
    "elements",
    "values",
    "discriminator",
    "properties",
    "optionalProperties",
    "enum",
    "type",
    "ref",
];
//# sourceMappingURL=types.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("./codegen");
const names = {
    // validation function arguments
    data: new codegen_1.Name("data"), // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
    errors: new codegen_1.Name("errors"), // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart"),
};
exports.default = names;
//# sourceMappingURL=names.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const resolve_1 = require("./resolve");
class MissingRefError extends Error {
    constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
    }
}
exports.default = MissingRefError;
//# sourceMappingURL=ref_error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = require("./util");
const equal = require("fast-deep-equal");
const traverse = require("json-schema-traverse");
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const",
]);
function inlineRef(schema, limit = true) {
    if (typeof schema == "boolean")
        return true;
    if (limit === true)
        return !hasRef(schema);
    if (!limit)
        return false;
    return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor",
]);
function hasRef(schema) {
    for (const key in schema) {
        if (REF_KEYWORDS.has(key))
            return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
            return true;
        if (typeof sch == "object" && hasRef(sch))
            return true;
    }
    return false;
}
function countKeys(schema) {
    let count = 0;
    for (const key in schema) {
        if (key === "$ref")
            return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
            continue;
        if (typeof schema[key] == "object") {
            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
        }
        if (count === Infinity)
            return Infinity;
    }
    return count;
}
function getFullPath(resolver, id = "", normalize) {
    if (normalize !== false)
        id = normalizeId(id);
    const p = resolver.parse(id);
    return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
    const serialized = resolver.serialize(p);
    return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
    id = normalizeId(id);
    return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
        return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === undefined)
            return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
            innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
            // eslint-disable-next-line @typescript-eslint/unbound-method
            const _resolve = this.opts.uriResolver.resolve;
            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
            if (schemaRefs.has(ref))
                throw ambiguos(ref);
            schemaRefs.add(ref);
            let schOrRef = this.refs[ref];
            if (typeof schOrRef == "string")
                schOrRef = this.refs[schOrRef];
            if (typeof schOrRef == "object") {
                checkAmbiguosRef(sch, schOrRef.schema, ref);
            }
            else if (ref !== normalizeId(fullPath)) {
                if (ref[0] === "#") {
                    checkAmbiguosRef(sch, localRefs[ref], ref);
                    localRefs[ref] = sch;
                }
                else {
                    this.refs[ref] = fullPath;
                }
            }
            return ref;
        }
        function addAnchor(anchor) {
            if (typeof anchor == "string") {
                if (!ANCHOR.test(anchor))
                    throw new Error(`invalid anchor "${anchor}"`);
                addRef.call(this, `#${anchor}`);
            }
        }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== undefined && !equal(sch1, sch2))
            throw ambiguos(ref);
    }
    function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
    }
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
    return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
    const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] },
    };
    return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {},
    };
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = require("./codegen");
const code_1 = require("./codegen/code");
// TODO refactor to use Set
function toHash(arr) {
    const hash = {};
    for (const item of arr)
        hash[item] = true;
    return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
    if (typeof schema == "boolean")
        return schema;
    if (Object.keys(schema).length === 0)
        return true;
    checkUnknownRules(it, schema);
    return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
    const { opts, self } = it;
    if (!opts.strictSchema)
        return;
    if (typeof schema === "boolean")
        return;
    const rules = self.RULES.keywords;
    for (const key in schema) {
        if (!rules[key])
            checkStrictMode(it, `unknown keyword: "${key}"`);
    }
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (rules[key])
            return true;
    return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
            return true;
    return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
    if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
            return schema;
        if (typeof schema == "string")
            return (0, codegen_1._) `${schema}`;
    }
    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
    if (typeof str == "number")
        return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
    if (Array.isArray(xs)) {
        for (const x of xs)
            f(x);
    }
    else {
        f(xs);
    }
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
    return (gen, from, to, toName) => {
        const res = to === undefined
            ? from
            : to instanceof codegen_1.Name
                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
                : from instanceof codegen_1.Name
                    ? (mergeToName(gen, to, from), from)
                    : mergeValues(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
}
exports.mergeEvaluated = {
    props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
            if (from === true) {
                gen.assign(to, true);
            }
            else {
                gen.assign(to, (0, codegen_1._) `${to} || {}`);
                setEvaluated(gen, to, from);
            }
        }),
        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
        resultToName: evaluatedPropsToName,
    }),
    items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
        resultToName: (gen, items) => gen.var("items", items),
    }),
};
function evaluatedPropsToName(gen, ps) {
    if (ps === true)
        return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._) `{}`);
    if (ps !== undefined)
        setEvaluated(gen, props, ps);
    return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
    return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
    });
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
    Type[Type["Num"] = 0] = "Num";
    Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    // let path
    if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax
            ? isNumber
                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
            : isNumber
                ? (0, codegen_1._) `"/" + ${dataProp}`
                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
    if (!mode)
        return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
        throw new Error(msg);
    it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
    const group = self.RULES.types[type];
    return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
    var _a;
    return (schema[rule.keyword] !== undefined ||
        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const boolError = {
    message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
    const { gen, schema, validateName } = it;
    if (schema === false) {
        falseSchemaError(it, false);
    }
    else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
        gen.return(true);
    }
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
    const { gen, schema } = it;
    if (schema === false) {
        gen.var(valid, false); // TODO var
        falseSchemaError(it);
    }
    else {
        gen.var(valid, true); // TODO var
    }
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
    const { gen, data } = it;
    // TODO maybe some other interface should be used for non-keyword validation errors...
    const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it,
    };
    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = require("../rules");
const applicability_1 = require("./applicability");
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const util_1 = require("../util");
var DataType;
(function (DataType) {
    DataType[DataType["Correct"] = 0] = "Correct";
    DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
    const types = getJSONTypes(schema.type);
    const hasNull = types.includes("null");
    if (hasNull) {
        if (schema.nullable === false)
            throw new Error("type: null contradicts nullable: false");
    }
    else {
        if (!types.length && schema.nullable !== undefined) {
            throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
            types.push("null");
    }
    return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
    if (types.every(rules_1.isJSONType))
        return types;
    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
    const { gen, data, opts } = it;
    const coerceTo = coerceToTypes(types, opts.coerceTypes);
    const checkTypes = types.length > 0 &&
        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
    if (checkTypes) {
        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
            if (coerceTo.length)
                coerceData(it, types, coerceTo);
            else
                reportTypeError(it);
        });
    }
    return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
    return coerceTypes
        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
        : [];
}
function coerceData(it, types, coerceTo) {
    const { gen, data, opts } = it;
    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
    if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
            .assign(data, (0, codegen_1._) `${data}[0]`)
            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
    }
    gen.if((0, codegen_1._) `${coerced} !== undefined`);
    for (const t of coerceTo) {
        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
            coerceSpecificType(t);
        }
    }
    gen.else();
    reportTypeError(it);
    gen.endIf();
    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
    });
    function coerceSpecificType(t) {
        switch (t) {
            case "string":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
                    .elseIf((0, codegen_1._) `${data} === null`)
                    .assign(coerced, (0, codegen_1._) `""`);
                return;
            case "number":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "integer":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "boolean":
                gen
                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
                    .assign(coerced, false)
                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
                    .assign(coerced, true);
                return;
            case "null":
                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
                gen.assign(coerced, null);
                return;
            case "array":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
                    .assign(coerced, (0, codegen_1._) `[${data}]`);
        }
    }
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    // TODO use gen.property
    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType) {
        case "null":
            return (0, codegen_1._) `${data} ${EQ} null`;
        case "array":
            cond = (0, codegen_1._) `Array.isArray(${data})`;
            break;
        case "object":
            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
            break;
        case "integer":
            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
            break;
        case "number":
            cond = numCond();
            break;
        default:
            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
    }
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
    if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
    }
    let cond;
    const types = (0, util_1.toHash)(dataTypes);
    if (types.array && types.object) {
        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
        delete types.null;
        delete types.array;
        delete types.object;
    }
    else {
        cond = codegen_1.nil;
    }
    if (types.number)
        delete types.integer;
    for (const t in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
    return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
    const cxt = getTypeErrorContext(it);
    (0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
    const { gen, data, schema } = it;
    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
    return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it,
    };
}
//# sourceMappingURL=dataType.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignDefaults = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function assignDefaults(it, ty) {
    const { properties, items } = it.schema;
    if (ty === "object" && properties) {
        for (const key in properties) {
            assignDefault(it, key, properties[key].default);
        }
    }
    else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
    }
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
    const { gen, compositeRule, data, opts } = it;
    if (defaultValue === undefined)
        return;
    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
    }
    let condition = (0, codegen_1._) `${childData} === undefined`;
    if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
    }
    // `${childData} === undefined` +
    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = require("./boolSchema");
const dataType_1 = require("./dataType");
const applicability_1 = require("./applicability");
const dataType_2 = require("./dataType");
const defaults_1 = require("./defaults");
const keyword_1 = require("./keyword");
const subschema_1 = require("./subschema");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const resolve_1 = require("../resolve");
const util_1 = require("../util");
const errors_1 = require("../errors");
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            topSchemaObjCode(it);
            return;
        }
    }
    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
            destructureValCxtES5(gen, opts);
            gen.code(body);
        });
    }
    else {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
}
function destructureValCxt(opts) {
    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
    });
}
function topSchemaObjCode(it) {
    const { schema, opts, gen } = it;
    validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
            commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
            resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
    });
    return;
}
function resetEvaluated(it) {
    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
    const { gen, validateName } = it;
    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            subSchemaObjCode(it, valid);
            return;
        }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (self.RULES.all[key])
            return true;
    return false;
}
function isSchemaObj(it) {
    return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
    const { schema, gen, opts } = it;
    if (opts.$comment && schema.$comment)
        commentKeyword(it);
    updateContext(it);
    checkAsyncSchema(it);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it, errsCount);
    // TODO var
    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
    (0, util_1.checkUnknownRules)(it);
    checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
    if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
    const types = (0, dataType_1.getSchemaTypes)(it.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
    schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
    const { schema, errSchemaPath, opts, self } = it;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
}
function checkNoDefault(it) {
    const { schema, opts } = it;
    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
    }
}
function updateContext(it) {
    const schId = it.schema[it.opts.schemaId];
    if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
    if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
    }
    else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
}
function returnResults(it) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
    if (schemaEnv.$async) {
        // TODO assign unevaluated
        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
            assignEvaluated(it);
        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
    }
}
function assignEvaluated({ gen, evaluated, props, items }) {
    if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
    if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
    const { gen, schema, data, allErrors, opts, self } = it;
    const { RULES } = self;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
        return;
    }
    if (!opts.jtd)
        checkStrictTypes(it, types);
    gen.block(() => {
        for (const group of RULES.rules)
            groupKeywords(group);
        groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
            return;
        if (group.type) {
            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
            iterateKeywords(it, group);
            if (types.length === 1 && types[0] === group.type && typeErrors) {
                gen.else();
                (0, dataType_2.reportTypeError)(it);
            }
            gen.endIf();
        }
        else {
            iterateKeywords(it, group);
        }
        // TODO make it "ok" call?
        if (!allErrors)
            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
    }
}
function iterateKeywords(it, group) {
    const { gen, schema, opts: { useDefaults }, } = it;
    if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
    gen.block(() => {
        for (const rule of group.rules) {
            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
                keywordCode(it, rule.keyword, rule.definition, group.type);
            }
        }
    });
}
function checkStrictTypes(it, types) {
    if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
    checkContextTypes(it, types);
    if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types);
    checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
    if (!types.length)
        return;
    if (!it.dataTypes.length) {
        it.dataTypes = types;
        return;
    }
    types.forEach((t) => {
        if (!includesType(it.dataTypes, t)) {
            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
    });
    narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
    }
}
function checkKeywordTypes(it, ts) {
    const rules = it.self.RULES.all;
    for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
            const { type } = rule.definition;
            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
            }
        }
    }
}
function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
    return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
    const ts = [];
    for (const t of it.dataTypes) {
        if (includesType(withTypes, t))
            ts.push(t);
        else if (withTypes.includes("integer") && t === "number")
            ts.push("integer");
    }
    it.dataTypes = ts;
}
function strictTypesError(it, msg) {
    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
    constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        }
        else {
            this.schemaCode = this.schemaValue;
            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
            }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
            this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
    }
    result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
            failAction();
        else
            this.error();
        if (successAction) {
            this.gen.else();
            successAction();
            if (this.allErrors)
                this.gen.endIf();
        }
        else {
            if (this.allErrors)
                this.gen.endIf();
            else
                this.gen.else();
        }
    }
    pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
    }
    fail(condition) {
        if (condition === undefined) {
            this.error();
            if (!this.allErrors)
                this.gen.if(false); // this branch will be removed by gen.optimize
            return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
            this.gen.endIf();
        else
            this.gen.else();
    }
    fail$data(condition) {
        if (!this.$data)
            return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
        if (errorParams) {
            this.setParams(errorParams);
            this._error(append, errorPaths);
            this.setParams({});
            return;
        }
        this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
        if (this.errsCount === undefined)
            throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
        if (!this.allErrors)
            this.gen.if(cond);
    }
    setParams(obj, assign) {
        if (assign)
            Object.assign(this.params, obj);
        else
            this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
            this.check$data(valid, $dataValid);
            codeBlock();
        });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
            return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
            gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
            gen.elseIf(this.invalid$data());
            this.$dataError();
            if (valid !== codegen_1.nil)
                gen.assign(valid, false);
        }
        gen.else();
    }
    invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
            if (schemaType.length) {
                /* istanbul ignore if */
                if (!(schemaCode instanceof codegen_1.Name))
                    throw new Error("ajv implementation error");
                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
            }
            return codegen_1.nil;
        }
        function invalid$DataSchema() {
            if (def.validateSchema) {
                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
            }
            return codegen_1.nil;
        }
    }
    subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
        subschemaCode(nextContext, valid);
        return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
            return;
        if (it.props !== true && schemaCxt.props !== undefined) {
            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== undefined) {
            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
    }
    mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
            return true;
        }
    }
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
    const cxt = new KeywordCxt(it, def, keyword);
    if ("code" in def) {
        def.code(cxt, ruleType);
    }
    else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
    else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
    }
    else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data;
    if ($data === "")
        return names_1.default.rootData;
    if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
    }
    else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
            if (up >= dataLevel)
                throw new Error(errorMsg("property/index", up));
            return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
            throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
            return data;
    }
    let expr = data;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
        if (segment) {
            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
            expr = (0, codegen_1._) `${expr} && ${data}`;
        }
    }
    return expr;
    function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
    }
}
exports.getData = getData;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const errors_1 = require("../errors");
function macroKeywordCode(cxt, def) {
    const { gen, keyword, schema, parentSchema, it } = cxt;
    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
    const schemaRef = useKeyword(gen, keyword, macroSchema);
    if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true,
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
    var _a;
    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
    checkAsyncKeyword(it, def);
    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
    const validateRef = useKeyword(gen, keyword, validate);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
    function validateKeyword() {
        if (def.errors === false) {
            assignValid();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => cxt.error());
        }
        else {
            const ruleErrs = def.async ? validateAsync() : validateSync();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => addErrs(cxt, ruleErrs));
        }
    }
    function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
        return ruleErrs;
    }
    function validateSync() {
        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !(("compile" in def && !$data) || def.schema === false);
        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors) {
        var _a;
        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
    }
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
    const { gen, data, it } = cxt;
    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
        gen
            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
    if (result === undefined)
        throw new Error(`keyword "${keyword}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
    // TODO add tests
    return (!schemaType.length ||
        schemaType.some((st) => st === "array"
            ? Array.isArray(schema)
            : st === "object"
                ? schema && typeof schema == "object" && !Array.isArray(schema)
                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
    /* istanbul ignore if */
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
                self.errorsText(def.validateSchema.errors);
            if (opts.validateSchema === "log")
                self.logger.error(msg);
            else
                throw new Error(msg);
        }
    }
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword !== undefined && schema !== undefined) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword !== undefined) {
        const sch = it.schema[keyword];
        return schemaProp === undefined
            ? {
                schema: sch,
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
            }
            : {
                schema: sch[schemaProp],
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
            };
    }
    if (schema !== undefined) {
        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
            schema,
            schemaPath,
            topSchemaRef,
            errSchemaPath,
        };
    }
    throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
    if (data !== undefined && dataProp !== undefined) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it;
    if (dataProp !== undefined) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
    }
    if (data !== undefined) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
        dataContextProps(nextData);
        if (propertyName !== undefined)
            subschema.propertyName = propertyName;
        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
    }
    if (dataTypes)
        subschema.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
    }
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== undefined)
        subschema.compositeRule = compositeRule;
    if (createErrors !== undefined)
        subschema.createErrors = createErrors;
    if (allErrors !== undefined)
        subschema.allErrors = allErrors;
    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
    subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error",
]);
const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now.",
};
const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver: uriResolver,
    };
}
class Ajv {
    constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = new Set();
        this._loading = {};
        this._cache = new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
            addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
        this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
            _dataRefSchema = { ...$dataRefSchema };
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
        }
        if (meta && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
        const { meta, schemaId } = this.opts;
        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
    }
    validate(schemaKeyRef, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data // to be validated
    ) {
        let v;
        if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        }
        else {
            v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
            this.errors = v.errors;
        return valid;
    }
    compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
            await loadMetaSchema.call(this, _schema.$schema);
            const sch = this._addSchema(_schema, _meta);
            return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
            if ($ref && !this.getSchema($ref)) {
                await runCompileAsync.call(this, { $ref }, true);
            }
        }
        async function _compileAsync(sch) {
            try {
                return this._compileSchemaEnv(sch);
            }
            catch (e) {
                if (!(e instanceof ref_error_1.default))
                    throw e;
                checkLoaded.call(this, e);
                await loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
            }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
            if (this.refs[ref]) {
                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
            }
        }
        async function loadMissingSchema(ref) {
            const _schema = await _loadSchema.call(this, ref);
            if (!this.refs[ref])
                await loadMetaSchema.call(this, _schema.$schema);
            if (!this.refs[ref])
                this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
            const p = this._loading[ref];
            if (p)
                return p;
            try {
                return await (this._loading[ref] = loadSchema(ref));
            }
            finally {
                delete this._loading[ref];
            }
        }
    }
    // Adds schema to the instance
    addSchema(schema, // If array is passed, `key` will be ignored
    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
    ) {
        if (Array.isArray(schema)) {
            for (const sch of schema)
                this.addSchema(sch, undefined, _meta, _validateSchema);
            return this;
        }
        let id;
        if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id = schema[schemaId];
            if (id !== undefined && typeof id != "string") {
                throw new Error(`schema ${schemaId} must be string`);
            }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
    ) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
            return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != "string") {
            throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
        if (sch === undefined) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
                return;
            this.refs[keyRef] = sch;
        }
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case "undefined":
                this._removeAllSchemas(this.schemas);
                this._removeAllSchemas(this.refs);
                this._cache.clear();
                return this;
            case "string": {
                const sch = getSchEnv.call(this, schemaKeyRef);
                if (typeof sch == "object")
                    this._cache.delete(sch.schema);
                delete this.schemas[schemaKeyRef];
                delete this.refs[schemaKeyRef];
                return this;
            }
            case "object": {
                const cacheKey = schemaKeyRef;
                this._cache.delete(cacheKey);
                let id = schemaKeyRef[this.opts.schemaId];
                if (id) {
                    id = (0, resolve_1.normalizeId)(id);
                    delete this.schemas[id];
                    delete this.refs[id];
                }
                return this;
            }
            default:
                throw new Error("ajv.removeSchema: invalid parameter");
        }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions) {
        for (const def of definitions)
            this.addKeyword(def);
        return this;
    }
    addKeyword(kwdOrDef, def // deprecated
    ) {
        let keyword;
        if (typeof kwdOrDef == "string") {
            keyword = kwdOrDef;
            if (typeof def == "object") {
                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
                def.keyword = keyword;
            }
        }
        else if (typeof kwdOrDef == "object" && def === undefined) {
            def = kwdOrDef;
            keyword = def.keyword;
            if (Array.isArray(keyword) && !keyword.length) {
                throw new Error("addKeywords: keyword must be string or non-empty array");
            }
        }
        else {
            throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
            return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
            ...def,
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0
            ? (k) => addRule.call(this, k, definition)
            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        return this;
    }
    getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword) {
        // TODO return type should be Ajv
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
            if (i >= 0)
                group.rules.splice(i, 1);
        }
        return this;
    }
    // Add format
    addFormat(name, format) {
        if (typeof format == "string")
            format = new RegExp(format);
        this.formats[name] = format;
        return this;
    }
    errorsText(errors = this.errors, // optional array of validation errors
    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
    ) {
        if (!errors || errors.length === 0)
            return "No errors";
        return errors
            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
            .reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
            let keywords = metaSchema;
            for (const seg of segments)
                keywords = keywords[seg];
            for (const key in rules) {
                const rule = rules[key];
                if (typeof rule != "object")
                    continue;
                const { $data } = rule.definition;
                const schema = keywords[key];
                if ($data && schema)
                    keywords[key] = schemaOrData(schema);
            }
        }
        return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
                if (typeof sch == "string") {
                    delete schemas[keyRef];
                }
                else if (sch && !sch.meta) {
                    this._cache.delete(sch.schema);
                    delete schemas[keyRef];
                }
            }
        }
    }
    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
            id = schema[schemaId];
        }
        else {
            if (this.opts.jtd)
                throw new Error("schema must be object");
            else if (typeof schema != "boolean")
                throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== undefined)
            return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
            if (baseId)
                this._checkUnique(baseId);
            this.refs[baseId] = sch;
        }
        if (validateSchema)
            this.validateSchema(schema, true);
        return sch;
    }
    _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
            throw new Error(`schema with key or id "${id}" already exists`);
        }
    }
    _compileSchemaEnv(sch) {
        if (sch.meta)
            this._compileMetaSchema(sch);
        else
            compile_1.compileSchema.call(this, sch);
        /* istanbul ignore if */
        if (!sch.validate)
            throw new Error("ajv implementation error");
        return sch.validate;
    }
    _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
            compile_1.compileSchema.call(this, sch);
        }
        finally {
            this.opts = currentOpts;
        }
    }
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
    for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
}
function getSchEnv(keyRef) {
    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
    return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
        return;
    if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
    else
        for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
    for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
            this.addFormat(name, format);
    }
}
function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
            def.keyword = keyword;
        this.addKeyword(def);
    }
}
function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
    return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
    if (logger === false)
        return noLogs;
    if (logger === undefined)
        return console;
    if (logger.log && logger.warn && logger.error)
        return logger;
    throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
    const { RULES } = this;
    (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def)
        return;
    if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
    }
}
function addRule(keyword, definition, dataType) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
    if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword] = true;
    if (!definition)
        return;
    const rule = {
        keyword,
        definition: {
            ...definition,
            type: (0, dataType_1.getJSONTypes)(definition.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
        },
    };
    if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
        ruleGroup.rules.push(rule);
    RULES.all[keyword] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
    }
    else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
    }
}
function keywordMetaschema(def) {
    let { metaSchema } = def;
    if (metaSchema === undefined)
        return;
    if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
    def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const jtd_1 = require("./vocabularies/jtd");
const jtd_schema_1 = require("./refs/jtd-schema");
const serialize_1 = require("./compile/jtd/serialize");
const parse_1 = require("./compile/jtd/parse");
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            jtd: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(jtd_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
    compileSerializer(schema) {
        const sch = this._addSchema(schema);
        return sch.serialize || this._compileSerializer(sch);
    }
    compileParser(schema) {
        const sch = this._addSchema(schema);
        return (sch.parse || this._compileParser(sch));
    }
    _compileSerializer(sch) {
        serialize_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.serialize)
            throw new Error("ajv implementation error");
        return sch.serialize;
    }
    _compileParser(sch) {
        parse_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.parse)
            throw new Error("ajv implementation error");
        return sch.parse;
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=jtd.js.map{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2019($data) {
    ;
    [
        metaSchema,
        applicator,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2019;
//# sourceMappingURL=index.js.map{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const unevaluated = require("./meta/unevaluated.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format-annotation.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
    ;
    [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2020;
//# sourceMappingURL=index.js.map{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared = (root) => {
    const sch = {
        nullable: { type: "boolean" },
        metadata: {
            optionalProperties: {
                union: { elements: { ref: "schema" } },
            },
            additionalProperties: true,
        },
    };
    if (root)
        sch.definitions = { values: { ref: "schema" } };
    return sch;
};
const emptyForm = (root) => ({
    optionalProperties: shared(root),
});
const refForm = (root) => ({
    properties: {
        ref: { type: "string" },
    },
    optionalProperties: shared(root),
});
const typeForm = (root) => ({
    properties: {
        type: {
            enum: [
                "boolean",
                "timestamp",
                "string",
                "float32",
                "float64",
                "int8",
                "uint8",
                "int16",
                "uint16",
                "int32",
                "uint32",
            ],
        },
    },
    optionalProperties: shared(root),
});
const enumForm = (root) => ({
    properties: {
        enum: { elements: { type: "string" } },
    },
    optionalProperties: shared(root),
});
const elementsForm = (root) => ({
    properties: {
        elements: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
    properties: {
        properties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        optionalProperties: { values: { ref: "schema" } },
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const optionalPropertiesForm = (root) => ({
    properties: {
        optionalProperties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const discriminatorForm = (root) => ({
    properties: {
        discriminator: { type: "string" },
        mapping: {
            values: {
                metadata: {
                    union: [propertiesForm(false), optionalPropertiesForm(false)],
                },
            },
        },
    },
    optionalProperties: shared(root),
});
const valuesForm = (root) => ({
    properties: {
        values: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const schema = (root) => ({
    metadata: {
        union: [
            emptyForm,
            refForm,
            typeForm,
            enumForm,
            elementsForm,
            propertiesForm,
            optionalPropertiesForm,
            discriminatorForm,
            valuesForm,
        ].map((s) => s(root)),
    },
});
const jtdMetaSchema = {
    definitions: {
        schema: schema(false),
    },
    ...schema(true),
};
exports.default = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/ajv-validator/ajv/issues/889
const equal = require("fast-deep-equal");
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
//# sourceMappingURL=equal.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
    let endPos;
    parseJson.message = undefined;
    let matches;
    if (pos)
        s = s.slice(pos);
    try {
        parseJson.position = pos + s.length;
        return JSON.parse(s);
    }
    catch (e) {
        matches = rxParseJson.exec(e.message);
        if (!matches) {
            parseJson.message = "unexpected end";
            return undefined;
        }
        endPos = +matches[1];
        const c = s[endPos];
        s = s.slice(0, endPos);
        parseJson.position = pos + endPos;
        try {
            return JSON.parse(s);
        }
        catch (e1) {
            parseJson.message = `unexpected token ${c}`;
            return undefined;
        }
    }
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
    let numStr = "";
    let c;
    parseJsonNumber.message = undefined;
    if (s[pos] === "-") {
        numStr += "-";
        pos++;
    }
    if (s[pos] === "0") {
        numStr += "0";
        pos++;
    }
    else {
        if (!parseDigits(maxDigits)) {
            errorMessage();
            return undefined;
        }
    }
    if (maxDigits) {
        parseJsonNumber.position = pos;
        return +numStr;
    }
    if (s[pos] === ".") {
        numStr += ".";
        pos++;
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    if (((c = s[pos]), c === "e" || c === "E")) {
        numStr += "e";
        pos++;
        if (((c = s[pos]), c === "+" || c === "-")) {
            numStr += c;
            pos++;
        }
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    parseJsonNumber.position = pos;
    return +numStr;
    function parseDigits(maxLen) {
        let digit = false;
        while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
            digit = true;
            numStr += c;
            pos++;
        }
        return digit;
    }
    function errorMessage() {
        parseJsonNumber.position = pos;
        parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
    }
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    '"': '"',
    "/": "/",
    "\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
    let str = "";
    let c;
    parseJsonString.message = undefined;
    // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
    while (true) {
        c = s[pos++];
        if (c === '"')
            break;
        if (c === "\\") {
            c = s[pos];
            if (c in escapedChars) {
                str += escapedChars[c];
                pos++;
            }
            else if (c === "u") {
                pos++;
                let count = 4;
                let code = 0;
                while (count--) {
                    code <<= 4;
                    c = s[pos];
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    if (c === undefined) {
                        errorMessage("unexpected end");
                        return undefined;
                    }
                    c = c.toLowerCase();
                    if (c >= "a" && c <= "f") {
                        code += c.charCodeAt(0) - CODE_A + 10;
                    }
                    else if (c >= "0" && c <= "9") {
                        code += c.charCodeAt(0) - CODE_0;
                    }
                    else {
                        errorMessage(`unexpected token ${c}`);
                        return undefined;
                    }
                    pos++;
                }
                str += String.fromCharCode(code);
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        }
        else if (c === undefined) {
            errorMessage("unexpected end");
            return undefined;
        }
        else {
            if (c.charCodeAt(0) >= 0x20) {
                str += c;
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
        }
    }
    parseJsonString.position = pos;
    return str;
    function errorMessage(msg) {
        parseJsonString.position = pos;
        parseJsonString.message = msg;
    }
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxEscapable = 
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
    "\b": "\\b",
    "\t": "\\t",
    "\n": "\\n",
    "\f": "\\f",
    "\r": "\\r",
    '"': '\\"',
    "\\": "\\\\",
};
function quote(s) {
    rxEscapable.lastIndex = 0;
    return ('"' +
        (rxEscapable.test(s)
            ? s.replace(rxEscapable, (a) => {
                const c = escaped[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            })
            : s) +
        '"');
}
exports.default = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const re2 = require("re2");
re2.code = 'require("ajv/dist/runtime/re2").default';
exports.default = re2;
//# sourceMappingURL=re2.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dt = str.split(DT_SEPARATOR);
    return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
        (allowDate && dt.length === 1 && validDate(dt[0])));
}
exports.default = validTimestamp;
function validDate(str) {
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const y = +matches[1];
    const m = +matches[2];
    const d = +matches[3];
    return (m >= 1 &&
        m <= 12 &&
        d >= 1 &&
        (d <= DAYS[m] ||
            // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
            (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hr = +matches[1];
    const min = +matches[2];
    const sec = +matches[3];
    const tzH = +(matches[4] || 0);
    const tzM = +(matches[5] || 0);
    return ((hr <= 23 && min <= 59 && sec <= 59) ||
        // leap second
        (hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let value;
    while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
            // high surrogate, and there is a next character
            value = str.charCodeAt(pos);
            if ((value & 0xfc00) === 0xdc00)
                pos++; // low surrogate
        }
    }
    return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uri = require("fast-uri");
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
//# sourceMappingURL=uri.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ValidationError extends Error {
    constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
    }
}
exports.default = ValidationError;
//# sourceMappingURL=validation_error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_1 = require("../compile/codegen/scope");
const code_1 = require("../compile/codegen/code");
function standaloneCode(ajv, refsOrFunc) {
    if (!ajv.opts.code.source) {
        throw new Error("moduleCode: ajv instance must have code.source option");
    }
    const { _n } = ajv.scope.opts;
    return typeof refsOrFunc == "function"
        ? funcExportCode(refsOrFunc.source)
        : refsOrFunc !== undefined
            ? multiExportsCode(refsOrFunc, getValidate)
            : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
    function getValidate(id) {
        const v = ajv.getSchema(id);
        if (!v)
            throw new Error(`moduleCode: no schema with id ${id}`);
        return v;
    }
    function funcExportCode(source) {
        const usedValues = {};
        const n = source === null || source === void 0 ? void 0 : source.validateName;
        const vCode = validateCode(usedValues, source);
        if (ajv.opts.code.esm) {
            // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
            return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
        }
        return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
    }
    function multiExportsCode(schemas, getValidateFunc) {
        var _a;
        const usedValues = {};
        let code = (0, code_1._) `"use strict";`;
        for (const name in schemas) {
            const v = getValidateFunc(schemas[name]);
            if (v) {
                const vCode = validateCode(usedValues, v.source);
                const exportSyntax = ajv.opts.code.esm
                    ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
                    : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
                code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
            }
        }
        return `${code}`;
    }
    function validateCode(usedValues, s) {
        if (!s)
            throw new Error('moduleCode: function does not have "source" property');
        if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
            return code_1.nil;
        setUsedState(s.validateName, scope_1.UsedValueState.Started);
        const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
        const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
        return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
        function refValidateCode(n) {
            var _a;
            const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
            if (n.prefix === "validate" && typeof vRef == "function") {
                const v = vRef;
                return validateCode(usedValues, v.source);
            }
            else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
                const { validate, validateName } = vRef;
                if (!validateName)
                    throw new Error("ajv internal error");
                const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
                const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
                if (usedState(validateName) === scope_1.UsedValueState.Started)
                    return wrapper;
                const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
                return (0, code_1._) `${wrapper}${_n}${vCode}`;
            }
            return undefined;
        }
        function usedState(name) {
            var _a;
            return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
        }
        function setUsedState(name, state) {
            const { prefix } = name;
            const names = (usedValues[prefix] = usedValues[prefix] || new Map());
            names.set(name, state);
        }
    }
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = standaloneCode;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("../core");
const _1 = require(".");
const requireFromString = require("require-from-string");
class AjvPack {
    constructor(ajv) {
        this.ajv = ajv;
    }
    validate(schemaKeyRef, data) {
        return core_1.default.prototype.validate.call(this, schemaKeyRef, data);
    }
    compile(schema, meta) {
        return this.getStandalone(this.ajv.compile(schema, meta));
    }
    getSchema(keyRef) {
        const v = this.ajv.getSchema(keyRef);
        if (!v)
            return undefined;
        return this.getStandalone(v);
    }
    getStandalone(v) {
        return requireFromString((0, _1.default)(this.ajv, v));
    }
    addSchema(...args) {
        this.ajv.addSchema.call(this.ajv, ...args);
        return this;
    }
    addKeyword(...args) {
        this.ajv.addKeyword.call(this.ajv, ...args);
        return this;
    }
}
exports.default = AjvPack;
//# sourceMappingURL=instance.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=json-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
            return;
        }
        validateAdditionalItems(cxt, items);
    },
};
function validateAdditionalItems(cxt, items) {
    const { gen, schema, data, keyword, it } = cxt;
    it.items = true;
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
    }
    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
    }
    function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
            if (!it.allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
    }
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
//# sourceMappingURL=additionalItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const util_1 = require("../../compile/util");
const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
            return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
            gen.forIn("key", data, (key) => {
                if (!props.length && !patProps.length)
                    additionalPropertyCode(key);
                else
                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
            });
        }
        function isAdditional(key) {
            let definedProp;
            if (props.length > 8) {
                // TODO maybe an option instead of hard-coded 8?
                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
            }
            else if (props.length) {
                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
            }
            else {
                definedProp = codegen_1.nil;
            }
            if (patProps.length) {
                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
            }
            return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
                deleteAdditional(key);
                return;
            }
            if (schema === false) {
                cxt.setParams({ additionalProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                if (opts.removeAdditional === "failing") {
                    applyAdditionalSchema(key, valid, false);
                    gen.if((0, codegen_1.not)(valid), () => {
                        cxt.reset();
                        deleteAdditional(key);
                    });
                }
                else {
                    applyAdditionalSchema(key, valid);
                    if (!allErrors)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                }
            }
        }
        function applyAdditionalSchema(key, valid, errors) {
            const subschema = {
                keyword: "additionalProperties",
                dataProp: key,
                dataPropType: util_1.Type.Str,
            };
            if (errors === false) {
                Object.assign(subschema, {
                    compositeRule: true,
                    createErrors: false,
                    allErrors: false,
                });
            }
            cxt.subschema(subschema, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=additionalProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
        const { gen, schema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
            if ((0, util_1.alwaysValidSchema)(it, sch))
                return;
            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
            cxt.ok(valid);
            cxt.mergeEvaluated(schCxt);
        });
    },
};
exports.default = def;
//# sourceMappingURL=allOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { min, max } }) => max === undefined
        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
            min = minContains === undefined ? 1 : minContains;
            max = maxContains;
        }
        else {
            min = 1;
        }
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        cxt.setParams({ min, max });
        if (max === undefined && min === 0) {
            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
            return;
        }
        if (max !== undefined && min > max) {
            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
            cxt.fail();
            return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            let cond = (0, codegen_1._) `${len} >= ${min}`;
            if (max !== undefined)
                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
            cxt.pass(cond);
            return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === undefined && min === 1) {
            validateItems(valid, () => gen.if(valid, () => gen.break()));
        }
        else if (min === 0) {
            gen.let(valid, true);
            if (max !== undefined)
                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
        }
        else {
            gen.let(valid, false);
            validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
            const schValid = gen.name("_valid");
            const count = gen.let("count", 0);
            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
            gen.forRange("i", 0, len, (i) => {
                cxt.subschema({
                    keyword: "contains",
                    dataProp: i,
                    dataPropType: util_1.Type.Num,
                    compositeRule: true,
                }, _valid);
                block();
            });
        }
        function checkLimits(count) {
            gen.code((0, codegen_1._) `${count}++`);
            if (max === undefined) {
                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
            }
            else {
                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
                if (min === 1)
                    gen.assign(valid, true);
                else
                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=contains.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
exports.error = {
    message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
    },
    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
};
const def = {
    keyword: "dependencies",
    type: "object",
    schemaType: "object",
    error: exports.error,
    code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
    },
};
function splitDependencies({ schema }) {
    const propertyDeps = {};
    const schemaDeps = {};
    for (const key in schema) {
        if (key === "__proto__")
            continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
    }
    return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
    const { gen, data, it } = cxt;
    if (Object.keys(propertyDeps).length === 0)
        return;
    const missing = gen.let("missing");
    for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
            continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
            property: prop,
            depsCount: deps.length,
            deps: deps.join(", "),
        });
        if (it.allErrors) {
            gen.if(hasProperty, () => {
                for (const depProp of deps) {
                    (0, code_1.checkReportMissingProp)(cxt, depProp);
                }
            });
        }
        else {
            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
        }
    }
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
            continue;
        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
        }, () => gen.var(valid, true) // TODO var
        );
        cxt.ok(valid);
    }
}
exports.validateSchemaDeps = validateSchemaDeps;
exports.default = def;
//# sourceMappingURL=dependencies.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("./dependencies");
const def = {
    keyword: "dependentSchemas",
    type: "object",
    schemaType: "object",
    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentSchemas.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === undefined && parentSchema.else === undefined) {
            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
            return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
            const ifClause = gen.let("ifClause");
            cxt.setParams({ ifClause });
            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        }
        else if (hasThen) {
            gen.if(schValid, validateClause("then"));
        }
        else {
            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
            const schCxt = cxt.subschema({
                keyword: "if",
                compositeRule: true,
                createErrors: false,
                allErrors: false,
            }, schValid);
            cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
            return () => {
                const schCxt = cxt.subschema({ keyword }, schValid);
                gen.assign(valid, schValid);
                cxt.mergeValidEvaluated(schCxt, valid);
                if (ifClause)
                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
                else
                    cxt.setParams({ ifClause: keyword });
            };
        }
    },
};
function hasSchema(it, keyword) {
    const schema = it.schema[keyword];
    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports.default = def;
//# sourceMappingURL=if.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const additionalItems_1 = require("./additionalItems");
const prefixItems_1 = require("./prefixItems");
const items_1 = require("./items");
const items2020_1 = require("./items2020");
const contains_1 = require("./contains");
const dependencies_1 = require("./dependencies");
const propertyNames_1 = require("./propertyNames");
const additionalProperties_1 = require("./additionalProperties");
const properties_1 = require("./properties");
const patternProperties_1 = require("./patternProperties");
const not_1 = require("./not");
const anyOf_1 = require("./anyOf");
const oneOf_1 = require("./oneOf");
const allOf_1 = require("./allOf");
const if_1 = require("./if");
const thenElse_1 = require("./thenElse");
function getApplicator(draft2020 = false) {
    const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default,
    ];
    // array
    if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
    else
        applicator.push(additionalItems_1.default, items_1.default);
    applicator.push(contains_1.default);
    return applicator;
}
exports.default = getApplicator;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTuple = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
            return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        cxt.ok((0, code_1.validateArray)(cxt));
    },
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data, keyword, it } = cxt;
    checkStrictTuple(parentSchema);
    if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
            keyword,
            schemaProp: i,
            dataProp: i,
        }, valid));
        cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
    }
}
exports.validateTuple = validateTuple;
exports.default = def;
//# sourceMappingURL=items.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const additionalItems_1 = require("./additionalItems");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        if (prefixItems)
            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
            cxt.ok((0, code_1.validateArray)(cxt));
    },
};
exports.default = def;
//# sourceMappingURL=items2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            cxt.fail();
            return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
            keyword: "not",
            compositeRule: true,
            createErrors: false,
            allErrors: false,
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" },
};
exports.default = def;
//# sourceMappingURL=not.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
            return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
            schArr.forEach((sch, i) => {
                let schCxt;
                if ((0, util_1.alwaysValidSchema)(it, sch)) {
                    gen.var(schValid, true);
                }
                else {
                    schCxt = cxt.subschema({
                        keyword: "oneOf",
                        schemaProp: i,
                        compositeRule: true,
                    }, schValid);
                }
                if (i > 0) {
                    gen
                        .if((0, codegen_1._) `${schValid} && ${valid}`)
                        .assign(valid, false)
                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
                        .else();
                }
                gen.if(schValid, () => {
                    gen.assign(valid, true);
                    gen.assign(passing, i);
                    if (schCxt)
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=oneOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const util_2 = require("../../compile/util");
const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 ||
            (alwaysValidPatterns.length === patterns.length &&
                (!it.opts.unevaluated || it.props === true))) {
            return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
            for (const pat of patterns) {
                if (checkProperties)
                    checkMatchingProperties(pat);
                if (it.allErrors) {
                    validateProperties(pat);
                }
                else {
                    gen.var(valid, true); // TODO var
                    validateProperties(pat);
                    gen.if(valid);
                }
            }
        }
        function checkMatchingProperties(pat) {
            for (const prop in checkProperties) {
                if (new RegExp(pat).test(prop)) {
                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
                }
            }
        }
        function validateProperties(pat) {
            gen.forIn("key", data, (key) => {
                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
                    const alwaysValid = alwaysValidPatterns.includes(pat);
                    if (!alwaysValid) {
                        cxt.subschema({
                            keyword: "patternProperties",
                            schemaProp: pat,
                            dataProp: key,
                            dataPropType: util_2.Type.Str,
                        }, valid);
                    }
                    if (it.opts.unevaluated && props !== true) {
                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
                    }
                    else if (!alwaysValid && !it.allErrors) {
                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
                        // or if all properties were evaluated (props === true)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                    }
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=patternProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const items_1 = require("./items");
const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports.default = def;
//# sourceMappingURL=prefixItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("../../compile/validate");
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const additionalProperties_1 = require("./additionalProperties");
const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
            it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
            return;
        const valid = gen.name("valid");
        for (const prop of properties) {
            if (hasDefault(prop)) {
                applyPropertySchema(prop);
            }
            else {
                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
                applyPropertySchema(prop);
                if (!it.allErrors)
                    gen.else().var(valid, true);
                gen.endIf();
            }
            cxt.it.definedProperties.add(prop);
            cxt.ok(valid);
        }
        function hasDefault(prop) {
            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
        }
        function applyPropertySchema(prop) {
            cxt.subschema({
                keyword: "properties",
                schemaProp: prop,
                dataProp: prop,
            }, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=properties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
            cxt.setParams({ propertyName: key });
            cxt.subschema({
                keyword: "propertyNames",
                data: key,
                dataTypes: ["string"],
                propertyName: key,
                compositeRule: true,
            }, valid);
            gen.if((0, codegen_1.not)(valid), () => {
                cxt.error(true);
                if (!it.allErrors)
                    gen.break();
            });
        });
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=propertyNames.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword, parentSchema, it }) {
        if (parentSchema.if === undefined)
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
    },
};
exports.default = def;
//# sourceMappingURL=thenElse.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = require("../compile/codegen");
const util_1 = require("../compile/util");
const names_1 = require("../compile/names");
const util_2 = require("../compile/util");
function checkReportMissingProp(cxt, prop) {
    const { gen, data, it } = cxt;
    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
        cxt.error();
    });
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
    return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
    });
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
    const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData],
    ];
    if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
    const u = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern, u);
    return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
    });
}
exports.usePattern = usePattern;
function validateArray(cxt) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
                keyword,
                dataProp: i,
                dataPropType: util_1.Type.Num,
            }, valid);
            gen.if((0, codegen_1.not)(valid), notValid);
        });
    }
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
    const { gen, schema, keyword, it } = cxt;
    /* istanbul ignore if */
    if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
    if (alwaysValid && !it.opts.unevaluated)
        return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
            keyword,
            schemaProp: i,
            compositeRule: true,
        }, schValid);
        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
        // or if all properties and items were evaluated (it.props === true && it.items === true)
        if (!merged)
            gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const def = {
    keyword: "id",
    code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    },
};
exports.default = def;
//# sourceMappingURL=id.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const id_1 = require("./id");
const ref_1 = require("./ref");
const core = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default,
];
exports.default = core;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = require("../../compile/ref_error");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
            return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
        if (schOrEnv === undefined)
            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
            return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
            if (env === root)
                return callRef(cxt, validateName, env, env.$async);
            const rootName = gen.scopeValue("root", { ref: root });
            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
            const v = getValidate(cxt, sch);
            callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
            const valid = gen.name("valid");
            const schCxt = cxt.subschema({
                schema: sch,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: $ref,
            }, valid);
            cxt.mergeEvaluated(schCxt);
            cxt.ok(valid);
        }
    },
};
function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate
        ? gen.scopeValue("validate", { ref: sch.validate })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
    const { gen, it } = cxt;
    const { allErrors, schemaEnv: env, opts } = it;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
        callAsyncRef();
    else
        callSyncRef();
    function callAsyncRef() {
        if (!env.$async)
            throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
            if (!allErrors)
                gen.assign(valid, true);
        }, (e) => {
            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
            addErrorsFrom(e);
            if (!allErrors)
                gen.assign(valid, false);
        });
        cxt.ok(valid);
    }
    function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
    }
    function addErrorsFrom(source) {
        const errs = (0, codegen_1._) `${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
        var _a;
        if (!it.opts.unevaluated)
            return;
        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
        // TODO refactor
        if (it.props !== true) {
            if (schEvaluated && !schEvaluated.dynamicProps) {
                if (schEvaluated.props !== undefined) {
                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
                }
            }
            else {
                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
            }
        }
        if (it.items !== true) {
            if (schEvaluated && !schEvaluated.dynamicItems) {
                if (schEvaluated.items !== undefined) {
                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
                }
            }
            else {
                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
            }
        }
    }
}
exports.callRef = callRef;
exports.default = def;
//# sourceMappingURL=ref.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const types_1 = require("../discriminator/types");
const compile_1 = require("../../compile");
const ref_error_1 = require("../../compile/ref_error");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
        ? `tag "${tagName}" must be string`
        : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
            throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
            throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
            throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
            throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
            const mapping = getMapping();
            gen.if(false);
            for (const tagValue in mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(mapping[tagValue]));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
            cxt.mergeEvaluated(schCxt, codegen_1.Name);
            return _valid;
        }
        function getMapping() {
            var _a;
            const oneOfMapping = {};
            const topRequired = hasRequired(parentSchema);
            let tagRequired = true;
            for (let i = 0; i < oneOf.length; i++) {
                let sch = oneOf[i];
                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
                    const ref = sch.$ref;
                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
                    if (sch instanceof compile_1.SchemaEnv)
                        sch = sch.schema;
                    if (sch === undefined)
                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
                }
                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
                if (typeof propSch != "object") {
                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
                }
                tagRequired = tagRequired && (topRequired || hasRequired(sch));
                addMappings(propSch, i);
            }
            if (!tagRequired)
                throw new Error(`discriminator: "${tagName}" must be required`);
            return oneOfMapping;
            function hasRequired({ required }) {
                return Array.isArray(required) && required.includes(tagName);
            }
            function addMappings(sch, i) {
                if (sch.const) {
                    addMapping(sch.const, i);
                }
                else if (sch.enum) {
                    for (const tagValue of sch.enum) {
                        addMapping(tagValue, i);
                    }
                }
                else {
                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
                }
            }
            function addMapping(tagValue, i) {
                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
                }
                oneOfMapping[tagValue] = i;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
    DiscrError["Tag"] = "tag";
    DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const dynamic_1 = require("./dynamic");
const next_1 = require("./next");
const unevaluated_1 = require("./unevaluated");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft2020Vocabularies = [
    dynamic_1.default,
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(true),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
    next_1.default,
    unevaluated_1.default,
];
exports.default = draft2020Vocabularies;
//# sourceMappingURL=draft2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
];
exports.default = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicAnchor = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicAnchor",
    schemaType: "string",
    code: (cxt) => dynamicAnchor(cxt, cxt.schema),
};
function dynamicAnchor(cxt, anchor) {
    const { gen, it } = cxt;
    it.schemaEnv.root.dynamicAnchors[anchor] = true;
    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
    const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));
}
exports.dynamicAnchor = dynamicAnchor;
function _getValidate(cxt) {
    const { schemaEnv, schema, self } = cxt.it;
    const { root, baseId, localRefs, meta } = schemaEnv.root;
    const { schemaId } = self.opts;
    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
    compile_1.compileSchema.call(self, sch);
    return (0, ref_1.getValidate)(cxt, sch);
}
exports.default = def;
//# sourceMappingURL=dynamicAnchor.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicRef = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicRef",
    schemaType: "string",
    code: (cxt) => dynamicRef(cxt, cxt.schema),
};
function dynamicRef(cxt, ref) {
    const { gen, keyword, it } = cxt;
    if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
    const anchor = ref.slice(1);
    if (it.allErrors) {
        _dynamicRef();
    }
    else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
    }
    function _dynamicRef(valid) {
        // TODO the assumption here is that `recursiveRef: #` always points to the root
        // of the schema object, which is not correct, because there may be $id that
        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
        // Because of that 2 tests in recursiveRef.json fail.
        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
        // (This problem is not tested in JSON-Schema-Test-Suite)
        if (it.schemaEnv.root.dynamicAnchors[anchor]) {
            const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
        }
        else {
            _callRef(it.validateName, valid)();
        }
    }
    function _callRef(validate, valid) {
        return valid
            ? () => gen.block(() => {
                (0, ref_1.callRef)(cxt, validate);
                gen.let(valid, true);
            })
            : () => (0, ref_1.callRef)(cxt, validate);
    }
}
exports.dynamicRef = dynamicRef;
exports.default = def;
//# sourceMappingURL=dynamicRef.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const dynamicRef_1 = require("./dynamicRef");
const recursiveAnchor_1 = require("./recursiveAnchor");
const recursiveRef_1 = require("./recursiveRef");
const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$recursiveAnchor",
    schemaType: "boolean",
    code(cxt) {
        if (cxt.schema)
            (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
        else
            (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
    },
};
exports.default = def;
//# sourceMappingURL=recursiveAnchor.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicRef_1 = require("./dynamicRef");
const def = {
    keyword: "$recursiveRef",
    schemaType: "string",
    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),
};
exports.default = def;
//# sourceMappingURL=recursiveRef.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=errors.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self } = it;
        if (!opts.validateFormats)
            return;
        if ($data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
            const fType = gen.let("fType");
            const format = gen.let("format");
            // TODO simplify
            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
            function unknownFmt() {
                if (opts.strictSchema === false)
                    return codegen_1.nil;
                return (0, codegen_1._) `${schemaCode} && !${format}`;
            }
            function invalidFmt() {
                const callFormat = schemaEnv.$async
                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
                    : (0, codegen_1._) `${format}(${data})`;
                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
            }
        }
        function validateFormat() {
            const formatDef = self.formats[schema];
            if (!formatDef) {
                unknownFormat();
                return;
            }
            if (formatDef === true)
                return;
            const [fmtType, format, fmtRef] = getFormat(formatDef);
            if (fmtType === ruleType)
                cxt.pass(validCondition());
            function unknownFormat() {
                if (opts.strictSchema === false) {
                    self.logger.warn(unknownMsg());
                    return;
                }
                throw new Error(unknownMsg());
                function unknownMsg() {
                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
                }
            }
            function getFormat(fmtDef) {
                const code = fmtDef instanceof RegExp
                    ? (0, codegen_1.regexpCode)(fmtDef)
                    : opts.code.formats
                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
                        : undefined;
                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
                }
                return ["string", fmtDef, fmt];
            }
            function validCondition() {
                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
                    if (!schemaEnv.$async)
                        throw new Error("async format in sync schema");
                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
                }
                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=format.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const format_1 = require("./format");
const format = [format_1.default];
exports.default = format;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const types_1 = require("../discriminator/types");
const error = {
    message: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? params.discrError === types_1.DiscrError.Tag
                ? `tag "${schema}" must be string`
                : `value of tag "${schema}" must be in mapping`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "discriminator",
    schemaType: "string",
    implements: ["mapping"],
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, parentSchema } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        gen.if(cond);
        validateDiscriminator();
        gen.elseIf((0, codegen_1.not)(valid));
        cxt.error();
        gen.endIf();
        cxt.ok(valid);
        function validateDiscriminator() {
            const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`);
            gen.if((0, codegen_1._) `${tag} === undefined`);
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag });
            gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`);
            validateMapping(tag);
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema });
            gen.endIf();
        }
        function validateMapping(tag) {
            gen.if(false);
            for (const tagValue in parentSchema.mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(tagValue));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            cxt.subschema({
                keyword: "mapping",
                schemaProp,
                jtdDiscriminator: schema,
            }, _valid);
            return _valid;
        }
    },
};
exports.default = def;
//# sourceMappingURL=discriminator.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "elements",
    schemaType: "object",
    error: (0, error_1.typeError)("array"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const [valid] = (0, nullable_1.checkNullable)(cxt);
        gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error()));
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=elements.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
        if (schema.length === 0)
            throw new Error("enum must have non-empty array");
        if (schema.length !== new Set(schema).size)
            throw new Error("enum items must be unique");
        let valid;
        const isString = (0, codegen_1._) `typeof ${data} == "string"`;
        if (schema.length >= it.opts.loopEnum) {
            let cond;
            [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString);
            gen.if(cond, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`)));
            if (parentSchema.nullable)
                valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid);
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break()));
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0;
const codegen_1 = require("../../compile/codegen");
function typeError(t) {
    return {
        message: (cxt) => typeErrorMessage(cxt, t),
        params: (cxt) => typeErrorParams(cxt, t),
    };
}
exports.typeError = typeError;
function typeErrorMessage({ parentSchema }, t) {
    return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`;
}
exports.typeErrorMessage = typeErrorMessage;
function typeErrorParams({ parentSchema }, t) {
    return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`;
}
exports.typeErrorParams = typeErrorParams;
//# sourceMappingURL=error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ref_1 = require("./ref");
const type_1 = require("./type");
const enum_1 = require("./enum");
const elements_1 = require("./elements");
const properties_1 = require("./properties");
const optionalProperties_1 = require("./optionalProperties");
const discriminator_1 = require("./discriminator");
const values_1 = require("./values");
const union_1 = require("./union");
const metadata_1 = require("./metadata");
const jtdVocabulary = [
    "definitions",
    ref_1.default,
    type_1.default,
    enum_1.default,
    elements_1.default,
    properties_1.default,
    optionalProperties_1.default,
    discriminator_1.default,
    values_1.default,
    union_1.default,
    metadata_1.default,
    { keyword: "additionalProperties", schemaType: "boolean" },
    { keyword: "nullable", schemaType: "boolean" },
];
exports.default = jtdVocabulary;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkMetadata = void 0;
const util_1 = require("../../compile/util");
const def = {
    keyword: "metadata",
    schemaType: "object",
    code(cxt) {
        checkMetadata(cxt);
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid);
        cxt.ok(valid);
    },
};
function checkMetadata({ it, keyword }, metadata) {
    if (it.jtdMetadata !== metadata) {
        throw new Error(`JTD: "${keyword}" cannot be used in this schema location`);
    }
}
exports.checkMetadata = checkMetadata;
exports.default = def;
//# sourceMappingURL=metadata.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkNullableObject = exports.checkNullable = void 0;
const codegen_1 = require("../../compile/codegen");
function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) {
    const valid = gen.name("valid");
    if (parentSchema.nullable) {
        gen.let(valid, (0, codegen_1._) `${data} === null`);
        cond = (0, codegen_1.not)(valid);
    }
    else {
        gen.let(valid, false);
    }
    return [valid, cond];
}
exports.checkNullable = checkNullable;
function checkNullableObject(cxt, cond) {
    const [valid, cond_] = checkNullable(cxt, cond);
    return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`];
}
exports.checkNullableObject = checkNullableObject;
//# sourceMappingURL=nullable.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const properties_1 = require("./properties");
const def = {
    keyword: "optionalProperties",
    schemaType: "object",
    error: properties_1.error,
    code(cxt) {
        if (cxt.parentSchema.properties)
            return;
        (0, properties_1.validateProperties)(cxt);
    },
};
exports.default = def;
//# sourceMappingURL=optionalProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperties = exports.error = void 0;
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
var PropError;
(function (PropError) {
    PropError["Additional"] = "additional";
    PropError["Missing"] = "missing";
})(PropError || (PropError = {}));
exports.error = {
    message: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? "must NOT have additional properties"
                : `must have property '${params.missingProperty}'`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
                : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "properties",
    schemaType: "object",
    error: exports.error,
    code: validateProperties,
};
// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }
function validateProperties(cxt) {
    (0, metadata_1.checkMetadata)(cxt);
    const { gen, data, parentSchema, it } = cxt;
    const { additionalProperties, nullable } = parentSchema;
    if (it.jtdDiscriminator && nullable)
        throw new Error("JTD: nullable inside discriminator mapping");
    if (commonProperties()) {
        throw new Error("JTD: properties and optionalProperties have common members");
    }
    const [allProps, properties] = schemaProperties("properties");
    const [allOptProps, optProperties] = schemaProperties("optionalProperties");
    if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
        return;
    }
    const [valid, cond] = it.jtdDiscriminator === undefined
        ? (0, nullable_1.checkNullableObject)(cxt, data)
        : [gen.let("valid", false), true];
    gen.if(cond, () => gen.assign(valid, true).block(() => {
        validateProps(properties, "properties", true);
        validateProps(optProperties, "optionalProperties");
        if (!additionalProperties)
            validateAdditional();
    }));
    cxt.pass(valid);
    function commonProperties() {
        const props = parentSchema.properties;
        const optProps = parentSchema.optionalProperties;
        if (!(props && optProps))
            return false;
        for (const p in props) {
            if (Object.prototype.hasOwnProperty.call(optProps, p))
                return true;
        }
        return false;
    }
    function schemaProperties(keyword) {
        const schema = parentSchema[keyword];
        const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
        if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
            throw new Error(`JTD: discriminator tag used in ${keyword}`);
        }
        const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        return [allPs, ps];
    }
    function validateProps(props, keyword, required) {
        const _valid = gen.var("valid");
        for (const prop of props) {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop));
            cxt.ok(_valid);
        }
        function missingProperty(prop) {
            if (required) {
                gen.assign(_valid, false);
                cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop });
            }
            else {
                gen.assign(_valid, true);
            }
        }
    }
    function applyPropertySchema(prop, keyword, _valid) {
        cxt.subschema({
            keyword,
            schemaProp: prop,
            dataProp: prop,
        }, _valid);
    }
    function validateAdditional() {
        gen.forIn("key", data, (key) => {
            const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator);
            const addOptProp = isAdditional(key, allOptProps, "optionalProperties");
            const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp);
            gen.if(extra, () => {
                if (it.opts.removeAdditional) {
                    gen.code((0, codegen_1._) `delete ${data}[${key}]`);
                }
                else {
                    cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true });
                    if (!it.opts.allErrors)
                        gen.break();
                }
            });
        });
    }
    function isAdditional(key, props, keyword, jtdDiscriminator) {
        let additional;
        if (props.length > 8) {
            // TODO maybe an option instead of hard-coded 8?
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword);
            additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key));
            if (jtdDiscriminator !== undefined) {
                additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`);
            }
        }
        else if (props.length || jtdDiscriminator !== undefined) {
            const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props);
            additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`));
        }
        else {
            additional = true;
        }
        return additional;
    }
}
exports.validateProperties = validateProperties;
exports.default = def;
//# sourceMappingURL=properties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasRef = void 0;
const compile_1 = require("../../compile");
const codegen_1 = require("../../compile/codegen");
const ref_error_1 = require("../../compile/ref_error");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const metadata_1 = require("./metadata");
const def = {
    keyword: "ref",
    schemaType: "string",
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema: ref, parentSchema, it } = cxt;
        const { schemaEnv: { root }, } = it;
        const valid = gen.name("valid");
        if (parentSchema.nullable) {
            gen.var(valid, (0, codegen_1._) `${data} === null`);
            gen.if((0, codegen_1.not)(valid), validateJtdRef);
        }
        else {
            gen.var(valid, false);
            validateJtdRef();
        }
        cxt.ok(valid);
        function validateJtdRef() {
            var _a;
            const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
            if (!refSchema) {
                throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
            }
            if (hasRef(refSchema) || !it.opts.inlineRefs)
                callValidate(refSchema);
            else
                inlineRefSchema(refSchema);
        }
        function callValidate(schema) {
            const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
            const v = (0, ref_1.getValidate)(cxt, sch);
            const errsCount = gen.const("_errs", names_1.default.errors);
            (0, ref_1.callRef)(cxt, v, sch, sch.$async);
            gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        }
        function inlineRefSchema(schema) {
            const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
            cxt.subschema({
                schema,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: `/definitions/${ref}`,
            }, valid);
        }
    },
};
function hasRef(schema) {
    for (const key in schema) {
        let sch;
        if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
            return true;
    }
    return false;
}
exports.hasRef = hasRef;
exports.default = def;
//# sourceMappingURL=ref.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intRange = void 0;
const codegen_1 = require("../../compile/codegen");
const timestamp_1 = require("../../runtime/timestamp");
const util_1 = require("../../compile/util");
const metadata_1 = require("./metadata");
const error_1 = require("./error");
exports.intRange = {
    int8: [-128, 127, 3],
    uint8: [0, 255, 3],
    int16: [-32768, 32767, 5],
    uint16: [0, 65535, 5],
    int32: [-2147483648, 2147483647, 10],
    uint32: [0, 4294967295, 10],
};
const error = {
    message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
    params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
};
function timestampCode(cxt) {
    const { gen, data, it } = cxt;
    const { timestamp, allowDate } = it.opts;
    if (timestamp === "date")
        return (0, codegen_1._) `${data} instanceof Date `;
    const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
    const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
    const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
    return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
}
const def = {
    keyword: "type",
    schemaType: "string",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { data, schema, parentSchema, it } = cxt;
        let cond;
        switch (schema) {
            case "boolean":
            case "string":
                cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
                break;
            case "timestamp": {
                cond = timestampCode(cxt);
                break;
            }
            case "float32":
            case "float64":
                cond = (0, codegen_1._) `typeof ${data} == "number"`;
                break;
            default: {
                const sch = schema;
                cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
                if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
                    if (sch === "uint32")
                        cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
                }
                else {
                    const [min, max] = exports.intRange[sch];
                    cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
                }
            }
        }
        cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
    },
};
exports.default = def;
//# sourceMappingURL=type.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "union",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in union" },
};
exports.default = def;
//# sourceMappingURL=union.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "values",
    schemaType: "object",
    error: (0, error_1.typeError)("object"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error());
        }
        else {
            gen.if(cond);
            gen.assign(valid, validateMap());
            gen.elseIf((0, codegen_1.not)(valid));
            cxt.error();
            gen.endIf();
        }
        cxt.ok(valid);
        function validateMap() {
            const _valid = gen.name("valid");
            if (it.allErrors) {
                const validMap = gen.let("valid", true);
                validateValues(() => gen.assign(validMap, false));
                return validMap;
            }
            gen.var(_valid, true);
            validateValues(() => gen.break());
            return _valid;
            function validateValues(notValid) {
                gen.forIn("key", data, (key) => {
                    cxt.subschema({
                        keyword: "values",
                        dataProp: key,
                        dataPropType: util_1.Type.Str,
                    }, _valid);
                    gen.if((0, codegen_1.not)(_valid), notValid);
                });
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=values.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples",
];
exports.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema",
];
//# sourceMappingURL=metadata.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependentRequired_1 = require("./validation/dependentRequired");
const dependentSchemas_1 = require("./applicator/dependentSchemas");
const limitContains_1 = require("./validation/limitContains");
const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
exports.default = next;
//# sourceMappingURL=next.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unevaluatedProperties_1 = require("./unevaluatedProperties");
const unevaluatedItems_1 = require("./unevaluatedItems");
const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
exports.default = unevaluated;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "unevaluatedItems",
    type: "array",
    schemaType: ["boolean", "object"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        const items = it.items || 0;
        if (items === true)
            return;
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        if (schema === false) {
            cxt.setParams({ len: items });
            cxt.fail((0, codegen_1._) `${len} > ${items}`);
        }
        else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`);
            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
            cxt.ok(valid);
        }
        it.items = true;
        function validateItems(valid, from) {
            gen.forRange("i", from, len, (i) => {
                cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
                if (!it.allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const names_1 = require("../../compile/names");
const error = {
    message: "must NOT have unevaluated properties",
    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,
};
const def = {
    keyword: "unevaluatedProperties",
    type: "object",
    schemaType: ["boolean", "object"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, props } = it;
        if (props instanceof codegen_1.Name) {
            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
        }
        else if (props !== true) {
            gen.forIn("key", data, (key) => props === undefined
                ? unevaluatedPropCode(key)
                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
        }
        it.props = true;
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function unevaluatedPropCode(key) {
            if (schema === false) {
                cxt.setParams({ unevaluatedProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (!(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                cxt.subschema({
                    keyword: "unevaluatedProperties",
                    dataProp: key,
                    dataPropType: util_1.Type.Str,
                }, valid);
                if (!allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
        }
        function unevaluatedDynamic(evaluatedProps, key) {
            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;
        }
        function unevaluatedStatic(evaluatedProps, key) {
            const ps = [];
            for (const p in evaluatedProps) {
                if (evaluatedProps[p] === true)
                    ps.push((0, codegen_1._) `${key} !== ${p}`);
            }
            return (0, codegen_1.and)(...ps);
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || (schema && typeof schema == "object")) {
            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        }
        else {
            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=const.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("../applicator/dependencies");
const def = {
    keyword: "dependentRequired",
    type: "object",
    schemaType: "object",
    error: dependencies_1.error,
    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentRequired.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
            throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
        let valid;
        if (useLoop || $data) {
            valid = gen.let("valid");
            cxt.block$data(valid, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            const vSchema = gen.const("vSchema", schemaCode);
            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.assign(valid, false);
            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i) {
            const sch = schema[i];
            return typeof sch === "object" && sch !== null
                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
                : (0, codegen_1._) `${data} === ${sch}`;
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const limitNumber_1 = require("./limitNumber");
const multipleOf_1 = require("./multipleOf");
const limitLength_1 = require("./limitLength");
const pattern_1 = require("./pattern");
const limitProperties_1 = require("./limitProperties");
const required_1 = require("./required");
const limitItems_1 = require("./limitItems");
const uniqueItems_1 = require("./uniqueItems");
const const_1 = require("./const");
const enum_1 = require("./enum");
const validation = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default,
];
exports.default = validation;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["maxContains", "minContains"],
    type: "array",
    schemaType: "number",
    code({ keyword, parentSchema, it }) {
        if (parentSchema.contains === undefined) {
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=limitContains.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const ucs2length_1 = require("../../runtime/ucs2length");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitLength.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
    },
};
exports.default = def;
//# sourceMappingURL=limitNumber.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec
            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
            : (0, codegen_1._) `${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
    },
};
exports.default = def;
//# sourceMappingURL=multipleOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
            const { regExp } = it.opts.code;
            const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);
            const valid = gen.let("valid");
            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
            cxt.fail$data((0, codegen_1._) `!${valid}`);
        }
        else {
            const regExp = (0, code_1.usePattern)(cxt, schema);
            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=pattern.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
            return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
            allErrorsMode();
        else
            exitOnErrorMode();
        if (opts.strictRequired) {
            const props = cxt.parentSchema.properties;
            const { definedProperties } = cxt.it;
            for (const requiredKey of schema) {
                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
                }
            }
        }
        function allErrorsMode() {
            if (useLoop || $data) {
                cxt.block$data(codegen_1.nil, loopAllRequired);
            }
            else {
                for (const prop of schema) {
                    (0, code_1.checkReportMissingProp)(cxt, prop);
                }
            }
        }
        function exitOnErrorMode() {
            const missing = gen.let("missing");
            if (useLoop || $data) {
                const valid = gen.let("valid", true);
                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
                cxt.ok(valid);
            }
            else {
                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
                (0, code_1.reportMissingProp)(cxt, missing);
                gen.else();
            }
        }
        function loopAllRequired() {
            gen.forOf("prop", schemaCode, (prop) => {
                cxt.setParams({ missingProperty: prop });
                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
            });
        }
        function loopUntilMissing(missing, valid) {
            cxt.setParams({ missingProperty: missing });
            gen.forOf(missing, schemaCode, () => {
                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
                gen.if((0, codegen_1.not)(valid), () => {
                    cxt.error();
                    gen.break();
                });
            }, codegen_1.nil);
        }
    },
};
exports.default = def;
//# sourceMappingURL=required.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dataType_1 = require("../../compile/validate/dataType");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
            return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
            const j = gen.let("j");
            cxt.setParams({ i, j });
            gen.assign(valid, true);
            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        function canOptimize() {
            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i, j) {
            const item = gen.name("item");
            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
            const indices = gen.const("indices", (0, codegen_1._) `{}`);
            gen.for((0, codegen_1._) `;${i}--;`, () => {
                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
                gen.if(wrongType, (0, codegen_1._) `continue`);
                if (itemTypes.length > 1)
                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
                gen
                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
                    cxt.error();
                    gen.assign(valid, false).break();
                })
                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
            });
        }
        function loopN2(i, j) {
            const eql = (0, util_1.useFunc)(gen, equal_1.default);
            const outer = gen.name("outer");
            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
                cxt.error();
                gen.assign(valid, false).break(outer);
            })));
        }
    },
};
exports.default = def;
//# sourceMappingURL=uniqueItems.js.map{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
{
  "name": "ajv",
  "version": "8.18.0",
  "description": "Another JSON Schema Validator",
  "main": "dist/ajv.js",
  "types": "dist/ajv.d.ts",
  "files": [
    "lib/",
    "dist/",
    ".runkit_example.js"
  ],
  "sideEffects": false,
  "scripts": {
    "eslint": "eslint \"lib/**/*.ts\" \"spec/**/*.*s\" --ignore-pattern spec/JSON-Schema-Test-Suite",
    "prettier:write": "prettier --write \"./**/*.{json,yaml,js,ts}\"",
    "prettier:check": "prettier --list-different \"./**/*.{json,yaml,js,ts}\"",
    "test-spec": "cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register \"spec/**/*.spec.{ts,js}\" -R dot",
    "test-codegen": "nyc cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register 'spec/codegen.spec.ts' -R spec",
    "test-debug": "npm run test-spec -- --inspect-brk",
    "test-cov": "nyc npm run test-spec",
    "rollup": "rm -rf bundle && rollup -c",
    "bundle": "rm -rf bundle && node ./scripts/bundle.js ajv ajv7 ajv7 && node ./scripts/bundle.js 2019 ajv2019 ajv2019 && node ./scripts/bundle.js 2020 ajv2020 ajv2020 && node ./scripts/bundle.js jtd ajvJTD ajvJTD",
    "build": "rm -rf dist && tsc && cp -r lib/refs dist && rm dist/refs/json-schema-2019-09/index.ts && rm dist/refs/json-schema-2020-12/index.ts && rm dist/refs/jtd-schema.ts",
    "json-tests": "rm -rf spec/_json/*.js && node scripts/jsontests",
    "test-karma": "karma start",
    "test-browser": "rm -rf .browser && npm run bundle && scripts/prepare-tests && karma start",
    "test-all": "npm run test-cov && if-node-version 12 npm run test-browser",
    "test": "npm run json-tests && npm run prettier:check && npm run eslint && npm link && npm link --legacy-peer-deps ajv && npm run test-cov",
    "test-ci": "AJV_FULL_TEST=true npm test",
    "prepublish": "npm run build",
    "benchmark": "npm i && npm run build && npm link && cd ./benchmark && npm link --legacy-peer-deps ajv && npm i && node ./jtd",
    "docs:dev": "./scripts/prepare-site && vuepress dev docs",
    "docs:build": "./scripts/prepare-site && vuepress build docs"
  },
  "nyc": {
    "exclude": [
      "**/spec/**",
      "node_modules"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ]
  },
  "repository": "ajv-validator/ajv",
  "keywords": [
    "JSON",
    "schema",
    "validator",
    "validation",
    "jsonschema",
    "json-schema",
    "json-schema-validator",
    "json-schema-validation"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": "https://github.com/ajv-validator/ajv/issues",
  "homepage": "https://ajv.js.org",
  "runkitExampleFilename": ".runkit_example.js",
  "dependencies": {
    "fast-deep-equal": "^3.1.3",
    "fast-uri": "^3.0.1",
    "json-schema-traverse": "^1.0.0",
    "require-from-string": "^2.0.2"
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.5.0",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-typescript": "^11.1.6",
    "@types/chai": "^4.3.11",
    "@types/mocha": "^10.0.6",
    "@types/node": "^20.11.30",
    "@types/require-from-string": "^1.2.3",
    "@typescript-eslint/eslint-plugin": "^7.3.1",
    "@typescript-eslint/parser": "^7.3.1",
    "ajv-formats": "^3.0.1",
    "browserify": "^17.0.0",
    "chai": "^4.4.1",
    "cross-env": "^7.0.3",
    "dayjs": "^1.11.10",
    "dayjs-plugin-utc": "^0.1.2",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "glob": "^10.3.10",
    "husky": "^9.0.11",
    "if-node-version": "^1.1.1",
    "jimp": "^0.22.10",
    "js-beautify": "^1.15.1",
    "json-schema-test": "^2.0.0",
    "karma": "^6.4.2",
    "karma-chrome-launcher": "^3.2.0",
    "karma-mocha": "^2.0.1",
    "lint-staged": "^15.2.2",
    "mocha": "^10.3.0",
    "module-from-string": "^3.3.0",
    "node-fetch": "^3.3.2",
    "nyc": "^15.1.0",
    "prettier": "3.0.3",
    "re2": "^1.20.9",
    "rollup": "^2.79.1",
    "rollup-plugin-terser": "^7.0.2",
    "ts-node": "^10.9.2",
    "tsify": "^5.0.4",
    "typescript": "5.3.3",
    "uri-js": "^4.4.1"
  },
  "collective": {
    "type": "opencollective",
    "url": "https://opencollective.com/ajv"
  },
  "funding": {
    "type": "github",
    "url": "https://github.com/sponsors/epoberezkin"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{json,yaml,js,ts}": "prettier --write"
  }
}
extends: eslint:recommended
env:
  node: true
  browser: true
rules:
  block-scoped-var: 2
  complexity: [2, 15]
  curly: [2, multi-or-nest, consistent]
  dot-location: [2, property]
  dot-notation: 2
  indent: [2, 2, SwitchCase: 1]
  linebreak-style: [2, unix]
  new-cap: 2
  no-console: [2, allow: [warn, error]]
  no-else-return: 2
  no-eq-null: 2
  no-fallthrough: 2
  no-invalid-this: 2
  no-return-assign: 2
  no-shadow: 1
  no-trailing-spaces: 2
  no-use-before-define: [2, nofunc]
  quotes: [2, single, avoid-escape]
  semi: [2, always]
  strict: [2, global]
  valid-jsdoc: [2, requireReturn: false]
  no-control-regex: 0
github: epoberezkin
tidelift: "npm/json-schema-traverse"
name: build

on:
  push:
    branches: [master]
  pull_request:
    branches: ["*"]

jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [10.x, 12.x, 14.x]

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm install
      - run: npm test
      - name: Coveralls
        uses: coverallsapp/github-action@master
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
name: publish

on:
  release:
    types: [published]

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: 14
          registry-url: https://registry.npmjs.org/
      - run: npm install
      - run: npm test
      - name: Publish beta version to npm
        if: "github.event.release.prerelease"
        run: npm publish --tag beta
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      - name: Publish to npm
        if: "!github.event.release.prerelease"
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
MIT License

Copyright (c) 2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# json-schema-traverse
Traverse JSON Schema passing each schema object to callback

[![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild)
[![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse)
[![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master)


## Install

```
npm install json-schema-traverse
```


## Usage

```javascript
const traverse = require('json-schema-traverse');
const schema = {
  properties: {
    foo: {type: 'string'},
    bar: {type: 'integer'}
  }
};

traverse(schema, {cb});
// cb is called 3 times with:
// 1. root schema
// 2. {type: 'string'}
// 3. {type: 'integer'}

// Or:

traverse(schema, {cb: {pre, post}});
// pre is called 3 times with:
// 1. root schema
// 2. {type: 'string'}
// 3. {type: 'integer'}
//
// post is called 3 times with:
// 1. {type: 'string'}
// 2. {type: 'integer'}
// 3. root schema

```

Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is.  Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed.

Callback is passed these parameters:

- _schema_: the current schema object
- _JSON pointer_: from the root schema to the current schema object
- _root schema_: the schema passed to `traverse` object
- _parent JSON pointer_: from the root schema to the parent schema object (see below)
- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.)
- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema
- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'`


## Traverse objects in all unknown keywords

```javascript
const traverse = require('json-schema-traverse');
const schema = {
  mySchema: {
    minimum: 1,
    maximum: 2
  }
};

traverse(schema, {allKeys: true, cb});
// cb is called 2 times with:
// 1. root schema
// 2. mySchema
```

Without option `allKeys: true` callback will be called only with root schema.


## Enterprise support

json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers.


## Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues.


## License

[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE)
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
{
  "name": "json-schema-traverse",
  "version": "1.0.0",
  "description": "Traverse JSON Schema passing each schema object to callback",
  "main": "index.js",
  "types": "index.d.ts",
  "scripts": {
    "eslint": "eslint index.js spec",
    "test-spec": "mocha spec -R spec",
    "test": "npm run eslint && nyc npm run test-spec"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/epoberezkin/json-schema-traverse.git"
  },
  "keywords": [
    "JSON-Schema",
    "traverse",
    "iterate"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/epoberezkin/json-schema-traverse/issues"
  },
  "homepage": "https://github.com/epoberezkin/json-schema-traverse#readme",
  "devDependencies": {
    "eslint": "^7.3.1",
    "mocha": "^8.0.1",
    "nyc": "^15.0.0",
    "pre-commit": "^1.2.2"
  },
  "nyc": {
    "exclude": [
      "**/spec/**",
      "node_modules"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ]
  }
}
parserOptions:
  ecmaVersion: 6
globals:
  beforeEach: false
  describe: false
  it: false
'use strict';

var schema = {
  additionalItems: subschema('additionalItems'),
  items: subschema('items'),
  contains: subschema('contains'),
  additionalProperties: subschema('additionalProperties'),
  propertyNames: subschema('propertyNames'),
  not: subschema('not'),
  allOf: [
    subschema('allOf_0'),
    subschema('allOf_1'),
    {
      items: [
        subschema('items_0'),
        subschema('items_1'),
      ]
    }
  ],
  anyOf: [
    subschema('anyOf_0'),
    subschema('anyOf_1'),
  ],
  oneOf: [
    subschema('oneOf_0'),
    subschema('oneOf_1'),
  ],
  definitions: {
    foo: subschema('definitions_foo'),
    bar: subschema('definitions_bar'),
  },
  properties: {
    foo: subschema('properties_foo'),
    bar: subschema('properties_bar'),
  },
  patternProperties: {
    foo: subschema('patternProperties_foo'),
    bar: subschema('patternProperties_bar'),
  },
  dependencies: {
    foo: subschema('dependencies_foo'),
    bar: subschema('dependencies_bar'),
  },
  required: ['foo', 'bar']
};


function subschema(keyword) {
  var sch = {
    properties: {},
    additionalProperties: false,
    additionalItems: false,
    anyOf: [
      {format: 'email'},
      {format: 'hostname'}
    ]
  };
  sch.properties['foo_' + keyword] = {title: 'foo'};
  sch.properties['bar_' + keyword] = {title: 'bar'};
  return sch;
}


module.exports = {
  schema: schema,

  // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
  expectedCalls: [[schema, '', schema, undefined, undefined, undefined, undefined]]
    .concat(expectedCalls('additionalItems'))
    .concat(expectedCalls('items'))
    .concat(expectedCalls('contains'))
    .concat(expectedCalls('additionalProperties'))
    .concat(expectedCalls('propertyNames'))
    .concat(expectedCalls('not'))
    .concat(expectedCallsChild('allOf', 0))
    .concat(expectedCallsChild('allOf', 1))
    .concat([
      [schema.allOf[2], '/allOf/2', schema, '', 'allOf', schema, 2],
      [schema.allOf[2].items[0], '/allOf/2/items/0', schema, '/allOf/2', 'items', schema.allOf[2], 0],
      [schema.allOf[2].items[0].properties.foo_items_0, '/allOf/2/items/0/properties/foo_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'foo_items_0'],
      [schema.allOf[2].items[0].properties.bar_items_0, '/allOf/2/items/0/properties/bar_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'bar_items_0'],
      [schema.allOf[2].items[0].anyOf[0], '/allOf/2/items/0/anyOf/0', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 0],
      [schema.allOf[2].items[0].anyOf[1], '/allOf/2/items/0/anyOf/1', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 1],

      [schema.allOf[2].items[1], '/allOf/2/items/1', schema, '/allOf/2', 'items', schema.allOf[2], 1],
      [schema.allOf[2].items[1].properties.foo_items_1, '/allOf/2/items/1/properties/foo_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'foo_items_1'],
      [schema.allOf[2].items[1].properties.bar_items_1, '/allOf/2/items/1/properties/bar_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'bar_items_1'],
      [schema.allOf[2].items[1].anyOf[0], '/allOf/2/items/1/anyOf/0', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 0],
      [schema.allOf[2].items[1].anyOf[1], '/allOf/2/items/1/anyOf/1', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 1]
    ])
    .concat(expectedCallsChild('anyOf', 0))
    .concat(expectedCallsChild('anyOf', 1))
    .concat(expectedCallsChild('oneOf', 0))
    .concat(expectedCallsChild('oneOf', 1))
    .concat(expectedCallsChild('definitions', 'foo'))
    .concat(expectedCallsChild('definitions', 'bar'))
    .concat(expectedCallsChild('properties', 'foo'))
    .concat(expectedCallsChild('properties', 'bar'))
    .concat(expectedCallsChild('patternProperties', 'foo'))
    .concat(expectedCallsChild('patternProperties', 'bar'))
    .concat(expectedCallsChild('dependencies', 'foo'))
    .concat(expectedCallsChild('dependencies', 'bar'))
};


function expectedCalls(keyword) {
  return [
    [schema[keyword], `/${keyword}`, schema, '', keyword, schema, undefined],
    [schema[keyword].properties[`foo_${keyword}`], `/${keyword}/properties/foo_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `foo_${keyword}`],
    [schema[keyword].properties[`bar_${keyword}`], `/${keyword}/properties/bar_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `bar_${keyword}`],
    [schema[keyword].anyOf[0], `/${keyword}/anyOf/0`, schema, `/${keyword}`, 'anyOf', schema[keyword], 0],
    [schema[keyword].anyOf[1], `/${keyword}/anyOf/1`, schema, `/${keyword}`, 'anyOf', schema[keyword], 1]
  ];
}


function expectedCallsChild(keyword, i) {
  return [
    [schema[keyword][i], `/${keyword}/${i}`, schema, '', keyword, schema, i],
    [schema[keyword][i].properties[`foo_${keyword}_${i}`], `/${keyword}/${i}/properties/foo_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `foo_${keyword}_${i}`],
    [schema[keyword][i].properties[`bar_${keyword}_${i}`], `/${keyword}/${i}/properties/bar_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `bar_${keyword}_${i}`],
    [schema[keyword][i].anyOf[0], `/${keyword}/${i}/anyOf/0`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 0],
    [schema[keyword][i].anyOf[1], `/${keyword}/${i}/anyOf/1`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 1]
  ];
}
'use strict';

var traverse = require('../index');
var assert = require('assert');

describe('json-schema-traverse', function() {
  var calls;

  beforeEach(function() {
    calls = [];
  });

  it('should traverse all keywords containing schemas recursively', function() {
    var schema = require('./fixtures/schema').schema;
    var expectedCalls = require('./fixtures/schema').expectedCalls;

    traverse(schema, {cb: callback});
    assert.deepStrictEqual(calls, expectedCalls);
  });

  describe('Legacy v0.3.1 API', function() {
    it('should traverse all keywords containing schemas recursively', function() {
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should work when an options object is provided', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, {}, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });


  describe('allKeys option', function() {
    var schema = {
      someObject: {
        minimum: 1,
        maximum: 2
      }
    };

    it('should traverse objects with allKeys: true option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined],
        [schema.someObject, '/someObject', schema, '', 'someObject', schema, undefined]
      ];

      traverse(schema, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects with allKeys: false option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {allKeys: false, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects without allKeys option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT travers objects in standard keywords which value is not a schema', function() {
      var schema2 = {
        const: {foo: 'bar'},
        enum: ['a', 'b'],
        required: ['foo'],
        another: {

        },
        patternProperties: {}, // will not traverse - no properties
        dependencies: true, // will not traverse - invalid
        properties: {
          smaller: {
            type: 'number'
          },
          larger: {
            type: 'number',
            minimum: {$data: '1/smaller'}
          }
        }
      };

      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema2, '', schema2, undefined, undefined, undefined, undefined],
        [schema2.another, '/another', schema2, '', 'another', schema2, undefined],
        [schema2.properties.smaller, '/properties/smaller', schema2, '', 'properties', schema2, 'smaller'],
        [schema2.properties.larger, '/properties/larger', schema2, '', 'properties', schema2, 'larger'],
      ];

      traverse(schema2, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  describe('pre and post', function() {
    var schema = {
      type: 'object',
      properties: {
        name: {type: 'string'},
        age: {type: 'number'}
      }
    };

    it('should traverse schema in pre-order', function() {
      traverse(schema, {cb: {pre}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in post-order', function() {
      traverse(schema, {cb: {post}});
      var expectedCalls = [
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in pre- and post-order at the same time', function() {
      traverse(schema, {cb: {pre, post}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  function callback() {
    calls.push(Array.prototype.slice.call(arguments));
  }

  function pre() {
    calls.push(['pre'].concat(Array.prototype.slice.call(arguments)));
  }

  function post() {
    calls.push(['post'].concat(Array.prototype.slice.call(arguments)));
  }
});
{
  "name": "ajv-formats",
  "version": "2.1.1",
  "description": "Format validation for Ajv v7+",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "files": [
    "src/",
    "dist/"
  ],
  "scripts": {
    "build": "tsc",
    "prettier:write": "prettier --write \"./**/*.{md,json,yaml,js,ts}\"",
    "prettier:check": "prettier --list-different \"./**/*.{md,json,yaml,js,ts}\"",
    "eslint": "eslint --ext .ts ./src/**/*",
    "test-spec": "jest",
    "test-cov": "jest --coverage",
    "test": "npm run prettier:check && npm run build && npm run eslint && npm run test-cov",
    "ci-test": "npm run test"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/ajv-validator/ajv-formats.git"
  },
  "keywords": [
    "Ajv",
    "JSON-Schema",
    "format",
    "validation"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/ajv-validator/ajv-formats/issues"
  },
  "homepage": "https://github.com/ajv-validator/ajv-formats#readme",
  "dependencies": {
    "ajv": "^8.0.0"
  },
  "peerDependencies": {
    "ajv": "^8.0.0"
  },
  "peerDependenciesMeta": {
    "ajv": {
      "optional": true
    }
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.3.0",
    "@types/jest": "^26.0.5",
    "@types/node": "^14.10.1",
    "@typescript-eslint/eslint-plugin": "^3.7.0",
    "@typescript-eslint/parser": "^3.7.0",
    "ajv": "^8.0.0",
    "eslint": "^7.5.0",
    "eslint-config-prettier": "^6.11.0",
    "husky": "^4.2.5",
    "jest": "^26.1.0",
    "json-schema-test": "^2.0.0",
    "lint-staged": "^10.2.11",
    "prettier": "^2.3.2",
    "ts-jest": "^26.1.3",
    "typescript": "^4.0.0"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{md,json,yaml,js,ts}": "prettier --write"
  }
}
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});

var schema = {
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "number", "maximum": 3 }
  }
};

var validate = ajv.compile(schema);

test({"foo": "abc", "bar": 2});
test({"foo": 2, "bar": 4});

function test(data) {
  var valid = validate(data);
  if (valid) console.log('Valid!');
  else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}The MIT License (MIT)

Copyright (c) 2015-2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png">

# Ajv: Another JSON Schema Validator

The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07.

[![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv)
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.4)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)


## Ajv v7 beta is released

[Ajv version 7 (beta)](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes:

- support of JSON Schema draft-2019-09 features: [`unevaluatedProperties`](./json-schema.md#unevaluatedproperties) and [`unevaluatedItems`](./json-schema.md#unevaluateditems), [dynamic recursive references](./validation.md#extending-recursive-schemas) and other [additional keywords](./json-schema.md#json-schema-draft-2019-09).
- to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements.
- to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe and to allow code optimization (compiled schema code size is reduced by more than 10%).
- to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package was updated to use the new API (in [v4.0.0-beta.0](https://github.com/ajv-validator/ajv-keywords/releases/tag/v4.0.0-beta.0))
- schemas are compiled to ES6 code (ES5 code generation is also supported with an option).
- to improve reliability and maintainability the code is migrated to TypeScript.

**Please note**:

- the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021).
- all formats are separated to ajv-formats package - they have to be explicitely added if you use them.

See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details.

To install the new version:

```bash
npm install ajv@beta
```

See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example.


## Mozilla MOSS grant and OpenJS Foundation

[<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/)

Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04).

Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users.

This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details.

I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community.


## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)

Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!

Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.

Please sponsor Ajv via:
- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)
- [Ajv Open Collective️](https://opencollective.com/ajv)

Thank you.


#### Open Collective sponsors

<a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a>

<a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a>


## Using version 6

[JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published.

[Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes).

__Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance:

```javascript
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'));
```

To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId:

```javascript
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
```


## Contents

- [Performance](#performance)
- [Features](#features)
- [Getting started](#getting-started)
- [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md)
- [Using in browser](#using-in-browser)
  - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)
- [Command line interface](#command-line-interface)
- Validation
  - [Keywords](#validation-keywords)
  - [Annotation keywords](#annotation-keywords)
  - [Formats](#formats)
  - [Combining schemas with $ref](#ref)
  - [$data reference](#data-reference)
  - NEW: [$merge and $patch keywords](#merge-and-patch-keywords)
  - [Defining custom keywords](#defining-custom-keywords)
  - [Asynchronous schema compilation](#asynchronous-schema-compilation)
  - [Asynchronous validation](#asynchronous-validation)
- [Security considerations](#security-considerations)
  - [Security contact](#security-contact)
  - [Untrusted schemas](#untrusted-schemas)
  - [Circular references in objects](#circular-references-in-javascript-objects)
  - [Trusted schemas](#security-risks-of-trusted-schemas)
  - [ReDoS attack](#redos-attack)
- Modifying data during validation
  - [Filtering data](#filtering-data)
  - [Assigning defaults](#assigning-defaults)
  - [Coercing data types](#coercing-data-types)
- API
  - [Methods](#api)
  - [Options](#options)
  - [Validation errors](#validation-errors)
- [Plugins](#plugins)
- [Related packages](#related-packages)
- [Some packages using Ajv](#some-packages-using-ajv)
- [Tests, Contributing, Changes history](#tests)
- [Support, Code of conduct, License](#open-source-software-support)


## Performance

Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:

- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)


Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):

[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)


## Features

- Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards:
  - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md))
  - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available)
  - support of circular references between schemas
  - correct string lengths for strings with unicode pairs (can be turned off)
  - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off)
  - [validates schemas against meta-schema](#api-validateschema)
- supports [browsers](#using-in-browser) and Node.js 0.10-14.x
- [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation
- "All errors" validation mode with [option allErrors](#options)
- [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages
- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package
- [filtering data](#filtering-data) from additional properties
- [assigning defaults](#assigning-defaults) to missing properties and items
- [coercing data](#coercing-data-types) to the types specified in `type` keywords
- [custom keywords](#defining-custom-keywords)
- draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else`
- draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail).
- keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package
- [$data reference](#data-reference) to use values from the validated data as values for the schema keywords
- [asynchronous validation](#asynchronous-validation) of custom formats and keywords


## Install

```
npm install ajv
```


## <a name="usage"></a>Getting started

Try it in the Node.js REPL: https://tonicdev.com/npm/ajv


The fastest validation call:

```javascript
// Node.js require:
var Ajv = require('ajv');
// or ESM/TypeScript import
import Ajv from 'ajv';

var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);
```

or with less code

```javascript
// ...
var valid = ajv.validate(schema, data);
if (!valid) console.log(ajv.errors);
// ...
```

or

```javascript
// ...
var valid = ajv.addSchema(schema, 'mySchema')
               .validate('mySchema', data);
if (!valid) console.log(ajv.errorsText());
// ...
```

See [API](#api) and [Options](#options) for more details.

Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again.

The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call).

__Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors)

__Note for TypeScript users__: `ajv` provides its own TypeScript declarations
out of the box, so you don't need to install the deprecated `@types/ajv`
module.


## Using in browser

You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle.

If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)).

Then you need to load Ajv in the browser:
```html
<script src="ajv.min.js"></script>
```

This bundle can be used with different module systems; it creates global `Ajv` if no module system is found.

The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv).

Ajv is tested with these browsers:

[![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin)

__Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)).


### Ajv and Content Security Policies (CSP)

If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`.
:warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks.

In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime.

Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime.


## Command line interface

CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports:

- compiling JSON Schemas to test their validity
- BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack))
- migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate))
- validating data file(s) against JSON Schema
- testing expected validity of data against JSON Schema
- referenced schemas
- custom meta-schemas
- files in JSON, JSON5, YAML, and JavaScript format
- all Ajv options
- reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format


## Validation keywords

Ajv supports all validation keywords from draft-07 of JSON Schema standard:

- [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type)
- [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf
- [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format
- [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains)
- [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames)
- [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const)
- [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse)

With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard:

- [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match.
- [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc.

See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details.


## Annotation keywords

JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation.

- `title` and `description`: information about the data represented by that schema
- `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options).
- `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults).
- `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema.
- `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.).
- `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64".
- `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png".

__Please note__:  Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance.


## Formats

Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack).

__Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios.

The following formats are implemented for string validation with "format" keyword:

- _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6).
- _time_: time with optional time-zone.
- _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)).
- _uri_: full URI.
- _uri-reference_: URI reference, including full and relative URIs.
- _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570)
- _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url).
- _email_: email address.
- _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5).
- _ipv4_: IP address v4.
- _ipv6_: IP address v6.
- _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor.
- _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122).
- _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901).
- _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00).

__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here.

There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details.

You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.

The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details.

You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js).


## <a name="ref"></a>Combining schemas with $ref

You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword.

Example:

```javascript
var schema = {
  "$id": "http://example.com/schemas/schema.json",
  "type": "object",
  "properties": {
    "foo": { "$ref": "defs.json#/definitions/int" },
    "bar": { "$ref": "defs.json#/definitions/str" }
  }
};

var defsSchema = {
  "$id": "http://example.com/schemas/defs.json",
  "definitions": {
    "int": { "type": "integer" },
    "str": { "type": "string" }
  }
};
```

Now to compile your schema you can either pass all schemas to Ajv instance:

```javascript
var ajv = new Ajv({schemas: [schema, defsSchema]});
var validate = ajv.getSchema('http://example.com/schemas/schema.json');
```

or use `addSchema` method:

```javascript
var ajv = new Ajv;
var validate = ajv.addSchema(defsSchema)
                  .compile(schema);
```

See [Options](#options) and [addSchema](#api) method.

__Please note__:
- `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example).
- References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.).
- You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs.
- The actual location of the schema file in the file system is not used.
- You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id.
- You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown.
- You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation).


## $data reference

With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works.

`$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems.

The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema).

Examples.

This schema requires that the value in property `smaller` is less or equal than the value in the property larger:

```javascript
var ajv = new Ajv({$data: true});

var schema = {
  "properties": {
    "smaller": {
      "type": "number",
      "maximum": { "$data": "1/larger" }
    },
    "larger": { "type": "number" }
  }
};

var validData = {
  smaller: 5,
  larger: 7
};

ajv.validate(schema, validData); // true
```

This schema requires that the properties have the same format as their field names:

```javascript
var schema = {
  "additionalProperties": {
    "type": "string",
    "format": { "$data": "0#" }
  }
};

var validData = {
  'date-time': '1963-06-19T08:30:06.283185Z',
  email: 'joe.bloggs@example.com'
}
```

`$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails.


## $merge and $patch keywords

With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902).

To add keywords `$merge` and `$patch` to Ajv instance use this code:

```javascript
require('ajv-merge-patch')(ajv);
```

Examples.

Using `$merge`:

```json
{
  "$merge": {
    "source": {
      "type": "object",
      "properties": { "p": { "type": "string" } },
      "additionalProperties": false
    },
    "with": {
      "properties": { "q": { "type": "number" } }
    }
  }
}
```

Using `$patch`:

```json
{
  "$patch": {
    "source": {
      "type": "object",
      "properties": { "p": { "type": "string" } },
      "additionalProperties": false
    },
    "with": [
      { "op": "add", "path": "/properties/q", "value": { "type": "number" } }
    ]
  }
}
```

The schemas above are equivalent to this schema:

```json
{
  "type": "object",
  "properties": {
    "p": { "type": "string" },
    "q": { "type": "number" }
  },
  "additionalProperties": false
}
```

The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema.

See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information.


## Defining custom keywords

The advantages of using custom keywords are:

- allow creating validation scenarios that cannot be expressed using JSON Schema
- simplify your schemas
- help bringing a bigger part of the validation logic to your schemas
- make your schemas more expressive, less verbose and closer to your application domain
- implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated

If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result).

The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas.

You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords.

Ajv allows defining keywords with:
- validation function
- compilation function
- macro function
- inline compilation function that should return code (as string) that will be inlined in the currently compiled schema.

Example. `range` and `exclusiveRange` keywords using compiled schema:

```javascript
ajv.addKeyword('range', {
  type: 'number',
  compile: function (sch, parentSchema) {
    var min = sch[0];
    var max = sch[1];

    return parentSchema.exclusiveRange === true
            ? function (data) { return data > min && data < max; }
            : function (data) { return data >= min && data <= max; }
  }
});

var schema = { "range": [2, 4], "exclusiveRange": true };
var validate = ajv.compile(schema);
console.log(validate(2.01)); // true
console.log(validate(3.99)); // true
console.log(validate(2)); // false
console.log(validate(4)); // false
```

Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords.

See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details.


## Asynchronous schema compilation

During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options).

Example:

```javascript
var ajv = new Ajv({ loadSchema: loadSchema });

ajv.compileAsync(schema).then(function (validate) {
  var valid = validate(data);
  // ...
});

function loadSchema(uri) {
  return request.json(uri).then(function (res) {
    if (res.statusCode >= 400)
      throw new Error('Loading error: ' + res.statusCode);
    return res.body;
  });
}
```

__Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work.


## Asynchronous validation

Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation

You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)).

If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation.

__Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail.

Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function).

Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options).

The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas.

Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property.


Example:

```javascript
var ajv = new Ajv;
// require('ajv-async')(ajv);

ajv.addKeyword('idExists', {
  async: true,
  type: 'number',
  validate: checkIdExists
});


function checkIdExists(schema, data) {
  return knex(schema.table)
  .select('id')
  .where('id', data)
  .then(function (rows) {
    return !!rows.length; // true if record is found
  });
}

var schema = {
  "$async": true,
  "properties": {
    "userId": {
      "type": "integer",
      "idExists": { "table": "users" }
    },
    "postId": {
      "type": "integer",
      "idExists": { "table": "posts" }
    }
  }
};

var validate = ajv.compile(schema);

validate({ userId: 1, postId: 19 })
.then(function (data) {
  console.log('Data is valid', data); // { userId: 1, postId: 19 }
})
.catch(function (err) {
  if (!(err instanceof Ajv.ValidationError)) throw err;
  // data is invalid
  console.log('Validation errors:', err.errors);
});
```

### Using transpilers with asynchronous validation functions.

[ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser).


#### Using nodent

```javascript
var ajv = new Ajv;
require('ajv-async')(ajv);
// in the browser if you want to load ajv-async bundle separately you can:
// window.ajvAsync(ajv);
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
```


#### Using other transpilers

```javascript
var ajv = new Ajv({ processCode: transpileFunc });
var validate = ajv.compile(schema); // transpiled es7 async function
validate(data).then(successFunc).catch(errorFunc);
```

See [Options](#options).


## Security considerations

JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider.


##### Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.


##### Untrusted schemas

Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application.

If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent:
- compiling schemas can cause stack overflow (if they are too deep)
- compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557))
- validating certain data can be slow

It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords.

Regardless the measures you take, using untrusted schemas increases security risks.


##### Circular references in JavaScript objects

Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802).

An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references.


##### Security risks of trusted schemas

Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to):

- `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)).
- `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well.
- `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate

__Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors).

You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed:

```javascript
const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json'));

const schema1 = {format: 'email'};
isSchemaSecure(schema1); // false

const schema2 = {format: 'email', maxLength: MAX_LENGTH};
isSchemaSecure(schema2); // true
```

__Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results.


##### Content Security Policies (CSP)
See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp)


## ReDoS attack

Certain regular expressions can lead to the exponential evaluation time even with relatively short strings.

Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example.

__Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following:

- making assessment of "format" implementations in Ajv.
- using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe).
- replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method.
- disabling format validation by ignoring "format" keyword with option `format: false`

Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios.


## Filtering data

With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation.

This option modifies original data.

Example:

```javascript
var ajv = new Ajv({ removeAdditional: true });
var schema = {
  "additionalProperties": false,
  "properties": {
    "foo": { "type": "number" },
    "bar": {
      "additionalProperties": { "type": "number" },
      "properties": {
        "baz": { "type": "string" }
      }
    }
  }
}

var data = {
  "foo": 0,
  "additional1": 1, // will be removed; `additionalProperties` == false
  "bar": {
    "baz": "abc",
    "additional2": 2 // will NOT be removed; `additionalProperties` != false
  },
}

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 }
```

If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed.

If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed).

__Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example:

```json
{
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "foo": { "type": "string" }
      },
      "required": [ "foo" ],
      "additionalProperties": false
    },
    {
      "properties": {
        "bar": { "type": "integer" }
      },
      "required": [ "bar" ],
      "additionalProperties": false
    }
  ]
}
```

The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties.

With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema).

While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way:

```json
{
  "type": "object",
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "integer" }
  },
  "additionalProperties": false,
  "oneOf": [
    { "required": [ "foo" ] },
    { "required": [ "bar" ] }
  ]
}
```

The schema above is also more efficient - it will compile into a faster function.


## Assigning defaults

With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items.

With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults.

This option modifies original data.

__Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema.


Example 1 (`default` in `properties`):

```javascript
var ajv = new Ajv({ useDefaults: true });
var schema = {
  "type": "object",
  "properties": {
    "foo": { "type": "number" },
    "bar": { "type": "string", "default": "baz" }
  },
  "required": [ "foo", "bar" ]
};

var data = { "foo": 1 };

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // { "foo": 1, "bar": "baz" }
```

Example 2 (`default` in `items`):

```javascript
var schema = {
  "type": "array",
  "items": [
    { "type": "number" },
    { "type": "string", "default": "foo" }
  ]
}

var data = [ 1 ];

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // [ 1, "foo" ]
```

`default` keywords in other cases are ignored:

- not in `properties` or `items` subschemas
- in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42))
- in `if` subschema of `switch` keyword
- in schemas generated by custom macro keywords

The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning).


## Coercing data types

When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards.

This option modifies original data.

__Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value.


Example 1:

```javascript
var ajv = new Ajv({ coerceTypes: true });
var schema = {
  "type": "object",
  "properties": {
    "foo": { "type": "number" },
    "bar": { "type": "boolean" }
  },
  "required": [ "foo", "bar" ]
};

var data = { "foo": "1", "bar": "false" };

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // { "foo": 1, "bar": false }
```

Example 2 (array coercions):

```javascript
var ajv = new Ajv({ coerceTypes: 'array' });
var schema = {
  "properties": {
    "foo": { "type": "array", "items": { "type": "number" } },
    "bar": { "type": "boolean" }
  }
};

var data = { "foo": "1", "bar": ["false"] };

var validate = ajv.compile(schema);

console.log(validate(data)); // true
console.log(data); // { "foo": [1], "bar": false }
```

The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords).

See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details.


## API

##### new Ajv(Object options) -&gt; Object

Create Ajv instance.


##### .compile(Object schema) -&gt; Function&lt;Object data&gt;

Generate validating function and cache the compiled schema for future use.

Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema.

The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options).


##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise

Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when:

- missing schema can't be loaded (`loadSchema` returns a Promise that rejects).
- a schema containing a missing reference is loaded, but the reference cannot be resolved.
- schema (or some loaded/referenced schema) is invalid.

The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded.

You can asynchronously compile meta-schema by passing `true` as the second parameter.

See example in [Asynchronous compilation](#asynchronous-schema-compilation).


##### .validate(Object schema|String key|String ref, data) -&gt; Boolean

Validate data using passed schema (it will be compiled and cached).

Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference.

Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors).

__Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later.

If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation).


##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv

Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole.

Array of schemas can be passed (schemas should have ids), the second parameter will be ignored.

Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key.


Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data.

Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time.

By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option.

__Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`.
This allows you to do nice things like the following.

```javascript
var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri);
```

##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv

Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option).

There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`.


##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean

Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard.

By default this method is called automatically when the schema is added, so you rarely need to use it directly.

If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false).

If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema.

Errors will be available at `ajv.errors`.


##### .getSchema(String key) -&gt; Function&lt;Object data&gt;

Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema.


##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv

Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references.

Schema can be removed using:
- key passed to `addSchema`
- it's full reference (id)
- RegExp that should match schema id or key (meta-schemas won't be removed)
- actual schema object that will be stable-stringified to remove schema from cache

If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared.


##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv

Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance.

Strings are converted to RegExp.

Function should return validation result as `true` or `false`.

If object is passed it should have properties `validate`, `compare` and `async`:

- _validate_: a string, RegExp or a function as described above.
- _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal.
- _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`.
- _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass.

Custom formats can be also added via `formats` option.


##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv

Add custom validation keyword to Ajv instance.

Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance.

Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`.
It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions.

Example Keywords:
- `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions.
- `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc.
- `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword

Keyword definition is an object with the following properties:

- _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types.
- _validate_: validating function
- _compile_: compiling function
- _macro_: macro function
- _inline_: compiling function that returns code (as string)
- _schema_: an optional `false` value used with "validate" keyword to not pass schema
- _metaSchema_: an optional meta-schema for keyword schema
- _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation
- _modifying_: `true` MUST be passed if keyword modifies data
- _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression)
- _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords.
- _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function).
- _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords.
- _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation.

_compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference.

__Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed.

See [Defining custom keywords](#defining-custom-keywords) for more details.


##### .getKeyword(String keyword) -&gt; Object|Boolean

Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown.


##### .removeKeyword(String keyword) -&gt; Ajv

Removes custom or pre-defined keyword so you can redefine them.

While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results.

__Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again.


##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String

Returns the text with all errors in a String.

Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default).


## Options

Defaults:

```javascript
{
  // validation and reporting options:
  $data:            false,
  allErrors:        false,
  verbose:          false,
  $comment:         false, // NEW in Ajv version 6.0
  jsonPointers:     false,
  uniqueItems:      true,
  unicode:          true,
  nullable:         false,
  format:           'fast',
  formats:          {},
  unknownFormats:   true,
  schemas:          {},
  logger:           undefined,
  // referenced schema options:
  schemaId:         '$id',
  missingRefs:      true,
  extendRefs:       'ignore', // recommended 'fail'
  loadSchema:       undefined, // function(uri: string): Promise {}
  // options to modify validated data:
  removeAdditional: false,
  useDefaults:      false,
  coerceTypes:      false,
  // strict mode options
  strictDefaults:   false,
  strictKeywords:   false,
  strictNumbers:    false,
  // asynchronous validation options:
  transpile:        undefined, // requires ajv-async package
  // advanced options:
  meta:             true,
  validateSchema:   true,
  addUsedSchema:    true,
  inlineRefs:       true,
  passContext:      false,
  loopRequired:     Infinity,
  ownProperties:    false,
  multipleOfPrecision: false,
  errorDataPath:    'object', // deprecated
  messages:         true,
  sourceCode:       false,
  processCode:      undefined, // function (str: string, schema: object): string {}
  cache:            new Cache,
  serialize:        undefined,
  regExp:           undefined // custom RegExp engine
}
```

##### Validation and reporting options

- _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api).
- _allErrors_: check all rules collecting all errors. Default is to return after the first error.
- _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default).
- _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values:
  - `false` (default): ignore $comment keyword.
  - `true`: log the keyword value to console.
  - function: pass the keyword value, its schema path and root schema to the specified function
- _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation.
- _uniqueItems_: validate `uniqueItems` keyword (true by default).
- _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters.
- _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/).
- _format_: formats validation mode. Option values:
  - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option).
  - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode.
  - `false` - ignore all format keywords.
- _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method.
- _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method.
- _unknownFormats_: handling of unknown formats. Option values:
  - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail.
  - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail.
  - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification.
- _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object.
- _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values:
  - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown.
  - `false` - logging is disabled.


##### Referenced schema options

- _schemaId_: this option defines which keywords are used as schema URI. Option value:
  - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged).
  - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged).
  - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation.
- _missingRefs_: handling of missing referenced schemas. Option values:
  - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted).
  - `"ignore"` - to log error during compilation and always pass validation.
  - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked.
- _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values:
  - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation.
  - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing.
  - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0).
- _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation).


##### Options to modify validated data

- _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values:
  - `false` (default) - not to remove additional properties
  - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them).
  - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed.
  - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema).
- _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values:
  - `false` (default) - do not use defaults
  - `true` - insert defaults by value (object literal is used).
  - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string).
  - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well.
- _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values:
  - `false` (default) - no type coercion.
  - `true` - coerce scalar data types.
  - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema).


##### Strict mode options

- _strictDefaults_: report ignored `default` keywords in schemas. Option values:
  - `false` (default) - ignored defaults are not reported
  - `true` - if an ignored default is present, throw an error
  - `"log"` - if an ignored default is present, log warning
- _strictKeywords_: report unknown keywords in schemas. Option values:
  - `false` (default) - unknown keywords are not reported
  - `true` - if an unknown keyword is present, throw an error
  - `"log"` - if an unknown keyword is present, log warning
- _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values:
  - `false` (default) - NaN or Infinity will pass validation for numeric types
  - `true` - NaN or Infinity will not pass validation for numeric types

##### Asynchronous validation options

- _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values:
  - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported.
  - `true` - always transpile with nodent.
  - `false` - do not transpile; if async functions are not supported an exception will be thrown.


##### Advanced options

- _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword.
- _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values:
  - `true` (default) -  if the validation fails, throw the exception.
  - `"log"` - if the validation fails, log error.
  - `false` - skip schema validation.
- _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method.
- _inlineRefs_: Affects compilation of referenced schemas. Option values:
  - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions.
  - `false` - to not inline referenced schemas (they will be compiled as separate functions).
  - integer number - to limit the maximum number of keywords of the schema that will be inlined.
- _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance.
- _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance.
- _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst.
- _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations).
- _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`.
- _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)).
- _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call).
- _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options:
  - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`.
  - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information.
- _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`.
- _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used.
- _regExp_: an optional function to create RegExp objects. This allows using a custom RegExp engine (e.g., [RE2](https://github.com/uhop/node-re2)) to mitigate ReDoS attacks. The function must have the signature `(pattern: string) => RegExpLike` where `RegExpLike` is an object with a `test(string) => boolean` method. Example with RE2:
  ```javascript
  var ajv = new Ajv({regExp: require('re2')});
  ```
  By default (`undefined`), native `RegExp` constructor is used.


## Validation errors

In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property.


### Error objects

Each error is an object with the following properties:

- _keyword_: validation keyword.
- _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`).
- _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation.
- _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords.
- _message_: the standard error message (can be excluded with option `messages` set to false).
- _schema_: the schema of the keyword (added with `verbose` option).
- _parentSchema_: the schema containing the keyword (added with `verbose` option)
- _data_: the data validated by the keyword (added with `verbose` option).

__Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`.


### Error parameters

Properties of `params` object in errors depend on the keyword that failed validation.

- `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword).
- `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false).
- `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords).
- `dependencies` - properties:
  - `property` (dependent property),
  - `missingProperty` (required missing dependency - only the first one is reported currently)
  - `deps` (required dependencies, comma separated list as a string),
  - `depsCount` (the number of required dependencies).
- `format` - property `format` (the schema of the keyword).
- `maximum`, `minimum` - properties:
  - `limit` (number, the schema of the keyword),
  - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`),
  - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=")
- `multipleOf` - property `multipleOf` (the schema of the keyword)
- `pattern` - property `pattern` (the schema of the keyword)
- `required` - property `missingProperty` (required property that is missing).
- `propertyNames` - property `propertyName` (an invalid property name).
- `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property).
- `type` - property `type` (required type(s), a string, can be a comma-separated list)
- `uniqueItems` - properties `i` and `j` (indices of duplicate items).
- `const` - property `allowedValue` pointing to the value (the schema of the keyword).
- `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword).
- `$ref` - property `ref` with the referenced schema URI.
- `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes).
- custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name).


### Error logging

Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown.
- **Required Methods**: `log`, `warn`, `error`

```javascript
var otherLogger = new OtherLogger();
var ajv = new Ajv({
  logger: {
    log: console.log.bind(console),
    warn: function warn() {
      otherLogger.logWarn.apply(otherLogger, arguments);
    },
    error: function error() {
      otherLogger.logError.apply(otherLogger, arguments);
      console.error.apply(console, arguments);
    }
  }
});
```


## Plugins

Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions:

- it exports a function
- this function accepts ajv instance as the first parameter and returns the same instance to allow chaining
- this function can accept an optional configuration as the second parameter

If you have published a useful plugin please submit a PR to add it to the next section.


## Related packages

- [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode
- [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats
- [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface
- [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages
- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages
- [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas
- [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.)
- [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch
- [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions
- [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`).

## Some packages using Ajv

- [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser
- [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services
- [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition
- [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator
- [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org
- [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com
- [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js
- [table](https://github.com/gajus/table) - formats data into a string table
- [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser
- [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content
- [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation
- [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation
- [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages
- [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema
- [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests
- [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema
- [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file
- [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app
- [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter
- [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages
- [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX
- [Spectral](https://github.com/stoplightio/spectral) - the customizable linting utility for JSON/YAML, OpenAPI, AsyncAPI, and JSON Schema


## Tests

```
npm install
git submodule update --init
npm test
```

## Contributing

All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency.

`npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder.

`npm run watch` - automatically compiles templates when files in dot folder change

Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md)


## Changes history

See https://github.com/ajv-validator/ajv/releases

__Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0)

[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0).

## Code of conduct

Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md).

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.


## Open-source software support

Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.


## License

[MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE)
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Ajv = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';


var Cache = module.exports = function Cache() {
  this._cache = {};
};


Cache.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};


Cache.prototype.get = function Cache_get(key) {
  return this._cache[key];
};


Cache.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};


Cache.prototype.clear = function Cache_clear() {
  this._cache = {};
};

},{}],2:[function(require,module,exports){
'use strict';

var MissingRefError = require('./error_classes').MissingRef;

module.exports = compileAsync;


/**
 * Creates validating function for passed schema with asynchronous loading of missing schemas.
 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
 * @this  Ajv
 * @param {Object}   schema schema object
 * @param {Boolean}  meta optional true to compile meta-schema; this parameter can be skipped
 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
 * @return {Promise} promise that resolves with a validating function.
 */
function compileAsync(schema, meta, callback) {
  /* eslint no-shadow: 0 */
  /* global Promise */
  /* jshint validthis: true */
  var self = this;
  if (typeof this._opts.loadSchema != 'function')
    throw new Error('options.loadSchema should be a function');

  if (typeof meta == 'function') {
    callback = meta;
    meta = undefined;
  }

  var p = loadMetaSchemaOf(schema).then(function () {
    var schemaObj = self._addSchema(schema, undefined, meta);
    return schemaObj.validate || _compileAsync(schemaObj);
  });

  if (callback) {
    p.then(
      function(v) { callback(null, v); },
      callback
    );
  }

  return p;


  function loadMetaSchemaOf(sch) {
    var $schema = sch.$schema;
    return $schema && !self.getSchema($schema)
            ? compileAsync.call(self, { $ref: $schema }, true)
            : Promise.resolve();
  }


  function _compileAsync(schemaObj) {
    try { return self._compile(schemaObj); }
    catch(e) {
      if (e instanceof MissingRefError) return loadMissingSchema(e);
      throw e;
    }


    function loadMissingSchema(e) {
      var ref = e.missingSchema;
      if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');

      var schemaPromise = self._loadingSchemas[ref];
      if (!schemaPromise) {
        schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
        schemaPromise.then(removePromise, removePromise);
      }

      return schemaPromise.then(function (sch) {
        if (!added(ref)) {
          return loadMetaSchemaOf(sch).then(function () {
            if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
          });
        }
      }).then(function() {
        return _compileAsync(schemaObj);
      });

      function removePromise() {
        delete self._loadingSchemas[ref];
      }

      function added(ref) {
        return self._refs[ref] || self._schemas[ref];
      }
    }
  }
}

},{"./error_classes":3}],3:[function(require,module,exports){
'use strict';

var resolve = require('./resolve');

module.exports = {
  Validation: errorSubclass(ValidationError),
  MissingRef: errorSubclass(MissingRefError)
};


function ValidationError(errors) {
  this.message = 'validation failed';
  this.errors = errors;
  this.ajv = this.validation = true;
}


MissingRefError.message = function (baseId, ref) {
  return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};


function MissingRefError(baseId, ref, message) {
  this.message = message || MissingRefError.message(baseId, ref);
  this.missingRef = resolve.url(baseId, ref);
  this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}


function errorSubclass(Subclass) {
  Subclass.prototype = Object.create(Error.prototype);
  Subclass.prototype.constructor = Subclass;
  return Subclass;
}

},{"./resolve":6}],4:[function(require,module,exports){
'use strict';

var util = require('./util');

var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?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a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
// uri-template: https://tools.ietf.org/html/rfc6570
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;


module.exports = formats;

function formats(mode) {
  mode = mode == 'full' ? 'full' : 'fast';
  return util.copy(formats[mode]);
}


formats.fast = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
  'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
  'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  'uri-template': URITEMPLATE,
  url: URL,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: UUID,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


formats.full = {
  date: date,
  time: time,
  'date-time': date_time,
  uri: uri,
  'uri-reference': URIREF,
  'uri-template': URITEMPLATE,
  url: URL,
  email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%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(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  uuid: UUID,
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


function isLeapYear(year) {
  // https://tools.ietf.org/html/rfc3339#appendix-C
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}


function date(str) {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  var matches = str.match(DATE);
  if (!matches) return false;

  var year = +matches[1];
  var month = +matches[2];
  var day = +matches[3];

  return month >= 1 && month <= 12 && day >= 1 &&
          day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}


function time(str, full) {
  var matches = str.match(TIME);
  if (!matches) return false;

  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return ((hour <= 23 && minute <= 59 && second <= 59) ||
          (hour == 23 && minute == 59 && second == 60)) &&
         (!full || timeZone);
}


var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}


var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}


var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
  if (Z_ANCHOR.test(str)) return false;
  try {
    new RegExp(str);
    return true;
  } catch(e) {
    return false;
  }
}

},{"./util":10}],5:[function(require,module,exports){
'use strict';

var resolve = require('./resolve')
  , util = require('./util')
  , errorClasses = require('./error_classes')
  , stableStringify = require('fast-json-stable-stringify');

var validateGenerator = require('../dotjs/validate');

/**
 * Functions below are used inside compiled validations function
 */

var ucs2length = util.ucs2length;
var equal = require('fast-deep-equal');

// this error is thrown by async schemas to return validation errors via exception
var ValidationError = errorClasses.Validation;

module.exports = compile;


/**
 * Compiles schema to validation function
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Object} root object with information about the root schema for this schema
 * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
 * @param  {String} baseId base ID for IDs in the schema
 * @return {Function} validation function
 */
function compile(schema, root, localRefs, baseId) {
  /* jshint validthis: true, evil: true */
  /* eslint no-shadow: 0 */
  var self = this
    , opts = this._opts
    , refVal = [ undefined ]
    , refs = {}
    , patterns = []
    , patternsHash = {}
    , defaults = []
    , defaultsHash = {}
    , customRules = [];

  function patternCode(i, patterns) {
    var regExpCode = opts.regExp ? 'regExp' : 'new RegExp';
    return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');';
  }

  root = root || { schema: schema, refVal: refVal, refs: refs };

  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling) return (compilation.callValidate = callValidate);

  var formats = this._formats;
  var RULES = this.RULES;

  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (opts.sourceCode) cv.source = v.source;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }

  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var validate = compilation.validate;
    var result = validate.apply(this, arguments);
    callValidate.errors = validate.errors;
    return result;
  }

  function localCompile(_schema, _root, localRefs, baseId) {
    var isRoot = !_root || (_root && _root.schema == _schema);
    if (_root.schema != root.schema)
      return compile.call(self, _schema, _root, localRefs, baseId);

    var $async = _schema.$async === true;

    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot: isRoot,
      baseId: baseId,
      root: _root,
      schemaPath: '',
      errSchemaPath: '#',
      errorPath: '""',
      MissingRefError: errorClasses.MissingRef,
      RULES: RULES,
      validate: validateGenerator,
      util: util,
      resolve: resolve,
      resolveRef: resolveRef,
      usePattern: usePattern,
      useDefault: useDefault,
      useCustomRule: useCustomRule,
      opts: opts,
      formats: formats,
      logger: self.logger,
      self: self
    });

    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                   + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                   + sourceCode;

    if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
    // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
    var validate;
    try {
      var makeValidate = new Function(
        'self',
        'RULES',
        'formats',
        'root',
        'refVal',
        'defaults',
        'customRules',
        'equal',
        'ucs2length',
        'ValidationError',
        'regExp',
        sourceCode
      );

      validate = makeValidate(
        self,
        RULES,
        formats,
        root,
        refVal,
        defaults,
        customRules,
        equal,
        ucs2length,
        ValidationError,
        opts.regExp
      );

      refVal[0] = validate;
    } catch(e) {
      self.logger.error('Error compiling schema, function code:', sourceCode);
      throw e;
    }

    validate.schema = _schema;
    validate.errors = null;
    validate.refs = refs;
    validate.refVal = refVal;
    validate.root = isRoot ? validate : _root;
    if ($async) validate.$async = true;
    if (opts.sourceCode === true) {
      validate.source = {
        code: sourceCode,
        patterns: patterns,
        defaults: defaults
      };
    }

    return validate;
  }

  function resolveRef(baseId, ref, isRoot) {
    ref = resolve.url(baseId, ref);
    var refIndex = refs[ref];
    var _refVal, refCode;
    if (refIndex !== undefined) {
      _refVal = refVal[refIndex];
      refCode = 'refVal[' + refIndex + ']';
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref];
      if (rootRefId !== undefined) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }

    refCode = addLocalRef(ref);
    var v = resolve.call(self, localCompile, root, ref);
    if (v === undefined) {
      var localSchema = localRefs && localRefs[ref];
      if (localSchema) {
        v = resolve.inlineRef(localSchema, opts.inlineRefs)
            ? localSchema
            : compile.call(self, localSchema, root, localRefs, baseId);
      }
    }

    if (v === undefined) {
      removeLocalRef(ref);
    } else {
      replaceLocalRef(ref, v);
      return resolvedRef(v, refCode);
    }
  }

  function addLocalRef(ref, v) {
    var refId = refVal.length;
    refVal[refId] = v;
    refs[ref] = refId;
    return 'refVal' + refId;
  }

  function removeLocalRef(ref) {
    delete refs[ref];
  }

  function replaceLocalRef(ref, v) {
    var refId = refs[ref];
    refVal[refId] = v;
  }

  function resolvedRef(refVal, code) {
    return typeof refVal == 'object' || typeof refVal == 'boolean'
            ? { code: code, schema: refVal, inline: true }
            : { code: code, $async: refVal && !!refVal.$async };
  }

  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === undefined) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return 'pattern' + index;
  }

  function useDefault(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
        return '' + value;
      case 'string':
        return util.toQuotedString(value);
      case 'object':
        if (value === null) return 'null';
        var valueStr = stableStringify(value);
        var index = defaultsHash[valueStr];
        if (index === undefined) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return 'default' + index;
    }
  }

  function useCustomRule(rule, schema, parentSchema, it) {
    if (self._opts.validateSchema !== false) {
      var deps = rule.definition.dependencies;
      if (deps && !deps.every(function(keyword) {
        return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
      }))
        throw new Error('parent schema must have all required keywords: ' + deps.join(','));

      var validateSchema = rule.definition.validateSchema;
      if (validateSchema) {
        var valid = validateSchema(schema);
        if (!valid) {
          var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
          if (self._opts.validateSchema == 'log') self.logger.error(message);
          else throw new Error(message);
        }
      }
    }

    var compile = rule.definition.compile
      , inline = rule.definition.inline
      , macro = rule.definition.macro;

    var validate;
    if (compile) {
      validate = compile.call(self, schema, parentSchema, it);
    } else if (macro) {
      validate = macro.call(self, schema, parentSchema, it);
      if (opts.validateSchema !== false) self.validateSchema(validate, true);
    } else if (inline) {
      validate = inline.call(self, it, rule.keyword, schema, parentSchema);
    } else {
      validate = rule.definition.validate;
      if (!validate) return;
    }

    if (validate === undefined)
      throw new Error('custom keyword "' + rule.keyword + '"failed to compile');

    var index = customRules.length;
    customRules[index] = validate;

    return {
      code: 'customRule' + index,
      validate: validate
    };
  }
}


/**
 * Checks if the schema is currently compiled
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
 */
function checkCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0) return { index: index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema: schema,
    root: root,
    baseId: baseId
  };
  return { index: index, compiling: false };
}


/**
 * Removes the schema from the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 */
function endCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0) this._compilations.splice(i, 1);
}


/**
 * Index of schema compilation in the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Integer} compilation index
 */
function compIndex(schema, root, baseId) {
  /* jshint validthis: true */
  for (var i=0; i<this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  }
  return -1;
}


function defaultCode(i) {
  return 'var default' + i + ' = defaults[' + i + '];';
}


function refValCode(i, refVal) {
  return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}


function customRuleCode(i) {
  return 'var customRule' + i + ' = customRules[' + i + '];';
}


function vars(arr, statement) {
  if (!arr.length) return '';
  var code = '';
  for (var i=0; i<arr.length; i++)
    code += statement(i, arr);
  return code;
}

},{"../dotjs/validate":38,"./error_classes":3,"./resolve":6,"./util":10,"fast-deep-equal":42,"fast-json-stable-stringify":43}],6:[function(require,module,exports){
'use strict';

var URI = require('uri-js')
  , equal = require('fast-deep-equal')
  , util = require('./util')
  , SchemaObject = require('./schema_obj')
  , traverse = require('json-schema-traverse');

module.exports = resolve;

resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;

/**
 * [resolve and compile the references ($ref)]
 * @this   Ajv
 * @param  {Function} compile reference to schema compilation funciton (localCompile)
 * @param  {Object} root object with information about the root schema for the current schema
 * @param  {String} ref reference to resolve
 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
 */
function resolve(compile, root, ref) {
  /* jshint validthis: true */
  var refVal = this._refs[ref];
  if (typeof refVal == 'string') {
    if (this._refs[refVal]) refVal = this._refs[refVal];
    else return resolve.call(this, compile, root, refVal);
  }

  refVal = refVal || this._schemas[ref];
  if (refVal instanceof SchemaObject) {
    return inlineRef(refVal.schema, this._opts.inlineRefs)
            ? refVal.schema
            : refVal.validate || this._compile(refVal);
  }

  var res = resolveSchema.call(this, root, ref);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }

  if (schema instanceof SchemaObject) {
    v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  } else if (schema !== undefined) {
    v = inlineRef(schema, this._opts.inlineRefs)
        ? schema
        : compile.call(this, schema, root, undefined, baseId);
  }

  return v;
}


/**
 * Resolve schema, its root and baseId
 * @this Ajv
 * @param  {Object} root root object with properties schema, refVal, refs
 * @param  {String} ref  reference to resolve
 * @return {Object} object with properties schema, root, baseId
 */
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = URI.parse(ref)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(this._getId(root.schema));
  if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}


/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
  /* jshint validthis: true */
  var res = resolveSchema.call(this, root, ref);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    var id = this._getId(schema);
    if (id) baseId = resolveUrl(baseId, id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}


var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
  /* jshint validthis: true */
  parsedRef.fragment = parsedRef.fragment || '';
  if (parsedRef.fragment.slice(0,1) != '/') return;
  var parts = parsedRef.fragment.split('/');

  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util.unescapeFragment(part);
      schema = schema[part];
      if (schema === undefined) break;
      var id;
      if (!PREVENT_SCOPE_CHANGE[part]) {
        id = this._getId(schema);
        if (id) baseId = resolveUrl(baseId, id);
        if (schema.$ref) {
          var $ref = resolveUrl(baseId, schema.$ref);
          var res = resolveSchema.call(this, root, $ref);
          if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
          }
        }
      }
    }
  }
  if (schema !== undefined && schema !== root.schema)
    return { schema: schema, root: root, baseId: baseId };
}


var SIMPLE_INLINED = util.toHash([
  'type', 'format', 'pattern',
  'maxLength', 'minLength',
  'maxProperties', 'minProperties',
  'maxItems', 'minItems',
  'maximum', 'minimum',
  'uniqueItems', 'multipleOf',
  'required', 'enum'
]);
function inlineRef(schema, limit) {
  if (limit === false) return false;
  if (limit === undefined || limit === true) return checkNoRef(schema);
  else if (limit) return countKeys(schema) <= limit;
}


function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return false;
      item = schema[key];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  }
  return true;
}


function countKeys(schema) {
  var count = 0, item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object') count += countKeys(item);
      if (count == Infinity) return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return Infinity;
      if (SIMPLE_INLINED[key]) {
        count++;
      } else {
        item = schema[key];
        if (typeof item == 'object') count += countKeys(item) + 1;
        if (count == Infinity) return Infinity;
      }
    }
  }
  return count;
}


function getFullPath(id, normalize) {
  if (normalize !== false) id = normalizeId(id);
  var p = URI.parse(id);
  return _getFullPath(p);
}


function _getFullPath(p) {
  return URI.serialize(p).split('#')[0] + '#';
}


var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}


function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return URI.resolve(baseId, id);
}


/* @this Ajv */
function resolveIds(schema) {
  var schemaId = normalizeId(this._getId(schema));
  var baseIds = {'': schemaId};
  var fullPaths = {'': getFullPath(schemaId, false)};
  var localRefs = {};
  var self = this;

  traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (jsonPtr === '') return;
    var id = self._getId(sch);
    var baseId = baseIds[parentJsonPtr];
    var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
    if (keyIndex !== undefined)
      fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));

    if (typeof id == 'string') {
      id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);

      var refVal = self._refs[id];
      if (typeof refVal == 'string') refVal = self._refs[refVal];
      if (refVal && refVal.schema) {
        if (!equal(sch, refVal.schema))
          throw new Error('id "' + id + '" resolves to more than one schema');
      } else if (id != normalizeId(fullPath)) {
        if (id[0] == '#') {
          if (localRefs[id] && !equal(sch, localRefs[id]))
            throw new Error('id "' + id + '" resolves to more than one schema');
          localRefs[id] = sch;
        } else {
          self._refs[id] = fullPath;
        }
      }
    }
    baseIds[jsonPtr] = baseId;
    fullPaths[jsonPtr] = fullPath;
  });

  return localRefs;
}

},{"./schema_obj":8,"./util":10,"fast-deep-equal":42,"json-schema-traverse":44,"uri-js":45}],7:[function(require,module,exports){
'use strict';

var ruleModules = require('../dotjs')
  , toHash = require('./util').toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
  ];

  var ALL = [ 'type', '$comment' ];
  var KEYWORDS = [
    '$schema', '$id', 'id', '$data', '$async', 'title',
    'description', 'default', 'definitions',
    'examples', 'readOnly', 'writeOnly',
    'contentMediaType', 'contentEncoding',
    'additionalItems', 'then', 'else'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    RULES.all.$comment = {
      keyword: '$comment',
      code: ruleModules.$comment
    };

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};

},{"../dotjs":27,"./util":10}],8:[function(require,module,exports){
'use strict';

var util = require('./util');

module.exports = SchemaObject;

function SchemaObject(obj) {
  util.copy(obj, this);
}

},{"./util":10}],9:[function(require,module,exports){
'use strict';

// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
  var length = 0
    , len = str.length
    , pos = 0
    , value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos);
      if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
    }
  }
  return length;
};

},{}],10:[function(require,module,exports){
'use strict';


module.exports = {
  copy: copy,
  checkDataType: checkDataType,
  checkDataTypes: checkDataTypes,
  coerceToTypes: coerceToTypes,
  toHash: toHash,
  getProperty: getProperty,
  escapeQuotes: escapeQuotes,
  equal: require('fast-deep-equal'),
  ucs2length: require('./ucs2length'),
  varOccurences: varOccurences,
  varReplace: varReplace,
  schemaHasRules: schemaHasRules,
  schemaHasRulesExcept: schemaHasRulesExcept,
  schemaUnknownRules: schemaUnknownRules,
  toQuotedString: toQuotedString,
  getPathExpr: getPathExpr,
  getPath: getPath,
  getData: getData,
  unescapeFragment: unescapeFragment,
  unescapeJsonPointer: unescapeJsonPointer,
  escapeFragment: escapeFragment,
  escapeJsonPointer: escapeJsonPointer
};


function copy(o, to) {
  to = to || {};
  for (var key in o) to[key] = o[key];
  return to;
}


function checkDataType(dataType, data, strictNumbers, negate) {
  var EQUAL = negate ? ' !== ' : ' === '
    , AND = negate ? ' || ' : ' && '
    , OK = negate ? '!' : ''
    , NOT = negate ? '' : '!';
  switch (dataType) {
    case 'null': return data + EQUAL + 'null';
    case 'array': return OK + 'Array.isArray(' + data + ')';
    case 'object': return '(' + OK + data + AND +
                          'typeof ' + data + EQUAL + '"object"' + AND +
                          NOT + 'Array.isArray(' + data + '))';
    case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                           NOT + '(' + data + ' % 1)' +
                           AND + data + EQUAL + data +
                           (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
    case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
                          (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
    default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  }
}


function checkDataTypes(dataTypes, data, strictNumbers) {
  switch (dataTypes.length) {
    case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
    default:
      var code = '';
      var types = toHash(dataTypes);
      if (types.array && types.object) {
        code = types.null ? '(': '(!' + data + ' || ';
        code += 'typeof ' + data + ' !== "object")';
        delete types.null;
        delete types.array;
        delete types.object;
      }
      if (types.number) delete types.integer;
      for (var t in types)
        code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);

      return code;
  }
}


var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types = [];
    for (var i=0; i<dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t]) types[types.length] = t;
      else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
    }
    if (types.length) return types;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
    return ['array'];
  }
}


function toHash(arr) {
  var hash = {};
  for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  return hash;
}


var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == 'number'
          ? '[' + key + ']'
          : IDENTIFIER.test(key)
            ? '.' + key
            : "['" + escapeQuotes(key) + "']";
}


function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
}


function varOccurences(str, dataVar) {
  dataVar += '[^0-9]';
  var matches = str.match(new RegExp(dataVar, 'g'));
  return matches ? matches.length : 0;
}


function varReplace(str, dataVar, expr) {
  dataVar += '([^0-9])';
  expr = expr.replace(/\$/g, '$$$$');
  return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}


function schemaHasRules(schema, rules) {
  if (typeof schema == 'boolean') return !schema;
  for (var key in schema) if (rules[key]) return true;
}


function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
  for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}


function schemaUnknownRules(schema, rules) {
  if (typeof schema == 'boolean') return;
  for (var key in schema) if (!rules[key]) return key;
}


function toQuotedString(str) {
  return '\'' + escapeQuotes(str) + '\'';
}


function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers // false by default
              ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
              : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  return joinPaths(currentPath, path);
}


function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers // false by default
              ? toQuotedString('/' + escapeJsonPointer(prop))
              : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}


var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data, matches;
  if ($data === '') return 'rootData';
  if ($data[0] == '/') {
    if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
    jsonPointer = $data;
    data = 'rootData';
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER);
    if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == '#') {
      if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
      return paths[lvl - up];
    }

    if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
    data = 'data' + ((lvl - up) || '');
    if (!jsonPointer) return data;
  }

  var expr = data;
  var segments = jsonPointer.split('/');
  for (var i=0; i<segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data += getProperty(unescapeJsonPointer(segment));
      expr += ' && ' + data;
    }
  }
  return expr;
}


function joinPaths (a, b) {
  if (a == '""') return b;
  return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}


function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}


function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}


function escapeJsonPointer(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


function unescapeJsonPointer(str) {
  return str.replace(/~1/g, '/').replace(/~0/g, '~');
}

},{"./ucs2length":9,"fast-deep-equal":42}],11:[function(require,module,exports){
'use strict';

var KEYWORDS = [
  'multipleOf',
  'maximum',
  'exclusiveMaximum',
  'minimum',
  'exclusiveMinimum',
  'maxLength',
  'minLength',
  'pattern',
  'additionalItems',
  'maxItems',
  'minItems',
  'uniqueItems',
  'maxProperties',
  'minProperties',
  'required',
  'additionalProperties',
  'enum',
  'format',
  'const'
];

module.exports = function (metaSchema, keywordsJsonPointers) {
  for (var i=0; i<keywordsJsonPointers.length; i++) {
    metaSchema = JSON.parse(JSON.stringify(metaSchema));
    var segments = keywordsJsonPointers[i].split('/');
    var keywords = metaSchema;
    var j;
    for (j=1; j<segments.length; j++)
      keywords = keywords[segments[j]];

    for (j=0; j<KEYWORDS.length; j++) {
      var key = KEYWORDS[j];
      var schema = keywords[key];
      if (schema) {
        keywords[key] = {
          anyOf: [
            schema,
            { $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
    }
  }

  return metaSchema;
};

},{}],12:[function(require,module,exports){
'use strict';

var metaSchema = require('./refs/json-schema-draft-07.json');

module.exports = {
  $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
  definitions: {
    simpleTypes: metaSchema.definitions.simpleTypes
  },
  type: 'object',
  dependencies: {
    schema: ['validate'],
    $data: ['validate'],
    statements: ['inline'],
    valid: {not: {required: ['macro']}}
  },
  properties: {
    type: metaSchema.properties.type,
    schema: {type: 'boolean'},
    statements: {type: 'boolean'},
    dependencies: {
      type: 'array',
      items: {type: 'string'}
    },
    metaSchema: {type: 'object'},
    modifying: {type: 'boolean'},
    valid: {type: 'boolean'},
    $data: {type: 'boolean'},
    async: {type: 'boolean'},
    errors: {
      anyOf: [
        {type: 'boolean'},
        {const: 'full'}
      ]
    }
  }
};

},{"./refs/json-schema-draft-07.json":41}],13:[function(require,module,exports){
'use strict';
module.exports = function generate__limit(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $isMax = $keyword == 'maximum',
    $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
    $schemaExcl = it.schema[$exclusiveKeyword],
    $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
    $op = $isMax ? '<' : '>',
    $notOp = $isMax ? '>' : '<',
    $errorKeyword = undefined;
  if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
    throw new Error($keyword + ' must be number');
  }
  if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
    throw new Error($exclusiveKeyword + ' must be number or boolean');
  }
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
      $exclusive = 'exclusive' + $lvl,
      $exclType = 'exclType' + $lvl,
      $exclIsNumber = 'exclIsNumber' + $lvl,
      $opExpr = 'op' + $lvl,
      $opStr = '\' + ' + $opExpr + ' + \'';
    out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
    $schemaValueExcl = 'schemaExcl' + $lvl;
    out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
    if ($schema === undefined) {
      $errorKeyword = $exclusiveKeyword;
      $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
      $schemaValue = $schemaValueExcl;
      $isData = $isDataExcl;
    }
  } else {
    var $exclIsNumber = typeof $schemaExcl == 'number',
      $opStr = $op;
    if ($exclIsNumber && $isData) {
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
    } else {
      if ($exclIsNumber && $schema === undefined) {
        $exclusive = true;
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
        $schemaValue = $schemaExcl;
        $notOp += '=';
      } else {
        if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
          $notOp += '=';
        } else {
          $exclusive = false;
          $opStr += '=';
        }
      }
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
    }
  }
  $errorKeyword = $errorKeyword || $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be ' + ($opStr) + ' ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],14:[function(require,module,exports){
'use strict';
module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxItems' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxItems') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' items\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],15:[function(require,module,exports){
'use strict';
module.exports = function generate__limitLength(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxLength' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  if (it.opts.unicode === false) {
    out += ' ' + ($data) + '.length ';
  } else {
    out += ' ucs2length(' + ($data) + ') ';
  }
  out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT be ';
      if ($keyword == 'maxLength') {
        out += 'longer';
      } else {
        out += 'shorter';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' characters\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],16:[function(require,module,exports){
'use strict';
module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxProperties' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxProperties') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' properties\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],17:[function(require,module,exports){
'use strict';
module.exports = function generate_allOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $allSchemasEmpty = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += ' if (true) { ';
    } else {
      out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
    }
  }
  return out;
}

},{}],18:[function(require,module,exports){
'use strict';
module.exports = function generate_anyOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $noEmptySchema = $schema.every(function($sch) {
    return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all));
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
        $closingBraces += '}';
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match some schema in anyOf\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}

},{}],19:[function(require,module,exports){
'use strict';
module.exports = function generate_comment(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $comment = it.util.toQuotedString($schema);
  if (it.opts.$comment === true) {
    out += ' console.log(' + ($comment) + ');';
  } else if (typeof it.opts.$comment == 'function') {
    out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
  }
  return out;
}

},{}],20:[function(require,module,exports){
'use strict';
module.exports = function generate_const(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!$isData) {
    out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to constant\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],21:[function(require,module,exports){
'use strict';
module.exports = function generate_contains(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId,
    $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all));
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($nonEmptySchema) {
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    out += ' if (' + ($nextValid) + ') break; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
  } else {
    out += ' if (' + ($data) + '.length == 0) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should contain a valid item\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } else { ';
  if ($nonEmptySchema) {
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  }
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}

},{}],22:[function(require,module,exports){
'use strict';
module.exports = function generate_custom(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $rule = this,
    $definition = 'definition' + $lvl,
    $rDef = $rule.definition,
    $closingBraces = '';
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    if (!$ruleValidate) return;
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + '.errors',
    $i = 'i' + $lvl,
    $ruleErr = 'ruleErr' + $lvl,
    $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  if (!($inline || $macro)) {
    out += '' + ($ruleErrs) + ' = null;';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($isData && $rDef.$data) {
    $closingBraces += '}';
    out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
    if ($validateSchema) {
      $closingBraces += '}';
      out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
    }
  }
  if ($inline) {
    if ($rDef.statements) {
      out += ' ' + ($ruleValidate.validate) + ' ';
    } else {
      out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    var $closingBraces = '';
    $it.level++;
    var $nextValid = 'valid' + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($code);
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    out += '  ' + ($validateCode) + '.call( ';
    if (it.opts.passContext) {
      out += 'this';
    } else {
      out += 'self';
    }
    if ($compile || $rDef.schema === false) {
      out += ' , ' + ($data) + ' ';
    } else {
      out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
    }
    out += ' , (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += ' ' + ($valid) + ' = ';
      if ($asyncKeyword) {
        out += 'await ';
      }
      out += '' + (def_callRuleValidate) + '; ';
    } else {
      if ($asyncKeyword) {
        $ruleErrs = 'customErrors' + $lvl;
        out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
      } else {
        out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
      }
    }
  }
  if ($rDef.modifying) {
    out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  }
  out += '' + ($closingBraces);
  if ($rDef.valid) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  } else {
    out += ' if ( ';
    if ($rDef.valid === undefined) {
      out += ' !';
      if ($macro) {
        out += '' + ($nextValid);
      } else {
        out += '' + ($valid);
      }
    } else {
      out += ' ' + (!$rDef.valid) + ' ';
    }
    out += ') { ';
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != 'full') {
          out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } ';
        }
      } else {
        if ($rDef.errors === false) {
          out += ' ' + (def_customError) + ' ';
        } else {
          out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } } ';
        }
      }
    } else if ($macro) {
      out += '   var err =   '; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError(vErrors); ';
        } else {
          out += ' validate.errors = vErrors; return false; ';
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += ' ' + (def_customError) + ' ';
      } else {
        out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
        if (it.opts.verbose) {
          out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
        }
        out += ' } } else { ' + (def_customError) + ' } ';
      }
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  }
  return out;
}

},{}],23:[function(require,module,exports){
'use strict';
module.exports = function generate_dependencies(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $schemaDeps = {},
    $propertyDeps = {},
    $ownProperties = it.opts.ownProperties;
  for ($property in $schema) {
    if ($property == '__proto__') continue;
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += 'var ' + ($errs) + ' = errors;';
  var $currentErrorPath = it.errorPath;
  out += 'var missing' + ($lvl) + ';';
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    if ($deps.length) {
      out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      if ($breakOnError) {
        out += ' && ( ';
        var arr1 = $deps;
        if (arr1) {
          var $propertyKey, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $propertyKey = arr1[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ')) {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should have ';
            if ($deps.length == 1) {
              out += 'property ' + (it.util.escapeQuotes($deps[0]));
            } else {
              out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
            }
            out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      } else {
        out += ' ) { ';
        var arr2 = $deps;
        if (arr2) {
          var $propertyKey, i2 = -1,
            l2 = arr2.length - 1;
          while (i2 < l2) {
            $propertyKey = arr2[i2 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'should have ';
                if ($deps.length == 1) {
                  out += 'property ' + (it.util.escapeQuotes($deps[0]));
                } else {
                  out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                }
                out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
      out += ' }   ';
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
      out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      out += ') { ';
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  }
  if ($breakOnError) {
    out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}

},{}],24:[function(require,module,exports){
'use strict';
module.exports = function generate_enum(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $i = 'i' + $lvl,
    $vSchema = 'schema' + $lvl;
  if (!$isData) {
    out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ';';
  if ($isData) {
    out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  }
  out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  if ($isData) {
    out += '  }  ';
  }
  out += ' if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to one of the allowed values\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],25:[function(require,module,exports){
'use strict';
module.exports = function generate_format(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
    return out;
  }
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $unknownFormats = it.opts.unknownFormats,
    $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = 'format' + $lvl,
      $isObject = 'isObject' + $lvl,
      $formatType = 'formatType' + $lvl;
    out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
    if (it.async) {
      out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
    }
    out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' (';
    if ($unknownFormats != 'ignore') {
      out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
      if ($allowUnknown) {
        out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
      }
      out += ') || ';
    }
    out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
    if (it.async) {
      out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
    } else {
      out += ' ' + ($format) + '(' + ($data) + ') ';
    }
    out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  } else {
    var $format = it.formats[$schema];
    if (!$format) {
      if ($unknownFormats == 'ignore') {
        it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else {
        throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
      }
    }
    var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
    var $formatType = $isObject && $format.type || 'string';
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($formatType != $ruleType) {
      if ($breakOnError) {
        out += ' if (true) { ';
      }
      return out;
    }
    if ($async) {
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
      out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
    } else {
      out += ' if (! ';
      var $formatRef = 'formats' + it.util.getProperty($schema);
      if ($isObject) $formatRef += '.validate';
      if (typeof $format == 'function') {
        out += ' ' + ($formatRef) + '(' + ($data) + ') ';
      } else {
        out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
      }
      out += ') { ';
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match format "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],26:[function(require,module,exports){
'use strict';
module.exports = function generate_if(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $thenSch = it.schema['then'],
    $elseSch = it.schema['else'],
    $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)),
    $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)),
    $currentBaseId = $it.baseId;
  if ($thenPresent || $elsePresent) {
    var $ifClause;
    $it.createErrors = false;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    out += '  ' + (it.validate($it)) + ' ';
    $it.baseId = $currentBaseId;
    $it.createErrors = true;
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    if ($thenPresent) {
      out += ' if (' + ($nextValid) + ') {  ';
      $it.schema = it.schema['then'];
      $it.schemaPath = it.schemaPath + '.then';
      $it.errSchemaPath = it.errSchemaPath + '/then';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'then\'; ';
      } else {
        $ifClause = '\'then\'';
      }
      out += ' } ';
      if ($elsePresent) {
        out += ' else { ';
      }
    } else {
      out += ' if (!' + ($nextValid) + ') { ';
    }
    if ($elsePresent) {
      $it.schema = it.schema['else'];
      $it.schemaPath = it.schemaPath + '.else';
      $it.errSchemaPath = it.errSchemaPath + '/else';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'else\'; ';
      } else {
        $ifClause = '\'else\'';
      }
      out += ' } ';
    }
    out += ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' }   ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}

},{}],27:[function(require,module,exports){
'use strict';

//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
  '$ref': require('./ref'),
  allOf: require('./allOf'),
  anyOf: require('./anyOf'),
  '$comment': require('./comment'),
  const: require('./const'),
  contains: require('./contains'),
  dependencies: require('./dependencies'),
  'enum': require('./enum'),
  format: require('./format'),
  'if': require('./if'),
  items: require('./items'),
  maximum: require('./_limit'),
  minimum: require('./_limit'),
  maxItems: require('./_limitItems'),
  minItems: require('./_limitItems'),
  maxLength: require('./_limitLength'),
  minLength: require('./_limitLength'),
  maxProperties: require('./_limitProperties'),
  minProperties: require('./_limitProperties'),
  multipleOf: require('./multipleOf'),
  not: require('./not'),
  oneOf: require('./oneOf'),
  pattern: require('./pattern'),
  properties: require('./properties'),
  propertyNames: require('./propertyNames'),
  required: require('./required'),
  uniqueItems: require('./uniqueItems'),
  validate: require('./validate')
};

},{"./_limit":13,"./_limitItems":14,"./_limitLength":15,"./_limitProperties":16,"./allOf":17,"./anyOf":18,"./comment":19,"./const":20,"./contains":21,"./dependencies":23,"./enum":24,"./format":25,"./if":26,"./items":28,"./multipleOf":29,"./not":30,"./oneOf":31,"./pattern":32,"./properties":33,"./propertyNames":34,"./ref":35,"./required":36,"./uniqueItems":37,"./validate":38}],28:[function(require,module,exports){
'use strict';
module.exports = function generate_items(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId;
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if (Array.isArray($schema)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += '  if (!' + ($valid) + ') {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } ';
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
    if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
      } else {
        out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
      }
      if ($breakOnError) {
        out += ' if (!' + ($nextValid) + ') break; ';
      }
      out += ' } }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    if ($breakOnError) {
      out += ' if (!' + ($nextValid) + ') break; ';
    }
    out += ' }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}

},{}],29:[function(require,module,exports){
'use strict';
module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  out += 'var division' + ($lvl) + ';if (';
  if ($isData) {
    out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  }
  out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  if (it.opts.multipleOfPrecision) {
    out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  } else {
    out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  }
  out += ' ) ';
  if ($isData) {
    out += '  )  ';
  }
  out += ' ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be multiple of ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],30:[function(require,module,exports){
'use strict';
module.exports = function generate_not(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += ' ' + (it.validate($it)) + ' ';
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (' + ($nextValid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    out += '  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if ($breakOnError) {
      out += ' if (false) { ';
    }
  }
  return out;
}

},{}],31:[function(require,module,exports){
'use strict';
module.exports = function generate_oneOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $prevValid = 'prevValid' + $lvl,
    $passingSchemas = 'passingSchemas' + $lvl;
  out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
      } else {
        out += ' var ' + ($nextValid) + ' = true; ';
      }
      if ($i) {
        out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
        $closingBraces += '}';
      }
      out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match exactly one schema in oneOf\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; return false; ';
    }
  }
  out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}

},{}],32:[function(require,module,exports){
'use strict';
module.exports = function generate_pattern(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
  if ($isData) {
    out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' !' + ($valid) + ') {';
  } else {
    var $regexp = it.usePattern($schema);
    out += ' if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match pattern "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}

},{}],33:[function(require,module,exports){
'use strict';
module.exports = function generate_properties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $key = 'key' + $lvl,
    $idx = 'idx' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $dataProperties = 'dataProperties' + $lvl;
  var $schemaKeys = Object.keys($schema || {}).filter(notProto),
    $pProperties = it.schema.patternProperties || {},
    $pPropertyKeys = Object.keys($pProperties).filter(notProto),
    $aProperties = it.schema.additionalProperties,
    $someProperties = $schemaKeys.length || $pPropertyKeys.length,
    $noAdditional = $aProperties === false,
    $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
    $removeAdditional = it.opts.removeAdditional,
    $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
    $ownProperties = it.opts.ownProperties,
    $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
    var $requiredHash = it.util.toHash($required);
  }

  function notProto(p) {
    return p !== '__proto__';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  if ($ownProperties) {
    out += ' var ' + ($dataProperties) + ' = undefined;';
  }
  if ($checkAdditional) {
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    if ($someProperties) {
      out += ' var isAdditional' + ($lvl) + ' = !(false ';
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 8) {
          out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1,
              l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      out += ' ); if (isAdditional' + ($lvl) + ') { ';
    }
    if ($removeAdditional == 'all') {
      out += ' delete ' + ($data) + '[' + ($key) + ']; ';
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = '\' + ' + $key + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += ' delete ' + ($data) + '[' + ($key) + ']; ';
        } else {
          out += ' ' + ($nextValid) + ' = false; ';
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = ''; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is an invalid additional property';
              } else {
                out += 'should NOT have additional properties';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            /* istanbul ignore if */
            if (it.async) {
              out += ' throw new ValidationError([' + (__err) + ']); ';
            } else {
              out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
          } else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += ' break; ';
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == 'failing') {
          out += ' var ' + ($errs) + ' = errors;  ';
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += ' } ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr3 = $schemaKeys;
    if (arr3) {
      var $propertyKey, i3 = -1,
        l3 = arr3.length - 1;
      while (i3 < l3) {
        $propertyKey = arr3[i3 += 1];
        var $sch = $schema[$propertyKey];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          var $prop = it.util.getProperty($propertyKey),
            $passData = $data + $prop,
            $hasDefault = $useDefaults && $sch.default !== undefined;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
          }
          if ($hasDefault) {
            out += ' ' + ($code) + ' ';
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += ' if ( ' + ($useData) + ' === undefined ';
              if ($ownProperties) {
                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
              }
              out += ') { ' + ($nextValid) + ' = false; ';
              var $currentErrorPath = it.errorPath,
                $currErrSchemaPath = $errSchemaPath,
                $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'';
                  if (it.opts._errorDataPathProperty) {
                    out += 'is a required property';
                  } else {
                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += ' } else { ';
            } else {
              if ($breakOnError) {
                out += ' if ( ' + ($useData) + ' === undefined ';
                if ($ownProperties) {
                  out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ') { ' + ($nextValid) + ' = true; } else { ';
              } else {
                out += ' if (' + ($useData) + ' !== undefined ';
                if ($ownProperties) {
                  out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ' ) { ';
              }
            }
            out += ' ' + ($code) + ' } ';
          }
        }
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($pPropertyKeys.length) {
    var arr4 = $pPropertyKeys;
    if (arr4) {
      var $pProperty, i4 = -1,
        l4 = arr4.length - 1;
      while (i4 < l4) {
        $pProperty = arr4[i4 += 1];
        var $sch = $pProperties[$pProperty];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
          $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
          if ($ownProperties) {
            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
          } else {
            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
          }
          out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}

},{}],34:[function(require,module,exports){
'use strict';
module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  out += 'var ' + ($errs) + ' = errors;';
  if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    var $key = 'key' + $lvl,
      $idx = 'idx' + $lvl,
      $i = 'i' + $lvl,
      $invalidName = '\' + ' + $key + ' + \'',
      $dataNxt = $it.dataLevel = it.dataLevel + 1,
      $nextData = 'data' + $dataNxt,
      $dataProperties = 'dataProperties' + $lvl,
      $ownProperties = it.opts.ownProperties,
      $currentBaseId = it.baseId;
    if ($ownProperties) {
      out += ' var ' + ($dataProperties) + ' = undefined; ';
    }
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    out += ' var startErrs' + ($lvl) + ' = errors; ';
    var $passData = $key;
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; }   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    if ($breakOnError) {
      out += ' break; ';
    }
    out += ' } }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}

},{}],35:[function(require,module,exports){
'use strict';
module.exports = function generate_ref(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $async, $refCode;
  if ($schema == '#' || $schema == '#/') {
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
    if ($refVal === undefined) {
      var $message = it.MissingRefError.message(it.baseId, $schema);
      if (it.opts.missingRefs == 'fail') {
        it.logger.error($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        if ($breakOnError) {
          out += ' if (false) { ';
        }
      } else if (it.opts.missingRefs == 'ignore') {
        it.logger.warn($message);
        if ($breakOnError) {
          out += ' if (true) { ';
        }
      } else {
        throw new it.MissingRefError(it.baseId, $schema, $message);
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = 'valid' + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += ' ' + ($code) + ' ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
      }
    } else {
      $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    if (it.opts.passContext) {
      out += ' ' + ($refCode) + '.call(this, ';
    } else {
      out += ' ' + ($refCode) + '( ';
    }
    out += ' ' + ($data) + ', (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async) throw new Error('async schema referenced by sync schema');
      if ($breakOnError) {
        out += ' var ' + ($valid) + '; ';
      }
      out += ' try { await ' + (__callValidate) + '; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = true; ';
      }
      out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = false; ';
      }
      out += ' } ';
      if ($breakOnError) {
        out += ' if (' + ($valid) + ') { ';
      }
    } else {
      out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' else { ';
      }
    }
  }
  return out;
}

},{}],36:[function(require,module,exports){
'use strict';
module.exports = function generate_required(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $vSchema = 'schema' + $lvl;
  if (!$isData) {
    if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema;
      if (arr1) {
        var $property, i1 = -1,
          l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath,
      $loopRequired = $isData || $required.length >= it.opts.loopRequired,
      $ownProperties = it.opts.ownProperties;
    if ($breakOnError) {
      out += ' var missing' + ($lvl) + '; ';
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += ' var ' + ($valid) + ' = true; ';
        if ($isData) {
          out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
        if ($ownProperties) {
          out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += '; if (!' + ($valid) + ') break; } ';
        if ($isData) {
          out += '  }  ';
        }
        out += '  if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      } else {
        out += ' if ( ';
        var arr2 = $required;
        if (arr2) {
          var $propertyKey, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $propertyKey = arr2[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ') {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is a required property';
              } else {
                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
        if ($ownProperties) {
          out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += ') {  var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
        if ($isData) {
          out += '  }  ';
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $propertyKey, i3 = -1,
            l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'';
                if (it.opts._errorDataPathProperty) {
                  out += 'is a required property';
                } else {
                  out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                }
                out += '\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += ' if (true) {';
  }
  return out;
}

},{}],37:[function(require,module,exports){
'use strict';
module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (($schema || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
    }
    out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
    var $itemType = it.schema.items && it.schema.items.type,
      $typeIsArray = Array.isArray($itemType);
    if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
      out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
    } else {
      out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
      var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
      out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
      if ($typeIsArray) {
        out += ' if (typeof item == \'string\') item = \'"\' + item; ';
      }
      out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
    }
    out += ' } ';
    if ($isData) {
      out += '  }  ';
    }
    out += ' if (!' + ($valid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema:  ';
        if ($isData) {
          out += 'validate.schema' + ($schemaPath);
        } else {
          out += '' + ($schema);
        }
        out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}

},{}],38:[function(require,module,exports){
'use strict';
module.exports = function generate_validate(it, $keyword, $ruleType) {
  var out = '';
  var $async = it.schema.$async === true,
    $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
    $id = it.self._getId(it.schema);
  if (it.opts.strictKeywords) {
    var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
    if ($unknownKwd) {
      var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
      if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
      else throw new Error($keywordsMsg);
    }
  }
  if (it.isTop) {
    out += ' var validate = ';
    if ($async) {
      it.async = true;
      out += 'async ';
    }
    out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
    if ($id && (it.opts.sourceCode || it.opts.processCode)) {
      out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
    }
  }
  if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
    var $keyword = 'false schema';
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = 'data' + ($dataLvl || '');
    var $valid = 'valid' + $lvl;
    if (it.schema === false) {
      if (it.isTop) {
        $breakOnError = true;
      } else {
        out += ' var ' + ($valid) + ' = false; ';
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
        if (it.opts.messages !== false) {
          out += ' , message: \'boolean schema is false\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
    } else {
      if (it.isTop) {
        if ($async) {
          out += ' return data; ';
        } else {
          out += ' validate.errors = null; return true; ';
        }
      } else {
        out += ' var ' + ($valid) + ' = true; ';
      }
    }
    if (it.isTop) {
      out += ' }; return validate; ';
    }
    return out;
  }
  if (it.isTop) {
    var $top = it.isTop,
      $lvl = it.level = 0,
      $dataLvl = it.dataLevel = 0,
      $data = 'data';
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;
    it.dataPathArr = [""];
    if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
      var $defaultMsg = 'default is ignored in the schema root';
      if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
      else throw new Error($defaultMsg);
    }
    out += ' var vErrors = null; ';
    out += ' var errors = 0;     ';
    out += ' if (rootData === undefined) rootData = data; ';
  } else {
    var $lvl = it.level,
      $dataLvl = it.dataLevel,
      $data = 'data' + ($dataLvl || '');
    if ($id) it.baseId = it.resolve.url(it.baseId, $id);
    if ($async && !it.async) throw new Error('async schema in sync schema');
    out += ' var errs_' + ($lvl) + ' = errors;';
  }
  var $valid = 'valid' + $lvl,
    $breakOnError = !it.opts.allErrors,
    $closingBraces1 = '',
    $closingBraces2 = '';
  var $errorKeyword;
  var $typeSchema = it.schema.type,
    $typeIsArray = Array.isArray($typeSchema);
  if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
    if ($typeIsArray) {
      if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
    } else if ($typeSchema != 'null') {
      $typeSchema = [$typeSchema, 'null'];
      $typeIsArray = true;
    }
  }
  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
  if (it.schema.$ref && $refKeywords) {
    if (it.opts.extendRefs == 'fail') {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
    } else if (it.opts.extendRefs !== true) {
      $refKeywords = false;
      it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }
  }
  if (it.schema.$comment && it.opts.$comment) {
    out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
  }
  if ($typeSchema) {
    if (it.opts.coerceTypes) {
      var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    }
    var $rulesGroup = it.RULES.types[$typeSchema];
    if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type';
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type',
        $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
      out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
      if ($coerceToTypes) {
        var $dataType = 'dataType' + $lvl,
          $coerced = 'coerced' + $lvl;
        out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';
        if (it.opts.coerceTypes == 'array') {
          out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';
        }
        out += ' if (' + ($coerced) + ' !== undefined) ; ';
        var arr1 = $coerceToTypes;
        if (arr1) {
          var $type, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $type = arr1[$i += 1];
            if ($type == 'string') {
              out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
            } else if ($type == 'number' || $type == 'integer') {
              out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
              if ($type == 'integer') {
                out += ' && !(' + ($data) + ' % 1)';
              }
              out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
            } else if ($type == 'boolean') {
              out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
            } else if ($type == 'null') {
              out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
            } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
              out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
            }
          }
        }
        out += ' else {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } if (' + ($coerced) + ' !== undefined) {  ';
        var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
          $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
        out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
        if (!$dataLvl) {
          out += 'if (' + ($parentData) + ' !== undefined)';
        }
        out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      }
      out += ' } ';
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
    if ($breakOnError) {
      out += ' } if (errors === ';
      if ($top) {
        out += '0';
      } else {
        out += 'errs_' + ($lvl);
      }
      out += ') { ';
      $closingBraces2 += '}';
    }
  } else {
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1,
        l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
          }
          if (it.opts.useDefaults) {
            if ($rulesGroup.type == 'object' && it.schema.properties) {
              var $schema = it.schema.properties,
                $schemaKeys = Object.keys($schema);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1,
                  l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema[$propertyKey];
                  if ($sch.default !== undefined) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1,
                  l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== undefined) {
                    var $passData = $data + '[' + $i + ']';
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1,
              l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                if ($code) {
                  out += ' ' + ($code) + ' ';
                  if ($breakOnError) {
                    $closingBraces1 += '}';
                  }
                }
              }
            }
          }
          if ($breakOnError) {
            out += ' ' + ($closingBraces1) + ' ';
            $closingBraces1 = '';
          }
          if ($rulesGroup.type) {
            out += ' } ';
            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
              out += ' else { ';
              var $schemaPath = it.schemaPath + '.type',
                $errSchemaPath = it.errSchemaPath + '/type';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                if ($typeIsArray) {
                  out += '' + ($typeSchema.join(","));
                } else {
                  out += '' + ($typeSchema);
                }
                out += '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should be ';
                  if ($typeIsArray) {
                    out += '' + ($typeSchema.join(","));
                  } else {
                    out += '' + ($typeSchema);
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
          }
          if ($breakOnError) {
            out += ' if (errors === ';
            if ($top) {
              out += '0';
            } else {
              out += 'errs_' + ($lvl);
            }
            out += ') { ';
            $closingBraces2 += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces2) + ' ';
  }
  if ($top) {
    if ($async) {
      out += ' if (errors === 0) return data;           ';
      out += ' else throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; ';
      out += ' return errors === 0;       ';
    }
    out += ' }; return validate;';
  } else {
    out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  }

  function $shouldUseGroup($rulesGroup) {
    var rules = $rulesGroup.rules;
    for (var i = 0; i < rules.length; i++)
      if ($shouldUseRule(rules[i])) return true;
  }

  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
  }

  function $ruleImplementsSomeKeyword($rule) {
    var impl = $rule.implements;
    for (var i = 0; i < impl.length; i++)
      if (it.schema[impl[i]] !== undefined) return true;
  }
  return out;
}

},{}],39:[function(require,module,exports){
'use strict';

var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
var customRuleCode = require('./dotjs/custom');
var definitionSchema = require('./definition_schema');

module.exports = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword,
  validate: validateKeyword
};


/**
 * Define custom keyword
 * @this  Ajv
 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
 * @return {Ajv} this for method chaining
 */
function addKeyword(keyword, definition) {
  /* jshint validthis: true */
  /* eslint no-shadow: 0 */
  var RULES = this.RULES;
  if (RULES.keywords[keyword])
    throw new Error('Keyword ' + keyword + ' is already defined');

  if (!IDENTIFIER.test(keyword))
    throw new Error('Keyword ' + keyword + ' is not a valid identifier');

  if (definition) {
    this.validateKeyword(definition, true);

    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      for (var i=0; i<dataType.length; i++)
        _addRule(keyword, dataType[i], definition);
    } else {
      _addRule(keyword, dataType, definition);
    }

    var metaSchema = definition.metaSchema;
    if (metaSchema) {
      if (definition.$data && this._opts.$data) {
        metaSchema = {
          anyOf: [
            metaSchema,
            { '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema, true);
    }
  }

  RULES.keywords[keyword] = RULES.all[keyword] = true;


  function _addRule(keyword, dataType, definition) {
    var ruleGroup;
    for (var i=0; i<RULES.length; i++) {
      var rg = RULES[i];
      if (rg.type == dataType) {
        ruleGroup = rg;
        break;
      }
    }

    if (!ruleGroup) {
      ruleGroup = { type: dataType, rules: [] };
      RULES.push(ruleGroup);
    }

    var rule = {
      keyword: keyword,
      definition: definition,
      custom: true,
      code: customRuleCode,
      implements: definition.implements
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword] = rule;
  }

  return this;
}


/**
 * Get keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
 */
function getKeyword(keyword) {
  /* jshint validthis: true */
  var rule = this.RULES.custom[keyword];
  return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}


/**
 * Remove keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Ajv} this for method chaining
 */
function removeKeyword(keyword) {
  /* jshint validthis: true */
  var RULES = this.RULES;
  delete RULES.keywords[keyword];
  delete RULES.all[keyword];
  delete RULES.custom[keyword];
  for (var i=0; i<RULES.length; i++) {
    var rules = RULES[i].rules;
    for (var j=0; j<rules.length; j++) {
      if (rules[j].keyword == keyword) {
        rules.splice(j, 1);
        break;
      }
    }
  }
  return this;
}


/**
 * Validate keyword definition
 * @this  Ajv
 * @param {Object} definition keyword definition object.
 * @param {Boolean} throwError true to throw exception if definition is invalid
 * @return {boolean} validation result
 */
function validateKeyword(definition, throwError) {
  validateKeyword.errors = null;
  var v = this._validateKeyword = this._validateKeyword
                                  || this.compile(definitionSchema, true);

  if (v(definition)) return true;
  validateKeyword.errors = v.errors;
  if (throwError)
    throw new Error('custom keyword definition is invalid: '  + this.errorsText(v.errors));
  else
    return false;
}

},{"./definition_schema":12,"./dotjs/custom":22}],40:[function(require,module,exports){
module.exports={
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
    "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
    "type": "object",
    "required": [ "$data" ],
    "properties": {
        "$data": {
            "type": "string",
            "anyOf": [
                { "format": "relative-json-pointer" }, 
                { "format": "json-pointer" }
            ]
        }
    },
    "additionalProperties": false
}

},{}],41:[function(require,module,exports){
module.exports={
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://json-schema.org/draft-07/schema#",
    "title": "Core schema meta-schema",
    "definitions": {
        "schemaArray": {
            "type": "array",
            "minItems": 1,
            "items": { "$ref": "#" }
        },
        "nonNegativeInteger": {
            "type": "integer",
            "minimum": 0
        },
        "nonNegativeIntegerDefault0": {
            "allOf": [
                { "$ref": "#/definitions/nonNegativeInteger" },
                { "default": 0 }
            ]
        },
        "simpleTypes": {
            "enum": [
                "array",
                "boolean",
                "integer",
                "null",
                "number",
                "object",
                "string"
            ]
        },
        "stringArray": {
            "type": "array",
            "items": { "type": "string" },
            "uniqueItems": true,
            "default": []
        }
    },
    "type": ["object", "boolean"],
    "properties": {
        "$id": {
            "type": "string",
            "format": "uri-reference"
        },
        "$schema": {
            "type": "string",
            "format": "uri"
        },
        "$ref": {
            "type": "string",
            "format": "uri-reference"
        },
        "$comment": {
            "type": "string"
        },
        "title": {
            "type": "string"
        },
        "description": {
            "type": "string"
        },
        "default": true,
        "readOnly": {
            "type": "boolean",
            "default": false
        },
        "examples": {
            "type": "array",
            "items": true
        },
        "multipleOf": {
            "type": "number",
            "exclusiveMinimum": 0
        },
        "maximum": {
            "type": "number"
        },
        "exclusiveMaximum": {
            "type": "number"
        },
        "minimum": {
            "type": "number"
        },
        "exclusiveMinimum": {
            "type": "number"
        },
        "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
        "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "pattern": {
            "type": "string",
            "format": "regex"
        },
        "additionalItems": { "$ref": "#" },
        "items": {
            "anyOf": [
                { "$ref": "#" },
                { "$ref": "#/definitions/schemaArray" }
            ],
            "default": true
        },
        "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
        "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "uniqueItems": {
            "type": "boolean",
            "default": false
        },
        "contains": { "$ref": "#" },
        "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
        "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "required": { "$ref": "#/definitions/stringArray" },
        "additionalProperties": { "$ref": "#" },
        "definitions": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "properties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "patternProperties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "propertyNames": { "format": "regex" },
            "default": {}
        },
        "dependencies": {
            "type": "object",
            "additionalProperties": {
                "anyOf": [
                    { "$ref": "#" },
                    { "$ref": "#/definitions/stringArray" }
                ]
            }
        },
        "propertyNames": { "$ref": "#" },
        "const": true,
        "enum": {
            "type": "array",
            "items": true,
            "minItems": 1,
            "uniqueItems": true
        },
        "type": {
            "anyOf": [
                { "$ref": "#/definitions/simpleTypes" },
                {
                    "type": "array",
                    "items": { "$ref": "#/definitions/simpleTypes" },
                    "minItems": 1,
                    "uniqueItems": true
                }
            ]
        },
        "format": { "type": "string" },
        "contentMediaType": { "type": "string" },
        "contentEncoding": { "type": "string" },
        "if": {"$ref": "#"},
        "then": {"$ref": "#"},
        "else": {"$ref": "#"},
        "allOf": { "$ref": "#/definitions/schemaArray" },
        "anyOf": { "$ref": "#/definitions/schemaArray" },
        "oneOf": { "$ref": "#/definitions/schemaArray" },
        "not": { "$ref": "#" }
    },
    "default": true
}

},{}],42:[function(require,module,exports){
'use strict';

// do not edit .js files directly - edit src/index.jst



module.exports = function equal(a, b) {
  if (a === b) return true;

  if (a && b && typeof a == 'object' && typeof b == 'object') {
    if (a.constructor !== b.constructor) return false;

    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length) return false;
      for (i = length; i-- !== 0;)
        if (!equal(a[i], b[i])) return false;
      return true;
    }



    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();

    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length) return false;

    for (i = length; i-- !== 0;)
      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;

    for (i = length; i-- !== 0;) {
      var key = keys[i];

      if (!equal(a[key], b[key])) return false;
    }

    return true;
  }

  // true if both NaN, false otherwise
  return a!==a && b!==b;
};

},{}],43:[function(require,module,exports){
'use strict';

module.exports = function (data, opts) {
    if (!opts) opts = {};
    if (typeof opts === 'function') opts = { cmp: opts };
    var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;

    var cmp = opts.cmp && (function (f) {
        return function (node) {
            return function (a, b) {
                var aobj = { key: a, value: node[a] };
                var bobj = { key: b, value: node[b] };
                return f(aobj, bobj);
            };
        };
    })(opts.cmp);

    var seen = [];
    return (function stringify (node) {
        if (node && node.toJSON && typeof node.toJSON === 'function') {
            node = node.toJSON();
        }

        if (node === undefined) return;
        if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
        if (typeof node !== 'object') return JSON.stringify(node);

        var i, out;
        if (Array.isArray(node)) {
            out = '[';
            for (i = 0; i < node.length; i++) {
                if (i) out += ',';
                out += stringify(node[i]) || 'null';
            }
            return out + ']';
        }

        if (node === null) return 'null';

        if (seen.indexOf(node) !== -1) {
            if (cycles) return JSON.stringify('__cycle__');
            throw new TypeError('Converting circular structure to JSON');
        }

        var seenIndex = seen.push(node) - 1;
        var keys = Object.keys(node).sort(cmp && cmp(node));
        out = '';
        for (i = 0; i < keys.length; i++) {
            var key = keys[i];
            var value = stringify(node[key]);

            if (!value) continue;
            if (out) out += ',';
            out += JSON.stringify(key) + ':' + value;
        }
        seen.splice(seenIndex, 1);
        return '{' + out + '}';
    })(data);
};

},{}],44:[function(require,module,exports){
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}

},{}],45:[function(require,module,exports){
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
	typeof define === 'function' && define.amd ? define(['exports'], factory) :
	(factory((global.URI = global.URI || {})));
}(this, (function (exports) { 'use strict';

function merge() {
    for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
        sets[_key] = arguments[_key];
    }

    if (sets.length > 1) {
        sets[0] = sets[0].slice(0, -1);
        var xl = sets.length - 1;
        for (var x = 1; x < xl; ++x) {
            sets[x] = sets[x].slice(1, -1);
        }
        sets[xl] = sets[xl].slice(1);
        return sets.join('');
    } else {
        return sets[0];
    }
}
function subexp(str) {
    return "(?:" + str + ")";
}
function typeOf(o) {
    return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
}
function toUpperCase(str) {
    return str.toUpperCase();
}
function toArray(obj) {
    return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
}
function assign(target, source) {
    var obj = target;
    if (source) {
        for (var key in source) {
            obj[key] = source[key];
        }
    }
    return obj;
}

function buildExps(isIRI) {
    var ALPHA$$ = "[A-Za-z]",
        CR$ = "[\\x0D]",
        DIGIT$$ = "[0-9]",
        DQUOTE$$ = "[\\x22]",
        HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
        //case-insensitive
    LF$$ = "[\\x0A]",
        SP$$ = "[\\x20]",
        PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
        //expanded
    GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
        SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
        RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
        UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
        //subset, excludes bidi control characters
    IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
        //subset
    UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
        SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
        USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
        DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
        DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
        //relaxed parsing rules
    IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
        H16$ = subexp(HEXDIG$$ + "{1,4}"),
        LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
        IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
        //                           6( h16 ":" ) ls32
    IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
        //                      "::" 5( h16 ":" ) ls32
    IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
        //[               h16 ] "::" 4( h16 ":" ) ls32
    IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
        //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
    IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
        //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
    IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
        //[ *3( h16 ":" ) h16 ] "::"    h16 ":"   ls32
    IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
        //[ *4( h16 ":" ) h16 ] "::"              ls32
    IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
        //[ *5( h16 ":" ) h16 ] "::"              h16
    IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
        //[ *6( h16 ":" ) h16 ] "::"
    IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
        ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
        //RFC 6874
    IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
        //RFC 6874
    IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
        //RFC 6874, with relaxed parsing rules
    IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
        IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
        //RFC 6874
    REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
        HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
        PORT$ = subexp(DIGIT$$ + "*"),
        AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
        PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
        SEGMENT$ = subexp(PCHAR$ + "*"),
        SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
        SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
        PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
        PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
        //simplified
    PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
        //simplified
    PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
        //simplified
    PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
        PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
        QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
        FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
        HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
        URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
        RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
        RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
        URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
        ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
        GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
        SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
        AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
    return {
        NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
        NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
        NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
        ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
        UNRESERVED: new RegExp(UNRESERVED$$, "g"),
        OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
        PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
        IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
        IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
    };
}
var URI_PROTOCOL = buildExps(false);

var IRI_PROTOCOL = buildExps(true);

var slicedToArray = function () {
  function sliceIterator(arr, i) {
    var _arr = [];
    var _n = true;
    var _d = false;
    var _e = undefined;

    try {
      for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
        _arr.push(_s.value);

        if (i && _arr.length === i) break;
      }
    } catch (err) {
      _d = true;
      _e = err;
    } finally {
      try {
        if (!_n && _i["return"]) _i["return"]();
      } finally {
        if (_d) throw _e;
      }
    }

    return _arr;
  }

  return function (arr, i) {
    if (Array.isArray(arr)) {
      return arr;
    } else if (Symbol.iterator in Object(arr)) {
      return sliceIterator(arr, i);
    } else {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }
  };
}();













var toConsumableArray = function (arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

    return arr2;
  } else {
    return Array.from(arr);
  }
};

/** Highest positive signed 32-bit float value */

var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1

/** Bootstring parameters */
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128; // 0x80
var delimiter = '-'; // '\x2D'

/** Regular expressions */
var regexPunycode = /^xn--/;
var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators

/** Error messages */
var errors = {
	'overflow': 'Overflow: input needs wider integers to process',
	'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
	'invalid-input': 'Invalid input'
};

/** Convenience shortcuts */
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;

/*--------------------------------------------------------------------------*/

/**
 * A generic error utility function.
 * @private
 * @param {String} type The error type.
 * @returns {Error} Throws a `RangeError` with the applicable error message.
 */
function error$1(type) {
	throw new RangeError(errors[type]);
}

/**
 * A generic `Array#map` utility function.
 * @private
 * @param {Array} array The array to iterate over.
 * @param {Function} callback The function that gets called for every array
 * item.
 * @returns {Array} A new array of values returned by the callback function.
 */
function map(array, fn) {
	var result = [];
	var length = array.length;
	while (length--) {
		result[length] = fn(array[length]);
	}
	return result;
}

/**
 * A simple `Array#map`-like wrapper to work with domain name strings or email
 * addresses.
 * @private
 * @param {String} domain The domain name or email address.
 * @param {Function} callback The function that gets called for every
 * character.
 * @returns {Array} A new string of characters returned by the callback
 * function.
 */
function mapDomain(string, fn) {
	var parts = string.split('@');
	var result = '';
	if (parts.length > 1) {
		// In email addresses, only the domain name should be punycoded. Leave
		// the local part (i.e. everything up to `@`) intact.
		result = parts[0] + '@';
		string = parts[1];
	}
	// Avoid `split(regex)` for IE8 compatibility. See #17.
	string = string.replace(regexSeparators, '\x2E');
	var labels = string.split('.');
	var encoded = map(labels, fn).join('.');
	return result + encoded;
}

/**
 * Creates an array containing the numeric code points of each Unicode
 * character in the string. While JavaScript uses UCS-2 internally,
 * this function will convert a pair of surrogate halves (each of which
 * UCS-2 exposes as separate characters) into a single code point,
 * matching UTF-16.
 * @see `punycode.ucs2.encode`
 * @see <https://mathiasbynens.be/notes/javascript-encoding>
 * @memberOf punycode.ucs2
 * @name decode
 * @param {String} string The Unicode input string (UCS-2).
 * @returns {Array} The new array of code points.
 */
function ucs2decode(string) {
	var output = [];
	var counter = 0;
	var length = string.length;
	while (counter < length) {
		var value = string.charCodeAt(counter++);
		if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
			// It's a high surrogate, and there is a next character.
			var extra = string.charCodeAt(counter++);
			if ((extra & 0xFC00) == 0xDC00) {
				// Low surrogate.
				output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
			} else {
				// It's an unmatched surrogate; only append this code unit, in case the
				// next code unit is the high surrogate of a surrogate pair.
				output.push(value);
				counter--;
			}
		} else {
			output.push(value);
		}
	}
	return output;
}

/**
 * Creates a string based on an array of numeric code points.
 * @see `punycode.ucs2.decode`
 * @memberOf punycode.ucs2
 * @name encode
 * @param {Array} codePoints The array of numeric code points.
 * @returns {String} The new Unicode string (UCS-2).
 */
var ucs2encode = function ucs2encode(array) {
	return String.fromCodePoint.apply(String, toConsumableArray(array));
};

/**
 * Converts a basic code point into a digit/integer.
 * @see `digitToBasic()`
 * @private
 * @param {Number} codePoint The basic numeric code point value.
 * @returns {Number} The numeric value of a basic code point (for use in
 * representing integers) in the range `0` to `base - 1`, or `base` if
 * the code point does not represent a value.
 */
var basicToDigit = function basicToDigit(codePoint) {
	if (codePoint - 0x30 < 0x0A) {
		return codePoint - 0x16;
	}
	if (codePoint - 0x41 < 0x1A) {
		return codePoint - 0x41;
	}
	if (codePoint - 0x61 < 0x1A) {
		return codePoint - 0x61;
	}
	return base;
};

/**
 * Converts a digit/integer into a basic code point.
 * @see `basicToDigit()`
 * @private
 * @param {Number} digit The numeric value of a basic code point.
 * @returns {Number} The basic code point whose value (when used for
 * representing integers) is `digit`, which needs to be in the range
 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
 * used; else, the lowercase form is used. The behavior is undefined
 * if `flag` is non-zero and `digit` has no uppercase form.
 */
var digitToBasic = function digitToBasic(digit, flag) {
	//  0..25 map to ASCII a..z or A..Z
	// 26..35 map to ASCII 0..9
	return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};

/**
 * Bias adaptation function as per section 3.4 of RFC 3492.
 * https://tools.ietf.org/html/rfc3492#section-3.4
 * @private
 */
var adapt = function adapt(delta, numPoints, firstTime) {
	var k = 0;
	delta = firstTime ? floor(delta / damp) : delta >> 1;
	delta += floor(delta / numPoints);
	for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
		delta = floor(delta / baseMinusTMin);
	}
	return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};

/**
 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
 * symbols.
 * @memberOf punycode
 * @param {String} input The Punycode string of ASCII-only symbols.
 * @returns {String} The resulting string of Unicode symbols.
 */
var decode = function decode(input) {
	// Don't use UCS-2.
	var output = [];
	var inputLength = input.length;
	var i = 0;
	var n = initialN;
	var bias = initialBias;

	// Handle the basic code points: let `basic` be the number of input code
	// points before the last delimiter, or `0` if there is none, then copy
	// the first basic code points to the output.

	var basic = input.lastIndexOf(delimiter);
	if (basic < 0) {
		basic = 0;
	}

	for (var j = 0; j < basic; ++j) {
		// if it's not a basic code point
		if (input.charCodeAt(j) >= 0x80) {
			error$1('not-basic');
		}
		output.push(input.charCodeAt(j));
	}

	// Main decoding loop: start just after the last delimiter if any basic code
	// points were copied; start at the beginning otherwise.

	for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{

		// `index` is the index of the next character to be consumed.
		// Decode a generalized variable-length integer into `delta`,
		// which gets added to `i`. The overflow checking is easier
		// if we increase `i` as we go, then subtract off its starting
		// value at the end to obtain `delta`.
		var oldi = i;
		for (var w = 1, k = base;; /* no condition */k += base) {

			if (index >= inputLength) {
				error$1('invalid-input');
			}

			var digit = basicToDigit(input.charCodeAt(index++));

			if (digit >= base || digit > floor((maxInt - i) / w)) {
				error$1('overflow');
			}

			i += digit * w;
			var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;

			if (digit < t) {
				break;
			}

			var baseMinusT = base - t;
			if (w > floor(maxInt / baseMinusT)) {
				error$1('overflow');
			}

			w *= baseMinusT;
		}

		var out = output.length + 1;
		bias = adapt(i - oldi, out, oldi == 0);

		// `i` was supposed to wrap around from `out` to `0`,
		// incrementing `n` each time, so we'll fix that now:
		if (floor(i / out) > maxInt - n) {
			error$1('overflow');
		}

		n += floor(i / out);
		i %= out;

		// Insert `n` at position `i` of the output.
		output.splice(i++, 0, n);
	}

	return String.fromCodePoint.apply(String, output);
};

/**
 * Converts a string of Unicode symbols (e.g. a domain name label) to a
 * Punycode string of ASCII-only symbols.
 * @memberOf punycode
 * @param {String} input The string of Unicode symbols.
 * @returns {String} The resulting Punycode string of ASCII-only symbols.
 */
var encode = function encode(input) {
	var output = [];

	// Convert the input in UCS-2 to an array of Unicode code points.
	input = ucs2decode(input);

	// Cache the length.
	var inputLength = input.length;

	// Initialize the state.
	var n = initialN;
	var delta = 0;
	var bias = initialBias;

	// Handle the basic code points.
	var _iteratorNormalCompletion = true;
	var _didIteratorError = false;
	var _iteratorError = undefined;

	try {
		for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
			var _currentValue2 = _step.value;

			if (_currentValue2 < 0x80) {
				output.push(stringFromCharCode(_currentValue2));
			}
		}
	} catch (err) {
		_didIteratorError = true;
		_iteratorError = err;
	} finally {
		try {
			if (!_iteratorNormalCompletion && _iterator.return) {
				_iterator.return();
			}
		} finally {
			if (_didIteratorError) {
				throw _iteratorError;
			}
		}
	}

	var basicLength = output.length;
	var handledCPCount = basicLength;

	// `handledCPCount` is the number of code points that have been handled;
	// `basicLength` is the number of basic code points.

	// Finish the basic string with a delimiter unless it's empty.
	if (basicLength) {
		output.push(delimiter);
	}

	// Main encoding loop:
	while (handledCPCount < inputLength) {

		// All non-basic code points < n have been handled already. Find the next
		// larger one:
		var m = maxInt;
		var _iteratorNormalCompletion2 = true;
		var _didIteratorError2 = false;
		var _iteratorError2 = undefined;

		try {
			for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
				var currentValue = _step2.value;

				if (currentValue >= n && currentValue < m) {
					m = currentValue;
				}
			}

			// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
			// but guard against overflow.
		} catch (err) {
			_didIteratorError2 = true;
			_iteratorError2 = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion2 && _iterator2.return) {
					_iterator2.return();
				}
			} finally {
				if (_didIteratorError2) {
					throw _iteratorError2;
				}
			}
		}

		var handledCPCountPlusOne = handledCPCount + 1;
		if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
			error$1('overflow');
		}

		delta += (m - n) * handledCPCountPlusOne;
		n = m;

		var _iteratorNormalCompletion3 = true;
		var _didIteratorError3 = false;
		var _iteratorError3 = undefined;

		try {
			for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
				var _currentValue = _step3.value;

				if (_currentValue < n && ++delta > maxInt) {
					error$1('overflow');
				}
				if (_currentValue == n) {
					// Represent delta as a generalized variable-length integer.
					var q = delta;
					for (var k = base;; /* no condition */k += base) {
						var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
						if (q < t) {
							break;
						}
						var qMinusT = q - t;
						var baseMinusT = base - t;
						output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
						q = floor(qMinusT / baseMinusT);
					}

					output.push(stringFromCharCode(digitToBasic(q, 0)));
					bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
					delta = 0;
					++handledCPCount;
				}
			}
		} catch (err) {
			_didIteratorError3 = true;
			_iteratorError3 = err;
		} finally {
			try {
				if (!_iteratorNormalCompletion3 && _iterator3.return) {
					_iterator3.return();
				}
			} finally {
				if (_didIteratorError3) {
					throw _iteratorError3;
				}
			}
		}

		++delta;
		++n;
	}
	return output.join('');
};

/**
 * Converts a Punycode string representing a domain name or an email address
 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
 * it doesn't matter if you call it on a string that has already been
 * converted to Unicode.
 * @memberOf punycode
 * @param {String} input The Punycoded domain name or email address to
 * convert to Unicode.
 * @returns {String} The Unicode representation of the given Punycode
 * string.
 */
var toUnicode = function toUnicode(input) {
	return mapDomain(input, function (string) {
		return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
	});
};

/**
 * Converts a Unicode string representing a domain name or an email address to
 * Punycode. Only the non-ASCII parts of the domain name will be converted,
 * i.e. it doesn't matter if you call it with a domain that's already in
 * ASCII.
 * @memberOf punycode
 * @param {String} input The domain name or email address to convert, as a
 * Unicode string.
 * @returns {String} The Punycode representation of the given domain name or
 * email address.
 */
var toASCII = function toASCII(input) {
	return mapDomain(input, function (string) {
		return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
	});
};

/*--------------------------------------------------------------------------*/

/** Define the public API */
var punycode = {
	/**
  * A string representing the current Punycode.js version number.
  * @memberOf punycode
  * @type String
  */
	'version': '2.1.0',
	/**
  * An object of methods to convert from JavaScript's internal character
  * representation (UCS-2) to Unicode code points, and back.
  * @see <https://mathiasbynens.be/notes/javascript-encoding>
  * @memberOf punycode
  * @type Object
  */
	'ucs2': {
		'decode': ucs2decode,
		'encode': ucs2encode
	},
	'decode': decode,
	'encode': encode,
	'toASCII': toASCII,
	'toUnicode': toUnicode
};

/**
 * URI.js
 *
 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
 * @see http://github.com/garycourt/uri-js
 */
/**
 * Copyright 2011 Gary Court. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Gary Court.
 */
var SCHEMES = {};
function pctEncChar(chr) {
    var c = chr.charCodeAt(0);
    var e = void 0;
    if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
    return e;
}
function pctDecChars(str) {
    var newStr = "";
    var i = 0;
    var il = str.length;
    while (i < il) {
        var c = parseInt(str.substr(i + 1, 2), 16);
        if (c < 128) {
            newStr += String.fromCharCode(c);
            i += 3;
        } else if (c >= 194 && c < 224) {
            if (il - i >= 6) {
                var c2 = parseInt(str.substr(i + 4, 2), 16);
                newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
            } else {
                newStr += str.substr(i, 6);
            }
            i += 6;
        } else if (c >= 224) {
            if (il - i >= 9) {
                var _c = parseInt(str.substr(i + 4, 2), 16);
                var c3 = parseInt(str.substr(i + 7, 2), 16);
                newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
            } else {
                newStr += str.substr(i, 9);
            }
            i += 9;
        } else {
            newStr += str.substr(i, 3);
            i += 3;
        }
    }
    return newStr;
}
function _normalizeComponentEncoding(components, protocol) {
    function decodeUnreserved(str) {
        var decStr = pctDecChars(str);
        return !decStr.match(protocol.UNRESERVED) ? str : decStr;
    }
    if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
    if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
    return components;
}

function _stripLeadingZeros(str) {
    return str.replace(/^0*(.*)/, "$1") || "0";
}
function _normalizeIPv4(host, protocol) {
    var matches = host.match(protocol.IPV4ADDRESS) || [];

    var _matches = slicedToArray(matches, 2),
        address = _matches[1];

    if (address) {
        return address.split(".").map(_stripLeadingZeros).join(".");
    } else {
        return host;
    }
}
function _normalizeIPv6(host, protocol) {
    var matches = host.match(protocol.IPV6ADDRESS) || [];

    var _matches2 = slicedToArray(matches, 3),
        address = _matches2[1],
        zone = _matches2[2];

    if (address) {
        var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
            _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
            last = _address$toLowerCase$2[0],
            first = _address$toLowerCase$2[1];

        var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
        var lastFields = last.split(":").map(_stripLeadingZeros);
        var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
        var fieldCount = isLastFieldIPv4Address ? 7 : 8;
        var lastFieldsStart = lastFields.length - fieldCount;
        var fields = Array(fieldCount);
        for (var x = 0; x < fieldCount; ++x) {
            fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
        }
        if (isLastFieldIPv4Address) {
            fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
        }
        var allZeroFields = fields.reduce(function (acc, field, index) {
            if (!field || field === "0") {
                var lastLongest = acc[acc.length - 1];
                if (lastLongest && lastLongest.index + lastLongest.length === index) {
                    lastLongest.length++;
                } else {
                    acc.push({ index: index, length: 1 });
                }
            }
            return acc;
        }, []);
        var longestZeroFields = allZeroFields.sort(function (a, b) {
            return b.length - a.length;
        })[0];
        var newHost = void 0;
        if (longestZeroFields && longestZeroFields.length > 1) {
            var newFirst = fields.slice(0, longestZeroFields.index);
            var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
            newHost = newFirst.join(":") + "::" + newLast.join(":");
        } else {
            newHost = fields.join(":");
        }
        if (zone) {
            newHost += "%" + zone;
        }
        return newHost;
    } else {
        return host;
    }
}
var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
function parse(uriString) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var components = {};
    var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
    if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
    var matches = uriString.match(URI_PARSE);
    if (matches) {
        if (NO_MATCH_IS_UNDEFINED) {
            //store each component
            components.scheme = matches[1];
            components.userinfo = matches[3];
            components.host = matches[4];
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = matches[7];
            components.fragment = matches[8];
            //fix port number
            if (isNaN(components.port)) {
                components.port = matches[5];
            }
        } else {
            //IE FIX for improper RegExp matching
            //store each component
            components.scheme = matches[1] || undefined;
            components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
            components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
            components.port = parseInt(matches[5], 10);
            components.path = matches[6] || "";
            components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
            components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
            //fix port number
            if (isNaN(components.port)) {
                components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
            }
        }
        if (components.host) {
            //normalize IP hosts
            components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
        }
        //determine reference type
        if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
            components.reference = "same-document";
        } else if (components.scheme === undefined) {
            components.reference = "relative";
        } else if (components.fragment === undefined) {
            components.reference = "absolute";
        } else {
            components.reference = "uri";
        }
        //check for reference errors
        if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
            components.error = components.error || "URI is not a " + options.reference + " reference.";
        }
        //find scheme handler
        var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
        //check if scheme can't handle IRIs
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
            //if host component is a domain name
            if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
                //convert Unicode IDN -> ASCII IDN
                try {
                    components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
                } catch (e) {
                    components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
                }
            }
            //convert IRI -> URI
            _normalizeComponentEncoding(components, URI_PROTOCOL);
        } else {
            //normalize encodings
            _normalizeComponentEncoding(components, protocol);
        }
        //perform scheme specific parsing
        if (schemeHandler && schemeHandler.parse) {
            schemeHandler.parse(components, options);
        }
    } else {
        components.error = components.error || "URI can not be parsed.";
    }
    return components;
}

function _recomposeAuthority(components, options) {
    var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
    var uriTokens = [];
    if (components.userinfo !== undefined) {
        uriTokens.push(components.userinfo);
        uriTokens.push("@");
    }
    if (components.host !== undefined) {
        //normalize IP hosts, add brackets and escape zone separator for IPv6
        uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
            return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
        }));
    }
    if (typeof components.port === "number" || typeof components.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(components.port));
    }
    return uriTokens.length ? uriTokens.join("") : undefined;
}

var RDS1 = /^\.\.?\//;
var RDS2 = /^\/\.(\/|$)/;
var RDS3 = /^\/\.\.(\/|$)/;
var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
function removeDotSegments(input) {
    var output = [];
    while (input.length) {
        if (input.match(RDS1)) {
            input = input.replace(RDS1, "");
        } else if (input.match(RDS2)) {
            input = input.replace(RDS2, "/");
        } else if (input.match(RDS3)) {
            input = input.replace(RDS3, "/");
            output.pop();
        } else if (input === "." || input === "..") {
            input = "";
        } else {
            var im = input.match(RDS5);
            if (im) {
                var s = im[0];
                input = input.slice(s.length);
                output.push(s);
            } else {
                throw new Error("Unexpected dot segment condition");
            }
        }
    }
    return output.join("");
}

function serialize(components) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
    var uriTokens = [];
    //find scheme handler
    var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
    //perform scheme specific serialization
    if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
    if (components.host) {
        //if host component is an IPv6 address
        if (protocol.IPV6ADDRESS.test(components.host)) {}
        //TODO: normalize IPv6 address as per RFC 5952

        //if host component is a domain name
        else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
                //convert IDN via punycode
                try {
                    components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
                } catch (e) {
                    components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
                }
            }
    }
    //normalize encoding
    _normalizeComponentEncoding(components, protocol);
    if (options.reference !== "suffix" && components.scheme) {
        uriTokens.push(components.scheme);
        uriTokens.push(":");
    }
    var authority = _recomposeAuthority(components, options);
    if (authority !== undefined) {
        if (options.reference !== "suffix") {
            uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (components.path && components.path.charAt(0) !== "/") {
            uriTokens.push("/");
        }
    }
    if (components.path !== undefined) {
        var s = components.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
            s = removeDotSegments(s);
        }
        if (authority === undefined) {
            s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
        }
        uriTokens.push(s);
    }
    if (components.query !== undefined) {
        uriTokens.push("?");
        uriTokens.push(components.query);
    }
    if (components.fragment !== undefined) {
        uriTokens.push("#");
        uriTokens.push(components.fragment);
    }
    return uriTokens.join(""); //merge tokens into a string
}

function resolveComponents(base, relative) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    var skipNormalization = arguments[3];

    var target = {};
    if (!skipNormalization) {
        base = parse(serialize(base, options), options); //normalize base components
        relative = parse(serialize(relative, options), options); //normalize relative components
    }
    options = options || {};
    if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        //target.authority = relative.authority;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
    } else {
        if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
            //target.authority = relative.authority;
            target.userinfo = relative.userinfo;
            target.host = relative.host;
            target.port = relative.port;
            target.path = removeDotSegments(relative.path || "");
            target.query = relative.query;
        } else {
            if (!relative.path) {
                target.path = base.path;
                if (relative.query !== undefined) {
                    target.query = relative.query;
                } else {
                    target.query = base.query;
                }
            } else {
                if (relative.path.charAt(0) === "/") {
                    target.path = removeDotSegments(relative.path);
                } else {
                    if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
                        target.path = "/" + relative.path;
                    } else if (!base.path) {
                        target.path = relative.path;
                    } else {
                        target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
                    }
                    target.path = removeDotSegments(target.path);
                }
                target.query = relative.query;
            }
            //target.authority = base.authority;
            target.userinfo = base.userinfo;
            target.host = base.host;
            target.port = base.port;
        }
        target.scheme = base.scheme;
    }
    target.fragment = relative.fragment;
    return target;
}

function resolve(baseURI, relativeURI, options) {
    var schemelessOptions = assign({ scheme: 'null' }, options);
    return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
}

function normalize(uri, options) {
    if (typeof uri === "string") {
        uri = serialize(parse(uri, options), options);
    } else if (typeOf(uri) === "object") {
        uri = parse(serialize(uri, options), options);
    }
    return uri;
}

function equal(uriA, uriB, options) {
    if (typeof uriA === "string") {
        uriA = serialize(parse(uriA, options), options);
    } else if (typeOf(uriA) === "object") {
        uriA = serialize(uriA, options);
    }
    if (typeof uriB === "string") {
        uriB = serialize(parse(uriB, options), options);
    } else if (typeOf(uriB) === "object") {
        uriB = serialize(uriB, options);
    }
    return uriA === uriB;
}

function escapeComponent(str, options) {
    return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
}

function unescapeComponent(str, options) {
    return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
}

var handler = {
    scheme: "http",
    domainHost: true,
    parse: function parse(components, options) {
        //report missing host
        if (!components.host) {
            components.error = components.error || "HTTP URIs must have a host.";
        }
        return components;
    },
    serialize: function serialize(components, options) {
        var secure = String(components.scheme).toLowerCase() === "https";
        //normalize the default port
        if (components.port === (secure ? 443 : 80) || components.port === "") {
            components.port = undefined;
        }
        //normalize the empty path
        if (!components.path) {
            components.path = "/";
        }
        //NOTE: We do not parse query strings for HTTP URIs
        //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
        //and not the HTTP spec.
        return components;
    }
};

var handler$1 = {
    scheme: "https",
    domainHost: handler.domainHost,
    parse: handler.parse,
    serialize: handler.serialize
};

function isSecure(wsComponents) {
    return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
}
//RFC 6455
var handler$2 = {
    scheme: "ws",
    domainHost: true,
    parse: function parse(components, options) {
        var wsComponents = components;
        //indicate if the secure flag is set
        wsComponents.secure = isSecure(wsComponents);
        //construct resouce name
        wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');
        wsComponents.path = undefined;
        wsComponents.query = undefined;
        return wsComponents;
    },
    serialize: function serialize(wsComponents, options) {
        //normalize the default port
        if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
            wsComponents.port = undefined;
        }
        //ensure scheme matches secure flag
        if (typeof wsComponents.secure === 'boolean') {
            wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws';
            wsComponents.secure = undefined;
        }
        //reconstruct path from resource name
        if (wsComponents.resourceName) {
            var _wsComponents$resourc = wsComponents.resourceName.split('?'),
                _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2),
                path = _wsComponents$resourc2[0],
                query = _wsComponents$resourc2[1];

            wsComponents.path = path && path !== '/' ? path : undefined;
            wsComponents.query = query;
            wsComponents.resourceName = undefined;
        }
        //forbid fragment component
        wsComponents.fragment = undefined;
        return wsComponents;
    }
};

var handler$3 = {
    scheme: "wss",
    domainHost: handler$2.domainHost,
    parse: handler$2.parse,
    serialize: handler$2.serialize
};

var O = {};
var isIRI = true;
//RFC 3986
var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]";  //(%d1-8 / %d11-12 / %d14-31 / %d127)
//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$);  //%d33 / %d35-91 / %d93-126 / obs-qtext
//const VCHAR$$ = "[\\x21-\\x7E]";
//const WSP$$ = "[\\x20\\x09]";
//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$));  //%d0 / CR / LF / obs-qtext
//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
var UNRESERVED = new RegExp(UNRESERVED$$, "g");
var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
var NOT_HFVALUE = NOT_HFNAME;
function decodeUnreserved(str) {
    var decStr = pctDecChars(str);
    return !decStr.match(UNRESERVED) ? str : decStr;
}
var handler$4 = {
    scheme: "mailto",
    parse: function parse$$1(components, options) {
        var mailtoComponents = components;
        var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
        mailtoComponents.path = undefined;
        if (mailtoComponents.query) {
            var unknownHeaders = false;
            var headers = {};
            var hfields = mailtoComponents.query.split("&");
            for (var x = 0, xl = hfields.length; x < xl; ++x) {
                var hfield = hfields[x].split("=");
                switch (hfield[0]) {
                    case "to":
                        var toAddrs = hfield[1].split(",");
                        for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                            to.push(toAddrs[_x]);
                        }
                        break;
                    case "subject":
                        mailtoComponents.subject = unescapeComponent(hfield[1], options);
                        break;
                    case "body":
                        mailtoComponents.body = unescapeComponent(hfield[1], options);
                        break;
                    default:
                        unknownHeaders = true;
                        headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
                        break;
                }
            }
            if (unknownHeaders) mailtoComponents.headers = headers;
        }
        mailtoComponents.query = undefined;
        for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
            var addr = to[_x2].split("@");
            addr[0] = unescapeComponent(addr[0]);
            if (!options.unicodeSupport) {
                //convert Unicode IDN -> ASCII IDN
                try {
                    addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
                } catch (e) {
                    mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
                }
            } else {
                addr[1] = unescapeComponent(addr[1], options).toLowerCase();
            }
            to[_x2] = addr.join("@");
        }
        return mailtoComponents;
    },
    serialize: function serialize$$1(mailtoComponents, options) {
        var components = mailtoComponents;
        var to = toArray(mailtoComponents.to);
        if (to) {
            for (var x = 0, xl = to.length; x < xl; ++x) {
                var toAddr = String(to[x]);
                var atIdx = toAddr.lastIndexOf("@");
                var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
                var domain = toAddr.slice(atIdx + 1);
                //convert IDN via punycode
                try {
                    domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
                } catch (e) {
                    components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
                }
                to[x] = localPart + "@" + domain;
            }
            components.path = to.join(",");
        }
        var headers = mailtoComponents.headers = mailtoComponents.headers || {};
        if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
        if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
        var fields = [];
        for (var name in headers) {
            if (headers[name] !== O[name]) {
                fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
            }
        }
        if (fields.length) {
            components.query = fields.join("&");
        }
        return components;
    }
};

var URN_PARSE = /^([^\:]+)\:(.*)/;
//RFC 2141
var handler$5 = {
    scheme: "urn",
    parse: function parse$$1(components, options) {
        var matches = components.path && components.path.match(URN_PARSE);
        var urnComponents = components;
        if (matches) {
            var scheme = options.scheme || urnComponents.scheme || "urn";
            var nid = matches[1].toLowerCase();
            var nss = matches[2];
            var urnScheme = scheme + ":" + (options.nid || nid);
            var schemeHandler = SCHEMES[urnScheme];
            urnComponents.nid = nid;
            urnComponents.nss = nss;
            urnComponents.path = undefined;
            if (schemeHandler) {
                urnComponents = schemeHandler.parse(urnComponents, options);
            }
        } else {
            urnComponents.error = urnComponents.error || "URN can not be parsed.";
        }
        return urnComponents;
    },
    serialize: function serialize$$1(urnComponents, options) {
        var scheme = options.scheme || urnComponents.scheme || "urn";
        var nid = urnComponents.nid;
        var urnScheme = scheme + ":" + (options.nid || nid);
        var schemeHandler = SCHEMES[urnScheme];
        if (schemeHandler) {
            urnComponents = schemeHandler.serialize(urnComponents, options);
        }
        var uriComponents = urnComponents;
        var nss = urnComponents.nss;
        uriComponents.path = (nid || options.nid) + ":" + nss;
        return uriComponents;
    }
};

var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
//RFC 4122
var handler$6 = {
    scheme: "urn:uuid",
    parse: function parse(urnComponents, options) {
        var uuidComponents = urnComponents;
        uuidComponents.uuid = uuidComponents.nss;
        uuidComponents.nss = undefined;
        if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
            uuidComponents.error = uuidComponents.error || "UUID is not valid.";
        }
        return uuidComponents;
    },
    serialize: function serialize(uuidComponents, options) {
        var urnComponents = uuidComponents;
        //normalize UUID
        urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
        return urnComponents;
    }
};

SCHEMES[handler.scheme] = handler;
SCHEMES[handler$1.scheme] = handler$1;
SCHEMES[handler$2.scheme] = handler$2;
SCHEMES[handler$3.scheme] = handler$3;
SCHEMES[handler$4.scheme] = handler$4;
SCHEMES[handler$5.scheme] = handler$5;
SCHEMES[handler$6.scheme] = handler$6;

exports.SCHEMES = SCHEMES;
exports.pctEncChar = pctEncChar;
exports.pctDecChars = pctDecChars;
exports.parse = parse;
exports.removeDotSegments = removeDotSegments;
exports.serialize = serialize;
exports.resolveComponents = resolveComponents;
exports.resolve = resolve;
exports.normalize = normalize;
exports.equal = equal;
exports.escapeComponent = escapeComponent;
exports.unescapeComponent = unescapeComponent;

Object.defineProperty(exports, '__esModule', { value: true });

})));


},{}],"ajv":[function(require,module,exports){
'use strict';

var compileSchema = require('./compile')
  , resolve = require('./compile/resolve')
  , Cache = require('./cache')
  , SchemaObject = require('./compile/schema_obj')
  , stableStringify = require('fast-json-stable-stringify')
  , formats = require('./compile/formats')
  , rules = require('./compile/rules')
  , $dataMetaSchema = require('./data')
  , util = require('./compile/util');

module.exports = Ajv;

Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;

Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;

Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;

var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;

var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';

var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];

/**
 * Creates validator instance.
 * Usage: `Ajv(opts)`
 * @param {Object} opts optional options
 * @return {Object} ajv instance
 */
function Ajv(opts) {
  if (!(this instanceof Ajv)) return new Ajv(opts);
  opts = this._opts = util.copy(opts) || {};
  setLogger(this);
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);

  this._cache = opts.cache || new Cache;
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules();
  this._getId = chooseGetId(opts);

  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  if (opts.serialize === undefined) opts.serialize = stableStringify;
  this._metaOpts = getMetaSchemaOptions(this);

  if (opts.formats) addInitialFormats(this);
  if (opts.keywords) addInitialKeywords(this);
  addDefaultMetaSchema(this);
  if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
  addInitialSchemas(this);
}



/**
 * Validate data using schema
 * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
 * @this   Ajv
 * @param  {String|Object} schemaKeyRef key, ref or schema object
 * @param  {Any} data to be validated
 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
 */
function validate(schemaKeyRef, data) {
  var v;
  if (typeof schemaKeyRef == 'string') {
    v = this.getSchema(schemaKeyRef);
    if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  } else {
    var schemaObj = this._addSchema(schemaKeyRef);
    v = schemaObj.validate || this._compile(schemaObj);
  }

  var valid = v(data);
  if (v.$async !== true) this.errors = v.errors;
  return valid;
}


/**
 * Create validating function for passed schema.
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
 * @return {Function} validating function
 */
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}


/**
 * Adds schema to the instance.
 * @this   Ajv
 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
 * @return {Ajv} this for method chaining
 */
function addSchema(schema, key, _skipValidation, _meta) {
  if (Array.isArray(schema)){
    for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
    return this;
  }
  var id = this._getId(schema);
  if (id !== undefined && typeof id != 'string')
    throw new Error('schema id must be string');
  key = resolve.normalizeId(key || id);
  checkUnique(this, key);
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  return this;
}


/**
 * Add schema that will be used to validate other schemas
 * options in META_IGNORE_OPTIONS are alway set to false
 * @this   Ajv
 * @param {Object} schema schema object
 * @param {String} key optional schema key
 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
 * @return {Ajv} this for method chaining
 */
function addMetaSchema(schema, key, skipValidation) {
  this.addSchema(schema, key, skipValidation, true);
  return this;
}


/**
 * Validate schema
 * @this   Ajv
 * @param {Object} schema schema to validate
 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
 * @return {Boolean} true if schema is valid
 */
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}


function defaultMeta(self) {
  var meta = self._opts.meta;
  self._opts.defaultMeta = typeof meta == 'object'
                            ? self._getId(meta) || meta
                            : self.getSchema(META_SCHEMA_ID)
                              ? META_SCHEMA_ID
                              : undefined;
  return self._opts.defaultMeta;
}


/**
 * Get compiled schema from the instance by `key` or `ref`.
 * @this   Ajv
 * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
 * @return {Function} schema validating function (with property `schema`).
 */
function getSchema(keyRef) {
  var schemaObj = _getSchemaObj(this, keyRef);
  switch (typeof schemaObj) {
    case 'object': return schemaObj.validate || this._compile(schemaObj);
    case 'string': return this.getSchema(schemaObj);
    case 'undefined': return _getSchemaFragment(this, keyRef);
  }
}


function _getSchemaFragment(self, ref) {
  var res = resolve.schema.call(self, { schema: {} }, ref);
  if (res) {
    var schema = res.schema
      , root = res.root
      , baseId = res.baseId;
    var v = compileSchema.call(self, schema, root, undefined, baseId);
    self._fragments[ref] = new SchemaObject({
      ref: ref,
      fragment: true,
      schema: schema,
      root: root,
      baseId: baseId,
      validate: v
    });
    return v;
  }
}


function _getSchemaObj(self, keyRef) {
  keyRef = resolve.normalizeId(keyRef);
  return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}


/**
 * Remove cached schema(s).
 * If no parameter is passed all schemas but meta-schemas are removed.
 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
 * @this   Ajv
 * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
 * @return {Ajv} this for method chaining
 */
function removeSchema(schemaKeyRef) {
  if (schemaKeyRef instanceof RegExp) {
    _removeAllSchemas(this, this._schemas, schemaKeyRef);
    _removeAllSchemas(this, this._refs, schemaKeyRef);
    return this;
  }
  switch (typeof schemaKeyRef) {
    case 'undefined':
      _removeAllSchemas(this, this._schemas);
      _removeAllSchemas(this, this._refs);
      this._cache.clear();
      return this;
    case 'string':
      var schemaObj = _getSchemaObj(this, schemaKeyRef);
      if (schemaObj) this._cache.del(schemaObj.cacheKey);
      delete this._schemas[schemaKeyRef];
      delete this._refs[schemaKeyRef];
      return this;
    case 'object':
      var serialize = this._opts.serialize;
      var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
      this._cache.del(cacheKey);
      var id = this._getId(schemaKeyRef);
      if (id) {
        id = resolve.normalizeId(id);
        delete this._schemas[id];
        delete this._refs[id];
      }
  }
  return this;
}


function _removeAllSchemas(self, schemas, regex) {
  for (var keyRef in schemas) {
    var schemaObj = schemas[keyRef];
    if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
      self._cache.del(schemaObj.cacheKey);
      delete schemas[keyRef];
    }
  }
}


/* @this   Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  if (typeof schema != 'object' && typeof schema != 'boolean')
    throw new Error('schema should be object or boolean');
  var serialize = this._opts.serialize;
  var cacheKey = serialize ? serialize(schema) : schema;
  var cached = this._cache.get(cacheKey);
  if (cached) return cached;

  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;

  var id = resolve.normalizeId(this._getId(schema));
  if (id && shouldAddSchema) checkUnique(this, id);

  var willValidate = this._opts.validateSchema !== false && !skipValidation;
  var recursiveMeta;
  if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
    this.validateSchema(schema, true);

  var localRefs = resolve.ids.call(this, schema);

  var schemaObj = new SchemaObject({
    id: id,
    schema: schema,
    localRefs: localRefs,
    cacheKey: cacheKey,
    meta: meta
  });

  if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  this._cache.put(cacheKey, schemaObj);

  if (willValidate && recursiveMeta) this.validateSchema(schema, true);

  return schemaObj;
}


/* @this   Ajv */
function _compile(schemaObj, root) {
  if (schemaObj.compiling) {
    schemaObj.validate = callValidate;
    callValidate.schema = schemaObj.schema;
    callValidate.errors = null;
    callValidate.root = root ? root : callValidate;
    if (schemaObj.schema.$async === true)
      callValidate.$async = true;
    return callValidate;
  }
  schemaObj.compiling = true;

  var currentOpts;
  if (schemaObj.meta) {
    currentOpts = this._opts;
    this._opts = this._metaOpts;
  }

  var v;
  try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  catch(e) {
    delete schemaObj.validate;
    throw e;
  }
  finally {
    schemaObj.compiling = false;
    if (schemaObj.meta) this._opts = currentOpts;
  }

  schemaObj.validate = v;
  schemaObj.refs = v.refs;
  schemaObj.refVal = v.refVal;
  schemaObj.root = v.root;
  return v;


  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var _validate = schemaObj.validate;
    var result = _validate.apply(this, arguments);
    callValidate.errors = _validate.errors;
    return result;
  }
}


function chooseGetId(opts) {
  switch (opts.schemaId) {
    case 'auto': return _get$IdOrId;
    case 'id': return _getId;
    default: return _get$Id;
  }
}

/* @this   Ajv */
function _getId(schema) {
  if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
  return schema.id;
}

/* @this   Ajv */
function _get$Id(schema) {
  if (schema.id) this.logger.warn('schema id ignored', schema.id);
  return schema.$id;
}


function _get$IdOrId(schema) {
  if (schema.$id && schema.id && schema.$id != schema.id)
    throw new Error('schema $id is different from id');
  return schema.$id || schema.id;
}


/**
 * Convert array of error message objects to string
 * @this   Ajv
 * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
 * @param  {Object} options optional options with properties `separator` and `dataVar`.
 * @return {String} human readable string with all errors descriptions
 */
function errorsText(errors, options) {
  errors = errors || this.errors;
  if (!errors) return 'No errors';
  options = options || {};
  var separator = options.separator === undefined ? ', ' : options.separator;
  var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;

  var text = '';
  for (var i=0; i<errors.length; i++) {
    var e = errors[i];
    if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  }
  return text.slice(0, -separator.length);
}


/**
 * Add custom format
 * @this   Ajv
 * @param {String} name format name
 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
 * @return {Ajv} this for method chaining
 */
function addFormat(name, format) {
  if (typeof format == 'string') format = new RegExp(format);
  this._formats[name] = format;
  return this;
}


function addDefaultMetaSchema(self) {
  var $dataSchema;
  if (self._opts.$data) {
    $dataSchema = require('./refs/data.json');
    self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  }
  if (self._opts.meta === false) return;
  var metaSchema = require('./refs/json-schema-draft-07.json');
  if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}


function addInitialSchemas(self) {
  var optsSchemas = self._opts.schemas;
  if (!optsSchemas) return;
  if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}


function addInitialFormats(self) {
  for (var name in self._opts.formats) {
    var format = self._opts.formats[name];
    self.addFormat(name, format);
  }
}


function addInitialKeywords(self) {
  for (var name in self._opts.keywords) {
    var keyword = self._opts.keywords[name];
    self.addKeyword(name, keyword);
  }
}


function checkUnique(self, id) {
  if (self._schemas[id] || self._refs[id])
    throw new Error('schema with key or id "' + id + '" already exists');
}


function getMetaSchemaOptions(self) {
  var metaOpts = util.copy(self._opts);
  for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
    delete metaOpts[META_IGNORE_OPTIONS[i]];
  return metaOpts;
}


function setLogger(self) {
  var logger = self._opts.logger;
  if (logger === false) {
    self.logger = {log: noop, warn: noop, error: noop};
  } else {
    if (logger === undefined) logger = console;
    if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
      throw new Error('logger must implement log, warn and error methods');
    self.logger = logger;
  }
}


function noop() {}

},{"./cache":1,"./compile":5,"./compile/async":2,"./compile/error_classes":3,"./compile/formats":4,"./compile/resolve":6,"./compile/rules":7,"./compile/schema_obj":8,"./compile/util":10,"./data":11,"./keyword":39,"./refs/data.json":40,"./refs/json-schema-draft-07.json":41,"fast-json-stable-stringify":43}]},{},[])("ajv")
});
/* ajv 6.14.0: Another JSON Schema Validator */
(e=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self,e())})(function(){return function a(s,o,i){function n(r,e){if(!o[r]){if(!s[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(l)return l(r,!0);throw(e=new Error("Cannot find module '"+r+"'")).code="MODULE_NOT_FOUND",e}t=o[r]={exports:{}},s[r][0].call(t.exports,function(e){return n(s[r][1][e]||e)},t,t.exports,a,s,o,i)}return o[r].exports}for(var l="function"==typeof require&&require,e=0;e<i.length;e++)n(i[e]);return n}({1:[function(e,r,t){r=r.exports=function(){this._cache={}};r.prototype.put=function(e,r){this._cache[e]=r},r.prototype.get=function(e){return this._cache[e]},r.prototype.del=function(e){delete this._cache[e]},r.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){var a=e("./error_classes").MissingRef;function s(r,i,t){var n=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof i&&(t=i,i=void 0);var e=l(r).then(function(){var e=n._addSchema(r,void 0,i);return e.validate||function s(o){try{return n._compile(o)}catch(e){if(e instanceof a)return r(e);throw e}function r(e){var r=e.missingSchema;if(a(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");e=n._loadingSchemas[r];return e||(e=n._loadingSchemas[r]=n._opts.loadSchema(r)).then(t,t),e.then(function(e){if(!a(r))return l(e).then(function(){a(r)||n.addSchema(e,r,void 0,i)})}).then(function(){return s(o)});function t(){delete n._loadingSchemas[r]}function a(e){return n._refs[e]||n._schemas[e]}}}(e)});return t&&e.then(function(e){t(null,e)},t),e;function l(e){e=e.$schema;return e&&!n.getSchema(e)?s.call(n,{$ref:e},!0):Promise.resolve()}}r.exports=s},{"./error_classes":3}],3:[function(e,r,t){var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){var a=e("./util"),s=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,o=[0,31,28,31,30,31,30,31,31,30,31,30,31],i=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,e=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,n=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(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/?]|%[0-9a-f]{2})*)?$/i,l=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,c=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,u=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,h=/^(?:\/(?:[^~/]|~0|~1)*)*$/,d=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,p=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function f(e){return a.copy(f[e="full"==e?"full":"fast"])}function m(e){var r,t,e=e.match(s);return!!e&&(t=+e[3],1<=(r=+e[2]))&&r<=12&&1<=t&&t<=(2!=r||(t=+e[1])%4!=0||t%100==0&&t%400!=0?o[r]:29)}function v(e,r){var t,a,s,e=e.match(i);return!!e&&(a=e[2],s=e[3],(t=e[1])<=23&&a<=59&&s<=59||23==t&&59==a&&60==s)&&(!r||e[5])}(r.exports=f).fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":l,url:c,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,hostname:e,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:E,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":d,"relative-json-pointer":p},f.full={date:m,time:v,"date-time":function(e){e=e.split(y);return 2==e.length&&m(e[0])&&v(e[1],!0)},uri:function(e){return g.test(e)&&n.test(e)},"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1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5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,regex:E,uuid:u,"json-pointer":h,"json-pointer-uri-fragment":d,"relative-json-pointer":p};var y=/t|\s/i;var g=/\/|:/;var P=/[^\\]\\Z/;function E(e){if(P.test(e))return!1;try{return new RegExp(e),!0}catch(e){return!1}}},{"./util":10}],5:[function(e,r,t){var $=e("./resolve"),j=e("./util"),D=e("./error_classes"),O=e("fast-json-stable-stringify"),I=e("../dotjs/validate"),A=j.ucs2length,k=e("fast-deep-equal"),C=D.Validation;function L(e,i,n,r){var l=this,c=this._opts,u=[void 0],h={},d=[],t={},p=[],a={},f=[];function m(e,r){return"var pattern"+e+" = "+(c.regExp?"regExp":"new RegExp")+"("+j.toQuotedString(r[e])+");"}i=i||{schema:e,refVal:u,refs:h};var s=function(e,r,t){var a=N.call(this,e,r,t);return 0<=a?{index:a,compiling:!0}:(this._compilations[a=this._compilations.length]={schema:e,root:r,baseId:t},{index:a,compiling:!1})}.call(this,e,i,r),o=this._compilations[s.index];if(s.compiling)return o.callValidate=E;var v=this._formats,y=this.RULES;try{var g=w(e,i,n,r),P=(o.validate=g,o.callValidate);return P&&(P.schema=g.schema,P.errors=null,P.refs=g.refs,P.refVal=g.refVal,P.root=g.root,P.$async=g.$async,c.sourceCode)&&(P.source=g.source),g}finally{!function(e,r,t){e=N.call(this,e,r,t);0<=e&&this._compilations.splice(e,1)}.call(this,e,i,r)}function E(){var e=o.validate,r=e.apply(this,arguments);return E.errors=e.errors,r}function w(e,r,t,a){var s=!r||r.schema==e;if(r.schema!=i.schema)return L.call(l,e,r,t,a);t=!0===e.$async,a=I({isTop:!0,schema:e,isRoot:s,baseId:a,root:r,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:D.MissingRef,RULES:y,validate:I,util:j,resolve:$,resolveRef:b,usePattern:F,useDefault:x,useCustomRule:R,opts:c,formats:v,logger:l.logger,self:l}),a=Q(u,q)+Q(d,m)+Q(p,z)+Q(f,T)+a;c.processCode&&(a=c.processCode(a,e));try{var o=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError","regExp",a)(l,y,v,i,u,p,f,k,A,C,c.regExp);u[0]=o}catch(e){throw l.logger.error("Error compiling schema, function code:",a),e}return o.schema=e,o.errors=null,o.refs=h,o.refVal=u,o.root=s?o:r,t&&(o.$async=!0),!0===c.sourceCode&&(o.source={code:a,patterns:d,defaults:p}),o}function b(e,r,t){r=$.url(e,r);var a=h[r];if(void 0!==a)return _(s=u[a],o="refVal["+a+"]");if(!t&&i.refs){a=i.refs[r];if(void 0!==a)return _(s=i.refVal[a],o=S(r,s))}var s,o=S(r),t=$.call(l,w,i,r);if(void 0!==(t=void 0===t&&(a=n&&n[r])?$.inlineRef(a,c.inlineRefs)?a:L.call(l,a,i,n,e):t))return s=t,u[h[r]]=s,_(t,o);delete h[r]}function S(e,r){var t=u.length;return u[t]=r,"refVal"+(h[e]=t)}function _(e,r){return"object"==typeof e||"boolean"==typeof e?{code:r,schema:e,inline:!0}:{code:r,$async:e&&!!e.$async}}function F(e){var r=t[e];return void 0===r&&(r=t[e]=d.length,d[r]=e),"pattern"+r}function x(e){switch(typeof e){case"boolean":case"number":return""+e;case"string":return j.toQuotedString(e);case"object":var r,t;return null===e?"null":(r=O(e),void 0===(t=a[r])&&(t=a[r]=p.length,p[t]=e),"default"+t)}}function R(e,r,t,a){if(!1!==l._opts.validateSchema){var s=e.definition.dependencies;if(s&&!s.every(function(e){return Object.prototype.hasOwnProperty.call(t,e)}))throw new Error("parent schema must have all required keywords: "+s.join(","));s=e.definition.validateSchema;if(s)if(!s(r)){s="keyword schema is invalid: "+l.errorsText(s.errors);if("log"!=l._opts.validateSchema)throw new Error(s);l.logger.error(s)}}var o,s=e.definition.compile,i=e.definition.inline,n=e.definition.macro;if(s)o=s.call(l,r,t,a);else if(n)o=n.call(l,r,t,a),!1!==c.validateSchema&&l.validateSchema(o,!0);else if(i)o=i.call(l,a,e.keyword,r,t);else if(!(o=e.definition.validate))return;if(void 0===o)throw new Error('custom keyword "'+e.keyword+'"failed to compile');s=f.length;return{code:"customRule"+s,validate:f[s]=o}}}function N(e,r,t){for(var a=0;a<this._compilations.length;a++){var s=this._compilations[a];if(s.schema==e&&s.root==r&&s.baseId==t)return a}return-1}function z(e){return"var default"+e+" = defaults["+e+"];"}function q(e,r){return void 0===r[e]?"":"var refVal"+e+" = refVal["+e+"];"}function T(e){return"var customRule"+e+" = customRules["+e+"];"}function Q(e,r){if(!e.length)return"";for(var t="",a=0;a<e.length;a++)t+=r(a,e);return t}r.exports=L},{"../dotjs/validate":38,"./error_classes":3,"./resolve":6,"./util":10,"fast-deep-equal":42,"fast-json-stable-stringify":43}],6:[function(e,r,t){var p=e("uri-js"),f=e("fast-deep-equal"),m=e("./util"),n=e("./schema_obj"),a=e("json-schema-traverse");function l(e,r,t){var a,s,o,i=this._refs[t];if("string"==typeof i){if(!this._refs[i])return l.call(this,e,r,i);i=this._refs[i]}return(i=i||this._schemas[t])instanceof n?d(i.schema,this._opts.inlineRefs)?i.schema:i.validate||this._compile(i):((i=c.call(this,r,t))&&(a=i.schema,r=i.root,o=i.baseId),a instanceof n?s=a.validate||e.call(this,a.schema,r,void 0,o):void 0!==a&&(s=d(a,this._opts.inlineRefs)?a:e.call(this,a,r,void 0,o)),s)}function c(e,r){var t=p.parse(r),a=y(t),s=v(this._getId(e.schema));if(0===Object.keys(e.schema).length||a!==s){var a=g(a),o=this._refs[a];if("string"==typeof o)return function(e,r,t){r=c.call(this,e,r);{var a,s;if(r)return a=r.baseId,e=r.root,(s=this._getId(r=r.schema))&&(a=P(a,s)),i.call(this,t,a,r,e)}}.call(this,e,o,t);if(o instanceof n)o.validate||this._compile(o);else{if(!((o=this._schemas[a])instanceof n))return;if(o.validate||this._compile(o),a==g(r))return{schema:o,root:e,baseId:s}}if(!(e=o).schema)return;s=v(this._getId(e.schema))}return i.call(this,t,s,e.schema,e)}(r.exports=l).normalizeId=g,l.fullPath=v,l.url=P,l.ids=function(e){var r=g(this._getId(e)),c={"":r},u={"":v(r,!1)},h={},d=this;return a(e,{allKeys:!0},function(e,r,t,a,s,o,i){if(""!==r){var n=d._getId(e),l=c[a],a=u[a]+"/"+s;if(void 0!==i&&(a+="/"+("number"==typeof i?i:m.escapeFragment(i))),"string"==typeof n){n=l=g(l?p.resolve(l,n):n),s=d._refs[n];if((s="string"==typeof s?d._refs[s]:s)&&s.schema){if(!f(e,s.schema))throw new Error('id "'+n+'" resolves to more than one schema')}else if(n!=g(a))if("#"==n[0]){if(h[n]&&!f(e,h[n]))throw new Error('id "'+n+'" resolves to more than one schema');h[n]=e}else d._refs[n]=a}c[r]=l,u[r]=a}}),h},l.inlineRef=d,l.schema=c;var u=m.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function i(e,r,t,a){if(e.fragment=e.fragment||"","/"==e.fragment.slice(0,1)){for(var s=e.fragment.split("/"),o=1;o<s.length;o++){var i=s[o];if(i){if(void 0===(t=t[i=m.unescapeFragment(i)]))break;u[i]||((i=this._getId(t))&&(r=P(r,i)),t.$ref&&(i=P(r,t.$ref),i=c.call(this,a,i))&&(t=i.schema,a=i.root,r=i.baseId))}}return void 0!==t&&t!==a.schema?{schema:t,root:a,baseId:r}:void 0}}var h=m.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function d(e,r){return!1!==r&&(void 0===r||!0===r?function e(r){var t;if(Array.isArray(r)){for(var a=0;a<r.length;a++)if("object"==typeof(t=r[a])&&!e(t))return!1}else for(var s in r){if("$ref"==s)return!1;if("object"==typeof(t=r[s])&&!e(t))return!1}return!0}(e):r?function e(r){var t,a=0;if(Array.isArray(r)){for(var s=0;s<r.length;s++)if("object"==typeof(t=r[s])&&(a+=e(t)),a==1/0)return 1/0}else for(var o in r){if("$ref"==o)return 1/0;if(h[o])a++;else if("object"==typeof(t=r[o])&&(a+=e(t)+1),a==1/0)return 1/0}return a}(e)<=r:void 0)}function v(e,r){return!1!==r&&(e=g(e)),y(p.parse(e))}function y(e){return p.serialize(e).split("#")[0]+"#"}var s=/#\/?$/;function g(e){return e?e.replace(s,""):""}function P(e,r){return r=g(r),p.resolve(e,r)}},{"./schema_obj":8,"./util":10,"fast-deep-equal":42,"json-schema-traverse":44,"uri-js":45}],7:[function(e,r,t){var o=e("../dotjs"),i=e("./util").toHash;r.exports=function(){var a=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],s=["type","$comment"];return a.all=i(s),a.types=i(["number","integer","string","array","object","boolean","null"]),a.forEach(function(e){e.rules=e.rules.map(function(e){var r,t;return"object"==typeof e&&(t=e[r=Object.keys(e)[0]],e=r,t.forEach(function(e){s.push(e),a.all[e]=!0})),s.push(e),a.all[e]={keyword:e,code:o[e],implements:t}}),a.all.$comment={keyword:"$comment",code:o.$comment},e.type&&(a.types[e.type]=e)}),a.keywords=i(s.concat(["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"])),a.custom={},a}},{"../dotjs":27,"./util":10}],8:[function(e,r,t){var a=e("./util");r.exports=function(e){a.copy(e,this)}},{"./util":10}],9:[function(e,r,t){r.exports=function(e){for(var r,t=0,a=e.length,s=0;s<a;)t++,55296<=(r=e.charCodeAt(s++))&&r<=56319&&s<a&&56320==(64512&e.charCodeAt(s))&&s++;return t}},{}],10:[function(e,r,t){function o(e,r,t,a){var s=a?" !== ":" === ",o=a?" || ":" && ",i=a?"!":"",n=a?"":"!";switch(e){case"null":return r+s+"null";case"array":return i+"Array.isArray("+r+")";case"object":return"("+i+r+o+"typeof "+r+s+'"object"'+o+n+"Array.isArray("+r+"))";case"integer":return"(typeof "+r+s+'"number"'+o+n+"("+r+" % 1)"+o+r+s+r+(t?o+i+"isFinite("+r+")":"")+")";case"number":return"(typeof "+r+s+'"'+e+'"'+(t?o+i+"isFinite("+r+")":"")+")";default:return"typeof "+r+s+'"'+e+'"'}}r.exports={copy:function(e,r){for(var t in r=r||{},e)r[t]=e[t];return r},checkDataType:o,checkDataTypes:function(e,r,t){{if(1===e.length)return o(e[0],r,t,!0);var a,s="",e=n(e);for(a in e.array&&e.object&&(s=e.null?"(":"(!"+r+" || ",s+="typeof "+r+' !== "object")',delete e.null,delete e.array,delete e.object),e.number&&delete e.integer,e)s+=(s?" && ":"")+o(a,r,t,!0);return s}},coerceToTypes:function(e,r){{if(!Array.isArray(r))return i[r]?[r]:"array"===e&&"array"===r?["array"]:void 0;for(var t=[],a=0;a<r.length;a++){var s=r[a];(i[s]||"array"===e&&"array"===s)&&(t[t.length]=s)}return t.length?t:void 0}},toHash:n,getProperty:u,escapeQuotes:l,equal:e("fast-deep-equal"),ucs2length:e("./ucs2length"),varOccurences:function(e,r){r+="[^0-9]";e=e.match(new RegExp(r,"g"));return e?e.length:0},varReplace:function(e,r,t){return r+="([^0-9])",t=t.replace(/\$/g,"$$$$"),e.replace(new RegExp(r,"g"),t+"$1")},schemaHasRules:function(e,r){if("boolean"==typeof e)return!e;for(var t in e)if(r[t])return!0},schemaHasRulesExcept:function(e,r,t){if("boolean"==typeof e)return!e&&"not"!=t;for(var a in e)if(a!=t&&r[a])return!0},schemaUnknownRules:function(e,r){if("boolean"!=typeof e)for(var t in e)if(!r[t])return t},toQuotedString:c,getPathExpr:function(e,r,t,a){return p(e,t?"'/' + "+r+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+r+" + ']'":"'[\\'' + "+r+" + '\\']'")},getPath:function(e,r,t){t=c(t?"/"+f(r):u(r));return p(e,t)},getData:function(e,r,t){var a,s,o;if(""===e)return"rootData";if("/"==e[0]){if(!h.test(e))throw new Error("Invalid JSON-pointer: "+e);a=e,s="rootData"}else{if(!(o=e.match(d)))throw new Error("Invalid JSON-pointer: "+e);if(e=+o[1],"#"==(a=o[2])){if(r<=e)throw new Error("Cannot access property/index "+e+" levels up, current level is "+r);return t[r-e]}if(r<e)throw new Error("Cannot access data "+e+" levels up, current level is "+r);if(s="data"+(r-e||""),!a)return s}for(var i=s,n=a.split("/"),l=0;l<n.length;l++){var c=n[l];c&&(s+=u(m(c)),i+=" && "+s)}return i},unescapeFragment:function(e){return m(decodeURIComponent(e))},unescapeJsonPointer:m,escapeFragment:function(e){return encodeURIComponent(f(e))},escapeJsonPointer:f};var i=n(["string","number","integer","boolean","null"]);function n(e){for(var r={},t=0;t<e.length;t++)r[e[t]]=!0;return r}var a=/^[a-z$_][a-z$_0-9]*$/i,s=/'|\\/g;function u(e){return"number"==typeof e?"["+e+"]":a.test(e)?"."+e:"['"+l(e)+"']"}function l(e){return e.replace(s,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function c(e){return"'"+l(e)+"'"}var h=/^\/(?:[^~]|~0|~1)*$/,d=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p(e,r){return'""'==e?r:(e+" + "+r).replace(/([^\\])' \+ '/g,"$1")}function f(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function m(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}},{"./ucs2length":9,"fast-deep-equal":42}],11:[function(e,r,t){var l=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];r.exports=function(e,r){for(var t=0;t<r.length;t++){e=JSON.parse(JSON.stringify(e));for(var a=r[t].split("/"),s=e,o=1;o<a.length;o++)s=s[a[o]];for(o=0;o<l.length;o++){var i=l[o],n=s[i];n&&(s[i]={anyOf:[n,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return e}},{}],12:[function(e,r,t){e=e("./refs/json-schema-draft-07.json");r.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:e.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:e.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}},{"./refs/json-schema-draft-07.json":41}],13:[function(e,r,t){r.exports=function(e,r,t){var a,s,o,i,n,l=" ",c=e.level,u=e.dataLevel,h=e.schema[r],d=e.schemaPath+e.util.getProperty(r),p=e.errSchemaPath+"/"+r,f=!e.opts.allErrors,m="data"+(u||""),v=e.opts.$data&&h&&h.$data,y=v?(l+=" var schema"+c+" = "+e.util.getData(h.$data,u,e.dataPathArr)+"; ","schema"+c):h,g="maximum"==r,P=g?"exclusiveMaximum":"exclusiveMinimum",E=e.schema[P],w=e.opts.$data&&E&&E.$data,b=g?"<":">",S=g?">":"<",_=void 0;if(!v&&"number"!=typeof h&&void 0!==h)throw new Error(r+" must be number");if(!w&&void 0!==E&&"number"!=typeof E&&"boolean"!=typeof E)throw new Error(P+" must be number or boolean");w?(u=e.util.getData(E.$data,u,e.dataPathArr),o="exclIsNumber"+c,i="' + "+(n="op"+c)+" + '",_=P,(F=F||[]).push(l=l+(" var schemaExcl"+c+" = "+u+"; ")+(" var "+(a="exclusive"+c)+"; var "+(s="exclType"+c)+" = typeof "+(u="schemaExcl"+c)+"; if ("+s+" != 'boolean' && "+s+" != 'undefined' && "+s+" != 'number') { ")),l="",!1!==e.createErrors?(l+=" { keyword: '"+(_||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: {} ",!1!==e.opts.messages&&(l+=" , message: '"+P+" should be boolean' "),e.opts.verbose&&(l+=" , schema: validate.schema"+d+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),l+=" } "):l+=" {} ",x=l,l=(l=F.pop())+(!e.compositeRule&&f?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } else if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" "+s+" == 'number' ? ( ("+a+" = "+y+" === undefined || "+u+" "+b+"= "+y+") ? "+m+" "+S+"= "+u+" : "+m+" "+S+" "+y+" ) : ( ("+a+" = "+u+" === true) ? "+m+" "+S+"= "+y+" : "+m+" "+S+" "+y+" ) || "+m+" !== "+m+") { var op"+c+" = "+a+" ? '"+b+"' : '"+b+"='; ",void 0===h&&(p=e.errSchemaPath+"/"+(_=P),y=u,v=w)):(i=b,(o="number"==typeof E)&&v?(n="'"+i+"'",l+=" if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" ( "+y+" === undefined || "+E+" "+b+"= "+y+" ? "+m+" "+S+"= "+E+" : "+m+" "+S+" "+y+" ) || "+m+" !== "+m+") { "):(o&&void 0===h?(a=!0,p=e.errSchemaPath+"/"+(_=P),y=E,S+="="):(o&&(y=Math[g?"min":"max"](E,h)),E===(!o||y)?(a=!0,p=e.errSchemaPath+"/"+(_=P),S+="="):(a=!1,i+="=")),n="'"+i+"'",l+=" if ( ",v&&(l+=" ("+y+" !== undefined && typeof "+y+" != 'number') || "),l+=" "+m+" "+S+" "+y+" || "+m+" !== "+m+") { ")),_=_||r;(F=F||[]).push(l),l="",!1!==e.createErrors?(l+=" { keyword: '"+(_||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(p)+" , params: { comparison: "+n+", limit: "+y+", exclusive: "+a+" } ",!1!==e.opts.messages&&(l=l+" , message: 'should be "+i+" "+(v?"' + "+y:y+"'")),e.opts.verbose&&(l=(l+=" , schema:  ")+(v?"validate.schema"+d:""+h)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),l+=" } "):l+=" {} ";var F,x=l;return l=(l=F.pop())+(!e.compositeRule&&f?e.async?" throw new ValidationError(["+x+"]); ":" validate.errors = ["+x+"]; return false; ":" var err = "+x+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",f&&(l+=" else { "),l}},{}],14:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s+=" "+h+".length "+("maxItems"==(a=r)?">":"<")+" "+i+") { "),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT have ")+("maxItems"==r?"more":"fewer")+" than ")+(d?"' + "+i+" + '":""+n)+" items' "),e.opts.verbose&&(s=(s+=" , schema:  ")+(d?"validate.schema"+l:""+n)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],15:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s=s+(!1===e.opts.unicode?" "+h+".length ":" ucs2length("+h+") ")+(" "+("maxLength"==(a=r)?">":"<")+" "+i+") { ")),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT be ")+("maxLength"==r?"longer":"shorter")+" than ")+(d?"' + "+i+" + '":""+n)+" characters' "),e.opts.verbose&&(s=(s+=" , schema:  ")+(d?"validate.schema"+l:""+n)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],16:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;if(d||"number"==typeof n)return s+="if ( ",d&&(s+=" ("+i+" !== undefined && typeof "+i+" != 'number') || "),(o=[]).push(s+=" Object.keys("+h+").length "+("maxProperties"==(a=r)?">":"<")+" "+i+") { "),s="",!1!==e.createErrors?(s+=" { keyword: '"+(a||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { limit: "+i+" } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should NOT have ")+("maxProperties"==r?"more":"fewer")+" than ")+(d?"' + "+i+" + '":""+n)+" properties' "),e.opts.verbose&&(s=(s+=" , schema:  ")+(d?"validate.schema"+l:""+n)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",a=s,s=(s=o.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+a+"]); ":" validate.errors = ["+a+"]; return false; ":" var err = "+a+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",u&&(s+=" else { "),s;throw new Error(r+" must be number")}},{}],17:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,n=!e.opts.allErrors,l=e.util.copy(e),c="",u=(l.level++,"valid"+l.level),h=l.baseId,d=!0,p=s;if(p)for(var f,m=-1,v=p.length-1;m<v;)f=p[m+=1],(e.opts.strictKeywords?"object"==typeof f&&0<Object.keys(f).length||!1===f:e.util.schemaHasRules(f,e.RULES.all))&&(d=!1,l.schema=f,l.schemaPath=o+"["+m+"]",l.errSchemaPath=i+"/"+m,a+="  "+e.validate(l)+" ",l.baseId=h,n)&&(a+=" if ("+u+") { ",c+="}");return n&&(a+=d?" if (true) { ":" "+c.slice(0,-1)+" "),a}},{}],18:[function(e,r,t){r.exports=function(r,e,t){var a=" ",s=r.level,o=r.dataLevel,i=r.schema[e],n=r.schemaPath+r.util.getProperty(e),l=r.errSchemaPath+"/"+e,e=!r.opts.allErrors,o="data"+(o||""),c="valid"+s,s="errs__"+s,u=r.util.copy(r),h="",d=(u.level++,"valid"+u.level);if(i.every(function(e){return r.opts.strictKeywords?"object"==typeof e&&0<Object.keys(e).length||!1===e:r.util.schemaHasRules(e,r.RULES.all)})){var p=u.baseId,f=(a+=" var "+s+" = errors; var "+c+" = false;  ",r.compositeRule),m=(r.compositeRule=u.compositeRule=!0,i);if(m)for(var v,y=-1,g=m.length-1;y<g;)v=m[y+=1],u.schema=v,u.schemaPath=n+"["+y+"]",u.errSchemaPath=l+"/"+y,a+="  "+r.validate(u)+" ",u.baseId=p,a+=" "+c+" = "+c+" || "+d+"; if (!"+c+") { ",h+="}";r.compositeRule=u.compositeRule=f,a+=" "+h+" if (!"+c+") {   var err =   ",!1!==r.createErrors?(a+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+r.errorPath+" , schemaPath: "+r.util.toQuotedString(l)+" , params: {} ",!1!==r.opts.messages&&(a+=" , message: 'should match some schema in anyOf' "),r.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+r.schemaPath+" , data: "+o+" "),a+=" } "):a+=" {} ",a+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!r.compositeRule&&e&&(a+=r.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),a+=" } else {  errors = "+s+"; if (vErrors !== null) { if ("+s+") vErrors.length = "+s+"; else vErrors = null; } ",r.opts.allErrors&&(a+=" } ")}else e&&(a+=" if (true) { ");return a}},{}],19:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.errSchemaPath+"/"+r,r=e.util.toQuotedString(e.schema[r]);return!0===e.opts.$comment?a+=" console.log("+r+");":"function"==typeof e.opts.$comment&&(a+=" self._opts.$comment("+r+", "+e.util.toQuotedString(s)+", validate.root.schema);"),a}},{}],20:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(o||""),u="valid"+s,h=e.opts.$data&&i&&i.$data,i=(h&&(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),h||(a+=" var schema"+s+" = validate.schema"+n+";"),[]),o=(i.push(a+="var "+u+" = equal("+c+", schema"+s+"); if (!"+u+") {   "),a="",!1!==e.createErrors?(a+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { allowedValue: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to constant' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a);return a=(a=i.pop())+(!e.compositeRule&&l?e.async?" throw new ValidationError(["+o+"]); ":" validate.errors = ["+o+"]; return false; ":" var err = "+o+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" }",l&&(a+=" else { "),a}},{}],21:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,o="data"+(o||""),c="valid"+s,u="errs__"+s,h=e.util.copy(e),d=(h.level++,"valid"+h.level),s="i"+s,p=h.dataLevel=e.dataLevel+1,f="data"+p,m=e.baseId,v=e.opts.strictKeywords?"object"==typeof i&&0<Object.keys(i).length||!1===i:e.util.schemaHasRules(i,e.RULES.all),s=(a+="var "+u+" = errors;var "+c+";",v?(c=e.compositeRule,e.compositeRule=h.compositeRule=!0,h.schema=i,h.schemaPath=n,h.errSchemaPath=r,a+=" var "+d+" = false; for (var "+s+" = 0; "+s+" < "+o+".length; "+s+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,s,e.opts.jsonPointers,!0),i=o+"["+s+"]",h.dataPathArr[p]=s,p=e.validate(h),h.baseId=m,e.util.varOccurences(p,f)<2?a+=" "+e.util.varReplace(p,f,i)+" ":a+=" var "+f+" = "+i+"; "+p+" ",a+=" if ("+d+") break; }  ",e.compositeRule=h.compositeRule=c,a+="  if (!"+d+") {"):a+=" if ("+o+".length == 0) {",[]),m=(s.push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: {} ",!1!==e.opts.messages&&(a+=" , message: 'should contain a valid item' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+o+" "),a+=" } "):a+=" {} ",a);return a=(a=s.pop())+(!e.compositeRule&&l?e.async?" throw new ValidationError(["+m+"]); ":" validate.errors = ["+m+"]; return false; ":" var err = "+m+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } else { ",v&&(a+="  errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; } "),e.opts.allErrors&&(a+=" } "),a}},{}],22:[function(e,r,t){r.exports=function(e,r,t){var a,s,o,i=" ",n=e.level,l=e.dataLevel,c=e.schema[r],u=e.schemaPath+e.util.getProperty(r),h=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,p="data"+(l||""),f="valid"+n,m="errs__"+n,v=e.opts.$data&&c&&c.$data,y=v?(i+=" var schema"+n+" = "+e.util.getData(c.$data,l,e.dataPathArr)+"; ","schema"+n):c,g=this,P="definition"+n,E=g.definition,w="";if(v&&E.$data){var b="keywordValidate"+n,S=E.validateSchema;i+=" var "+P+" = RULES.custom['"+r+"'].definition; var "+b+" = "+P+".validate;"}else{if(!(R=e.useCustomRule(g,c,e.schema,e)))return;y="validate.schema"+u,b=R.code,a=E.compile,s=E.inline,o=E.macro}var _,F,x,R,$,r=b+".errors",c="i"+n,j="ruleErr"+n,D=E.async;if(D&&!e.async)throw new Error("async keyword in sync schema");return s||o||(i+=r+" = null;"),i+="var "+m+" = errors;var "+f+";",v&&E.$data&&(w+="}",i+=" if ("+y+" === undefined) { "+f+" = true; } else { ",S)&&(w+="}",i+=" "+f+" = "+P+".validateSchema("+y+"); if ("+f+") { "),s?i+=E.statements?" "+R.validate+" ":" "+f+" = "+R.validate+"; ":o?(w="",(v=e.util.copy(e)).level++,_="valid"+v.level,v.schema=R.validate,v.schemaPath="",S=e.compositeRule,e.compositeRule=v.compositeRule=!0,P=e.validate(v).replace(/validate\.schema/g,b),e.compositeRule=v.compositeRule=S,i+=" "+P):(($=$||[]).push(i),i=(i=(i="")+"  "+b+".call( "+(e.opts.passContext?"this":"self"))+(a||!1===E.schema?" , "+p+" ":" , "+y+" , "+p+" , validate.schema"+e.schemaPath+" ")+" , (dataPath || '')",'""'!=e.errorPath&&(i+=" + "+e.errorPath),R=i+=" , "+(F=l?"data"+(l-1||""):"parentData")+" , "+(x=l?e.dataPathArr[l]:"parentDataProperty")+" , rootData )  ",i=$.pop(),!1===E.errors?(i+=" "+f+" = ",D&&(i+="await "),i+=R+"; "):i+=D?" var "+(r="customErrors"+n)+" = null; try { "+f+" = await "+R+"; } catch (e) { "+f+" = false; if (e instanceof ValidationError) "+r+" = e.errors; else throw e; } ":" "+r+" = null; "+f+" = "+R+"; "),E.modifying&&(i+=" if ("+F+") "+p+" = "+F+"["+x+"];"),i+=""+w,E.valid?d&&(i+=" if (true) { "):(i+=" if ( ",void 0===E.valid?i=i+" !"+(o?""+_:f):i+=" "+!E.valid+" ",v=g.keyword,($=$||[]).push(i+=") { "),($=$||[]).push(i=""),i="",!1!==e.createErrors?(i+=" { keyword: '"+(v||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { keyword: '"+g.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+g.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+u+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ",S=i,i=$.pop(),P=i+=!e.compositeRule&&d?e.async?" throw new ValidationError(["+S+"]); ":" validate.errors = ["+S+"]; return false; ":" var err = "+S+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",i=$.pop(),s?E.errors?"full"!=E.errors&&(i+="  for (var "+c+"="+m+"; "+c+"<errors; "+c+"++) { var "+j+" = vErrors["+c+"]; if ("+j+".dataPath === undefined) "+j+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+j+".schemaPath === undefined) { "+j+'.schemaPath = "'+h+'"; } ',e.opts.verbose&&(i+=" "+j+".schema = "+y+"; "+j+".data = "+p+"; "),i+=" } "):!1===E.errors?i+=" "+P+" ":(i+=" if ("+m+" == errors) { "+P+" } else {  for (var "+c+"="+m+"; "+c+"<errors; "+c+"++) { var "+j+" = vErrors["+c+"]; if ("+j+".dataPath === undefined) "+j+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+j+".schemaPath === undefined) { "+j+'.schemaPath = "'+h+'"; } ',e.opts.verbose&&(i+=" "+j+".schema = "+y+"; "+j+".data = "+p+"; "),i+=" } } "):o?(i+="   var err =   ",!1!==e.createErrors?(i+=" { keyword: '"+(v||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(h)+" , params: { keyword: '"+g.keyword+"' } ",!1!==e.opts.messages&&(i+=" , message: 'should pass \""+g.keyword+"\" keyword validation' "),e.opts.verbose&&(i+=" , schema: validate.schema"+u+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+p+" "),i+=" } "):i+=" {} ",i+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(i+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; ")):!1===E.errors?i+=" "+P+" ":(i+=" if (Array.isArray("+r+")) { if (vErrors === null) vErrors = "+r+"; else vErrors = vErrors.concat("+r+"); errors = vErrors.length;  for (var "+c+"="+m+"; "+c+"<errors; "+c+"++) { var "+j+" = vErrors["+c+"]; if ("+j+".dataPath === undefined) "+j+".dataPath = (dataPath || '') + "+e.errorPath+";  "+j+'.schemaPath = "'+h+'";  ',e.opts.verbose&&(i+=" "+j+".schema = "+y+"; "+j+".data = "+p+"; "),i+=" } } else { "+P+" } "),i+=" } ",d&&(i+=" else { ")),i}},{}],23:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),c=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,h="data"+(i||""),r="errs__"+o,d=e.util.copy(e),p="",f=(d.level++,"valid"+d.level),m={},v={},y=e.opts.ownProperties;for(O in n)"__proto__"!=O&&(A=n[O],(a=Array.isArray(A)?v:m)[O]=A);var g=e.errorPath;for(O in s=s+("var "+r+" = errors;")+("var missing"+o+";"),v)if((a=v[O]).length){if(s+=" if ( "+h+e.util.getProperty(O)+" !== undefined ",y&&(s+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(O)+"') "),u){s+=" && ( ";var P=a;if(P)for(var E=-1,w=P.length-1;E<w;)x=P[E+=1],E&&(s+=" || "),s+=" ( ( "+(D=h+(j=e.util.getProperty(x)))+" === undefined ",y&&(s+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(x)+"') "),s+=") && (missing"+o+" = "+e.util.toQuotedString(e.opts.jsonPointers?x:j)+") ) ";s+=")) {  ";var b="missing"+o,S="' + "+b+" + '",_=(e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(g,b,!0):g+" + "+b),_||[]),b=(_.push(s),s="",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(O)+"', missingProperty: '"+S+"', depsCount: "+a.length+", deps: '"+e.util.escapeQuotes(1==a.length?a[0]:a.join(", "))+"' } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should have ")+(1==a.length?"property "+e.util.escapeQuotes(a[0]):"properties "+e.util.escapeQuotes(a.join(", "))))+" when property "+e.util.escapeQuotes(O)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",s),s=_.pop();s+=!e.compositeRule&&u?e.async?" throw new ValidationError(["+b+"]); ":" validate.errors = ["+b+"]; return false; ":" var err = "+b+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{s+=" ) { ";var F=a;if(F)for(var x,R=-1,$=F.length-1;R<$;){x=F[R+=1];var j=e.util.getProperty(x),S=e.util.escapeQuotes(x),D=h+j;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(g,x,e.opts.jsonPointers)),s+=" if ( "+D+" === undefined ",y&&(s+=" || ! Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(x)+"') "),s+=") {  var err =   ",!1!==e.createErrors?(s+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(c)+" , params: { property: '"+e.util.escapeQuotes(O)+"', missingProperty: '"+S+"', depsCount: "+a.length+", deps: '"+e.util.escapeQuotes(1==a.length?a[0]:a.join(", "))+"' } ",!1!==e.opts.messages&&(s=(s=(s+=" , message: 'should have ")+(1==a.length?"property "+e.util.escapeQuotes(a[0]):"properties "+e.util.escapeQuotes(a.join(", "))))+" when property "+e.util.escapeQuotes(O)+" is present' "),e.opts.verbose&&(s+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+h+" "),s+=" } "):s+=" {} ",s+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}s+=" }   ",u&&(p+="}",s+=" else { ")}e.errorPath=g;var O,I=d.baseId;for(O in m){var A=m[O];(e.opts.strictKeywords?"object"==typeof A&&0<Object.keys(A).length||!1===A:e.util.schemaHasRules(A,e.RULES.all))&&(s+=" "+f+" = true; if ( "+h+e.util.getProperty(O)+" !== undefined ",y&&(s+=" && Object.prototype.hasOwnProperty.call("+h+", '"+e.util.escapeQuotes(O)+"') "),s+=") { ",d.schema=A,d.schemaPath=l+e.util.getProperty(O),d.errSchemaPath=c+"/"+e.util.escapeFragment(O),s+="  "+e.validate(d)+" ",d.baseId=I,s+=" }  ",u)&&(s+=" if ("+f+") { ",p+="}")}return u&&(s+="   "+p+" if ("+r+" == errors) {"),s}},{}],24:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(o||""),u="valid"+s,h=e.opts.$data&&i&&i.$data,i=(h&&(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),"i"+s),o="schema"+s,o=(h||(a+=" var "+o+" = validate.schema"+n+";"),a+="var "+u+";",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=u+" = false;for (var "+i+"=0; "+i+"<"+o+".length; "+i+"++) if (equal("+c+", "+o+"["+i+"])) { "+u+" = true; break; }",h&&(a+="  }  "),[]),i=(o.push(a+=" if (!"+u+") {   "),a="",!1!==e.createErrors?(a+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { allowedValues: schema"+s+" } ",!1!==e.opts.messages&&(a+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a);return a=(a=o.pop())+(!e.compositeRule&&l?e.async?" throw new ValidationError(["+i+"]); ":" validate.errors = ["+i+"]; return false; ":" var err = "+i+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" }",l&&(a+=" else { "),a}},{}],25:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(o||"");if(!1===e.opts.format)l&&(a+=" if (true) { ");else{var u,h=e.opts.$data&&i&&i.$data,o=h?(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ","schema"+s):i,d=e.opts.unknownFormats,p=Array.isArray(d);if(h)a+=" var "+(u="format"+s)+" = formats["+o+"]; var "+(f="isObject"+s)+" = typeof "+u+" == 'object' && !("+u+" instanceof RegExp) && "+u+".validate; var "+(v="formatType"+s)+" = "+f+" && "+u+".type || 'string'; if ("+f+") { ",e.async&&(a+=" var async"+s+" = "+u+".async; "),a+=" "+u+" = "+u+".validate; } if (  ",h&&(a+=" ("+o+" !== undefined && typeof "+o+" != 'string') || "),a+=" (","ignore"!=d&&(a+=" ("+o+" && !"+u+" ",p&&(a+=" && self._opts.unknownFormats.indexOf("+o+") == -1 "),a+=") || "),a=(a+=" ("+u+" && "+v+" == '"+t+"' && !(typeof "+u+" == 'function' ? ")+(e.async?" (async"+s+" ? await "+u+"("+c+") : "+u+"("+c+")) ":" "+u+"("+c+") ")+(" : "+u+".test("+c+"))))) {");else{if(!(u=e.formats[i])){if("ignore"==d)return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),l&&(a+=" if (true) { "),a;if(p&&0<=d.indexOf(i))return l&&(a+=" if (true) { "),a;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var f,m,v=(f="object"==typeof u&&!(u instanceof RegExp)&&u.validate)&&u.type||"string";if(f&&(m=!0===u.async,u=u.validate),v!=t)return l&&(a+=" if (true) { "),a;if(m){if(!e.async)throw new Error("async format in sync schema");a+=" if (!(await "+(y="formats"+e.util.getProperty(i)+".validate")+"("+c+"))) { "}else{a+=" if (! ";var y="formats"+e.util.getProperty(i);f&&(y+=".validate"),a=a+("function"==typeof u?" "+y+"("+c+") ":" "+y+".test("+c+") ")+") { "}}s=[],p=(s.push(a),a="",!1!==e.createErrors?(a=(a+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { format:  ")+(h?""+o:""+e.util.toQuotedString(i))+"  } ",!1!==e.opts.messages&&(a=(a+=" , message: 'should match format \"")+(h?"' + "+o+" + '":""+e.util.escapeQuotes(i))+"\"' "),e.opts.verbose&&(a=(a=(a+=" , schema:  ")+(h?"validate.schema"+n:""+e.util.toQuotedString(i)))+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a);a=(a=s.pop())+(!e.compositeRule&&l?e.async?" throw new ValidationError(["+p+"]); ":" validate.errors = ["+p+"]; return false; ":" var err = "+p+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",l&&(a+=" else { ")}return a}},{}],26:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,i="data"+(i||""),u="valid"+o,h="errs__"+o,d=e.util.copy(e),p=(d.level++,"valid"+d.level),f=e.schema.then,m=e.schema.else,f=void 0!==f&&(e.opts.strictKeywords?"object"==typeof f&&0<Object.keys(f).length||!1===f:e.util.schemaHasRules(f,e.RULES.all)),m=void 0!==m&&(e.opts.strictKeywords?"object"==typeof m&&0<Object.keys(m).length||!1===m:e.util.schemaHasRules(m,e.RULES.all)),v=d.baseId;return f||m?(d.createErrors=!1,d.schema=n,d.schemaPath=l,d.errSchemaPath=r,s+=" var "+h+" = errors; var "+u+" = true;  ",n=e.compositeRule,e.compositeRule=d.compositeRule=!0,s+="  "+e.validate(d)+" ",d.baseId=v,d.createErrors=!0,s+="  errors = "+h+"; if (vErrors !== null) { if ("+h+") vErrors.length = "+h+"; else vErrors = null; }  ",e.compositeRule=d.compositeRule=n,f?(s+=" if ("+p+") {  ",d.schema=e.schema.then,d.schemaPath=e.schemaPath+".then",d.errSchemaPath=e.errSchemaPath+"/then",s+="  "+e.validate(d)+" ",d.baseId=v,s+=" "+u+" = "+p+"; ",f&&m?s+=" var "+(a="ifClause"+o)+" = 'then'; ":a="'then'",s+=" } ",m&&(s+=" else { ")):s+=" if (!"+p+") { ",m&&(d.schema=e.schema.else,d.schemaPath=e.schemaPath+".else",d.errSchemaPath=e.errSchemaPath+"/else",s+="  "+e.validate(d)+" ",d.baseId=v,s+=" "+u+" = "+p+"; ",f&&m?s+=" var "+(a="ifClause"+o)+" = 'else'; ":a="'else'",s+=" } "),s+=" if (!"+u+") {   var err =   ",!1!==e.createErrors?(s+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { failingKeyword: "+a+" } ",!1!==e.opts.messages&&(s+=" , message: 'should match \"' + "+a+" + '\" schema' "),e.opts.verbose&&(s+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+i+" "),s+=" } "):s+=" {} ",s+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&c&&(s+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),s+=" }   ",c&&(s+=" else { ")):c&&(s+=" if (true) { "),s}},{}],27:[function(e,r,t){r.exports={$ref:e("./ref"),allOf:e("./allOf"),anyOf:e("./anyOf"),$comment:e("./comment"),const:e("./const"),contains:e("./contains"),dependencies:e("./dependencies"),enum:e("./enum"),format:e("./format"),if:e("./if"),items:e("./items"),maximum:e("./_limit"),minimum:e("./_limit"),maxItems:e("./_limitItems"),minItems:e("./_limitItems"),maxLength:e("./_limitLength"),minLength:e("./_limitLength"),maxProperties:e("./_limitProperties"),minProperties:e("./_limitProperties"),multipleOf:e("./multipleOf"),not:e("./not"),oneOf:e("./oneOf"),pattern:e("./pattern"),properties:e("./properties"),propertyNames:e("./propertyNames"),required:e("./required"),uniqueItems:e("./uniqueItems"),validate:e("./validate")}},{"./_limit":13,"./_limitItems":14,"./_limitLength":15,"./_limitProperties":16,"./allOf":17,"./anyOf":18,"./comment":19,"./const":20,"./contains":21,"./dependencies":23,"./enum":24,"./format":25,"./if":26,"./items":28,"./multipleOf":29,"./not":30,"./oneOf":31,"./pattern":32,"./properties":33,"./propertyNames":34,"./ref":35,"./required":36,"./uniqueItems":37,"./validate":38}],28:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(o||""),r="valid"+s,o="errs__"+s,h=e.util.copy(e),d="",p=(h.level++,"valid"+h.level),s="i"+s,f=h.dataLevel=e.dataLevel+1,m="data"+f,v=e.baseId;if(a+="var "+o+" = errors;var "+r+";",Array.isArray(i)){var y,g,P=e.schema.additionalItems,E=(!1===P&&(y=l,l=e.errSchemaPath+"/additionalItems",(g=g||[]).push(a=a+(" "+r+" = "+u+".length <= "+i.length+"; ")+("  if (!"+r+") {   ")),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { limit: "+i.length+" } ",!1!==e.opts.messages&&(a+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",r=a,a=(a=g.pop())+(!e.compositeRule&&c?e.async?" throw new ValidationError(["+r+"]); ":" validate.errors = ["+r+"]; return false; ":" var err = "+r+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",l=y,c)&&(d+="}",a+=" else { "),i);if(E)for(var w=-1,b=E.length-1;w<b;){var S,_,F=E[w+=1];(e.opts.strictKeywords?"object"==typeof F&&0<Object.keys(F).length||!1===F:e.util.schemaHasRules(F,e.RULES.all))&&(a+=" "+p+" = true; if ("+u+".length > "+w+") { ",S=u+"["+w+"]",h.schema=F,h.schemaPath=n+"["+w+"]",h.errSchemaPath=l+"/"+w,h.errorPath=e.util.getPathExpr(e.errorPath,w,e.opts.jsonPointers,!0),h.dataPathArr[f]=w,_=e.validate(h),h.baseId=v,e.util.varOccurences(_,m)<2?a+=" "+e.util.varReplace(_,m,S)+" ":a+=" var "+m+" = "+S+"; "+_+" ",a+=" }  ",c)&&(a+=" if ("+p+") { ",d+="}")}"object"==typeof P&&(e.opts.strictKeywords?"object"==typeof P&&0<Object.keys(P).length||!1===P:e.util.schemaHasRules(P,e.RULES.all))&&(h.schema=P,h.schemaPath=e.schemaPath+".additionalItems",h.errSchemaPath=e.errSchemaPath+"/additionalItems",a+=" "+p+" = true; if ("+u+".length > "+i.length+") {  for (var "+s+" = "+i.length+"; "+s+" < "+u+".length; "+s+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,s,e.opts.jsonPointers,!0),S=u+"["+s+"]",h.dataPathArr[f]=s,_=e.validate(h),h.baseId=v,e.util.varOccurences(_,m)<2?a+=" "+e.util.varReplace(_,m,S)+" ":a+=" var "+m+" = "+S+"; "+_+" ",c&&(a+=" if (!"+p+") break; "),a+=" } }  ",c)&&(a+=" if ("+p+") { ",d+="}")}else(e.opts.strictKeywords?"object"==typeof i&&0<Object.keys(i).length||!1===i:e.util.schemaHasRules(i,e.RULES.all))&&(h.schema=i,h.schemaPath=n,h.errSchemaPath=l,a+="  for (var "+s+" = 0; "+s+" < "+u+".length; "+s+"++) { ",h.errorPath=e.util.getPathExpr(e.errorPath,s,e.opts.jsonPointers,!0),S=u+"["+s+"]",h.dataPathArr[f]=s,_=e.validate(h),h.baseId=v,e.util.varOccurences(_,m)<2?a+=" "+e.util.varReplace(_,m,S)+" ":a+=" var "+m+" = "+S+"; "+_+" ",c&&(a+=" if (!"+p+") break; "),a+=" }");return c&&(a+=" "+d+" if ("+o+" == errors) {"),a}},{}],29:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(o||""),h=e.opts.$data&&i&&i.$data,o=h?(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ","schema"+s):i;if(!h&&"number"!=typeof i)throw new Error(r+" must be number");a+="var division"+s+";if (",h&&(a+=" "+o+" !== undefined && ( typeof "+o+" != 'number' || "),a=(a+=" (division"+s+" = "+u+" / "+o+", ")+(e.opts.multipleOfPrecision?" Math.abs(Math.round(division"+s+") - division"+s+") > 1e-"+e.opts.multipleOfPrecision+" ":" division"+s+" !== parseInt(division"+s+") ")+" ) ",h&&(a+="  )  ");r=[],r.push(a+=" ) {   "),a="",!1!==e.createErrors?(a+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { multipleOf: "+o+" } ",!1!==e.opts.messages&&(a=a+" , message: 'should be multiple of "+(h?"' + "+o:o+"'")),e.opts.verbose&&(a=(a+=" , schema:  ")+(h?"validate.schema"+n:""+i)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),a+=" } "):a+=" {} ",s=a;return a=(a=r.pop())+(!e.compositeRule&&c?e.async?" throw new ValidationError(["+s+"]); ":" validate.errors = ["+s+"]; return false; ":" var err = "+s+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",c&&(a+=" else { "),a}},{}],30:[function(e,r,t){r.exports=function(e,r,t){var a,s,o=" ",i=e.level,n=e.dataLevel,l=e.schema[r],c=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,n="data"+(n||""),i="errs__"+i,h=e.util.copy(e),d=(h.level++,"valid"+h.level);return(e.opts.strictKeywords?"object"==typeof l&&0<Object.keys(l).length||!1===l:e.util.schemaHasRules(l,e.RULES.all))?(h.schema=l,h.schemaPath=c,h.errSchemaPath=r,o+=" var "+i+" = errors;  ",l=e.compositeRule,e.compositeRule=h.compositeRule=!0,h.createErrors=!1,h.opts.allErrors&&(s=h.opts.allErrors,h.opts.allErrors=!1),o+=" "+e.validate(h)+" ",h.createErrors=!0,s&&(h.opts.allErrors=s),e.compositeRule=h.compositeRule=l,(a=a||[]).push(o+=" if ("+d+") {   "),o="",!1!==e.createErrors?(o+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: {} ",!1!==e.opts.messages&&(o+=" , message: 'should NOT be valid' "),e.opts.verbose&&(o+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+n+" "),o+=" } "):o+=" {} ",s=o,o=(o=a.pop())+(!e.compositeRule&&u?e.async?" throw new ValidationError(["+s+"]); ":" validate.errors = ["+s+"]; return false; ":" var err = "+s+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } else {  errors = "+i+"; if (vErrors !== null) { if ("+i+") vErrors.length = "+i+"; else vErrors = null; } ",e.opts.allErrors&&(o+=" } ")):(o+="  var err =   ",!1!==e.createErrors?(o+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: {} ",!1!==e.opts.messages&&(o+=" , message: 'should NOT be valid' "),e.opts.verbose&&(o+=" , schema: validate.schema"+c+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+n+" "),o+=" } "):o+=" {} ",o+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(o+=" if (false) { ")),o}},{}],31:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,r=!e.opts.allErrors,o="data"+(o||""),c="valid"+s,u="errs__"+s,h=e.util.copy(e),d="",p=(h.level++,"valid"+h.level),f=h.baseId,m="prevValid"+s,v="passingSchemas"+s,s=(a+="var "+u+" = errors , "+m+" = false , "+c+" = false , "+v+" = null; ",e.compositeRule),y=(e.compositeRule=h.compositeRule=!0,i);if(y)for(var g,P=-1,E=y.length-1;P<E;)g=y[P+=1],(e.opts.strictKeywords?"object"==typeof g&&0<Object.keys(g).length||!1===g:e.util.schemaHasRules(g,e.RULES.all))?(h.schema=g,h.schemaPath=n+"["+P+"]",h.errSchemaPath=l+"/"+P,a+="  "+e.validate(h)+" ",h.baseId=f):a+=" var "+p+" = true; ",P&&(a+=" if ("+p+" && "+m+") { "+c+" = false; "+v+" = ["+v+", "+P+"]; } else { ",d+="}"),a+=" if ("+p+") { "+c+" = "+m+" = true; "+v+" = "+P+"; }";return e.compositeRule=h.compositeRule=s,a+=d+"if (!"+c+") {   var err =   ",!1!==e.createErrors?(a+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { passingSchemas: "+v+" } ",!1!==e.opts.messages&&(a+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+o+" "),a+=" } "):a+=" {} ",a+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&r&&(a+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),a+="} else {  errors = "+u+"; if (vErrors !== null) { if ("+u+") vErrors.length = "+u+"; else vErrors = null; }",e.opts.allErrors&&(a+=" } "),a}},{}],32:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(o||""),u="valid"+s,h=e.opts.$data&&i&&i.$data,o=h?(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ","schema"+s):i,s=(h?(a+=" var "+u+" = true; try { "+u+" = "+(e.opts.regExp?"regExp":"new RegExp")+"("+o+").test("+c+"); } catch(e) { "+u+" = false; } if ( ",h&&(a+=" ("+o+" !== undefined && typeof "+o+" != 'string') || "),a+=" !"+u+") {"):(a+=" if ( ",h&&(a+=" ("+o+" !== undefined && typeof "+o+" != 'string') || "),a+=" !"+e.usePattern(i)+".test("+c+") ) {"),[]),u=(s.push(a),a="",!1!==e.createErrors?(a=(a+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { pattern:  ")+(h?""+o:""+e.util.toQuotedString(i))+"  } ",!1!==e.opts.messages&&(a=(a+=" , message: 'should match pattern \"")+(h?"' + "+o+" + '":""+e.util.escapeQuotes(i))+"\"' "),e.opts.verbose&&(a=(a=(a+=" , schema:  ")+(h?"validate.schema"+n:""+e.util.toQuotedString(i)))+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a);return a=(a=s.pop())+(!e.compositeRule&&l?e.async?" throw new ValidationError(["+u+"]); ":" validate.errors = ["+u+"]; return false; ":" var err = "+u+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+"} ",l&&(a+=" else { "),a}},{}],33:[function(e,r,t){r.exports=function(e,r,L){var t,a=" ",s=e.level,o=e.dataLevel,N=e.schema[r],i=e.schemaPath+e.util.getProperty(r),n=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(o||""),r="errs__"+s,u=e.util.copy(e),h="",d=(u.level++,"valid"+u.level),p="key"+s,f="idx"+s,m=u.dataLevel=e.dataLevel+1,v="data"+m,y="dataProperties"+s,o=Object.keys(N||{}).filter(V),z=e.schema.patternProperties||{},g=Object.keys(z).filter(V),P=e.schema.additionalProperties,q=o.length||g.length,T=!1===P,Q="object"==typeof P&&Object.keys(P).length,E=e.opts.removeAdditional,w=T||Q||E,b=e.opts.ownProperties,S=e.baseId,_=e.schema.required;function V(e){return"__proto__"!==e}if(_&&(!e.opts.$data||!_.$data)&&_.length<e.opts.loopRequired&&(t=e.util.toHash(_)),a+="var "+r+" = errors;var "+d+" = true;",b&&(a+=" var "+y+" = undefined;"),w){if(a+=b?" "+y+" = "+y+" || Object.keys("+c+"); for (var "+f+"=0; "+f+"<"+y+".length; "+f+"++) { var "+p+" = "+y+"["+f+"]; ":" for (var "+p+" in "+c+") { ",q){if(a+=" var isAdditional"+s+" = !(false ",o.length)if(8<o.length)a+=" || validate.schema"+i+".hasOwnProperty("+p+") ";else{var U=o;if(U)for(var H=-1,M=U.length-1;H<M;)F=U[H+=1],a+=" || "+p+" == "+e.util.toQuotedString(F)+" "}if(g.length){var K=g;if(K)for(var B=-1,J=K.length-1;B<J;)A=K[B+=1],a+=" || "+e.usePattern(A)+".test("+p+") "}a+=" ); if (isAdditional"+s+") { "}"all"==E?a+=" delete "+c+"["+p+"]; ":(R=e.errorPath,_="' + "+p+" + '",e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers)),T?E?a+=" delete "+c+"["+p+"]; ":($=n,n=e.errSchemaPath+"/additionalProperties",(D=D||[]).push(a+=" "+d+" = false; "),a="",!1!==e.createErrors?(a+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { additionalProperty: '"+_+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is an invalid additional property":"should NOT have additional properties")+"' "),e.opts.verbose&&(a+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",O=a,a=D.pop(),a+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+O+"]); ":" validate.errors = ["+O+"]; return false; ":" var err = "+O+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n=$,l&&(a+=" break; ")):Q&&("failing"==E?(a+=" var "+r+" = errors;  ",w=e.compositeRule,e.compositeRule=u.compositeRule=!0,u.schema=P,u.schemaPath=e.schemaPath+".additionalProperties",u.errSchemaPath=e.errSchemaPath+"/additionalProperties",u.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers),k=c+"["+p+"]",u.dataPathArr[m]=p,C=e.validate(u),u.baseId=S,e.util.varOccurences(C,v)<2?a+=" "+e.util.varReplace(C,v,k)+" ":a+=" var "+v+" = "+k+"; "+C+" ",a+=" if (!"+d+") { errors = "+r+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+c+"["+p+"]; }  ",e.compositeRule=u.compositeRule=w):(u.schema=P,u.schemaPath=e.schemaPath+".additionalProperties",u.errSchemaPath=e.errSchemaPath+"/additionalProperties",u.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers),k=c+"["+p+"]",u.dataPathArr[m]=p,C=e.validate(u),u.baseId=S,e.util.varOccurences(C,v)<2?a+=" "+e.util.varReplace(C,v,k)+" ":a+=" var "+v+" = "+k+"; "+C+" ",l&&(a+=" if (!"+d+") break; "))),e.errorPath=R),q&&(a+=" } "),a+=" }  ",l&&(a+=" if ("+d+") { ",h+="}")}var Z=e.opts.useDefaults&&!e.compositeRule;if(o.length){var G=o;if(G)for(var F,Y=-1,W=G.length-1;Y<W;){var X,x,R,$,j,D,O,I=N[F=G[Y+=1]];(e.opts.strictKeywords?"object"==typeof I&&0<Object.keys(I).length||!1===I:e.util.schemaHasRules(I,e.RULES.all))&&(k=c+(j=e.util.getProperty(F)),X=Z&&void 0!==I.default,u.schema=I,u.schemaPath=i+j,u.errSchemaPath=n+"/"+e.util.escapeFragment(F),u.errorPath=e.util.getPath(e.errorPath,F,e.opts.jsonPointers),u.dataPathArr[m]=e.util.toQuotedString(F),C=e.validate(u),u.baseId=S,e.util.varOccurences(C,v)<2?(C=e.util.varReplace(C,v,k),x=k):a+=" var "+(x=v)+" = "+k+"; ",X?a+=" "+C+" ":(t&&t[F]?(a+=" if ( "+x+" === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+c+", '"+e.util.escapeQuotes(F)+"') "),a+=") { "+d+" = false; ",R=e.errorPath,$=n,j=e.util.escapeQuotes(F),e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(R,F,e.opts.jsonPointers)),n=e.errSchemaPath+"/required",(D=D||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(n)+" , params: { missingProperty: '"+j+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+j+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+i+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",O=a,a=D.pop(),a+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+O+"]); ":" validate.errors = ["+O+"]; return false; ":" var err = "+O+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",n=$,e.errorPath=R,a+=" } else { "):l?(a+=" if ( "+x+" === undefined ",b&&(a+=" || ! Object.prototype.hasOwnProperty.call("+c+", '"+e.util.escapeQuotes(F)+"') "),a+=") { "+d+" = true; } else { "):(a+=" if ("+x+" !== undefined ",b&&(a+=" &&   Object.prototype.hasOwnProperty.call("+c+", '"+e.util.escapeQuotes(F)+"') "),a+=" ) { "),a+=" "+C+" } ")),l&&(a+=" if ("+d+") { ",h+="}")}}if(g.length){var ee=g;if(ee)for(var A,re=-1,te=ee.length-1;re<te;){var k,C,I=z[A=ee[re+=1]];(e.opts.strictKeywords?"object"==typeof I&&0<Object.keys(I).length||!1===I:e.util.schemaHasRules(I,e.RULES.all))&&(u.schema=I,u.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(A),u.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(A),a=(a+=b?" "+y+" = "+y+" || Object.keys("+c+"); for (var "+f+"=0; "+f+"<"+y+".length; "+f+"++) { var "+p+" = "+y+"["+f+"]; ":" for (var "+p+" in "+c+") { ")+" if ("+e.usePattern(A)+".test("+p+")) { ",u.errorPath=e.util.getPathExpr(e.errorPath,p,e.opts.jsonPointers),k=c+"["+p+"]",u.dataPathArr[m]=p,C=e.validate(u),u.baseId=S,e.util.varOccurences(C,v)<2?a+=" "+e.util.varReplace(C,v,k)+" ":a+=" var "+v+" = "+k+"; "+C+" ",l&&(a+=" if (!"+d+") break; "),a+=" } ",l&&(a+=" else "+d+" = true; "),a+=" }  ",l)&&(a+=" if ("+d+") { ",h+="}")}}return l&&(a+=" "+h+" if ("+r+" == errors) {"),a}},{}],34:[function(e,r,t){r.exports=function(e,r,t){var a,s,o,i,n,l,c,u=" ",h=e.level,d=e.dataLevel,p=e.schema[r],f=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,m=!e.opts.allErrors,d="data"+(d||""),v="errs__"+h,y=e.util.copy(e),g=(y.level++,"valid"+y.level);return u+="var "+v+" = errors;",(e.opts.strictKeywords?"object"==typeof p&&0<Object.keys(p).length||!1===p:e.util.schemaHasRules(p,e.RULES.all))&&(y.schema=p,y.schemaPath=f,y.errSchemaPath=r,p="idx"+h,s="i"+h,o="' + "+(a="key"+h)+" + '",i="data"+(y.dataLevel=e.dataLevel+1),c="dataProperties"+h,n=e.baseId,(l=e.opts.ownProperties)&&(u+=" var "+c+" = undefined; "),u=u+(l?" "+c+" = "+c+" || Object.keys("+d+"); for (var "+p+"=0; "+p+"<"+c+".length; "+p+"++) { var "+a+" = "+c+"["+p+"]; ":" for (var "+a+" in "+d+") { ")+" var startErrs"+h+" = errors; ",l=a,c=e.compositeRule,e.compositeRule=y.compositeRule=!0,p=e.validate(y),y.baseId=n,e.util.varOccurences(p,i)<2?u+=" "+e.util.varReplace(p,i,l)+" ":u+=" var "+i+" = "+l+"; "+p+" ",e.compositeRule=y.compositeRule=c,u+=" if (!"+g+") { for (var "+s+"=startErrs"+h+"; "+s+"<errors; "+s+"++) { vErrors["+s+"].propertyName = "+a+"; }   var err =   ",!1!==e.createErrors?(u+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { propertyName: '"+o+"' } ",!1!==e.opts.messages&&(u+=" , message: 'property name \\'"+o+"\\' is invalid' "),e.opts.verbose&&(u+=" , schema: validate.schema"+f+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),u+=" } "):u+=" {} ",u+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&m&&(u+=e.async?" throw new ValidationError(vErrors); ":" validate.errors = vErrors; return false; "),m&&(u+=" break; "),u+=" } }"),m&&(u+="  if ("+v+" == errors) {"),u}},{}],35:[function(e,r,t){r.exports=function(e,r,t){var a,s,o=" ",i=e.dataLevel,n=e.schema[r],r=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,c="data"+(i||""),u="valid"+e.level;if("#"==n||"#/"==n)s=e.isRoot?(a=e.async,"validate"):(a=!0===e.root.schema.$async,"root.refVal[0]");else{var h=e.resolveRef(e.baseId,n,e.isRoot);if(void 0===h){var d=e.MissingRefError.message(e.baseId,n);if("fail"==e.opts.missingRefs){e.logger.error(d);(p=p||[]).push(o),o="",!1!==e.createErrors?(o+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { ref: '"+e.util.escapeQuotes(n)+"' } ",!1!==e.opts.messages&&(o+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(n)+"' "),e.opts.verbose&&(o+=" , schema: "+e.util.toQuotedString(n)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),o+=" } "):o+=" {} ";r=o,o=p.pop();o+=!e.compositeRule&&l?e.async?" throw new ValidationError(["+r+"]); ":" validate.errors = ["+r+"]; return false; ":" var err = "+r+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",l&&(o+=" if (false) { ")}else{if("ignore"!=e.opts.missingRefs)throw new e.MissingRefError(e.baseId,n,d);e.logger.warn(d),l&&(o+=" if (true) { ")}}else h.inline?((r=e.util.copy(e)).level++,d="valid"+r.level,r.schema=h.schema,r.schemaPath="",r.errSchemaPath=n,o+=" "+e.validate(r).replace(/validate\.schema/g,h.code)+" ",l&&(o+=" if ("+d+") { ")):(a=!0===h.$async||e.async&&!1!==h.$async,s=h.code)}if(s){(p=p||[]).push(o),o=(o="")+(e.opts.passContext?" "+s+".call(this, ":" "+s+"( ")+(" "+c+", (dataPath || '')"),'""'!=e.errorPath&&(o+=" + "+e.errorPath);var p,n=i?"data"+(i-1||""):"parentData",r=o+=" , "+n+" , "+(i?e.dataPathArr[i]:"parentDataProperty")+", rootData)  ";if(o=p.pop(),a){if(!e.async)throw new Error("async schema referenced by sync schema");l&&(o+=" var "+u+"; "),o+=" try { await "+r+"; ",l&&(o+=" "+u+" = true; "),o+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",l&&(o+=" "+u+" = false; "),o+=" } ",l&&(o+=" if ("+u+") { ")}else o+=" if (!"+r+") { if (vErrors === null) vErrors = "+s+".errors; else vErrors = vErrors.concat("+s+".errors); errors = vErrors.length; } ",l&&(o+=" else { ")}return o}},{}],36:[function(e,r,t){r.exports=function(e,r,t){var a=" ",s=e.level,o=e.dataLevel,i=e.schema[r],n=e.schemaPath+e.util.getProperty(r),l=e.errSchemaPath+"/"+r,r=!e.opts.allErrors,c="data"+(o||""),u="valid"+s,h=e.opts.$data&&i&&i.$data,o=(h&&(a+=" var schema"+s+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; "),"schema"+s);if(!h)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var d=[],p=i;if(p)for(var f=-1,m=p.length-1;f<m;){var v=p[f+=1],y=e.schema.properties[v];y&&(e.opts.strictKeywords?"object"==typeof y&&0<Object.keys(y).length||!1===y:e.util.schemaHasRules(y,e.RULES.all))||(d[d.length]=v)}}else d=i;if(h||d.length){var g=e.errorPath,i=h||e.opts.loopRequired<=d.length,P=e.opts.ownProperties;if(r){if(a+=" var missing"+s+"; ",i){h||(a+=" var "+o+" = validate.schema"+n+"; ");var E="' + "+(x="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(g,x,e.opts.jsonPointers)),a+=" var "+u+" = true; ",h&&(a+=" if (schema"+s+" === undefined) "+u+" = true; else if (!Array.isArray(schema"+s+")) "+u+" = false; else {"),a+=" for (var "+S+" = 0; "+S+" < "+o+".length; "+S+"++) { "+u+" = "+c+"["+o+"["+S+"]] !== undefined ",P&&(a+=" &&   Object.prototype.hasOwnProperty.call("+c+", "+o+"["+S+"]) "),a+="; if (!"+u+") break; } ",h&&(a+="  }  ");(F=F||[]).push(a+="  if (!"+u+") {   "),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+E+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ";var w=a}else{a+=" if ( ";var b=d;if(b)for(var S=-1,_=b.length-1;S<_;)$=b[S+=1],S&&(a+=" || "),a+=" ( ( "+(I=c+(O=e.util.getProperty($)))+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+c+", '"+e.util.escapeQuotes($)+"') "),a+=") && (missing"+s+" = "+e.util.toQuotedString(e.opts.jsonPointers?$:O)+") ) ";a+=") {  ";E="' + "+(x="missing"+s)+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(g,x,!0):g+" + "+x);(F=F||[]).push(a),a="",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+E+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ";var F,w=a}a=(a=F.pop())+(!e.compositeRule&&r?e.async?" throw new ValidationError(["+w+"]); ":" validate.errors = ["+w+"]; return false; ":" var err = "+w+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } else { "}else if(i){h||(a+=" var "+o+" = validate.schema"+n+"; ");var x,E="' + "+(x="schema"+s+"["+(S="i"+s)+"]")+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(g,x,e.opts.jsonPointers)),h&&(a+=" if ("+o+" && !Array.isArray("+o+")) {  var err =   ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+E+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+o+" !== undefined) { "),a+=" for (var "+S+" = 0; "+S+" < "+o+".length; "+S+"++) { if ("+c+"["+o+"["+S+"]] === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+c+", "+o+"["+S+"]) "),a+=") {  var err =   ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+E+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",h&&(a+="  }  ")}else{var R=d;if(R)for(var $,j=-1,D=R.length-1;j<D;){$=R[j+=1];var O=e.util.getProperty($),E=e.util.escapeQuotes($),I=c+O;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(g,$,e.opts.jsonPointers)),a+=" if ( "+I+" === undefined ",P&&(a+=" || ! Object.prototype.hasOwnProperty.call("+c+", '"+e.util.escapeQuotes($)+"') "),a+=") {  var err =   ",!1!==e.createErrors?(a+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { missingProperty: '"+E+"' } ",!1!==e.opts.messages&&(a=(a+=" , message: '")+(e.opts._errorDataPathProperty?"is a required property":"should have required property \\'"+E+"\\'")+"' "),e.opts.verbose&&(a+=" , schema: validate.schema"+n+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+c+" "),a+=" } "):a+=" {} ",a+=";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=g}else r&&(a+=" if (true) {");return a}},{}],37:[function(e,r,t){r.exports=function(e,r,t){var a,s=" ",o=e.level,i=e.dataLevel,n=e.schema[r],l=e.schemaPath+e.util.getProperty(r),r=e.errSchemaPath+"/"+r,c=!e.opts.allErrors,u="data"+(i||""),h="valid"+o,d=e.opts.$data&&n&&n.$data,i=d?(s+=" var schema"+o+" = "+e.util.getData(n.$data,i,e.dataPathArr)+"; ","schema"+o):n;return(n||d)&&!1!==e.opts.uniqueItems?(d&&(s+=" var "+h+"; if ("+i+" === false || "+i+" === undefined) "+h+" = true; else if (typeof "+i+" != 'boolean') "+h+" = false; else { "),s+=" var i = "+u+".length , "+h+" = true , j; if (i > 1) { ",o=e.schema.items&&e.schema.items.type,i=Array.isArray(o),!o||"object"==o||"array"==o||i&&(0<=o.indexOf("object")||0<=o.indexOf("array"))?s+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+u+"[i], "+u+"[j])) { "+h+" = false; break outer; } } } ":(s=(s+=" var itemIndices = {}, item; for (;i--;) { var item = "+u+"[i]; ")+" if ("+e.util["checkDataType"+(i?"s":"")](o,"item",e.opts.strictNumbers,!0)+") continue; ",i&&(s+=" if (typeof item == 'string') item = '\"' + item; "),s+=" if (typeof itemIndices[item] == 'number') { "+h+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "),s+=" } ",d&&(s+="  }  "),(a=a||[]).push(s+=" if (!"+h+") {   "),s="",!1!==e.createErrors?(s+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(r)+" , params: { i: i, j: j } ",!1!==e.opts.messages&&(s+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(s=(s+=" , schema:  ")+(d?"validate.schema"+l:""+n)+"         , parentSchema: validate.schema"+e.schemaPath+" , data: "+u+" "),s+=" } "):s+=" {} ",o=s,s=(s=a.pop())+(!e.compositeRule&&c?e.async?" throw new ValidationError(["+o+"]); ":" validate.errors = ["+o+"]; return false; ":" var err = "+o+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } ",c&&(s+=" else { ")):c&&(s+=" if (true) { "),s}},{}],38:[function(e,r,t){r.exports=function(a,e,L){var r="",t=!0===a.schema.$async,s=a.util.schemaHasRulesExcept(a.schema,a.RULES.all,"$ref"),o=a.self._getId(a.schema);if(a.opts.strictKeywords){var i=a.util.schemaUnknownRules(a.schema,a.RULES.keywords);if(i){i="unknown keyword: "+i;if("log"!==a.opts.strictKeywords)throw new Error(i);a.logger.warn(i)}}if(a.isTop&&(r+=" var validate = ",t&&(a.async=!0,r+="async "),r+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",o)&&(a.opts.sourceCode||a.opts.processCode)&&(r+=" /*# sourceURL="+o+" */ "),"boolean"==typeof a.schema||!s&&!a.schema.$ref)l=a.level,c=a.dataLevel,j=a.schema[e="false schema"],E=a.schemaPath+a.util.getProperty(e),w=a.errSchemaPath+"/"+e,p=!a.opts.allErrors,u="data"+(c||""),d="valid"+l,!1===a.schema?(a.isTop?p=!0:r+=" var "+d+" = false; ",(k=k||[]).push(r),r="",!1!==a.createErrors?(r+=" { keyword: 'false schema' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(w)+" , params: {} ",!1!==a.opts.messages&&(r+=" , message: 'boolean schema is false' "),a.opts.verbose&&(r+=" , schema: false , parentSchema: validate.schema"+a.schemaPath+" , data: "+u+" "),r+=" } "):r+=" {} ",R=r,r=k.pop(),r+=!a.compositeRule&&p?a.async?" throw new ValidationError(["+R+"]); ":" validate.errors = ["+R+"]; return false; ":" var err = "+R+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "):r+=a.isTop?t?" return data; ":" validate.errors = null; return true; ":" var "+d+" = true; ",a.isTop&&(r+=" }; return validate; ");else{if(a.isTop){var n=a.isTop,l=a.level=0,c=a.dataLevel=0,u="data";if(a.rootId=a.resolve.fullPath(a.self._getId(a.root.schema)),a.baseId=a.baseId||a.rootId,delete a.isTop,a.dataPathArr=[""],void 0!==a.schema.default&&a.opts.useDefaults&&a.opts.strictDefaults){var h="default is ignored in the schema root";if("log"!==a.opts.strictDefaults)throw new Error(h);a.logger.warn(h)}r=(r+=" var vErrors = null; ")+" var errors = 0;     "+" if (rootData === undefined) rootData = data; "}else{l=a.level,u="data"+((c=a.dataLevel)||"");if(o&&(a.baseId=a.resolve.url(a.baseId,o)),t&&!a.async)throw new Error("async schema in sync schema");r+=" var errs_"+l+" = errors;"}var d="valid"+l,p=!a.opts.allErrors,f="",m="",v=a.schema.type,y=Array.isArray(v);if(v&&a.opts.nullable&&!0===a.schema.nullable&&(y?-1==v.indexOf("null")&&(v=v.concat("null")):"null"!=v&&(v=[v,"null"],y=!0)),y&&1==v.length&&(v=v[0],y=!1),a.schema.$ref&&s){if("fail"==a.opts.extendRefs)throw new Error('$ref: validation keywords used in schema at path "'+a.errSchemaPath+'" (see option extendRefs)');!0!==a.opts.extendRefs&&(s=!1,a.logger.warn('$ref: keywords ignored in schema at path "'+a.errSchemaPath+'"'))}if(a.schema.$comment&&a.opts.$comment&&(r+=" "+a.RULES.all.$comment.code(a,"$comment")),v){a.opts.coerceTypes&&(g=a.util.coerceToTypes(a.opts.coerceTypes,v));var g,P=a.RULES.types[v];if(g||y||!0===P||P&&!B(P)){var E=a.schemaPath+".type",w=a.errSchemaPath+"/type",E=a.schemaPath+".type",w=a.errSchemaPath+"/type";if(r+=" if ("+a.util[y?"checkDataTypes":"checkDataType"](v,u,a.opts.strictNumbers,!0)+") { ",g){var b="dataType"+l,S="coerced"+l,_=(r+=" var "+b+" = typeof "+u+"; var "+S+" = undefined; ","array"==a.opts.coerceTypes&&(r+=" if ("+b+" == 'object' && Array.isArray("+u+") && "+u+".length == 1) { "+u+" = "+u+"[0]; "+b+" = typeof "+u+"; if ("+a.util.checkDataType(a.schema.type,u,a.opts.strictNumbers)+") "+S+" = "+u+"; } "),r+=" if ("+S+" !== undefined) ; ",g);if(_)for(var F,x=-1,N=_.length-1;x<N;)"string"==(F=_[x+=1])?r+=" else if ("+b+" == 'number' || "+b+" == 'boolean') "+S+" = '' + "+u+"; else if ("+u+" === null) "+S+" = ''; ":"number"==F||"integer"==F?(r+=" else if ("+b+" == 'boolean' || "+u+" === null || ("+b+" == 'string' && "+u+" && "+u+" == +"+u+" ","integer"==F&&(r+=" && !("+u+" % 1)"),r+=")) "+S+" = +"+u+"; "):"boolean"==F?r+=" else if ("+u+" === 'false' || "+u+" === 0 || "+u+" === null) "+S+" = false; else if ("+u+" === 'true' || "+u+" === 1) "+S+" = true; ":"null"==F?r+=" else if ("+u+" === '' || "+u+" === 0 || "+u+" === false) "+S+" = null; ":"array"==a.opts.coerceTypes&&"array"==F&&(r+=" else if ("+b+" == 'string' || "+b+" == 'number' || "+b+" == 'boolean' || "+u+" == null) "+S+" = ["+u+"]; ");(k=k||[]).push(r+=" else {   "),r="",!1!==a.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(w)+" , params: { type: '")+(y?""+v.join(","):""+v)+"' } ",!1!==a.opts.messages&&(r=(r+=" , message: 'should be ")+(y?""+v.join(","):""+v)+"' "),a.opts.verbose&&(r+=" , schema: validate.schema"+E+" , parentSchema: validate.schema"+a.schemaPath+" , data: "+u+" "),r+=" } "):r+=" {} ";var R=r,i=(r=k.pop(),c?"data"+(c-1||""):"parentData");r=(r+=!a.compositeRule&&p?a.async?" throw new ValidationError(["+R+"]); ":" validate.errors = ["+R+"]; return false; ":" var err = "+R+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+(" } if ("+S+" !== undefined) {  ")+(" "+u+" = "+S+"; "),c||(r+="if ("+i+" !== undefined)"),r+=" "+i+"["+(c?a.dataPathArr[c]:"parentDataProperty")+"] = "+S+"; } "}else{R=((k=k||[]).push(r),r="",!1!==a.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(w)+" , params: { type: '")+(y?""+v.join(","):""+v)+"' } ",!1!==a.opts.messages&&(r=(r+=" , message: 'should be ")+(y?""+v.join(","):""+v)+"' "),a.opts.verbose&&(r+=" , schema: validate.schema"+E+" , parentSchema: validate.schema"+a.schemaPath+" , data: "+u+" "),r+=" } "):r+=" {} ",r);r=k.pop(),r+=!a.compositeRule&&p?a.async?" throw new ValidationError(["+R+"]); ":" validate.errors = ["+R+"]; return false; ":" var err = "+R+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}r+=" } "}}if(a.schema.$ref&&!s)r+=" "+a.RULES.all.$ref.code(a,"$ref")+" ",p&&(r=(r+=" } if (errors === ")+(n?"0":"errs_"+l)+") { ",m+="}");else{var $=a.RULES;if($)for(var z=-1,q=$.length-1;z<q;)if(B(P=$[z+=1])){if(P.type&&(r+=" if ("+a.util.checkDataType(P.type,u,a.opts.strictNumbers)+") { "),a.opts.useDefaults)if("object"==P.type&&a.schema.properties){var j=a.schema.properties,D=Object.keys(j);if(D)for(var T,Q=-1,V=D.length-1;Q<V;)if(void 0!==(A=j[T=D[Q+=1]]).default){var O=u+a.util.getProperty(T);if(a.compositeRule){if(a.opts.strictDefaults){h="default is ignored for: "+O;if("log"!==a.opts.strictDefaults)throw new Error(h);a.logger.warn(h)}}else r+=" if ("+O+" === undefined ","empty"==a.opts.useDefaults&&(r+=" || "+O+" === null || "+O+" === '' "),r=(r+=" ) "+O+" = ")+("shared"==a.opts.useDefaults?" "+a.useDefault(A.default)+" ":" "+JSON.stringify(A.default)+" ")+"; "}}else if("array"==P.type&&Array.isArray(a.schema.items)){var I=a.schema.items;if(I)for(var A,x=-1,U=I.length-1;x<U;)if(void 0!==(A=I[x+=1]).default){O=u+"["+x+"]";if(a.compositeRule){if(a.opts.strictDefaults){h="default is ignored for: "+O;if("log"!==a.opts.strictDefaults)throw new Error(h);a.logger.warn(h)}}else r+=" if ("+O+" === undefined ","empty"==a.opts.useDefaults&&(r+=" || "+O+" === null || "+O+" === '' "),r=(r+=" ) "+O+" = ")+("shared"==a.opts.useDefaults?" "+a.useDefault(A.default)+" ":" "+JSON.stringify(A.default)+" ")+"; "}}var k,H=P.rules;if(H)for(var C,M=-1,K=H.length-1;M<K;)J(C=H[M+=1])&&(C=C.code(a,C.keyword,P.type))&&(r+=" "+C+" ",p)&&(f+="}");p&&(r+=" "+f+" ",f=""),P.type&&(r+=" } ",v)&&v===P.type&&!g&&(E=a.schemaPath+".type",w=a.errSchemaPath+"/type",(k=k||[]).push(r+=" else { "),r="",!1!==a.createErrors?(r=(r+=" { keyword: 'type' , dataPath: (dataPath || '') + "+a.errorPath+" , schemaPath: "+a.util.toQuotedString(w)+" , params: { type: '")+(y?""+v.join(","):""+v)+"' } ",!1!==a.opts.messages&&(r=(r+=" , message: 'should be ")+(y?""+v.join(","):""+v)+"' "),a.opts.verbose&&(r+=" , schema: validate.schema"+E+" , parentSchema: validate.schema"+a.schemaPath+" , data: "+u+" "),r+=" } "):r+=" {} ",R=r,r=(r=k.pop())+(!a.compositeRule&&p?a.async?" throw new ValidationError(["+R+"]); ":" validate.errors = ["+R+"]; return false; ":" var err = "+R+";  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ")+" } "),p&&(r=(r+=" if (errors === ")+(n?"0":"errs_"+l)+") { ",m+="}")}}p&&(r+=" "+m+" "),n?r=r+(t?" if (errors === 0) return data;            else throw new ValidationError(vErrors); ":" validate.errors = vErrors;  return errors === 0;       ")+" }; return validate;":r+=" var "+d+" = errors === errs_"+l+";"}return r;function B(e){for(var r=e.rules,t=0;t<r.length;t++)if(J(r[t]))return 1}function J(e){return void 0!==a.schema[e.keyword]||e.implements&&(e=>{for(var r=e.implements,t=0;t<r.length;t++)if(void 0!==a.schema[r[t]])return 1})(e)}}},{}],39:[function(e,r,t){var n=/^[a-z_$][a-z0-9_$-]*$/i,l=e("./dotjs/custom"),a=e("./definition_schema");function s(e,r){s.errors=null;var t=this._validateKeyword=this._validateKeyword||this.compile(a,!0);if(t(e))return!0;if(s.errors=t.errors,r)throw new Error("custom keyword definition is invalid: "+this.errorsText(t.errors));return!1}r.exports={add:function(e,r){var i=this.RULES;if(i.keywords[e])throw new Error("Keyword "+e+" is already defined");if(!n.test(e))throw new Error("Keyword "+e+" is not a valid identifier");if(r){this.validateKeyword(r,!0);var t=r.type;if(Array.isArray(t))for(var a=0;a<t.length;a++)o(e,t[a],r);else o(e,t,r);var s=r.metaSchema;s&&(r.validateSchema=this.compile(s=r.$data&&this._opts.$data?{anyOf:[s,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}:s,!0))}function o(e,r,t){for(var a,s=0;s<i.length;s++){var o=i[s];if(o.type==r){a=o;break}}a||i.push(a={type:r,rules:[]});t={keyword:e,definition:t,custom:!0,code:l,implements:t.implements};a.rules.push(t),i.custom[e]=t}return i.keywords[e]=i.all[e]=!0,this},get:function(e){var r=this.RULES.custom[e];return r?r.definition:this.RULES.keywords[e]||!1},remove:function(e){var r=this.RULES;delete r.keywords[e],delete r.all[e],delete r.custom[e];for(var t=0;t<r.length;t++)for(var a=r[t].rules,s=0;s<a.length;s++)if(a[s].keyword==e){a.splice(s,1);break}return this},validate:s}},{"./definition_schema":12,"./dotjs/custom":22}],40:[function(e,r,t){r.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}},{}],41:[function(e,r,t){r.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}},{}],42:[function(e,r,t){r.exports=function e(r,t){if(r===t)return!0;if(r&&t&&"object"==typeof r&&"object"==typeof t){if(r.constructor!==t.constructor)return!1;var a,s,o;if(Array.isArray(r)){if((a=r.length)!=t.length)return!1;for(s=a;0!=s--;)if(!e(r[s],t[s]))return!1}else{if(r.constructor===RegExp)return r.source===t.source&&r.flags===t.flags;if(r.valueOf!==Object.prototype.valueOf)return r.valueOf()===t.valueOf();if(r.toString!==Object.prototype.toString)return r.toString()===t.toString();if((a=(o=Object.keys(r)).length)!==Object.keys(t).length)return!1;for(s=a;0!=s--;)if(!Object.prototype.hasOwnProperty.call(t,o[s]))return!1;for(s=a;0!=s--;){var i=o[s];if(!e(r[i],t[i]))return!1}}return!0}return r!=r&&t!=t}},{}],43:[function(e,r,t){r.exports=function(e,r){var a,l="boolean"==typeof(r="function"==typeof(r=r||{})?{cmp:r}:r).cycles&&r.cycles,c=r.cmp&&(a=r.cmp,function(t){return function(e,r){return a({key:e,value:t[e]},{key:r,value:t[r]})}}),u=[];return function e(r){if(void 0!==(r=r&&r.toJSON&&"function"==typeof r.toJSON?r.toJSON():r)){if("number"==typeof r)return isFinite(r)?""+r:"null";if("object"!=typeof r)return JSON.stringify(r);if(Array.isArray(r)){for(s="[",o=0;o<r.length;o++)o&&(s+=","),s+=e(r[o])||"null";return s+"]"}if(null===r)return"null";if(-1!==u.indexOf(r)){if(l)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}for(var t=u.push(r)-1,a=Object.keys(r).sort(c&&c(r)),s="",o=0;o<a.length;o++){var i=a[o],n=e(r[i]);n&&(s&&(s+=","),s+=JSON.stringify(i)+":"+n)}return u.splice(t,1),"{"+s+"}"}}(e)}},{}],44:[function(e,r,t){var m=r.exports=function(e,r,t){"function"==typeof r&&(t=r,r={}),function e(r,t,a,s,o,i,n,l,c,u){if(s&&"object"==typeof s&&!Array.isArray(s)){for(var h in t(s,o,i,n,l,c,u),s){var d=s[h];if(Array.isArray(d)){if(h in m.arrayKeywords)for(var p=0;p<d.length;p++)e(r,t,a,d[p],o+"/"+h+"/"+p,i,o,h,s,p)}else if(h in m.propsKeywords){if(d&&"object"==typeof d)for(var f in d)e(r,t,a,d[f],o+"/"+h+"/"+v(f),i,o,h,s,f)}else(h in m.keywords||r.allKeys&&!(h in m.skipKeywords))&&e(r,t,a,d,o+"/"+h,i,o,h,s)}a(s,o,i,n,l,c,u)}}(r,"function"==typeof(t=r.cb||t)?t:t.pre||function(){},t.post||function(){},e,"",e)};function v(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}m.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0},m.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},m.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},m.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0}},{}],45:[function(e,r,t){var a;a=this,function(e){function g(){for(var e=arguments.length,r=Array(e),t=0;t<e;t++)r[t]=arguments[t];if(1<r.length){r[0]=r[0].slice(0,-1);for(var a=r.length-1,s=1;s<a;++s)r[s]=r[s].slice(1,-1);return r[a]=r[a].slice(1),r.join("")}return r[0]}function P(e){return"(?:"+e+")"}function a(e){return void 0===e?"undefined":null===e?"null":Object.prototype.toString.call(e).split(" ").pop().split("]").shift().toLowerCase()}function p(e){return e.toUpperCase()}function r(e){var r="[A-Za-z]",t="[0-9]",a=g(t,"[A-Fa-f]"),s=P(P("%[EFef]"+a+"%"+a+a+"%"+a+a)+"|"+P("%[89A-Fa-f]"+a+"%"+a+a)+"|"+P("%"+a+a)),o="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",i=g("[\\:\\/\\?\\#\\[\\]\\@]",o),n=e?"[\\uE000-\\uF8FF]":"[]",e=g(r,t,"[\\-\\.\\_\\~]",e?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]"),l=(P(r+g(r,t,"[\\+\\-\\.]")+"*"),P(P(s+"|"+g(e,o,"[\\:]"))+"*"),P("(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9][0-9])|(?:0?[1-9][0-9])|0?0?"+t)),l=P(l+"\\."+l+"\\."+l+"\\."+l),c=P(a+"{1,4}"),u=P(P(c+"\\:"+c)+"|"+l),h=P(P(c+"\\:")+"{6}"+u),d=P("\\:\\:"+P(c+"\\:")+"{5}"+u),p=P(P(c)+"?\\:\\:"+P(c+"\\:")+"{4}"+u),f=P(P(P(c+"\\:")+"{0,1}"+c)+"?\\:\\:"+P(c+"\\:")+"{3}"+u),m=P(P(P(c+"\\:")+"{0,2}"+c)+"?\\:\\:"+P(c+"\\:")+"{2}"+u),v=P(P(P(c+"\\:")+"{0,3}"+c)+"?\\:\\:"+c+"\\:"+u),u=P(P(P(c+"\\:")+"{0,4}"+c)+"?\\:\\:"+u),y=P(P(P(c+"\\:")+"{0,5}"+c)+"?\\:\\:"+c),c=P(P(P(c+"\\:")+"{0,6}"+c)+"?\\:\\:"),h=P([h,d,p,f,m,v,u,y,c].join("|")),d=P(P(e+"|"+s)+"+"),p=(P("[vV]"+a+"+\\."+g(e,o,"[\\:]")+"+"),P(P(s+"|"+g(e,o))+"*"),P(s+"|"+g(e,o,"[\\:\\@]")));P(P(s+"|"+g(e,o,"[\\@]"))+"+"),P(P(p+"|"+g("[\\/\\?]",n))+"*");return{NOT_SCHEME:new RegExp(g("[^]",r,t,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(g("[^\\%\\:]",e,o),"g"),NOT_HOST:new RegExp(g("[^\\%\\[\\]\\:]",e,o),"g"),NOT_PATH:new RegExp(g("[^\\%\\/\\:\\@]",e,o),"g"),NOT_PATH_NOSCHEME:new RegExp(g("[^\\%\\/\\@]",e,o),"g"),NOT_QUERY:new RegExp(g("[^\\%]",e,o,"[\\:\\@\\/\\?]",n),"g"),NOT_FRAGMENT:new RegExp(g("[^\\%]",e,o,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(g("[^]",e,o),"g"),UNRESERVED:new RegExp(e,"g"),OTHER_CHARS:new RegExp(g("[^\\%]",e,i),"g"),PCT_ENCODED:new RegExp(s,"g"),IPV4ADDRESS:new RegExp("^("+l+")$"),IPV6ADDRESS:new RegExp("^\\[?("+h+")"+P(P("\\%25|\\%(?!"+a+"{2})")+"("+d+")")+"?\\]?$")}}var n=r(!1),l=r(!0),h=function(e,r){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e)){var t=r,a=[],s=!0,r=!1,o=void 0;try{for(var i,n=e[Symbol.iterator]();!(s=(i=n.next()).done)&&(a.push(i.value),!t||a.length!==t);s=!0);}catch(e){r=!0,o=e}finally{try{!s&&n.return&&n.return()}finally{if(r)throw o}}return a}throw new TypeError("Invalid attempt to destructure non-iterable instance")},O=2147483647,I=36,A=26,$=38,j=700,D=/^xn--/,q=/[^\0-\x7E]/,T=/[\x2E\u3002\uFF0E\uFF61]/g,Q={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},s=I-1,k=Math.floor,C=String.fromCharCode;function L(e){throw new RangeError(Q[e])}function t(e,r){var t=e.split("@"),a="",t=(1<t.length&&(a=t[0]+"@",e=t[1]),(e=e.replace(T,".")).split("."));return a+((e,r)=>{for(var t=[],a=e.length;a--;)t[a]=r(e[a]);return t})(t,r).join(".")}function V(e){for(var r=[],t=0,a=e.length;t<a;){var s,o=e.charCodeAt(t++);55296<=o&&o<=56319&&t<a?56320==(64512&(s=e.charCodeAt(t++)))?r.push(((1023&o)<<10)+(1023&s)+65536):(r.push(o),t--):r.push(o)}return r}function N(e,r){return e+22+75*(e<26)-((0!=r)<<5)}function z(e,r,t){var a=0;for(e=t?k(e/j):e>>1,e+=k(e/r);s*A>>1<e;a+=I)e=k(e/s);return k(a+(s+1)*e/(e+$))}function U(e){var r=[],t=e.length,a=0,s=128,o=72,i=e.lastIndexOf("-");i<0&&(i=0);for(var n=0;n<i;++n)128<=e.charCodeAt(n)&&L("not-basic"),r.push(e.charCodeAt(n));for(var l=0<i?i+1:0;l<t;){for(var c=a,u=1,h=I;;h+=I){t<=l&&L("invalid-input");var d=(d=e.charCodeAt(l++))-48<10?d-22:d-65<26?d-65:d-97<26?d-97:I,p=((I<=d||d>k((O-a)/u))&&L("overflow"),a+=d*u,h<=o?1:o+A<=h?A:h-o);if(d<p)break;d=I-p;u>k(O/d)&&L("overflow"),u*=d}var f=r.length+1,o=z(a-c,f,0==c);k(a/f)>O-s&&L("overflow"),s+=k(a/f),a%=f,r.splice(a++,0,s)}return String.fromCodePoint.apply(String,r)}function H(e){var r=[],t=(e=V(e)).length,a=128,s=0,o=72,i=!0,n=!1,l=void 0;try{for(var c,u=e[Symbol.iterator]();!(i=(c=u.next()).done);i=!0){var h=c.value;h<128&&r.push(C(h))}}catch(e){n=!0,l=e}finally{try{!i&&u.return&&u.return()}finally{if(n)throw l}}var d=r.length,p=d;for(d&&r.push("-");p<t;){var f=O,m=!0,v=!1,y=void 0;try{for(var g,P=e[Symbol.iterator]();!(m=(g=P.next()).done);m=!0){var E=g.value;a<=E&&E<f&&(f=E)}}catch(e){v=!0,y=e}finally{try{!m&&P.return&&P.return()}finally{if(v)throw y}}var w=p+1,b=(f-a>k((O-s)/w)&&L("overflow"),s+=(f-a)*w,a=f,!0),v=!1,y=void 0;try{for(var S,_=e[Symbol.iterator]();!(b=(S=_.next()).done);b=!0){var F=S.value;if(F<a&&++s>O&&L("overflow"),F==a){for(var x=s,R=I;;R+=I){var $=R<=o?1:o+A<=R?A:R-o;if(x<$)break;var j=x-$,D=I-$;r.push(C(N($+j%D,0))),x=k(j/D)}r.push(C(N(x,0))),o=z(s,w,p==d),s=0,++p}}}catch(e){v=!0,y=e}finally{try{!b&&_.return&&_.return()}finally{if(v)throw y}}++s,++a}return r.join("")}var v=function(e){return t(e,function(e){return q.test(e)?"xn--"+H(e):e})},M=function(e){return t(e,function(e){return D.test(e)?U(e.slice(4).toLowerCase()):e})},c={};function f(e){e=e.charCodeAt(0);return e<16?"%0"+e.toString(16).toUpperCase():e<128?"%"+e.toString(16).toUpperCase():e<2048?"%"+(e>>6|192).toString(16).toUpperCase()+"%"+(63&e|128).toString(16).toUpperCase():"%"+(e>>12|224).toString(16).toUpperCase()+"%"+(e>>6&63|128).toString(16).toUpperCase()+"%"+(63&e|128).toString(16).toUpperCase()}function u(e){for(var r="",t=0,a=e.length;t<a;){var s,o,i=parseInt(e.substr(t+1,2),16);i<128?(r+=String.fromCharCode(i),t+=3):194<=i&&i<224?(6<=a-t?(s=parseInt(e.substr(t+4,2),16),r+=String.fromCharCode((31&i)<<6|63&s)):r+=e.substr(t,6),t+=6):224<=i?(9<=a-t?(s=parseInt(e.substr(t+4,2),16),o=parseInt(e.substr(t+7,2),16),r+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)):r+=e.substr(t,9),t+=9):(r+=e.substr(t,3),t+=3)}return r}function d(e,t){function r(e){var r=u(e);return r.match(t.UNRESERVED)?r:e}e.scheme&&(e.scheme=String(e.scheme).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_SCHEME,"")),void 0!==e.userinfo&&(e.userinfo=String(e.userinfo).replace(t.PCT_ENCODED,r).replace(t.NOT_USERINFO,f).replace(t.PCT_ENCODED,p)),void 0!==e.host&&(e.host=String(e.host).replace(t.PCT_ENCODED,r).toLowerCase().replace(t.NOT_HOST,f).replace(t.PCT_ENCODED,p)),void 0!==e.path&&(e.path=String(e.path).replace(t.PCT_ENCODED,r).replace(e.scheme?t.NOT_PATH:t.NOT_PATH_NOSCHEME,f).replace(t.PCT_ENCODED,p)),void 0!==e.query&&(e.query=String(e.query).replace(t.PCT_ENCODED,r).replace(t.NOT_QUERY,f).replace(t.PCT_ENCODED,p)),void 0!==e.fragment&&(e.fragment=String(e.fragment).replace(t.PCT_ENCODED,r).replace(t.NOT_FRAGMENT,f).replace(t.PCT_ENCODED,p))}function m(e){return e.replace(/^0*(.*)/,"$1")||"0"}function y(e,r){r=e.match(r.IPV4ADDRESS)||[],r=h(r,2)[1];return r?r.split(".").map(m).join("."):e}function K(e,r){var t=e.match(r.IPV6ADDRESS)||[],t=h(t,3),a=t[1],t=t[2];if(a){for(var a=a.toLowerCase().split("::").reverse(),a=h(a,2),s=a[0],a=a[1],o=a?a.split(":").map(m):[],i=s.split(":").map(m),a=r.IPV4ADDRESS.test(i[i.length-1]),n=a?7:8,l=i.length-n,c=Array(n),u=0;u<n;++u)c[u]=o[u]||i[l+u]||"";a&&(c[n-1]=y(c[n-1],r));var s=c.reduce(function(e,r,t){return r&&"0"!==r||((r=e[e.length-1])&&r.index+r.length===t?r.length++:e.push({index:t,length:1})),e},[]).sort(function(e,r){return r.length-e.length})[0],a=void 0;return a=s&&1<s.length?(r=c.slice(0,s.index),s=c.slice(s.index+s.length),r.join(":")+"::"+s.join(":")):c.join(":"),t&&(a+="%"+t),a}return e}var B=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,J=void 0==="".match(/(){0}/)[1];function o(e){var r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},t={},a=!1!==r.iri?l:n,s=(e="suffix"===r.reference?(r.scheme?r.scheme+":":"")+"//"+e:e).match(B);if(s){J?(t.scheme=s[1],t.userinfo=s[3],t.host=s[4],t.port=parseInt(s[5],10),t.path=s[6]||"",t.query=s[7],t.fragment=s[8],isNaN(t.port)&&(t.port=s[5])):(t.scheme=s[1]||void 0,t.userinfo=-1!==e.indexOf("@")?s[3]:void 0,t.host=-1!==e.indexOf("//")?s[4]:void 0,t.port=parseInt(s[5],10),t.path=s[6]||"",t.query=-1!==e.indexOf("?")?s[7]:void 0,t.fragment=-1!==e.indexOf("#")?s[8]:void 0,isNaN(t.port)&&(t.port=e.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?s[4]:void 0)),t.host&&(t.host=K(y(t.host,a),a)),t.reference=void 0!==t.scheme||void 0!==t.userinfo||void 0!==t.host||void 0!==t.port||t.path||void 0!==t.query?void 0===t.scheme?"relative":void 0===t.fragment?"absolute":"uri":"same-document",r.reference&&"suffix"!==r.reference&&r.reference!==t.reference&&(t.error=t.error||"URI is not a "+r.reference+" reference.");e=c[(r.scheme||t.scheme||"").toLowerCase()];if(r.unicodeSupport||e&&e.unicodeSupport)d(t,a);else{if(t.host&&(r.domainHost||e&&e.domainHost))try{t.host=v(t.host.replace(a.PCT_ENCODED,u).toLowerCase())}catch(e){t.error=t.error||"Host's domain name can not be converted to ASCII via punycode: "+e}d(t,n)}e&&e.parse&&e.parse(t,r)}else t.error=t.error||"URI can not be parsed.";return t}var Z=/^\.\.?\//,G=/^\/\.(\/|$)/,Y=/^\/\.\.(\/|$)/,W=/^\/?(?:.|\n)*?(?=\/|$)/;function E(e){for(var r=[];e.length;)if(e.match(Z))e=e.replace(Z,"");else if(e.match(G))e=e.replace(G,"/");else if(e.match(Y))e=e.replace(Y,"/"),r.pop();else if("."===e||".."===e)e="";else{var t=e.match(W);if(!t)throw new Error("Unexpected dot segment condition");t=t[0];e=e.slice(t.length),r.push(t)}return r.join("")}function i(r){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=t.iri?l:n,a=[],s=c[(t.scheme||r.scheme||"").toLowerCase()];if(s&&s.serialize&&s.serialize(r,t),r.host&&!e.IPV6ADDRESS.test(r.host)&&(t.domainHost||s&&s.domainHost))try{r.host=t.iri?M(r.host):v(r.host.replace(e.PCT_ENCODED,u).toLowerCase())}catch(e){r.error=r.error||"Host's domain name can not be converted to "+(t.iri?"Unicode":"ASCII")+" via punycode: "+e}d(r,e),"suffix"!==t.reference&&r.scheme&&(a.push(r.scheme),a.push(":"));e=!1!==(e=t).iri?l:n,o=[],void 0!==(i=r).userinfo&&(o.push(i.userinfo),o.push("@")),void 0!==i.host&&o.push(K(y(String(i.host),e),e).replace(e.IPV6ADDRESS,function(e,r,t){return"["+r+(t?"%25"+t:"")+"]"})),"number"!=typeof i.port&&"string"!=typeof i.port||(o.push(":"),o.push(String(i.port)));var o,i,e=o.length?o.join(""):void 0;return void 0!==e&&("suffix"!==t.reference&&a.push("//"),a.push(e),r.path)&&"/"!==r.path.charAt(0)&&a.push("/"),void 0!==r.path&&(i=r.path,t.absolutePath||s&&s.absolutePath||(i=E(i)),void 0===e&&(i=i.replace(/^\/\//,"/%2F")),a.push(i)),void 0!==r.query&&(a.push("?"),a.push(r.query)),void 0!==r.fragment&&(a.push("#"),a.push(r.fragment)),a.join("")}function X(e,r){var t=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},a={};return arguments[3]||(e=o(i(e,t),t),r=o(i(r,t),t)),!(t||{}).tolerant&&r.scheme?(a.scheme=r.scheme,a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=E(r.path||""),a.query=r.query):(void 0!==r.userinfo||void 0!==r.host||void 0!==r.port?(a.userinfo=r.userinfo,a.host=r.host,a.port=r.port,a.path=E(r.path||""),a.query=r.query):(r.path?("/"===r.path.charAt(0)?a.path=E(r.path):(a.path=void 0===e.userinfo&&void 0===e.host&&void 0===e.port||e.path?e.path?e.path.slice(0,e.path.lastIndexOf("/")+1)+r.path:r.path:"/"+r.path,a.path=E(a.path)),a.query=r.query):(a.path=e.path,a.query=(void 0!==r.query?r:e).query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=r.fragment,a}function w(e,r){return e&&e.toString().replace((r&&r.iri?l:n).PCT_ENCODED,u)}var b={scheme:"http",domainHost:!0,parse:function(e,r){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e},serialize:function(e,r){var t="https"===String(e.scheme).toLowerCase();return e.port!==(t?443:80)&&""!==e.port||(e.port=void 0),e.path||(e.path="/"),e}},ee={scheme:"https",domainHost:b.domainHost,parse:b.parse,serialize:b.serialize};function re(e){return"boolean"==typeof e.secure?e.secure:"wss"===String(e.scheme).toLowerCase()}var S={scheme:"ws",domainHost:!0,parse:function(e,r){return e.secure=re(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e},serialize:function(e,r){var t,a;return e.port!==(re(e)?443:80)&&""!==e.port||(e.port=void 0),"boolean"==typeof e.secure&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName&&(t=e.resourceName.split("?"),a=(t=h(t,2))[1],e.path=(t=t[0])&&"/"!==t?t:void 0,e.query=a,e.resourceName=void 0),e.fragment=void 0,e}},te={scheme:"wss",domainHost:S.domainHost,parse:S.parse,serialize:S.serialize},ae={},_="[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]",F=g("[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",'[\\"\\\\]'),se=new RegExp(_,"g"),x=new RegExp("(?:(?:%[EFef][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[89A-Fa-f][0-9A-Fa-f]%[0-9A-Fa-f][0-9A-Fa-f])|(?:%[0-9A-Fa-f][0-9A-Fa-f]))","g"),oe=new RegExp(g("[^]","[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]","[\\.]",'[\\"]',F),"g"),ie=new RegExp(g("[^]",_,"[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"),"g"),ne=ie;function R(e){var r=u(e);return r.match(se)?r:e}var F={scheme:"mailto",parse:function(e,r){var t=e,a=t.to=t.path?t.path.split(","):[];if(t.path=void 0,t.query){for(var s=!1,o={},i=t.query.split("&"),n=0,l=i.length;n<l;++n){var c=i[n].split("=");switch(c[0]){case"to":for(var u=c[1].split(","),h=0,d=u.length;h<d;++h)a.push(u[h]);break;case"subject":t.subject=w(c[1],r);break;case"body":t.body=w(c[1],r);break;default:s=!0,o[w(c[0],r)]=w(c[1],r)}}s&&(t.headers=o)}t.query=void 0;for(var p=0,f=a.length;p<f;++p){var m=a[p].split("@");if(m[0]=w(m[0]),r.unicodeSupport)m[1]=w(m[1],r).toLowerCase();else try{m[1]=v(w(m[1],r).toLowerCase())}catch(e){t.error=t.error||"Email address's domain name can not be converted to ASCII via punycode: "+e}a[p]=m.join("@")}return t},serialize:function(e,r){var t,a=e,s=null!=(t=e.to)?t instanceof Array?t:"number"!=typeof t.length||t.split||t.setInterval||t.call?[t]:Array.prototype.slice.call(t):[];if(s){for(var o=0,i=s.length;o<i;++o){var n=String(s[o]),l=n.lastIndexOf("@"),c=n.slice(0,l).replace(x,R).replace(x,p).replace(oe,f),n=n.slice(l+1);try{n=r.iri?M(n):v(w(n,r).toLowerCase())}catch(e){a.error=a.error||"Email address's domain name can not be converted to "+(r.iri?"Unicode":"ASCII")+" via punycode: "+e}s[o]=c+"@"+n}a.path=s.join(",")}var u,h=e.headers=e.headers||{},d=(e.subject&&(h.subject=e.subject),e.body&&(h.body=e.body),[]);for(u in h)h[u]!==ae[u]&&d.push(u.replace(x,R).replace(x,p).replace(ie,f)+"="+h[u].replace(x,R).replace(x,p).replace(ne,f));return d.length&&(a.query=d.join("&")),a}},le=/^([^\:]+)\:(.*)/,_={scheme:"urn",parse:function(e,r){var t,a,s=e.path&&e.path.match(le);return s?(a=r.scheme||e.scheme||"urn",t=s[1].toLowerCase(),s=s[2],a=c[a+":"+(r.nid||t)],e.nid=t,e.nss=s,e.path=void 0,a&&(e=a.parse(e,r))):e.error=e.error||"URN can not be parsed.",e},serialize:function(e,r){var t=e.nid,a=c[(r.scheme||e.scheme||"urn")+":"+(r.nid||t)],a=e=a?a.serialize(e,r):e;return a.path=(t||r.nid)+":"+e.nss,a}},ce=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,ue={scheme:"urn:uuid",parse:function(e,r){return e.uuid=e.nss,e.nss=void 0,r.tolerant||e.uuid&&e.uuid.match(ce)||(e.error=e.error||"UUID is not valid."),e},serialize:function(e,r){var t=e;return t.nss=(e.uuid||"").toLowerCase(),t}};c[b.scheme]=b,c[ee.scheme]=ee,c[S.scheme]=S,c[te.scheme]=te,c[F.scheme]=F,c[_.scheme]=_,c[ue.scheme]=ue,e.SCHEMES=c,e.pctEncChar=f,e.pctDecChars=u,e.parse=o,e.removeDotSegments=E,e.serialize=i,e.resolveComponents=X,e.resolve=function(e,r,t){return t=((e,r)=>{var t=e;if(r)for(var a in r)t[a]=r[a];return t})({scheme:"null"},t),i(X(o(e,t),o(r,t),t,!0),t)},e.normalize=function(e,r){return"string"==typeof e?e=i(o(e,r),r):"object"===a(e)&&(e=o(i(e,r),r)),e},e.equal=function(e,r,t){return"string"==typeof e?e=i(o(e,t),t):"object"===a(e)&&(e=i(e,t)),"string"==typeof r?r=i(o(r,t),t):"object"===a(r)&&(r=i(r,t)),e===r},e.escapeComponent=function(e,r){return e&&e.toString().replace((r&&r.iri?l:n).ESCAPE,f)},e.unescapeComponent=w,Object.defineProperty(e,"__esModule",{value:!0})}("object"==typeof t&&void 0!==r?t:a.URI=a.URI||{})},{}],ajv:[function(h,e,r){var i=h("./compile"),l=h("./compile/resolve"),d=h("./cache"),c=h("./compile/schema_obj"),p=h("fast-json-stable-stringify"),f=h("./compile/formats"),m=h("./compile/rules"),v=h("./data"),y=h("./compile/util"),e=((e.exports=w).prototype.validate=function(e,r){var t;if("string"==typeof e){if(!(t=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{e=this._addSchema(e);t=e.validate||this._compile(e)}e=t(r);!0!==t.$async&&(this.errors=t.errors);return e},w.prototype.compile=function(e,r){e=this._addSchema(e,void 0,r);return e.validate||this._compile(e)},w.prototype.addSchema=function(e,r,t,a){if(Array.isArray(e))for(var s=0;s<e.length;s++)this.addSchema(e[s],void 0,t,a);else{var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");u(this,r=l.normalizeId(r||o)),this._schemas[r]=this._addSchema(e,t,a,!0)}return this},w.prototype.addMetaSchema=function(e,r,t){return this.addSchema(e,r,t,!0),this},w.prototype.validateSchema=function(e,r){var t=e.$schema;if(void 0!==t&&"string"!=typeof t)throw new Error("$schema must be a string");if(!(t=t||this._opts.defaultMeta||(e=>{var r=e._opts.meta;return e._opts.defaultMeta="object"==typeof r?e._getId(r)||r:e.getSchema(g)?g:void 0,e._opts.defaultMeta})(this)))return this.logger.warn("meta-schema not available"),!(this.errors=null);t=this.validate(t,e);if(!t&&r){e="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(e);this.logger.error(e)}return t},w.prototype.getSchema=function(e){var r=t(this,e);switch(typeof r){case"object":return r.validate||this._compile(r);case"string":return this.getSchema(r);case"undefined":return((e,r)=>{var t,a,s,o=l.schema.call(e,{schema:{}},r);if(o)return s=i.call(e,t=o.schema,a=o.root,void 0,o=o.baseId),e._fragments[r]=new c({ref:r,fragment:!0,schema:t,root:a,baseId:o,validate:s}),s})(this,e)}},w.prototype.removeSchema=function(e){if(e instanceof RegExp)a(this,this._schemas,e),a(this,this._refs,e);else switch(typeof e){case"undefined":return a(this,this._schemas),a(this,this._refs),this._cache.clear(),this;case"string":var r=t(this,e);return r&&this._cache.del(r.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":r=this._opts.serialize,r=r?r(e):e,r=(this._cache.del(r),this._getId(e));r&&(r=l.normalizeId(r),delete this._schemas[r],delete this._refs[r])}return this},w.prototype.addFormat=function(e,r){"string"==typeof r&&(r=new RegExp(r));return this._formats[e]=r,this},w.prototype.errorsText=function(e,r){if(!(e=e||this.errors))return"No errors";for(var t=void 0===(r=r||{}).separator?", ":r.separator,a=void 0===r.dataVar?"data":r.dataVar,s="",o=0;o<e.length;o++){var i=e[o];i&&(s+=a+i.dataPath+" "+i.message+t)}return s.slice(0,-t.length)},w.prototype._addSchema=function(e,r,t,a){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var s=this._opts.serialize,s=s?s(e):e,o=this._cache.get(s);if(o)return o;a=a||!1!==this._opts.addUsedSchema;o=l.normalizeId(this._getId(e));o&&a&&u(this,o);var i,r=!1!==this._opts.validateSchema&&!r;r&&!(i=o&&o==l.normalizeId(e.$schema))&&this.validateSchema(e,!0);var n=l.ids.call(this,e),n=new c({id:o,schema:e,localRefs:n,cacheKey:s,meta:t});"#"!=o[0]&&a&&(this._refs[o]=n);this._cache.put(s,n),r&&i&&this.validateSchema(e,!0);return n},w.prototype._compile=function(t,e){if(t.compiling)return(t.validate=s).schema=t.schema,s.errors=null,s.root=e||s,!0===t.schema.$async&&(s.$async=!0),s;var r,a;t.compiling=!0,t.meta&&(r=this._opts,this._opts=this._metaOpts);try{a=i.call(this,t.schema,e,t.localRefs)}catch(e){throw delete t.validate,e}finally{t.compiling=!1,t.meta&&(this._opts=r)}return t.validate=a,t.refs=a.refs,t.refVal=a.refVal,t.root=a.root,a;function s(){var e=t.validate,r=e.apply(this,arguments);return s.errors=e.errors,r}},w.prototype.compileAsync=h("./compile/async"),h("./keyword")),e=(w.prototype.addKeyword=e.add,w.prototype.getKeyword=e.get,w.prototype.removeKeyword=e.remove,w.prototype.validateKeyword=e.validate,h("./compile/error_classes")),g=(w.ValidationError=e.Validation,w.MissingRefError=e.MissingRef,w.$dataMetaSchema=v,"http://json-schema.org/draft-07/schema"),P=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],E=["/properties"];function w(e){if(!(this instanceof w))return new w(e);e=this._opts=y.copy(e)||{};var r=this,t=r._opts.logger;if(!1===t)r.logger={log:F,warn:F,error:F};else{if(!("object"==typeof(t=void 0===t?console:t)&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");r.logger=t}if(this._schemas={},this._refs={},this._fragments={},this._formats=f(e.format),this._cache=e.cache||new d,this._loadingSchemas={},this._compilations=[],this.RULES=m(),this._getId=(e=>{switch(e.schemaId){case"auto":return _;case"id":return b;default:return S}})(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=p),this._metaOpts=(e=>{for(var r=y.copy(e._opts),t=0;t<P.length;t++)delete r[P[t]];return r})(this),e.formats){var a,s=this;for(a in s._opts.formats)s.addFormat(a,s._opts.formats[a])}if(e.keywords){var o,i=this;for(o in i._opts.keywords)i.addKeyword(o,i._opts.keywords[o])}var n,r=this,l=(r._opts.$data&&(n=h("./refs/data.json"),r.addMetaSchema(n,n.$id,!0)),!1!==r._opts.meta&&(n=h("./refs/json-schema-draft-07.json"),r._opts.$data&&(n=v(n,E)),r.addMetaSchema(n,g,!0),r._refs["http://json-schema.org/schema"]=g),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),this),c=l._opts.schemas;if(c)if(Array.isArray(c))l.addSchema(c);else for(var u in c)l.addSchema(c[u],u)}function t(e,r){return r=l.normalizeId(r),e._schemas[r]||e._refs[r]||e._fragments[r]}function a(e,r,t){for(var a in r){var s=r[a];s.meta||t&&!t.test(a)||(e._cache.del(s.cacheKey),delete r[a])}}function b(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function S(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function _(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function u(e,r){if(e._schemas[r]||e._refs[r])throw new Error('schema with key or id "'+r+'" already exists')}function F(){}},{"./cache":1,"./compile":5,"./compile/async":2,"./compile/error_classes":3,"./compile/formats":4,"./compile/resolve":6,"./compile/rules":7,"./compile/schema_obj":8,"./compile/util":10,"./data":11,"./keyword":39,"./refs/data.json":40,"./refs/json-schema-draft-07.json":41,"fast-json-stable-stringify":43}]},{},[])("ajv")});
//# sourceMappingURL=ajv.min.js.map'use strict';

var compileSchema = require('./compile')
  , resolve = require('./compile/resolve')
  , Cache = require('./cache')
  , SchemaObject = require('./compile/schema_obj')
  , stableStringify = require('fast-json-stable-stringify')
  , formats = require('./compile/formats')
  , rules = require('./compile/rules')
  , $dataMetaSchema = require('./data')
  , util = require('./compile/util');

module.exports = Ajv;

Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;

Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;

Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;

var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;

var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';

var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];

/**
 * Creates validator instance.
 * Usage: `Ajv(opts)`
 * @param {Object} opts optional options
 * @return {Object} ajv instance
 */
function Ajv(opts) {
  if (!(this instanceof Ajv)) return new Ajv(opts);
  opts = this._opts = util.copy(opts) || {};
  setLogger(this);
  this._schemas = {};
  this._refs = {};
  this._fragments = {};
  this._formats = formats(opts.format);

  this._cache = opts.cache || new Cache;
  this._loadingSchemas = {};
  this._compilations = [];
  this.RULES = rules();
  this._getId = chooseGetId(opts);

  opts.loopRequired = opts.loopRequired || Infinity;
  if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  if (opts.serialize === undefined) opts.serialize = stableStringify;
  this._metaOpts = getMetaSchemaOptions(this);

  if (opts.formats) addInitialFormats(this);
  if (opts.keywords) addInitialKeywords(this);
  addDefaultMetaSchema(this);
  if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
  addInitialSchemas(this);
}



/**
 * Validate data using schema
 * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
 * @this   Ajv
 * @param  {String|Object} schemaKeyRef key, ref or schema object
 * @param  {Any} data to be validated
 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
 */
function validate(schemaKeyRef, data) {
  var v;
  if (typeof schemaKeyRef == 'string') {
    v = this.getSchema(schemaKeyRef);
    if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  } else {
    var schemaObj = this._addSchema(schemaKeyRef);
    v = schemaObj.validate || this._compile(schemaObj);
  }

  var valid = v(data);
  if (v.$async !== true) this.errors = v.errors;
  return valid;
}


/**
 * Create validating function for passed schema.
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
 * @return {Function} validating function
 */
function compile(schema, _meta) {
  var schemaObj = this._addSchema(schema, undefined, _meta);
  return schemaObj.validate || this._compile(schemaObj);
}


/**
 * Adds schema to the instance.
 * @this   Ajv
 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
 * @return {Ajv} this for method chaining
 */
function addSchema(schema, key, _skipValidation, _meta) {
  if (Array.isArray(schema)){
    for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
    return this;
  }
  var id = this._getId(schema);
  if (id !== undefined && typeof id != 'string')
    throw new Error('schema id must be string');
  key = resolve.normalizeId(key || id);
  checkUnique(this, key);
  this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  return this;
}


/**
 * Add schema that will be used to validate other schemas
 * options in META_IGNORE_OPTIONS are alway set to false
 * @this   Ajv
 * @param {Object} schema schema object
 * @param {String} key optional schema key
 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
 * @return {Ajv} this for method chaining
 */
function addMetaSchema(schema, key, skipValidation) {
  this.addSchema(schema, key, skipValidation, true);
  return this;
}


/**
 * Validate schema
 * @this   Ajv
 * @param {Object} schema schema to validate
 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
 * @return {Boolean} true if schema is valid
 */
function validateSchema(schema, throwOrLogError) {
  var $schema = schema.$schema;
  if ($schema !== undefined && typeof $schema != 'string')
    throw new Error('$schema must be a string');
  $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  if (!$schema) {
    this.logger.warn('meta-schema not available');
    this.errors = null;
    return true;
  }
  var valid = this.validate($schema, schema);
  if (!valid && throwOrLogError) {
    var message = 'schema is invalid: ' + this.errorsText();
    if (this._opts.validateSchema == 'log') this.logger.error(message);
    else throw new Error(message);
  }
  return valid;
}


function defaultMeta(self) {
  var meta = self._opts.meta;
  self._opts.defaultMeta = typeof meta == 'object'
                            ? self._getId(meta) || meta
                            : self.getSchema(META_SCHEMA_ID)
                              ? META_SCHEMA_ID
                              : undefined;
  return self._opts.defaultMeta;
}


/**
 * Get compiled schema from the instance by `key` or `ref`.
 * @this   Ajv
 * @param  {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
 * @return {Function} schema validating function (with property `schema`).
 */
function getSchema(keyRef) {
  var schemaObj = _getSchemaObj(this, keyRef);
  switch (typeof schemaObj) {
    case 'object': return schemaObj.validate || this._compile(schemaObj);
    case 'string': return this.getSchema(schemaObj);
    case 'undefined': return _getSchemaFragment(this, keyRef);
  }
}


function _getSchemaFragment(self, ref) {
  var res = resolve.schema.call(self, { schema: {} }, ref);
  if (res) {
    var schema = res.schema
      , root = res.root
      , baseId = res.baseId;
    var v = compileSchema.call(self, schema, root, undefined, baseId);
    self._fragments[ref] = new SchemaObject({
      ref: ref,
      fragment: true,
      schema: schema,
      root: root,
      baseId: baseId,
      validate: v
    });
    return v;
  }
}


function _getSchemaObj(self, keyRef) {
  keyRef = resolve.normalizeId(keyRef);
  return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}


/**
 * Remove cached schema(s).
 * If no parameter is passed all schemas but meta-schemas are removed.
 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
 * @this   Ajv
 * @param  {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
 * @return {Ajv} this for method chaining
 */
function removeSchema(schemaKeyRef) {
  if (schemaKeyRef instanceof RegExp) {
    _removeAllSchemas(this, this._schemas, schemaKeyRef);
    _removeAllSchemas(this, this._refs, schemaKeyRef);
    return this;
  }
  switch (typeof schemaKeyRef) {
    case 'undefined':
      _removeAllSchemas(this, this._schemas);
      _removeAllSchemas(this, this._refs);
      this._cache.clear();
      return this;
    case 'string':
      var schemaObj = _getSchemaObj(this, schemaKeyRef);
      if (schemaObj) this._cache.del(schemaObj.cacheKey);
      delete this._schemas[schemaKeyRef];
      delete this._refs[schemaKeyRef];
      return this;
    case 'object':
      var serialize = this._opts.serialize;
      var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
      this._cache.del(cacheKey);
      var id = this._getId(schemaKeyRef);
      if (id) {
        id = resolve.normalizeId(id);
        delete this._schemas[id];
        delete this._refs[id];
      }
  }
  return this;
}


function _removeAllSchemas(self, schemas, regex) {
  for (var keyRef in schemas) {
    var schemaObj = schemas[keyRef];
    if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
      self._cache.del(schemaObj.cacheKey);
      delete schemas[keyRef];
    }
  }
}


/* @this   Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  if (typeof schema != 'object' && typeof schema != 'boolean')
    throw new Error('schema should be object or boolean');
  var serialize = this._opts.serialize;
  var cacheKey = serialize ? serialize(schema) : schema;
  var cached = this._cache.get(cacheKey);
  if (cached) return cached;

  shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;

  var id = resolve.normalizeId(this._getId(schema));
  if (id && shouldAddSchema) checkUnique(this, id);

  var willValidate = this._opts.validateSchema !== false && !skipValidation;
  var recursiveMeta;
  if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
    this.validateSchema(schema, true);

  var localRefs = resolve.ids.call(this, schema);

  var schemaObj = new SchemaObject({
    id: id,
    schema: schema,
    localRefs: localRefs,
    cacheKey: cacheKey,
    meta: meta
  });

  if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  this._cache.put(cacheKey, schemaObj);

  if (willValidate && recursiveMeta) this.validateSchema(schema, true);

  return schemaObj;
}


/* @this   Ajv */
function _compile(schemaObj, root) {
  if (schemaObj.compiling) {
    schemaObj.validate = callValidate;
    callValidate.schema = schemaObj.schema;
    callValidate.errors = null;
    callValidate.root = root ? root : callValidate;
    if (schemaObj.schema.$async === true)
      callValidate.$async = true;
    return callValidate;
  }
  schemaObj.compiling = true;

  var currentOpts;
  if (schemaObj.meta) {
    currentOpts = this._opts;
    this._opts = this._metaOpts;
  }

  var v;
  try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  catch(e) {
    delete schemaObj.validate;
    throw e;
  }
  finally {
    schemaObj.compiling = false;
    if (schemaObj.meta) this._opts = currentOpts;
  }

  schemaObj.validate = v;
  schemaObj.refs = v.refs;
  schemaObj.refVal = v.refVal;
  schemaObj.root = v.root;
  return v;


  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var _validate = schemaObj.validate;
    var result = _validate.apply(this, arguments);
    callValidate.errors = _validate.errors;
    return result;
  }
}


function chooseGetId(opts) {
  switch (opts.schemaId) {
    case 'auto': return _get$IdOrId;
    case 'id': return _getId;
    default: return _get$Id;
  }
}

/* @this   Ajv */
function _getId(schema) {
  if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
  return schema.id;
}

/* @this   Ajv */
function _get$Id(schema) {
  if (schema.id) this.logger.warn('schema id ignored', schema.id);
  return schema.$id;
}


function _get$IdOrId(schema) {
  if (schema.$id && schema.id && schema.$id != schema.id)
    throw new Error('schema $id is different from id');
  return schema.$id || schema.id;
}


/**
 * Convert array of error message objects to string
 * @this   Ajv
 * @param  {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
 * @param  {Object} options optional options with properties `separator` and `dataVar`.
 * @return {String} human readable string with all errors descriptions
 */
function errorsText(errors, options) {
  errors = errors || this.errors;
  if (!errors) return 'No errors';
  options = options || {};
  var separator = options.separator === undefined ? ', ' : options.separator;
  var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;

  var text = '';
  for (var i=0; i<errors.length; i++) {
    var e = errors[i];
    if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  }
  return text.slice(0, -separator.length);
}


/**
 * Add custom format
 * @this   Ajv
 * @param {String} name format name
 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
 * @return {Ajv} this for method chaining
 */
function addFormat(name, format) {
  if (typeof format == 'string') format = new RegExp(format);
  this._formats[name] = format;
  return this;
}


function addDefaultMetaSchema(self) {
  var $dataSchema;
  if (self._opts.$data) {
    $dataSchema = require('./refs/data.json');
    self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  }
  if (self._opts.meta === false) return;
  var metaSchema = require('./refs/json-schema-draft-07.json');
  if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}


function addInitialSchemas(self) {
  var optsSchemas = self._opts.schemas;
  if (!optsSchemas) return;
  if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}


function addInitialFormats(self) {
  for (var name in self._opts.formats) {
    var format = self._opts.formats[name];
    self.addFormat(name, format);
  }
}


function addInitialKeywords(self) {
  for (var name in self._opts.keywords) {
    var keyword = self._opts.keywords[name];
    self.addKeyword(name, keyword);
  }
}


function checkUnique(self, id) {
  if (self._schemas[id] || self._refs[id])
    throw new Error('schema with key or id "' + id + '" already exists');
}


function getMetaSchemaOptions(self) {
  var metaOpts = util.copy(self._opts);
  for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
    delete metaOpts[META_IGNORE_OPTIONS[i]];
  return metaOpts;
}


function setLogger(self) {
  var logger = self._opts.logger;
  if (logger === false) {
    self.logger = {log: noop, warn: noop, error: noop};
  } else {
    if (logger === undefined) logger = console;
    if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
      throw new Error('logger must implement log, warn and error methods');
    self.logger = logger;
  }
}


function noop() {}
'use strict';


var Cache = module.exports = function Cache() {
  this._cache = {};
};


Cache.prototype.put = function Cache_put(key, value) {
  this._cache[key] = value;
};


Cache.prototype.get = function Cache_get(key) {
  return this._cache[key];
};


Cache.prototype.del = function Cache_del(key) {
  delete this._cache[key];
};


Cache.prototype.clear = function Cache_clear() {
  this._cache = {};
};
'use strict';

var MissingRefError = require('./error_classes').MissingRef;

module.exports = compileAsync;


/**
 * Creates validating function for passed schema with asynchronous loading of missing schemas.
 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
 * @this  Ajv
 * @param {Object}   schema schema object
 * @param {Boolean}  meta optional true to compile meta-schema; this parameter can be skipped
 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
 * @return {Promise} promise that resolves with a validating function.
 */
function compileAsync(schema, meta, callback) {
  /* eslint no-shadow: 0 */
  /* global Promise */
  /* jshint validthis: true */
  var self = this;
  if (typeof this._opts.loadSchema != 'function')
    throw new Error('options.loadSchema should be a function');

  if (typeof meta == 'function') {
    callback = meta;
    meta = undefined;
  }

  var p = loadMetaSchemaOf(schema).then(function () {
    var schemaObj = self._addSchema(schema, undefined, meta);
    return schemaObj.validate || _compileAsync(schemaObj);
  });

  if (callback) {
    p.then(
      function(v) { callback(null, v); },
      callback
    );
  }

  return p;


  function loadMetaSchemaOf(sch) {
    var $schema = sch.$schema;
    return $schema && !self.getSchema($schema)
            ? compileAsync.call(self, { $ref: $schema }, true)
            : Promise.resolve();
  }


  function _compileAsync(schemaObj) {
    try { return self._compile(schemaObj); }
    catch(e) {
      if (e instanceof MissingRefError) return loadMissingSchema(e);
      throw e;
    }


    function loadMissingSchema(e) {
      var ref = e.missingSchema;
      if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');

      var schemaPromise = self._loadingSchemas[ref];
      if (!schemaPromise) {
        schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
        schemaPromise.then(removePromise, removePromise);
      }

      return schemaPromise.then(function (sch) {
        if (!added(ref)) {
          return loadMetaSchemaOf(sch).then(function () {
            if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
          });
        }
      }).then(function() {
        return _compileAsync(schemaObj);
      });

      function removePromise() {
        delete self._loadingSchemas[ref];
      }

      function added(ref) {
        return self._refs[ref] || self._schemas[ref];
      }
    }
  }
}
'use strict';

// do NOT remove this file - it would break pre-compiled schemas
// https://github.com/ajv-validator/ajv/issues/889
module.exports = require('fast-deep-equal');
'use strict';

var resolve = require('./resolve');

module.exports = {
  Validation: errorSubclass(ValidationError),
  MissingRef: errorSubclass(MissingRefError)
};


function ValidationError(errors) {
  this.message = 'validation failed';
  this.errors = errors;
  this.ajv = this.validation = true;
}


MissingRefError.message = function (baseId, ref) {
  return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};


function MissingRefError(baseId, ref, message) {
  this.message = message || MissingRefError.message(baseId, ref);
  this.missingRef = resolve.url(baseId, ref);
  this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}


function errorSubclass(Subclass) {
  Subclass.prototype = Object.create(Error.prototype);
  Subclass.prototype.constructor = Subclass;
  return Subclass;
}
'use strict';

var util = require('./util');

var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0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0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
// uri-template: https://tools.ietf.org/html/rfc6570
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
// For the source: https://gist.github.com/dperini/729294
// For test cases: https://mathiasbynens.be/demo/url-regex
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;


module.exports = formats;

function formats(mode) {
  mode = mode == 'full' ? 'full' : 'fast';
  return util.copy(formats[mode]);
}


formats.fast = {
  // date: http://tools.ietf.org/html/rfc3339#section-5.6
  date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
  // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
  time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
  'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
  // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
  uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
  'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
  'uri-template': URITEMPLATE,
  url: URL,
  // email (sources from jsen validator):
  // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
  // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
  email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
  hostname: HOSTNAME,
  // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-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:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  // uuid: http://tools.ietf.org/html/rfc4122
  uuid: UUID,
  // JSON-pointer: https://tools.ietf.org/html/rfc6901
  // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


formats.full = {
  date: date,
  time: time,
  'date-time': date_time,
  uri: uri,
  'uri-reference': URIREF,
  'uri-template': URITEMPLATE,
  url: URL,
  email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
  hostname: HOSTNAME,
  ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
  ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
  regex: regex,
  uuid: UUID,
  'json-pointer': JSON_POINTER,
  'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
  'relative-json-pointer': RELATIVE_JSON_POINTER
};


function isLeapYear(year) {
  // https://tools.ietf.org/html/rfc3339#appendix-C
  return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}


function date(str) {
  // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
  var matches = str.match(DATE);
  if (!matches) return false;

  var year = +matches[1];
  var month = +matches[2];
  var day = +matches[3];

  return month >= 1 && month <= 12 && day >= 1 &&
          day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
}


function time(str, full) {
  var matches = str.match(TIME);
  if (!matches) return false;

  var hour = matches[1];
  var minute = matches[2];
  var second = matches[3];
  var timeZone = matches[5];
  return ((hour <= 23 && minute <= 59 && second <= 59) ||
          (hour == 23 && minute == 59 && second == 60)) &&
         (!full || timeZone);
}


var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
  // http://tools.ietf.org/html/rfc3339#section-5.6
  var dateTime = str.split(DATE_TIME_SEPARATOR);
  return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}


var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
  // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
  return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}


var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
  if (Z_ANCHOR.test(str)) return false;
  try {
    new RegExp(str);
    return true;
  } catch(e) {
    return false;
  }
}
'use strict';

var resolve = require('./resolve')
  , util = require('./util')
  , errorClasses = require('./error_classes')
  , stableStringify = require('fast-json-stable-stringify');

var validateGenerator = require('../dotjs/validate');

/**
 * Functions below are used inside compiled validations function
 */

var ucs2length = util.ucs2length;
var equal = require('fast-deep-equal');

// this error is thrown by async schemas to return validation errors via exception
var ValidationError = errorClasses.Validation;

module.exports = compile;


/**
 * Compiles schema to validation function
 * @this   Ajv
 * @param  {Object} schema schema object
 * @param  {Object} root object with information about the root schema for this schema
 * @param  {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
 * @param  {String} baseId base ID for IDs in the schema
 * @return {Function} validation function
 */
function compile(schema, root, localRefs, baseId) {
  /* jshint validthis: true, evil: true */
  /* eslint no-shadow: 0 */
  var self = this
    , opts = this._opts
    , refVal = [ undefined ]
    , refs = {}
    , patterns = []
    , patternsHash = {}
    , defaults = []
    , defaultsHash = {}
    , customRules = [];

  function patternCode(i, patterns) {
    var regExpCode = opts.regExp ? 'regExp' : 'new RegExp';
    return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');';
  }

  root = root || { schema: schema, refVal: refVal, refs: refs };

  var c = checkCompiling.call(this, schema, root, baseId);
  var compilation = this._compilations[c.index];
  if (c.compiling) return (compilation.callValidate = callValidate);

  var formats = this._formats;
  var RULES = this.RULES;

  try {
    var v = localCompile(schema, root, localRefs, baseId);
    compilation.validate = v;
    var cv = compilation.callValidate;
    if (cv) {
      cv.schema = v.schema;
      cv.errors = null;
      cv.refs = v.refs;
      cv.refVal = v.refVal;
      cv.root = v.root;
      cv.$async = v.$async;
      if (opts.sourceCode) cv.source = v.source;
    }
    return v;
  } finally {
    endCompiling.call(this, schema, root, baseId);
  }

  /* @this   {*} - custom context, see passContext option */
  function callValidate() {
    /* jshint validthis: true */
    var validate = compilation.validate;
    var result = validate.apply(this, arguments);
    callValidate.errors = validate.errors;
    return result;
  }

  function localCompile(_schema, _root, localRefs, baseId) {
    var isRoot = !_root || (_root && _root.schema == _schema);
    if (_root.schema != root.schema)
      return compile.call(self, _schema, _root, localRefs, baseId);

    var $async = _schema.$async === true;

    var sourceCode = validateGenerator({
      isTop: true,
      schema: _schema,
      isRoot: isRoot,
      baseId: baseId,
      root: _root,
      schemaPath: '',
      errSchemaPath: '#',
      errorPath: '""',
      MissingRefError: errorClasses.MissingRef,
      RULES: RULES,
      validate: validateGenerator,
      util: util,
      resolve: resolve,
      resolveRef: resolveRef,
      usePattern: usePattern,
      useDefault: useDefault,
      useCustomRule: useCustomRule,
      opts: opts,
      formats: formats,
      logger: self.logger,
      self: self
    });

    sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
                   + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
                   + sourceCode;

    if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
    // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
    var validate;
    try {
      var makeValidate = new Function(
        'self',
        'RULES',
        'formats',
        'root',
        'refVal',
        'defaults',
        'customRules',
        'equal',
        'ucs2length',
        'ValidationError',
        'regExp',
        sourceCode
      );

      validate = makeValidate(
        self,
        RULES,
        formats,
        root,
        refVal,
        defaults,
        customRules,
        equal,
        ucs2length,
        ValidationError,
        opts.regExp
      );

      refVal[0] = validate;
    } catch(e) {
      self.logger.error('Error compiling schema, function code:', sourceCode);
      throw e;
    }

    validate.schema = _schema;
    validate.errors = null;
    validate.refs = refs;
    validate.refVal = refVal;
    validate.root = isRoot ? validate : _root;
    if ($async) validate.$async = true;
    if (opts.sourceCode === true) {
      validate.source = {
        code: sourceCode,
        patterns: patterns,
        defaults: defaults
      };
    }

    return validate;
  }

  function resolveRef(baseId, ref, isRoot) {
    ref = resolve.url(baseId, ref);
    var refIndex = refs[ref];
    var _refVal, refCode;
    if (refIndex !== undefined) {
      _refVal = refVal[refIndex];
      refCode = 'refVal[' + refIndex + ']';
      return resolvedRef(_refVal, refCode);
    }
    if (!isRoot && root.refs) {
      var rootRefId = root.refs[ref];
      if (rootRefId !== undefined) {
        _refVal = root.refVal[rootRefId];
        refCode = addLocalRef(ref, _refVal);
        return resolvedRef(_refVal, refCode);
      }
    }

    refCode = addLocalRef(ref);
    var v = resolve.call(self, localCompile, root, ref);
    if (v === undefined) {
      var localSchema = localRefs && localRefs[ref];
      if (localSchema) {
        v = resolve.inlineRef(localSchema, opts.inlineRefs)
            ? localSchema
            : compile.call(self, localSchema, root, localRefs, baseId);
      }
    }

    if (v === undefined) {
      removeLocalRef(ref);
    } else {
      replaceLocalRef(ref, v);
      return resolvedRef(v, refCode);
    }
  }

  function addLocalRef(ref, v) {
    var refId = refVal.length;
    refVal[refId] = v;
    refs[ref] = refId;
    return 'refVal' + refId;
  }

  function removeLocalRef(ref) {
    delete refs[ref];
  }

  function replaceLocalRef(ref, v) {
    var refId = refs[ref];
    refVal[refId] = v;
  }

  function resolvedRef(refVal, code) {
    return typeof refVal == 'object' || typeof refVal == 'boolean'
            ? { code: code, schema: refVal, inline: true }
            : { code: code, $async: refVal && !!refVal.$async };
  }

  function usePattern(regexStr) {
    var index = patternsHash[regexStr];
    if (index === undefined) {
      index = patternsHash[regexStr] = patterns.length;
      patterns[index] = regexStr;
    }
    return 'pattern' + index;
  }

  function useDefault(value) {
    switch (typeof value) {
      case 'boolean':
      case 'number':
        return '' + value;
      case 'string':
        return util.toQuotedString(value);
      case 'object':
        if (value === null) return 'null';
        var valueStr = stableStringify(value);
        var index = defaultsHash[valueStr];
        if (index === undefined) {
          index = defaultsHash[valueStr] = defaults.length;
          defaults[index] = value;
        }
        return 'default' + index;
    }
  }

  function useCustomRule(rule, schema, parentSchema, it) {
    if (self._opts.validateSchema !== false) {
      var deps = rule.definition.dependencies;
      if (deps && !deps.every(function(keyword) {
        return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
      }))
        throw new Error('parent schema must have all required keywords: ' + deps.join(','));

      var validateSchema = rule.definition.validateSchema;
      if (validateSchema) {
        var valid = validateSchema(schema);
        if (!valid) {
          var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
          if (self._opts.validateSchema == 'log') self.logger.error(message);
          else throw new Error(message);
        }
      }
    }

    var compile = rule.definition.compile
      , inline = rule.definition.inline
      , macro = rule.definition.macro;

    var validate;
    if (compile) {
      validate = compile.call(self, schema, parentSchema, it);
    } else if (macro) {
      validate = macro.call(self, schema, parentSchema, it);
      if (opts.validateSchema !== false) self.validateSchema(validate, true);
    } else if (inline) {
      validate = inline.call(self, it, rule.keyword, schema, parentSchema);
    } else {
      validate = rule.definition.validate;
      if (!validate) return;
    }

    if (validate === undefined)
      throw new Error('custom keyword "' + rule.keyword + '"failed to compile');

    var index = customRules.length;
    customRules[index] = validate;

    return {
      code: 'customRule' + index,
      validate: validate
    };
  }
}


/**
 * Checks if the schema is currently compiled
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
 */
function checkCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var index = compIndex.call(this, schema, root, baseId);
  if (index >= 0) return { index: index, compiling: true };
  index = this._compilations.length;
  this._compilations[index] = {
    schema: schema,
    root: root,
    baseId: baseId
  };
  return { index: index, compiling: false };
}


/**
 * Removes the schema from the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 */
function endCompiling(schema, root, baseId) {
  /* jshint validthis: true */
  var i = compIndex.call(this, schema, root, baseId);
  if (i >= 0) this._compilations.splice(i, 1);
}


/**
 * Index of schema compilation in the currently compiled list
 * @this   Ajv
 * @param  {Object} schema schema to compile
 * @param  {Object} root root object
 * @param  {String} baseId base schema ID
 * @return {Integer} compilation index
 */
function compIndex(schema, root, baseId) {
  /* jshint validthis: true */
  for (var i=0; i<this._compilations.length; i++) {
    var c = this._compilations[i];
    if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  }
  return -1;
}


function defaultCode(i) {
  return 'var default' + i + ' = defaults[' + i + '];';
}


function refValCode(i, refVal) {
  return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}


function customRuleCode(i) {
  return 'var customRule' + i + ' = customRules[' + i + '];';
}


function vars(arr, statement) {
  if (!arr.length) return '';
  var code = '';
  for (var i=0; i<arr.length; i++)
    code += statement(i, arr);
  return code;
}
'use strict';

var URI = require('uri-js')
  , equal = require('fast-deep-equal')
  , util = require('./util')
  , SchemaObject = require('./schema_obj')
  , traverse = require('json-schema-traverse');

module.exports = resolve;

resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;

/**
 * [resolve and compile the references ($ref)]
 * @this   Ajv
 * @param  {Function} compile reference to schema compilation funciton (localCompile)
 * @param  {Object} root object with information about the root schema for the current schema
 * @param  {String} ref reference to resolve
 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
 */
function resolve(compile, root, ref) {
  /* jshint validthis: true */
  var refVal = this._refs[ref];
  if (typeof refVal == 'string') {
    if (this._refs[refVal]) refVal = this._refs[refVal];
    else return resolve.call(this, compile, root, refVal);
  }

  refVal = refVal || this._schemas[ref];
  if (refVal instanceof SchemaObject) {
    return inlineRef(refVal.schema, this._opts.inlineRefs)
            ? refVal.schema
            : refVal.validate || this._compile(refVal);
  }

  var res = resolveSchema.call(this, root, ref);
  var schema, v, baseId;
  if (res) {
    schema = res.schema;
    root = res.root;
    baseId = res.baseId;
  }

  if (schema instanceof SchemaObject) {
    v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
  } else if (schema !== undefined) {
    v = inlineRef(schema, this._opts.inlineRefs)
        ? schema
        : compile.call(this, schema, root, undefined, baseId);
  }

  return v;
}


/**
 * Resolve schema, its root and baseId
 * @this Ajv
 * @param  {Object} root root object with properties schema, refVal, refs
 * @param  {String} ref  reference to resolve
 * @return {Object} object with properties schema, root, baseId
 */
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = URI.parse(ref)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(this._getId(root.schema));
  if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}


/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
  /* jshint validthis: true */
  var res = resolveSchema.call(this, root, ref);
  if (res) {
    var schema = res.schema;
    var baseId = res.baseId;
    root = res.root;
    var id = this._getId(schema);
    if (id) baseId = resolveUrl(baseId, id);
    return getJsonPointer.call(this, parsedRef, baseId, schema, root);
  }
}


var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
  /* jshint validthis: true */
  parsedRef.fragment = parsedRef.fragment || '';
  if (parsedRef.fragment.slice(0,1) != '/') return;
  var parts = parsedRef.fragment.split('/');

  for (var i = 1; i < parts.length; i++) {
    var part = parts[i];
    if (part) {
      part = util.unescapeFragment(part);
      schema = schema[part];
      if (schema === undefined) break;
      var id;
      if (!PREVENT_SCOPE_CHANGE[part]) {
        id = this._getId(schema);
        if (id) baseId = resolveUrl(baseId, id);
        if (schema.$ref) {
          var $ref = resolveUrl(baseId, schema.$ref);
          var res = resolveSchema.call(this, root, $ref);
          if (res) {
            schema = res.schema;
            root = res.root;
            baseId = res.baseId;
          }
        }
      }
    }
  }
  if (schema !== undefined && schema !== root.schema)
    return { schema: schema, root: root, baseId: baseId };
}


var SIMPLE_INLINED = util.toHash([
  'type', 'format', 'pattern',
  'maxLength', 'minLength',
  'maxProperties', 'minProperties',
  'maxItems', 'minItems',
  'maximum', 'minimum',
  'uniqueItems', 'multipleOf',
  'required', 'enum'
]);
function inlineRef(schema, limit) {
  if (limit === false) return false;
  if (limit === undefined || limit === true) return checkNoRef(schema);
  else if (limit) return countKeys(schema) <= limit;
}


function checkNoRef(schema) {
  var item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return false;
      item = schema[key];
      if (typeof item == 'object' && !checkNoRef(item)) return false;
    }
  }
  return true;
}


function countKeys(schema) {
  var count = 0, item;
  if (Array.isArray(schema)) {
    for (var i=0; i<schema.length; i++) {
      item = schema[i];
      if (typeof item == 'object') count += countKeys(item);
      if (count == Infinity) return Infinity;
    }
  } else {
    for (var key in schema) {
      if (key == '$ref') return Infinity;
      if (SIMPLE_INLINED[key]) {
        count++;
      } else {
        item = schema[key];
        if (typeof item == 'object') count += countKeys(item) + 1;
        if (count == Infinity) return Infinity;
      }
    }
  }
  return count;
}


function getFullPath(id, normalize) {
  if (normalize !== false) id = normalizeId(id);
  var p = URI.parse(id);
  return _getFullPath(p);
}


function _getFullPath(p) {
  return URI.serialize(p).split('#')[0] + '#';
}


var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
  return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}


function resolveUrl(baseId, id) {
  id = normalizeId(id);
  return URI.resolve(baseId, id);
}


/* @this Ajv */
function resolveIds(schema) {
  var schemaId = normalizeId(this._getId(schema));
  var baseIds = {'': schemaId};
  var fullPaths = {'': getFullPath(schemaId, false)};
  var localRefs = {};
  var self = this;

  traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
    if (jsonPtr === '') return;
    var id = self._getId(sch);
    var baseId = baseIds[parentJsonPtr];
    var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
    if (keyIndex !== undefined)
      fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));

    if (typeof id == 'string') {
      id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);

      var refVal = self._refs[id];
      if (typeof refVal == 'string') refVal = self._refs[refVal];
      if (refVal && refVal.schema) {
        if (!equal(sch, refVal.schema))
          throw new Error('id "' + id + '" resolves to more than one schema');
      } else if (id != normalizeId(fullPath)) {
        if (id[0] == '#') {
          if (localRefs[id] && !equal(sch, localRefs[id]))
            throw new Error('id "' + id + '" resolves to more than one schema');
          localRefs[id] = sch;
        } else {
          self._refs[id] = fullPath;
        }
      }
    }
    baseIds[jsonPtr] = baseId;
    fullPaths[jsonPtr] = fullPath;
  });

  return localRefs;
}
'use strict';

var ruleModules = require('../dotjs')
  , toHash = require('./util').toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
  ];

  var ALL = [ 'type', '$comment' ];
  var KEYWORDS = [
    '$schema', '$id', 'id', '$data', '$async', 'title',
    'description', 'default', 'definitions',
    'examples', 'readOnly', 'writeOnly',
    'contentMediaType', 'contentEncoding',
    'additionalItems', 'then', 'else'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    RULES.all.$comment = {
      keyword: '$comment',
      code: ruleModules.$comment
    };

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};
'use strict';

var util = require('./util');

module.exports = SchemaObject;

function SchemaObject(obj) {
  util.copy(obj, this);
}
'use strict';

// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
  var length = 0
    , len = str.length
    , pos = 0
    , value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
      // high surrogate, and there is a next character
      value = str.charCodeAt(pos);
      if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
    }
  }
  return length;
};
'use strict';


module.exports = {
  copy: copy,
  checkDataType: checkDataType,
  checkDataTypes: checkDataTypes,
  coerceToTypes: coerceToTypes,
  toHash: toHash,
  getProperty: getProperty,
  escapeQuotes: escapeQuotes,
  equal: require('fast-deep-equal'),
  ucs2length: require('./ucs2length'),
  varOccurences: varOccurences,
  varReplace: varReplace,
  schemaHasRules: schemaHasRules,
  schemaHasRulesExcept: schemaHasRulesExcept,
  schemaUnknownRules: schemaUnknownRules,
  toQuotedString: toQuotedString,
  getPathExpr: getPathExpr,
  getPath: getPath,
  getData: getData,
  unescapeFragment: unescapeFragment,
  unescapeJsonPointer: unescapeJsonPointer,
  escapeFragment: escapeFragment,
  escapeJsonPointer: escapeJsonPointer
};


function copy(o, to) {
  to = to || {};
  for (var key in o) to[key] = o[key];
  return to;
}


function checkDataType(dataType, data, strictNumbers, negate) {
  var EQUAL = negate ? ' !== ' : ' === '
    , AND = negate ? ' || ' : ' && '
    , OK = negate ? '!' : ''
    , NOT = negate ? '' : '!';
  switch (dataType) {
    case 'null': return data + EQUAL + 'null';
    case 'array': return OK + 'Array.isArray(' + data + ')';
    case 'object': return '(' + OK + data + AND +
                          'typeof ' + data + EQUAL + '"object"' + AND +
                          NOT + 'Array.isArray(' + data + '))';
    case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
                           NOT + '(' + data + ' % 1)' +
                           AND + data + EQUAL + data +
                           (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
    case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' +
                          (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';
    default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
  }
}


function checkDataTypes(dataTypes, data, strictNumbers) {
  switch (dataTypes.length) {
    case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);
    default:
      var code = '';
      var types = toHash(dataTypes);
      if (types.array && types.object) {
        code = types.null ? '(': '(!' + data + ' || ';
        code += 'typeof ' + data + ' !== "object")';
        delete types.null;
        delete types.array;
        delete types.object;
      }
      if (types.number) delete types.integer;
      for (var t in types)
        code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);

      return code;
  }
}


var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
  if (Array.isArray(dataTypes)) {
    var types = [];
    for (var i=0; i<dataTypes.length; i++) {
      var t = dataTypes[i];
      if (COERCE_TO_TYPES[t]) types[types.length] = t;
      else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
    }
    if (types.length) return types;
  } else if (COERCE_TO_TYPES[dataTypes]) {
    return [dataTypes];
  } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
    return ['array'];
  }
}


function toHash(arr) {
  var hash = {};
  for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
  return hash;
}


var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
  return typeof key == 'number'
          ? '[' + key + ']'
          : IDENTIFIER.test(key)
            ? '.' + key
            : "['" + escapeQuotes(key) + "']";
}


function escapeQuotes(str) {
  return str.replace(SINGLE_QUOTE, '\\$&')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\f/g, '\\f')
            .replace(/\t/g, '\\t');
}


function varOccurences(str, dataVar) {
  dataVar += '[^0-9]';
  var matches = str.match(new RegExp(dataVar, 'g'));
  return matches ? matches.length : 0;
}


function varReplace(str, dataVar, expr) {
  dataVar += '([^0-9])';
  expr = expr.replace(/\$/g, '$$$$');
  return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}


function schemaHasRules(schema, rules) {
  if (typeof schema == 'boolean') return !schema;
  for (var key in schema) if (rules[key]) return true;
}


function schemaHasRulesExcept(schema, rules, exceptKeyword) {
  if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
  for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}


function schemaUnknownRules(schema, rules) {
  if (typeof schema == 'boolean') return;
  for (var key in schema) if (!rules[key]) return key;
}


function toQuotedString(str) {
  return '\'' + escapeQuotes(str) + '\'';
}


function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
  var path = jsonPointers // false by default
              ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
              : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
  return joinPaths(currentPath, path);
}


function getPath(currentPath, prop, jsonPointers) {
  var path = jsonPointers // false by default
              ? toQuotedString('/' + escapeJsonPointer(prop))
              : toQuotedString(getProperty(prop));
  return joinPaths(currentPath, path);
}


var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
  var up, jsonPointer, data, matches;
  if ($data === '') return 'rootData';
  if ($data[0] == '/') {
    if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
    jsonPointer = $data;
    data = 'rootData';
  } else {
    matches = $data.match(RELATIVE_JSON_POINTER);
    if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
    up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer == '#') {
      if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
      return paths[lvl - up];
    }

    if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
    data = 'data' + ((lvl - up) || '');
    if (!jsonPointer) return data;
  }

  var expr = data;
  var segments = jsonPointer.split('/');
  for (var i=0; i<segments.length; i++) {
    var segment = segments[i];
    if (segment) {
      data += getProperty(unescapeJsonPointer(segment));
      expr += ' && ' + data;
    }
  }
  return expr;
}


function joinPaths (a, b) {
  if (a == '""') return b;
  return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}


function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}


function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}


function escapeJsonPointer(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}


function unescapeJsonPointer(str) {
  return str.replace(/~1/g, '/').replace(/~0/g, '~');
}
'use strict';

var KEYWORDS = [
  'multipleOf',
  'maximum',
  'exclusiveMaximum',
  'minimum',
  'exclusiveMinimum',
  'maxLength',
  'minLength',
  'pattern',
  'additionalItems',
  'maxItems',
  'minItems',
  'uniqueItems',
  'maxProperties',
  'minProperties',
  'required',
  'additionalProperties',
  'enum',
  'format',
  'const'
];

module.exports = function (metaSchema, keywordsJsonPointers) {
  for (var i=0; i<keywordsJsonPointers.length; i++) {
    metaSchema = JSON.parse(JSON.stringify(metaSchema));
    var segments = keywordsJsonPointers[i].split('/');
    var keywords = metaSchema;
    var j;
    for (j=1; j<segments.length; j++)
      keywords = keywords[segments[j]];

    for (j=0; j<KEYWORDS.length; j++) {
      var key = KEYWORDS[j];
      var schema = keywords[key];
      if (schema) {
        keywords[key] = {
          anyOf: [
            schema,
            { $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
    }
  }

  return metaSchema;
};
'use strict';

var metaSchema = require('./refs/json-schema-draft-07.json');

module.exports = {
  $id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
  definitions: {
    simpleTypes: metaSchema.definitions.simpleTypes
  },
  type: 'object',
  dependencies: {
    schema: ['validate'],
    $data: ['validate'],
    statements: ['inline'],
    valid: {not: {required: ['macro']}}
  },
  properties: {
    type: metaSchema.properties.type,
    schema: {type: 'boolean'},
    statements: {type: 'boolean'},
    dependencies: {
      type: 'array',
      items: {type: 'string'}
    },
    metaSchema: {type: 'object'},
    modifying: {type: 'boolean'},
    valid: {type: 'boolean'},
    $data: {type: 'boolean'},
    async: {type: 'boolean'},
    errors: {
      anyOf: [
        {type: 'boolean'},
        {const: 'full'}
      ]
    }
  }
};
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{## def.setExclusiveLimit:
  $exclusive = true;
  $errorKeyword = $exclusiveKeyword;
  $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
#}}

{{
  var $isMax = $keyword == 'maximum'
    , $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum'
    , $schemaExcl = it.schema[$exclusiveKeyword]
    , $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data
    , $op = $isMax ? '<' : '>'
    , $notOp = $isMax ? '>' : '<'
    , $errorKeyword = undefined;

  if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
    throw new Error($keyword + ' must be number');
  }
  if (!($isDataExcl || $schemaExcl === undefined
                    || typeof $schemaExcl == 'number'
                    || typeof $schemaExcl == 'boolean')) {
    throw new Error($exclusiveKeyword + ' must be number or boolean');
  }
}}

{{? $isDataExcl }}
  {{
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr)
      , $exclusive = 'exclusive' + $lvl
      , $exclType = 'exclType' + $lvl
      , $exclIsNumber = 'exclIsNumber' + $lvl
      , $opExpr = 'op' + $lvl
      , $opStr = '\' + ' + $opExpr + ' + \'';
  }}
  var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}};
  {{ $schemaValueExcl = 'schemaExcl' + $lvl; }}

  var {{=$exclusive}};
  var {{=$exclType}} = typeof {{=$schemaValueExcl}};
  if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') {
    {{ var $errorKeyword = $exclusiveKeyword; }}
    {{# def.error:'_exclusiveLimit' }}
  } else if ({{# def.$dataNotType:'number' }}
            {{=$exclType}} == 'number'
              ? (
                  ({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}})
                    ? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}}
                    : {{=$data}} {{=$notOp}} {{=$schemaValue}}
                )
              : (
                  ({{=$exclusive}} = {{=$schemaValueExcl}} === true)
                    ? {{=$data}} {{=$notOp}}= {{=$schemaValue}}
                    : {{=$data}} {{=$notOp}} {{=$schemaValue}}
                )
            || {{=$data}} !== {{=$data}}) {
    var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}=';
    {{
      if ($schema === undefined) {
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
        $schemaValue = $schemaValueExcl;
        $isData = $isDataExcl;
      }
    }}
{{??}}
  {{
    var $exclIsNumber = typeof $schemaExcl == 'number'
      , $opStr = $op;  /*used in error*/
  }}

  {{? $exclIsNumber && $isData }}
    {{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }}
    if ({{# def.$dataNotType:'number' }}
        ( {{=$schemaValue}} === undefined
          || {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}}
            ? {{=$data}} {{=$notOp}}= {{=$schemaExcl}}
            : {{=$data}} {{=$notOp}} {{=$schemaValue}} )
        || {{=$data}} !== {{=$data}}) {
  {{??}}
    {{
      if ($exclIsNumber && $schema === undefined) {
          {{# def.setExclusiveLimit }}
          $schemaValue = $schemaExcl;
          $notOp += '=';
      } else {
        if ($exclIsNumber)
          $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);

        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          {{# def.setExclusiveLimit }}
          $notOp += '=';
        } else {
          $exclusive = false;
          $opStr += '=';
        }
      }

      var $opExpr = '\'' + $opStr + '\''; /*used in error*/
    }}

    if ({{# def.$dataNotType:'number' }}
        {{=$data}} {{=$notOp}} {{=$schemaValue}}
        || {{=$data}} !== {{=$data}}) {
  {{?}}
{{?}}
    {{ $errorKeyword = $errorKeyword || $keyword; }}
    {{# def.error:'_limit' }}
  } {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{# def.numberKeyword }}

{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) {
  {{ var $errorKeyword = $keyword; }}
  {{# def.error:'_limitItems' }}
} {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{# def.numberKeyword }}

{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) {
  {{ var $errorKeyword = $keyword; }}
  {{# def.error:'_limitLength' }}
} {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{# def.numberKeyword }}

{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }}
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) {
  {{ var $errorKeyword = $keyword; }}
  {{# def.error:'_limitProperties' }}
} {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

{{
  var $currentBaseId = $it.baseId
    , $allSchemasEmpty = true;
}}

{{~ $schema:$sch:$i }}
  {{? {{# def.nonEmptySchema:$sch }} }}
    {{
      $allSchemasEmpty = false;
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + '[' + $i + ']';
      $it.errSchemaPath = $errSchemaPath + '/' + $i;
    }}

    {{# def.insertSubschemaCode }}

    {{# def.ifResultValid }}
  {{?}}
{{~}}

{{? $breakOnError }}
  {{? $allSchemasEmpty }}
    if (true) {
  {{??}}
    {{= $closingBraces.slice(0,-1) }}
  {{?}}
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

{{
  var $noEmptySchema = $schema.every(function($sch) {
    return {{# def.nonEmptySchema:$sch }};
  });
}}
{{? $noEmptySchema }}
  {{ var $currentBaseId = $it.baseId; }}
  var {{=$errs}} = errors;
  var {{=$valid}} = false;

  {{# def.setCompositeRule }}

  {{~ $schema:$sch:$i }}
    {{
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + '[' + $i + ']';
      $it.errSchemaPath = $errSchemaPath + '/' + $i;
    }}

    {{# def.insertSubschemaCode }}

    {{=$valid}} = {{=$valid}} || {{=$nextValid}};

    if (!{{=$valid}}) {
    {{ $closingBraces += '}'; }}
  {{~}}

  {{# def.resetCompositeRule }}

  {{= $closingBraces }}

  if (!{{=$valid}}) {
    {{# def.extraError:'anyOf' }}
  } else {
    {{# def.resetErrors }}
  {{? it.opts.allErrors }} } {{?}}
{{??}}
  {{? $breakOnError }}
    if (true) {
  {{?}}
{{?}}
{{## def.coerceType:
  {{
    var $dataType = 'dataType' + $lvl
      , $coerced = 'coerced' + $lvl;
  }}
  var {{=$dataType}} = typeof {{=$data}};
  var {{=$coerced}} = undefined;

  {{? it.opts.coerceTypes == 'array' }}
    if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) {
      {{=$data}} = {{=$data}}[0];
      {{=$dataType}} = typeof {{=$data}};
      if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}};
    }
  {{?}}

  if ({{=$coerced}} !== undefined) ;
  {{~ $coerceToTypes:$type:$i }}
    {{? $type == 'string' }}
      else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean')
        {{=$coerced}} = '' + {{=$data}};
      else if ({{=$data}} === null) {{=$coerced}} = '';
    {{?? $type == 'number' || $type == 'integer' }}
      else if ({{=$dataType}} == 'boolean' || {{=$data}} === null
          || ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}}
          {{? $type == 'integer' }} && !({{=$data}} % 1){{?}}))
        {{=$coerced}} = +{{=$data}};
    {{?? $type == 'boolean' }}
      else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null)
        {{=$coerced}} = false;
      else if ({{=$data}} === 'true' || {{=$data}} === 1)
        {{=$coerced}} = true;
    {{?? $type == 'null' }}
      else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false)
        {{=$coerced}} = null;
    {{?? it.opts.coerceTypes == 'array' && $type == 'array' }}
      else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null)
        {{=$coerced}} = [{{=$data}}];
    {{?}}
  {{~}}
  else {
    {{# def.error:'type' }}
  }

  if ({{=$coerced}} !== undefined) {
    {{# def.setParentData }}
    {{=$data}} = {{=$coerced}};
    {{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}}
      {{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}};
  }
#}}
{{# def.definitions }}
{{# def.setupKeyword }}

{{ var $comment = it.util.toQuotedString($schema); }}
{{? it.opts.$comment === true }}
  console.log({{=$comment}});
{{?? typeof it.opts.$comment == 'function' }}
  self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema);
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{? !$isData }}
  var schema{{=$lvl}} = validate.schema{{=$schemaPath}};
{{?}}
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}});
{{# def.checkError:'const' }}
{{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}


{{
  var $idx = 'i' + $lvl
    , $dataNxt = $it.dataLevel = it.dataLevel + 1
    , $nextData = 'data' + $dataNxt
    , $currentBaseId = it.baseId
    , $nonEmptySchema = {{# def.nonEmptySchema:$schema }};
}}

var {{=$errs}} = errors;
var {{=$valid}};

{{? $nonEmptySchema }}
  {{# def.setCompositeRule }}

  {{
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
  }}

  var {{=$nextValid}} = false;

  for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
    {{
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
    }}

    {{# def.generateSubschemaCode }}
    {{# def.optimizeValidate }}

    if ({{=$nextValid}}) break;
  }

  {{# def.resetCompositeRule }}
  {{= $closingBraces }}

  if (!{{=$nextValid}}) {
{{??}}
  if ({{=$data}}.length == 0) {
{{?}}

    {{# def.error:'contains' }}
  } else {
    {{? $nonEmptySchema }}
      {{# def.resetErrors }}
    {{?}}
  {{? it.opts.allErrors }} } {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{
  var $rule = this
    , $definition = 'definition' + $lvl
    , $rDef = $rule.definition
    , $closingBraces = '';
  var $validate = $rDef.validate;
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
}}

{{? $isData && $rDef.$data }}
  {{
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
  }}
  var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition;
  var {{=$validateCode}} = {{=$definition}}.validate;
{{??}}
  {{
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    if (!$ruleValidate) return;
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }}
{{?}}

{{
  var $ruleErrs = $validateCode + '.errors'
    , $i = 'i' + $lvl
    , $ruleErr = 'ruleErr' + $lvl
    , $asyncKeyword = $rDef.async;

  if ($asyncKeyword && !it.async)
    throw new Error('async keyword in sync schema');
}}


{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}}
var {{=$errs}} = errors;
var {{=$valid}};

{{## def.callRuleValidate:
  {{=$validateCode}}.call(
    {{? it.opts.passContext }}this{{??}}self{{?}}
    {{? $compile || $rDef.schema === false }}
      , {{=$data}}
    {{??}}
      , {{=$schemaValue}}
      , {{=$data}}
      , validate.schema{{=it.schemaPath}}
    {{?}}
    , {{# def.dataPath }}
    {{# def.passParentData }}
    , rootData
  )
#}}

{{## def.extendErrors:_inline:
  for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) {
    var {{=$ruleErr}} = vErrors[{{=$i}}];
    if ({{=$ruleErr}}.dataPath === undefined)
      {{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }};
    {{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }}
      {{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}";
    {{# _inline ? '}' : '' }}
    {{? it.opts.verbose }}
      {{=$ruleErr}}.schema = {{=$schemaValue}};
      {{=$ruleErr}}.data = {{=$data}};
    {{?}}
  }
#}}


{{? $isData && $rDef.$data }}
  {{ $closingBraces += '}'; }}
  if ({{=$schemaValue}} === undefined) {
    {{=$valid}} = true;
  } else {
  {{? $validateSchema }}
    {{ $closingBraces += '}'; }}
    {{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}});
    if ({{=$valid}}) {
  {{?}}
{{?}}

{{? $inline }}
  {{? $rDef.statements }}
    {{= $ruleValidate.validate }}
  {{??}}
    {{=$valid}} = {{= $ruleValidate.validate }};
  {{?}}
{{?? $macro }}
  {{# def.setupNextLevel }}
  {{
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
  }}
  {{# def.setCompositeRule }}
  {{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }}
  {{# def.resetCompositeRule }}
  {{= $code }}
{{??}}
  {{# def.beginDefOut}}
    {{# def.callRuleValidate }}
  {{# def.storeDefOut:def_callRuleValidate }}

  {{? $rDef.errors === false }}
    {{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }};
  {{??}}
    {{? $asyncKeyword }}
      {{ $ruleErrs = 'customErrors' + $lvl; }}
      var {{=$ruleErrs}} = null;
      try {
        {{=$valid}} = await {{= def_callRuleValidate }};
      } catch (e) {
        {{=$valid}} = false;
        if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors;
        else throw e;
      }
    {{??}}
      {{=$ruleErrs}} = null;
      {{=$valid}} = {{= def_callRuleValidate }};
    {{?}}
  {{?}}
{{?}}

{{? $rDef.modifying }}
  if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}];
{{?}}

{{= $closingBraces }}

{{## def.notValidationResult:
  {{? $rDef.valid === undefined }}
    !{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}}
  {{??}}
    {{= !$rDef.valid }}
  {{?}}
#}}

{{? $rDef.valid }}
  {{? $breakOnError }} if (true) { {{?}}
{{??}}
  if ({{# def.notValidationResult }}) {
    {{ $errorKeyword = $rule.keyword; }}
    {{# def.beginDefOut}}
      {{# def.error:'custom' }}
    {{# def.storeDefOut:def_customError }}

    {{? $inline }}
      {{? $rDef.errors }}
        {{? $rDef.errors != 'full' }}
          {{# def.extendErrors:true }}
        {{?}}
      {{??}}
        {{? $rDef.errors === false}}
          {{= def_customError }}
        {{??}}
          if ({{=$errs}} == errors) {
            {{= def_customError }}
          } else {
            {{# def.extendErrors:true }}
          }
        {{?}}
      {{?}}
    {{?? $macro }}
      {{# def.extraError:'custom' }}
    {{??}}
      {{? $rDef.errors === false}}
        {{= def_customError }}
      {{??}}
        if (Array.isArray({{=$ruleErrs}})) {
          if (vErrors === null) vErrors = {{=$ruleErrs}};
          else vErrors = vErrors.concat({{=$ruleErrs}});
          errors = vErrors.length;
          {{# def.extendErrors:false }}
        } else {
          {{= def_customError }}
        }
      {{?}}
    {{?}}

  } {{? $breakOnError }} else { {{?}}
{{?}}
{{## def.assignDefault:
  {{? it.compositeRule }}
    {{
      if (it.opts.strictDefaults) {
        var $defaultMsg = 'default is ignored for: ' + $passData;
        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
        else throw new Error($defaultMsg);
      }
    }}
  {{??}}
    if ({{=$passData}} === undefined
      {{? it.opts.useDefaults == 'empty' }}
        || {{=$passData}} === null
        || {{=$passData}} === ''
      {{?}}
    )
      {{=$passData}} = {{? it.opts.useDefaults == 'shared' }}
                         {{= it.useDefault($sch.default) }}
                       {{??}}
                         {{= JSON.stringify($sch.default) }}
                       {{?}};
  {{?}}
#}}


{{## def.defaultProperties:
  {{
    var $schema = it.schema.properties
      , $schemaKeys = Object.keys($schema); }}
  {{~ $schemaKeys:$propertyKey }}
    {{ var $sch = $schema[$propertyKey]; }}
    {{? $sch.default !== undefined }}
      {{ var $passData = $data + it.util.getProperty($propertyKey); }}
      {{# def.assignDefault }}
    {{?}}
  {{~}}
#}}


{{## def.defaultItems:
  {{~ it.schema.items:$sch:$i }}
    {{? $sch.default !== undefined }}
      {{ var $passData = $data + '[' + $i + ']'; }}
      {{# def.assignDefault }}
    {{?}}
  {{~}}
#}}
{{## def.setupKeyword:
  {{
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;

    var $data = 'data' + ($dataLvl || '');
    var $valid = 'valid' + $lvl;
    var $errs = 'errs__' + $lvl;
  }}
#}}


{{## def.setCompositeRule:
  {{
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
  }}
#}}


{{## def.resetCompositeRule:
  {{ it.compositeRule = $it.compositeRule = $wasComposite; }}
#}}


{{## def.setupNextLevel:
  {{
    var $it = it.util.copy(it);
    var $closingBraces = '';
    $it.level++;
    var $nextValid = 'valid' + $it.level;
  }}
#}}


{{## def.ifValid:
  {{? $breakOnError }}
    if ({{=$valid}}) {
    {{ $closingBraces += '}'; }}
  {{?}}
#}}


{{## def.ifResultValid:
  {{? $breakOnError }}
    if ({{=$nextValid}}) {
    {{ $closingBraces += '}'; }}
  {{?}}
#}}


{{## def.elseIfValid:
  {{? $breakOnError }}
    {{ $closingBraces += '}'; }}
    else {
  {{?}}
#}}


{{## def.nonEmptySchema:_schema:
  (it.opts.strictKeywords
    ? (typeof _schema == 'object' && Object.keys(_schema).length > 0)
      || _schema === false
    : it.util.schemaHasRules(_schema, it.RULES.all))
#}}


{{## def.strLength:
  {{? it.opts.unicode === false }}
    {{=$data}}.length
  {{??}}
    ucs2length({{=$data}})
  {{?}}
#}}


{{## def.willOptimize:
  it.util.varOccurences($code, $nextData) < 2
#}}


{{## def.generateSubschemaCode:
  {{
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
  }}
#}}


{{## def.insertSubschemaCode:
  {{= it.validate($it) }}
  {{ $it.baseId = $currentBaseId; }}
#}}


{{## def._optimizeValidate:
  it.util.varReplace($code, $nextData, $passData)
#}}


{{## def.optimizeValidate:
  {{? {{# def.willOptimize}} }}
    {{= {{# def._optimizeValidate }} }}
  {{??}}
    var {{=$nextData}} = {{=$passData}};
    {{= $code }}
  {{?}}
#}}


{{## def.$data:
  {{
    var $isData = it.opts.$data && $schema && $schema.$data
      , $schemaValue;
  }}
  {{? $isData }}
    var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }};
    {{ $schemaValue = 'schema' + $lvl; }}
  {{??}}
    {{ $schemaValue = $schema; }}
  {{?}}
#}}


{{## def.$dataNotType:_type:
  {{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}}
#}}


{{## def.check$dataIsArray:
  if (schema{{=$lvl}} === undefined) {{=$valid}} = true;
  else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false;
  else {
#}}


{{## def.numberKeyword:
  {{? !($isData || typeof $schema == 'number') }}
    {{ throw new Error($keyword + ' must be number'); }}
  {{?}}
#}}


{{## def.beginDefOut:
  {{
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
  }}
#}}


{{## def.storeDefOut:_variable:
  {{
    var _variable = out;
    out = $$outStack.pop();
  }}
#}}


{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}}

{{## def.setParentData:
  {{
    var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData'
      , $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
  }}
#}}

{{## def.passParentData:
  {{# def.setParentData }}
  , {{= $parentData }}
  , {{= $parentDataProperty }}
#}}


{{## def.iterateProperties:
  {{? $ownProperties }}
    {{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}});
    for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) {
      var {{=$key}} = {{=$dataProperties}}[{{=$idx}}];
  {{??}}
    for (var {{=$key}} in {{=$data}}) {
  {{?}}
#}}


{{## def.noPropertyInData:
  {{=$useData}} === undefined
  {{? $ownProperties }}
    || !{{# def.isOwnProperty }}
  {{?}}
#}}


{{## def.isOwnProperty:
  Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}')
#}}
{{# def.definitions }}
{{# def.errors }}
{{# def.missing }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}


{{## def.propertyInData:
  {{=$data}}{{= it.util.getProperty($property) }} !== undefined
  {{? $ownProperties }}
    && Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}')
  {{?}}
#}}


{{
  var $schemaDeps = {}
    , $propertyDeps = {}
    , $ownProperties = it.opts.ownProperties;

  for ($property in $schema) {
    if ($property == '__proto__') continue;
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
}}

var {{=$errs}} = errors;

{{ var $currentErrorPath = it.errorPath; }}

var missing{{=$lvl}};
{{ for (var $property in $propertyDeps) { }}
  {{ $deps = $propertyDeps[$property]; }}
  {{? $deps.length }}
    if ({{# def.propertyInData }}
      {{? $breakOnError }}
          && ({{# def.checkMissingProperty:$deps }})) {
          {{# def.errorMissingProperty:'dependencies' }}
      {{??}}
        ) {
          {{~ $deps:$propertyKey }}
            {{# def.allErrorsMissingProperty:'dependencies' }}
          {{~}}
      {{?}}
    } {{# def.elseIfValid }}
  {{?}}
{{ } }}

{{
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
}}


{{ for (var $property in $schemaDeps) { }}
  {{ var $sch = $schemaDeps[$property]; }}
  {{? {{# def.nonEmptySchema:$sch }} }}
    {{=$nextValid}} = true;

    if ({{# def.propertyInData }}) {
      {{ 
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + it.util.getProperty($property);
        $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      }}

      {{# def.insertSubschemaCode }}
    }

    {{# def.ifResultValid }}
  {{?}}
{{ } }}

{{? $breakOnError }} 
  {{= $closingBraces }}
  if ({{=$errs}} == errors) {
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{
  var $i = 'i' + $lvl
    , $vSchema = 'schema' + $lvl;
}}

{{? !$isData }}
  var {{=$vSchema}} = validate.schema{{=$schemaPath}};
{{?}}
var {{=$valid}};

{{?$isData}}{{# def.check$dataIsArray }}{{?}}

{{=$valid}} = false;

for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++)
  if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) {
    {{=$valid}} = true;
    break;
  }

{{? $isData }}  }  {{?}}

{{# def.checkError:'enum' }}

{{? $breakOnError }} else { {{?}}
{{# def.definitions }}

{{## def._error:_rule:
  {{ 'istanbul ignore else'; }}
  {{? it.createErrors !== false }}
    {
      keyword: '{{= $errorKeyword || _rule }}'
      , dataPath: (dataPath || '') + {{= it.errorPath }}
      , schemaPath: {{=it.util.toQuotedString($errSchemaPath)}}
      , params: {{# def._errorParams[_rule] }}
      {{? it.opts.messages !== false }}
        , message: {{# def._errorMessages[_rule] }}
      {{?}}
      {{? it.opts.verbose }}
        , schema: {{# def._errorSchemas[_rule] }}
        , parentSchema: validate.schema{{=it.schemaPath}}
        , data: {{=$data}}
      {{?}}
    }
  {{??}}
    {}
  {{?}}
#}}


{{## def._addError:_rule:
  if (vErrors === null) vErrors = [err];
  else vErrors.push(err);
  errors++;
#}}


{{## def.addError:_rule:
  var err = {{# def._error:_rule }};
  {{# def._addError:_rule }}
#}}


{{## def.error:_rule:
  {{# def.beginDefOut}}
    {{# def._error:_rule }}
  {{# def.storeDefOut:__err }}

  {{? !it.compositeRule && $breakOnError }}
    {{ 'istanbul ignore if'; }}
    {{? it.async }}
      throw new ValidationError([{{=__err}}]);
    {{??}}
      validate.errors = [{{=__err}}];
      return false;
    {{?}}
  {{??}}
    var err = {{=__err}};
    {{# def._addError:_rule }}
  {{?}}
#}}


{{## def.extraError:_rule:
  {{# def.addError:_rule}}
  {{? !it.compositeRule && $breakOnError }}
    {{ 'istanbul ignore if'; }}
    {{? it.async }}
      throw new ValidationError(vErrors);
    {{??}}
      validate.errors = vErrors;
      return false;
    {{?}}
  {{?}}
#}}


{{## def.checkError:_rule:
  if (!{{=$valid}}) {
    {{# def.error:_rule }}
  }
#}}


{{## def.resetErrors:
  errors = {{=$errs}};
  if (vErrors !== null) {
    if ({{=$errs}}) vErrors.length = {{=$errs}};
    else vErrors = null;
  }
#}}


{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}}
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}}
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}}

{{## def._errorMessages = {
  'false schema':  "'boolean schema is false'",
  $ref:            "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
  additionalItems: "'should NOT have more than {{=$schema.length}} items'",
  additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
  anyOf:           "'should match some schema in anyOf'",
  const:           "'should be equal to constant'",
  contains:        "'should contain a valid item'",
  dependencies:    "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
  'enum':          "'should be equal to one of the allowed values'",
  format:          "'should match format \"{{#def.concatSchemaEQ}}\"'",
  'if':            "'should match \"' + {{=$ifClause}} + '\" schema'",
  _limit:          "'should be {{=$opStr}} {{#def.appendSchema}}",
  _exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
  _limitItems:     "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
  _limitLength:    "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
  _limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
  multipleOf:      "'should be multiple of {{#def.appendSchema}}",
  not:             "'should NOT be valid'",
  oneOf:           "'should match exactly one schema in oneOf'",
  pattern:         "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
  propertyNames:   "'property name \\'{{=$invalidName}}\\' is invalid'",
  required:        "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
  type:            "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
  uniqueItems:     "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'",
  custom:          "'should pass \"{{=$rule.keyword}}\" keyword validation'",
  patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''",
  switch:          "'should pass \"switch\" keyword validation'",
  _formatLimit:    "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'",
  _formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'"
} #}}


{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}}
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}

{{## def._errorSchemas = {
  'false schema':  "false",
  $ref:            "{{=it.util.toQuotedString($schema)}}",
  additionalItems: "false",
  additionalProperties: "false",
  anyOf:           "validate.schema{{=$schemaPath}}",
  const:           "validate.schema{{=$schemaPath}}",
  contains:        "validate.schema{{=$schemaPath}}",
  dependencies:    "validate.schema{{=$schemaPath}}",
  'enum':          "validate.schema{{=$schemaPath}}",
  format:          "{{#def.schemaRefOrQS}}",
  'if':            "validate.schema{{=$schemaPath}}",
  _limit:          "{{#def.schemaRefOrVal}}",
  _exclusiveLimit: "validate.schema{{=$schemaPath}}",
  _limitItems:     "{{#def.schemaRefOrVal}}",
  _limitLength:    "{{#def.schemaRefOrVal}}",
  _limitProperties:"{{#def.schemaRefOrVal}}",
  multipleOf:      "{{#def.schemaRefOrVal}}",
  not:             "validate.schema{{=$schemaPath}}",
  oneOf:           "validate.schema{{=$schemaPath}}",
  pattern:         "{{#def.schemaRefOrQS}}",
  propertyNames:   "validate.schema{{=$schemaPath}}",
  required:        "validate.schema{{=$schemaPath}}",
  type:            "validate.schema{{=$schemaPath}}",
  uniqueItems:     "{{#def.schemaRefOrVal}}",
  custom:          "validate.schema{{=$schemaPath}}",
  patternRequired: "validate.schema{{=$schemaPath}}",
  switch:          "validate.schema{{=$schemaPath}}",
  _formatLimit:    "{{#def.schemaRefOrQS}}",
  _formatExclusiveLimit: "validate.schema{{=$schemaPath}}"
} #}}


{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}

{{## def._errorParams = {
  'false schema':  "{}",
  $ref:            "{ ref: '{{=it.util.escapeQuotes($schema)}}' }",
  additionalItems: "{ limit: {{=$schema.length}} }",
  additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
  anyOf:           "{}",
  const:           "{ allowedValue: schema{{=$lvl}} }",
  contains:        "{}",
  dependencies:    "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
  'enum':          "{ allowedValues: schema{{=$lvl}} }",
  format:          "{ format: {{#def.schemaValueQS}} }",
  'if':            "{ failingKeyword: {{=$ifClause}} }",
  _limit:          "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
  _exclusiveLimit: "{}",
  _limitItems:     "{ limit: {{=$schemaValue}} }",
  _limitLength:    "{ limit: {{=$schemaValue}} }",
  _limitProperties:"{ limit: {{=$schemaValue}} }",
  multipleOf:      "{ multipleOf: {{=$schemaValue}} }",
  not:             "{}",
  oneOf:           "{ passingSchemas: {{=$passingSchemas}} }",
  pattern:         "{ pattern: {{#def.schemaValueQS}} }",
  propertyNames:   "{ propertyName: '{{=$invalidName}}' }",
  required:        "{ missingProperty: '{{=$missingProperty}}' }",
  type:            "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",
  uniqueItems:     "{ i: i, j: j }",
  custom:          "{ keyword: '{{=$rule.keyword}}' }",
  patternRequired: "{ missingPattern: '{{=$missingPattern}}' }",
  switch:          "{ caseIndex: {{=$caseIndex}} }",
  _formatLimit:    "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }",
  _formatExclusiveLimit: "{}"
} #}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}

{{## def.skipFormat:
  {{? $breakOnError }} if (true) { {{?}}
  {{ return out; }}
#}}

{{? it.opts.format === false }}{{# def.skipFormat }}{{?}}


{{# def.$data }}


{{## def.$dataCheckFormat:
  {{# def.$dataNotType:'string' }}
  ({{? $unknownFormats != 'ignore' }}
     ({{=$schemaValue}} && !{{=$format}}
      {{? $allowUnknown }}
        && self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1
      {{?}}) ||
   {{?}}
   ({{=$format}} && {{=$formatType}} == '{{=$ruleType}}'
                 && !(typeof {{=$format}} == 'function'
                     ? {{? it.async}}
                        (async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}}))
                       {{??}}
                        {{=$format}}({{=$data}})
                       {{?}}
                     : {{=$format}}.test({{=$data}}))))
#}}

{{## def.checkFormat:
  {{
    var $formatRef = 'formats' + it.util.getProperty($schema);
    if ($isObject) $formatRef += '.validate';
  }}
  {{? typeof $format == 'function' }}
    {{=$formatRef}}({{=$data}})
  {{??}}
    {{=$formatRef}}.test({{=$data}})
  {{?}}
#}}


{{
  var $unknownFormats = it.opts.unknownFormats
    , $allowUnknown = Array.isArray($unknownFormats);
}}

{{? $isData }}
  {{
    var $format = 'format' + $lvl
      , $isObject = 'isObject' + $lvl
      , $formatType = 'formatType' + $lvl;
  }}
  var {{=$format}} = formats[{{=$schemaValue}}];
  var {{=$isObject}} = typeof {{=$format}} == 'object'
                        && !({{=$format}} instanceof RegExp)
                        && {{=$format}}.validate;
  var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string';
  if ({{=$isObject}}) {
    {{? it.async}}
      var async{{=$lvl}} = {{=$format}}.async;
    {{?}}
    {{=$format}} = {{=$format}}.validate;
  }
  if ({{# def.$dataCheckFormat }}) {
{{??}}
  {{ var $format = it.formats[$schema]; }}
  {{? !$format }}
    {{? $unknownFormats == 'ignore' }}
      {{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }}
      {{# def.skipFormat }}
    {{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }}
      {{# def.skipFormat }}
    {{??}}
      {{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }}
    {{?}}
  {{?}}
  {{
    var $isObject = typeof $format == 'object'
                    && !($format instanceof RegExp)
                    && $format.validate;
    var $formatType = $isObject && $format.type || 'string';
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
  }}
  {{? $formatType != $ruleType }}
    {{# def.skipFormat }}
  {{?}}
  {{? $async }}
    {{
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
    }}
    if (!(await {{=$formatRef}}({{=$data}}))) {
  {{??}}
    if (!{{# def.checkFormat }}) {
  {{?}}
{{?}}
    {{# def.error:'format' }}
  } {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}


{{## def.validateIfClause:_clause:
  {{
    $it.schema = it.schema['_clause'];
    $it.schemaPath = it.schemaPath + '._clause';
    $it.errSchemaPath = it.errSchemaPath + '/_clause';
  }}
  {{# def.insertSubschemaCode }}
  {{=$valid}} = {{=$nextValid}};
  {{? $thenPresent && $elsePresent }}
    {{ $ifClause = 'ifClause' + $lvl; }}
    var {{=$ifClause}} = '_clause';
  {{??}}
    {{ $ifClause = '\'_clause\''; }}
  {{?}}
#}}

{{
  var $thenSch = it.schema['then']
    , $elseSch = it.schema['else']
    , $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }}
    , $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }}
    , $currentBaseId = $it.baseId;
}}

{{? $thenPresent || $elsePresent }}
  {{
    var $ifClause;
    $it.createErrors = false;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
  }}
  var {{=$errs}} = errors;
  var {{=$valid}} = true;

  {{# def.setCompositeRule }}
  {{# def.insertSubschemaCode }}
  {{ $it.createErrors = true; }}
  {{# def.resetErrors }}
  {{# def.resetCompositeRule }}

  {{? $thenPresent }}
    if ({{=$nextValid}}) {
      {{# def.validateIfClause:then }}
    }
    {{? $elsePresent }}
      else {
    {{?}}
  {{??}}
    if (!{{=$nextValid}}) {
  {{?}}

  {{? $elsePresent }}
      {{# def.validateIfClause:else }}
    }
  {{?}}

  if (!{{=$valid}}) {
    {{# def.extraError:'if' }}
  } 
  {{? $breakOnError }} else { {{?}}
{{??}}
  {{? $breakOnError }}
    if (true) {
  {{?}}
{{?}}

{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}


{{## def.validateItems:startFrom:
  for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) {
    {{
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
    }}

    {{# def.generateSubschemaCode }}
    {{# def.optimizeValidate }}

    {{? $breakOnError }}
      if (!{{=$nextValid}}) break;
    {{?}}
  }
#}}

{{
  var $idx = 'i' + $lvl
    , $dataNxt = $it.dataLevel = it.dataLevel + 1
    , $nextData = 'data' + $dataNxt
    , $currentBaseId = it.baseId;
}}

var {{=$errs}} = errors;
var {{=$valid}};

{{? Array.isArray($schema) }}
  {{ /* 'items' is an array of schemas */}}
  {{ var $additionalItems = it.schema.additionalItems; }}
  {{? $additionalItems === false }}
    {{=$valid}} = {{=$data}}.length <= {{= $schema.length }};
    {{
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';      
    }}
    {{# def.checkError:'additionalItems' }}
    {{ $errSchemaPath = $currErrSchemaPath; }}
    {{# def.elseIfValid}}
  {{?}}

  {{~ $schema:$sch:$i }}
    {{? {{# def.nonEmptySchema:$sch }} }}
      {{=$nextValid}} = true;

      if ({{=$data}}.length > {{=$i}}) {
        {{
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
        }}

        {{# def.generateSubschemaCode }}
        {{# def.optimizeValidate }}
      }

      {{# def.ifResultValid }}
    {{?}}
  {{~}}

  {{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }}
    {{
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
    }}
    {{=$nextValid}} = true;

    if ({{=$data}}.length > {{= $schema.length }}) {
      {{# def.validateItems: $schema.length }}
    }

    {{# def.ifResultValid }}
  {{?}}

{{?? {{# def.nonEmptySchema:$schema }} }}
  {{ /* 'items' is a single schema */}}
  {{
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
  }}
  {{# def.validateItems: 0 }}
{{?}}

{{? $breakOnError }}
  {{= $closingBraces }}
  if ({{=$errs}} == errors) {
{{?}}
{{## def.checkMissingProperty:_properties:
  {{~ _properties:$propertyKey:$i }}
    {{?$i}} || {{?}}
    {{
      var $prop = it.util.getProperty($propertyKey)
        , $useData = $data + $prop;
    }}
    ( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) )
  {{~}}
#}}


{{## def.errorMissingProperty:_error:
  {{
    var $propertyPath = 'missing' + $lvl
      , $missingProperty = '\' + ' + $propertyPath + ' + \'';
    if (it.opts._errorDataPathProperty) {
      it.errorPath = it.opts.jsonPointers
                      ? it.util.getPathExpr($currentErrorPath,  $propertyPath, true)
                      : $currentErrorPath + ' + ' + $propertyPath;
    }
  }}
  {{# def.error:_error }}
#}}


{{## def.allErrorsMissingProperty:_error:
  {{
    var $prop = it.util.getProperty($propertyKey)
      , $missingProperty = it.util.escapeQuotes($propertyKey)
      , $useData = $data + $prop;
    if (it.opts._errorDataPathProperty) {
      it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
    }
  }}
  if ({{# def.noPropertyInData }}) {
    {{# def.addError:_error }}
  }
#}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{# def.numberKeyword }}

var division{{=$lvl}};
if ({{?$isData}}
      {{=$schemaValue}} !== undefined && (
      typeof {{=$schemaValue}} != 'number' ||
    {{?}}
      (division{{=$lvl}} = {{=$data}} / {{=$schemaValue}},
      {{? it.opts.multipleOfPrecision }}
        Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}}
      {{??}}
        division{{=$lvl}} !== parseInt(division{{=$lvl}})
      {{?}}
      )
    {{?$isData}}  )  {{?}} ) {
  {{# def.error:'multipleOf' }}
} {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

{{? {{# def.nonEmptySchema:$schema }} }}
  {{
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
  }}

  var {{=$errs}} = errors;

  {{# def.setCompositeRule }}

  {{
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
  }}
  {{= it.validate($it) }}
  {{
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
  }}

  {{# def.resetCompositeRule }}

  if ({{=$nextValid}}) {
    {{# def.error:'not' }}
  } else {
    {{# def.resetErrors }}
  {{? it.opts.allErrors }} } {{?}}
{{??}}
  {{# def.addError:'not' }}
  {{? $breakOnError}}
    if (false) {
  {{?}}
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

{{
  var $currentBaseId = $it.baseId
    , $prevValid = 'prevValid' + $lvl
    , $passingSchemas = 'passingSchemas' + $lvl;
}}

var {{=$errs}} = errors
  , {{=$prevValid}} = false
  , {{=$valid}} = false
  , {{=$passingSchemas}} = null;

{{# def.setCompositeRule }}

{{~ $schema:$sch:$i }}
  {{? {{# def.nonEmptySchema:$sch }} }}
    {{
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + '[' + $i + ']';
      $it.errSchemaPath = $errSchemaPath + '/' + $i;
    }}

    {{# def.insertSubschemaCode }}
  {{??}}
    var {{=$nextValid}} = true;
  {{?}}

  {{? $i }}
    if ({{=$nextValid}} && {{=$prevValid}}) {
      {{=$valid}} = false;
      {{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}];
    } else {
    {{ $closingBraces += '}'; }}
  {{?}}

    if ({{=$nextValid}}) {
      {{=$valid}} = {{=$prevValid}} = true;
      {{=$passingSchemas}} = {{=$i}};
    }
{{~}}

{{# def.resetCompositeRule }}

{{= $closingBraces }}

if (!{{=$valid}}) {
  {{# def.extraError:'oneOf' }}
} else {
  {{# def.resetErrors }}
{{? it.opts.allErrors }} } {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}

{{
  var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
}}

{{? $isData }}
  var {{=$valid}} = true;
  try {
    {{=$valid}} = {{=$regExpCode}}({{=$schemaValue}}).test({{=$data}});
  } catch(e) {
    {{=$valid}} = false;
  }
  if ({{# def.$dataNotType:'string' }} !{{=$valid}}) {
{{??}}
  {{
    var $regexp = it.usePattern($schema);
  }}
  if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) {
{{?}}
  {{# def.error:'pattern' }}
} {{? $breakOnError }} else { {{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}


{{## def.validateAdditional:
  {{ /* additionalProperties is schema */
    $it.schema = $aProperties;
    $it.schemaPath = it.schemaPath + '.additionalProperties';
    $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
    $it.errorPath = it.opts._errorDataPathProperty
                    ? it.errorPath
                    : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
    var $passData = $data + '[' + $key + ']';
    $it.dataPathArr[$dataNxt] = $key;
  }}

  {{# def.generateSubschemaCode }}
  {{# def.optimizeValidate }}
#}}


{{
  var $key = 'key' + $lvl
    , $idx = 'idx' + $lvl
    , $dataNxt = $it.dataLevel = it.dataLevel + 1
    , $nextData = 'data' + $dataNxt
    , $dataProperties = 'dataProperties' + $lvl;

  var $schemaKeys = Object.keys($schema || {}).filter(notProto)
    , $pProperties = it.schema.patternProperties || {}
    , $pPropertyKeys = Object.keys($pProperties).filter(notProto)
    , $aProperties = it.schema.additionalProperties
    , $someProperties = $schemaKeys.length || $pPropertyKeys.length
    , $noAdditional = $aProperties === false
    , $additionalIsSchema = typeof $aProperties == 'object'
                              && Object.keys($aProperties).length
    , $removeAdditional = it.opts.removeAdditional
    , $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional
    , $ownProperties = it.opts.ownProperties
    , $currentBaseId = it.baseId;

  var $required = it.schema.required;
  if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
    var $requiredHash = it.util.toHash($required);
  }

  function notProto(p) { return p !== '__proto__'; }
}}


var {{=$errs}} = errors;
var {{=$nextValid}} = true;
{{? $ownProperties }}
  var {{=$dataProperties}} = undefined;
{{?}}

{{? $checkAdditional }}
  {{# def.iterateProperties }}
    {{? $someProperties }}
      var isAdditional{{=$lvl}} = !(false
        {{? $schemaKeys.length }}
          {{? $schemaKeys.length > 8 }}
            || validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}})
          {{??}}
            {{~ $schemaKeys:$propertyKey }}
              || {{=$key}} == {{= it.util.toQuotedString($propertyKey) }}
            {{~}}
          {{?}}
        {{?}}
        {{? $pPropertyKeys.length }}
          {{~ $pPropertyKeys:$pProperty:$i }}
            || {{= it.usePattern($pProperty) }}.test({{=$key}})
          {{~}}
        {{?}}
      );

      if (isAdditional{{=$lvl}}) {
    {{?}}
    {{? $removeAdditional == 'all' }}
      delete {{=$data}}[{{=$key}}];
    {{??}}
      {{
        var $currentErrorPath = it.errorPath;
        var $additionalProperty = '\' + ' + $key + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
        }
      }}
      {{? $noAdditional }}
        {{? $removeAdditional }}
          delete {{=$data}}[{{=$key}}];
        {{??}}
          {{=$nextValid}} = false;
          {{
            var $currErrSchemaPath = $errSchemaPath;
            $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          }}
          {{# def.error:'additionalProperties' }}
          {{ $errSchemaPath = $currErrSchemaPath; }}
          {{? $breakOnError }} break; {{?}}
        {{?}}
      {{?? $additionalIsSchema }}
        {{? $removeAdditional == 'failing' }}
          var {{=$errs}} = errors;
          {{# def.setCompositeRule }}

          {{# def.validateAdditional }}

          if (!{{=$nextValid}}) {
            errors = {{=$errs}};
            if (validate.errors !== null) {
              if (errors) validate.errors.length = errors;
              else validate.errors = null;
            }
            delete {{=$data}}[{{=$key}}];
          }

          {{# def.resetCompositeRule }}
        {{??}}
          {{# def.validateAdditional }}
          {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}}
        {{?}}
      {{?}}
      {{ it.errorPath = $currentErrorPath; }}
    {{?}}
    {{? $someProperties }}
      }
    {{?}}
  }

  {{# def.ifResultValid }}
{{?}}

{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }}

{{? $schemaKeys.length }}
  {{~ $schemaKeys:$propertyKey }}
    {{ var $sch = $schema[$propertyKey]; }}

    {{? {{# def.nonEmptySchema:$sch}} }}
      {{
        var $prop = it.util.getProperty($propertyKey)
          , $passData = $data + $prop
          , $hasDefault = $useDefaults && $sch.default !== undefined;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + $prop;
        $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
        $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
        $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
      }}

      {{# def.generateSubschemaCode }}

      {{? {{# def.willOptimize }} }}
        {{
          $code = {{# def._optimizeValidate }};
          var $useData = $passData;
        }}
      {{??}}
        {{ var $useData = $nextData; }}
        var {{=$nextData}} = {{=$passData}};
      {{?}}

      {{? $hasDefault }}
        {{= $code }}
      {{??}}
        {{? $requiredHash && $requiredHash[$propertyKey] }}
          if ({{# def.noPropertyInData }}) {
            {{=$nextValid}} = false;
            {{
              var $currentErrorPath = it.errorPath
                , $currErrSchemaPath = $errSchemaPath
                , $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
            }}
            {{# def.error:'required' }}
            {{ $errSchemaPath = $currErrSchemaPath; }}
            {{ it.errorPath = $currentErrorPath; }}
          } else {
        {{??}}
          {{? $breakOnError }}
            if ({{# def.noPropertyInData }}) {
              {{=$nextValid}} = true;
            } else {
          {{??}}
            if ({{=$useData}} !== undefined
              {{? $ownProperties }}
                && {{# def.isOwnProperty }}
              {{?}}
            ) {
          {{?}}
        {{?}}

          {{= $code }}
        }
      {{?}}  {{ /* $hasDefault */ }}
    {{?}} {{ /* def.nonEmptySchema */ }}

    {{# def.ifResultValid }}
  {{~}}
{{?}}

{{? $pPropertyKeys.length }}
  {{~ $pPropertyKeys:$pProperty }}
    {{ var $sch = $pProperties[$pProperty]; }}

    {{? {{# def.nonEmptySchema:$sch}} }}
      {{
        $it.schema = $sch;
        $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
        $it.errSchemaPath = it.errSchemaPath + '/patternProperties/'
                                             + it.util.escapeFragment($pProperty);
      }}

      {{# def.iterateProperties }}
        if ({{= it.usePattern($pProperty) }}.test({{=$key}})) {
          {{
            $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
            var $passData = $data + '[' + $key + ']';
            $it.dataPathArr[$dataNxt] = $key;
          }}

          {{# def.generateSubschemaCode }}
          {{# def.optimizeValidate }}

          {{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}}
        }
        {{? $breakOnError }} else {{=$nextValid}} = true; {{?}}
      }

      {{# def.ifResultValid }}
    {{?}} {{ /* def.nonEmptySchema */ }}
  {{~}}
{{?}}


{{? $breakOnError }}
  {{= $closingBraces }}
  if ({{=$errs}} == errors) {
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

var {{=$errs}} = errors;

{{? {{# def.nonEmptySchema:$schema }} }}
  {{
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
  }}

  {{
    var $key = 'key' + $lvl
      , $idx = 'idx' + $lvl
      , $i = 'i' + $lvl
      , $invalidName = '\' + ' + $key + ' + \''
      , $dataNxt = $it.dataLevel = it.dataLevel + 1
      , $nextData = 'data' + $dataNxt
      , $dataProperties = 'dataProperties' + $lvl
      , $ownProperties = it.opts.ownProperties
      , $currentBaseId = it.baseId;
  }}

  {{? $ownProperties }}
    var {{=$dataProperties}} = undefined;
  {{?}}
  {{# def.iterateProperties }}
    var startErrs{{=$lvl}} = errors;

    {{ var $passData = $key; }}
    {{# def.setCompositeRule }}
    {{# def.generateSubschemaCode }}
    {{# def.optimizeValidate }}
    {{# def.resetCompositeRule }}

    if (!{{=$nextValid}}) {
      for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}<errors; {{=$i}}++) {
        vErrors[{{=$i}}].propertyName = {{=$key}};
      }
      {{# def.extraError:'propertyNames' }}
      {{? $breakOnError }} break; {{?}}
    }
  }
{{?}}

{{? $breakOnError }}
  {{= $closingBraces }}
  if ({{=$errs}} == errors) {
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}

{{## def._validateRef:_v:
  {{? it.opts.passContext }}
    {{=_v}}.call(this,
  {{??}}
    {{=_v}}(
  {{?}}
    {{=$data}}, {{# def.dataPath }}{{# def.passParentData }}, rootData)
#}}

{{ var $async, $refCode; }}
{{? $schema == '#' || $schema == '#/' }}
  {{
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  }}
{{??}}
  {{ var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); }}
  {{? $refVal === undefined }}
    {{ var $message = it.MissingRefError.message(it.baseId, $schema); }}
    {{? it.opts.missingRefs == 'fail' }}
      {{ it.logger.error($message); }}
      {{# def.error:'$ref' }}
      {{? $breakOnError }} if (false) { {{?}}
    {{?? it.opts.missingRefs == 'ignore' }}
      {{ it.logger.warn($message); }}
      {{? $breakOnError }} if (true) { {{?}}
    {{??}}
      {{ throw new it.MissingRefError(it.baseId, $schema, $message); }}
    {{?}}
  {{?? $refVal.inline }}
    {{# def.setupNextLevel }}
    {{
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
    }}
    {{ var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); }}
    {{= $code }}
    {{? $breakOnError}}
      if ({{=$nextValid}}) {
    {{?}}
  {{??}}
    {{
      $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
      $refCode = $refVal.code;
    }}
  {{?}}
{{?}}

{{? $refCode }}
  {{# def.beginDefOut}}
    {{# def._validateRef:$refCode }}
  {{# def.storeDefOut:__callValidate }}

  {{? $async }}
    {{ if (!it.async) throw new Error('async schema referenced by sync schema'); }}
    {{? $breakOnError }} var {{=$valid}}; {{?}}
    try {
      await {{=__callValidate}};
      {{? $breakOnError }} {{=$valid}} = true; {{?}}
    } catch (e) {
      if (!(e instanceof ValidationError)) throw e;
      if (vErrors === null) vErrors = e.errors;
      else vErrors = vErrors.concat(e.errors);
      errors = vErrors.length;
      {{? $breakOnError }} {{=$valid}} = false; {{?}}
    }
    {{? $breakOnError }} if ({{=$valid}}) { {{?}}
  {{??}}
    if (!{{=__callValidate}}) {
      if (vErrors === null) vErrors = {{=$refCode}}.errors;
      else vErrors = vErrors.concat({{=$refCode}}.errors);
      errors = vErrors.length;
    } {{? $breakOnError }} else { {{?}}
  {{?}}
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.missing }}
{{# def.setupKeyword }}
{{# def.$data }}

{{ var $vSchema = 'schema' + $lvl; }}

{{## def.setupLoop:
  {{? !$isData }}
    var {{=$vSchema}} = validate.schema{{=$schemaPath}};
  {{?}}

  {{
    var $i = 'i' + $lvl
      , $propertyPath = 'schema' + $lvl + '[' + $i + ']'
      , $missingProperty = '\' + ' + $propertyPath + ' + \'';
    if (it.opts._errorDataPathProperty) {
      it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
    }
  }}
#}}


{{## def.isRequiredOwnProperty:
  Object.prototype.hasOwnProperty.call({{=$data}}, {{=$vSchema}}[{{=$i}}])
#}}


{{? !$isData }}
  {{? $schema.length < it.opts.loopRequired &&
      it.schema.properties && Object.keys(it.schema.properties).length }}
    {{ var $required = []; }}
    {{~ $schema:$property }}
      {{ var $propertySch = it.schema.properties[$property]; }}
      {{? !($propertySch && {{# def.nonEmptySchema:$propertySch}}) }}
        {{ $required[$required.length] = $property; }}
      {{?}}
    {{~}}
  {{??}}
    {{ var $required = $schema; }}
  {{?}}
{{?}}


{{? $isData || $required.length }}
  {{
    var $currentErrorPath = it.errorPath
      , $loopRequired = $isData || $required.length >= it.opts.loopRequired
      , $ownProperties = it.opts.ownProperties;
  }}

  {{? $breakOnError }}
    var missing{{=$lvl}};
    {{? $loopRequired }}
      {{# def.setupLoop }}
      var {{=$valid}} = true;

      {{?$isData}}{{# def.check$dataIsArray }}{{?}}

      for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
        {{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined
                      {{? $ownProperties }}
                        && {{# def.isRequiredOwnProperty }}
                      {{?}};
        if (!{{=$valid}}) break;
      }

      {{? $isData }}  }  {{?}}

      {{# def.checkError:'required' }}
      else {
    {{??}}
      if ({{# def.checkMissingProperty:$required }}) {
        {{# def.errorMissingProperty:'required' }}
      } else {
    {{?}}
  {{??}}
    {{? $loopRequired }}
      {{# def.setupLoop }}
      {{? $isData }}
        if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) {
          {{# def.addError:'required' }}
        } else if ({{=$vSchema}} !== undefined) {
      {{?}}

      for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) {
        if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined
            {{? $ownProperties }}
              || !{{# def.isRequiredOwnProperty }}
            {{?}}) {
          {{# def.addError:'required' }}
        }
      }

      {{? $isData }}  }  {{?}}
    {{??}}
      {{~ $required:$propertyKey }}
        {{# def.allErrorsMissingProperty:'required' }}
      {{~}}
    {{?}}
  {{?}}

  {{ it.errorPath = $currentErrorPath; }}

{{?? $breakOnError }}
  if (true) {
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.$data }}


{{? ($schema || $isData) && it.opts.uniqueItems !== false }}
  {{? $isData }}
    var {{=$valid}};
    if ({{=$schemaValue}} === false || {{=$schemaValue}} === undefined)
      {{=$valid}} = true;
    else if (typeof {{=$schemaValue}} != 'boolean')
      {{=$valid}} = false;
    else {
  {{?}}

  var i = {{=$data}}.length
    , {{=$valid}} = true
    , j;
  if (i > 1) {
    {{
      var $itemType = it.schema.items && it.schema.items.type
        , $typeIsArray = Array.isArray($itemType);
    }}
    {{? !$itemType || $itemType == 'object' || $itemType == 'array' ||
        ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) }}
      outer:
      for (;i--;) {
        for (j = i; j--;) {
          if (equal({{=$data}}[i], {{=$data}}[j])) {
            {{=$valid}} = false;
            break outer;
          }
        }
      }
    {{??}}
      var itemIndices = {}, item;
      for (;i--;) {
        var item = {{=$data}}[i];
        {{ var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); }}
        if ({{= it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) }}) continue;
        {{? $typeIsArray}}
          if (typeof item == 'string') item = '"' + item;
        {{?}}
        if (typeof itemIndices[item] == 'number') {
          {{=$valid}} = false;
          j = itemIndices[item];
          break;
        }
        itemIndices[item] = i;
      }
    {{?}}
  }

  {{? $isData }}  }  {{?}}

  if (!{{=$valid}}) {
    {{# def.error:'uniqueItems' }}
  } {{? $breakOnError }} else { {{?}}
{{??}}
  {{? $breakOnError }} if (true) { {{?}}
{{?}}
{{# def.definitions }}
{{# def.errors }}
{{# def.defaults }}
{{# def.coerce }}

{{ /**
    * schema compilation (render) time:
    * it = { schema, RULES, _validate, opts }
    * it.validate - this template function,
    *   it is used recursively to generate code for subschemas
    *
    * runtime:
    * "validate" is a variable name to which this function will be assigned
    * validateRef etc. are defined in the parent scope in index.js
    */ }}

{{
  var $async = it.schema.$async === true
    , $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref')
    , $id = it.self._getId(it.schema);
}}

{{
  if (it.opts.strictKeywords) {
    var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
    if ($unknownKwd) {
      var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
      if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
      else throw new Error($keywordsMsg);
    }
  }
}}

{{? it.isTop }}
  var validate = {{?$async}}{{it.async = true;}}async {{?}}function(data, dataPath, parentData, parentDataProperty, rootData) {
    'use strict';
    {{? $id && (it.opts.sourceCode || it.opts.processCode) }}
      {{= '/\*# sourceURL=' + $id + ' */' }}
    {{?}}
{{?}}

{{? typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref) }}
  {{ var $keyword = 'false schema'; }}
  {{# def.setupKeyword }}
  {{? it.schema === false}}
    {{? it.isTop}}
      {{ $breakOnError = true; }}
    {{??}}
      var {{=$valid}} = false;
    {{?}}
    {{# def.error:'false schema' }}
  {{??}}
    {{? it.isTop}}
      {{? $async }}
        return data;
      {{??}}
        validate.errors = null;
        return true;
      {{?}}
    {{??}}
      var {{=$valid}} = true;
    {{?}}
  {{?}}

  {{? it.isTop}}
    };
    return validate;
  {{?}}

  {{ return out; }}
{{?}}


{{? it.isTop }}
  {{
    var $top = it.isTop
      , $lvl = it.level = 0
      , $dataLvl = it.dataLevel = 0
      , $data = 'data';
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;

    it.dataPathArr = [""];

    if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
      var $defaultMsg = 'default is ignored in the schema root';
      if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
      else throw new Error($defaultMsg);
    }
  }}

  var vErrors = null; {{ /* don't edit, used in replace */ }}
  var errors = 0;     {{ /* don't edit, used in replace */ }}
  if (rootData === undefined) rootData = data; {{ /* don't edit, used in replace */ }}
{{??}}
  {{
    var $lvl = it.level
      , $dataLvl = it.dataLevel
      , $data = 'data' + ($dataLvl || '');

    if ($id) it.baseId = it.resolve.url(it.baseId, $id);

    if ($async && !it.async) throw new Error('async schema in sync schema');
  }}

  var errs_{{=$lvl}} = errors;
{{?}}

{{
  var $valid = 'valid' + $lvl
    , $breakOnError = !it.opts.allErrors
    , $closingBraces1 = ''
    , $closingBraces2 = '';

  var $errorKeyword;
  var $typeSchema = it.schema.type
    , $typeIsArray = Array.isArray($typeSchema);

  if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
    if ($typeIsArray) {
      if ($typeSchema.indexOf('null') == -1)
        $typeSchema = $typeSchema.concat('null');
    } else if ($typeSchema != 'null') {
      $typeSchema = [$typeSchema, 'null'];
      $typeIsArray = true;
    }
  }

  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
}}

{{## def.checkType:
  {{
    var $schemaPath = it.schemaPath + '.type'
      , $errSchemaPath = it.errSchemaPath + '/type'
      , $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
  }}

  if ({{= it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) }}) {
#}}

{{? it.schema.$ref && $refKeywords }}
  {{? it.opts.extendRefs == 'fail' }}
    {{ throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); }}
  {{?? it.opts.extendRefs !== true }}
    {{
      $refKeywords = false;
      it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }}
  {{?}}
{{?}}

{{? it.schema.$comment && it.opts.$comment }}
  {{= it.RULES.all.$comment.code(it, '$comment') }}
{{?}}

{{? $typeSchema }}
  {{? it.opts.coerceTypes }}
    {{ var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); }}
  {{?}}

  {{ var $rulesGroup = it.RULES.types[$typeSchema]; }}
  {{? $coerceToTypes || $typeIsArray || $rulesGroup === true ||
    ($rulesGroup && !$shouldUseGroup($rulesGroup)) }}
    {{
      var $schemaPath = it.schemaPath + '.type'
        , $errSchemaPath = it.errSchemaPath + '/type';
    }}
    {{# def.checkType }}
      {{? $coerceToTypes }}
        {{# def.coerceType }}
      {{??}}
        {{# def.error:'type' }}
      {{?}}
    }
  {{?}}
{{?}}


{{? it.schema.$ref && !$refKeywords }}
  {{= it.RULES.all.$ref.code(it, '$ref') }}
  {{? $breakOnError }}
    }
    if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) {
    {{ $closingBraces2 += '}'; }}
  {{?}}
{{??}}
  {{~ it.RULES:$rulesGroup }}
    {{? $shouldUseGroup($rulesGroup) }}
      {{? $rulesGroup.type }}
        if ({{= it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) }}) {
      {{?}}
        {{? it.opts.useDefaults }}
          {{? $rulesGroup.type == 'object' && it.schema.properties }}
            {{# def.defaultProperties }}
          {{?? $rulesGroup.type == 'array' && Array.isArray(it.schema.items) }}
            {{# def.defaultItems }}
          {{?}}
        {{?}}
        {{~ $rulesGroup.rules:$rule }}
          {{? $shouldUseRule($rule) }}
            {{ var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); }}
            {{? $code }}
              {{= $code }}
              {{? $breakOnError }}
                {{ $closingBraces1 += '}'; }}
              {{?}}
            {{?}}
          {{?}}
        {{~}}
        {{? $breakOnError }}
          {{= $closingBraces1 }}
          {{ $closingBraces1 = ''; }}
        {{?}}
      {{? $rulesGroup.type }}
        }
        {{? $typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes }}
          else {
            {{
              var $schemaPath = it.schemaPath + '.type'
                , $errSchemaPath = it.errSchemaPath + '/type';
            }}
            {{# def.error:'type' }}
          }
        {{?}}
      {{?}}

      {{? $breakOnError }}
        if (errors === {{?$top}}0{{??}}errs_{{=$lvl}}{{?}}) {
        {{ $closingBraces2 += '}'; }}
      {{?}}
    {{?}}
  {{~}}
{{?}}

{{? $breakOnError }} {{= $closingBraces2 }} {{?}}

{{? $top }}
    {{? $async }}
      if (errors === 0) return data;           {{ /* don't edit, used in replace */ }}
      else throw new ValidationError(vErrors); {{ /* don't edit, used in replace */ }}
    {{??}}
      validate.errors = vErrors; {{ /* don't edit, used in replace */ }}
      return errors === 0;       {{ /* don't edit, used in replace */ }}
    {{?}}
  };

  return validate;
{{??}}
  var {{=$valid}} = errors === errs_{{=$lvl}};
{{?}}

{{
  function $shouldUseGroup($rulesGroup) {
    var rules = $rulesGroup.rules;
    for (var i=0; i < rules.length; i++)
      if ($shouldUseRule(rules[i]))
        return true;
  }

  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined ||
           ($rule.implements && $ruleImplementsSomeKeyword($rule));
  }

  function $ruleImplementsSomeKeyword($rule) {
    var impl = $rule.implements;
    for (var i=0; i < impl.length; i++)
      if (it.schema[impl[i]] !== undefined)
        return true;
  }
}}
These files are compiled dot templates from dot folder.

Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder.
'use strict';
module.exports = function generate__limit(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $isMax = $keyword == 'maximum',
    $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
    $schemaExcl = it.schema[$exclusiveKeyword],
    $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
    $op = $isMax ? '<' : '>',
    $notOp = $isMax ? '>' : '<',
    $errorKeyword = undefined;
  if (!($isData || typeof $schema == 'number' || $schema === undefined)) {
    throw new Error($keyword + ' must be number');
  }
  if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {
    throw new Error($exclusiveKeyword + ' must be number or boolean');
  }
  if ($isDataExcl) {
    var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
      $exclusive = 'exclusive' + $lvl,
      $exclType = 'exclType' + $lvl,
      $exclIsNumber = 'exclIsNumber' + $lvl,
      $opExpr = 'op' + $lvl,
      $opStr = '\' + ' + $opExpr + ' + \'';
    out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
    $schemaValueExcl = 'schemaExcl' + $lvl;
    out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
    var $errorKeyword = $exclusiveKeyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
    }
    out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
    if ($schema === undefined) {
      $errorKeyword = $exclusiveKeyword;
      $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
      $schemaValue = $schemaValueExcl;
      $isData = $isDataExcl;
    }
  } else {
    var $exclIsNumber = typeof $schemaExcl == 'number',
      $opStr = $op;
    if ($exclIsNumber && $isData) {
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
    } else {
      if ($exclIsNumber && $schema === undefined) {
        $exclusive = true;
        $errorKeyword = $exclusiveKeyword;
        $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
        $schemaValue = $schemaExcl;
        $notOp += '=';
      } else {
        if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
        if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
          $exclusive = true;
          $errorKeyword = $exclusiveKeyword;
          $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
          $notOp += '=';
        } else {
          $exclusive = false;
          $opStr += '=';
        }
      }
      var $opExpr = '\'' + $opStr + '\'';
      out += ' if ( ';
      if ($isData) {
        out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
      }
      out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
    }
  }
  $errorKeyword = $errorKeyword || $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be ' + ($opStr) + ' ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate__limitItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxItems' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxItems') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' items\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate__limitLength(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxLength' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  if (it.opts.unicode === false) {
    out += ' ' + ($data) + '.length ';
  } else {
    out += ' ucs2length(' + ($data) + ') ';
  }
  out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT be ';
      if ($keyword == 'maxLength') {
        out += 'longer';
      } else {
        out += 'shorter';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' characters\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  var $op = $keyword == 'maxProperties' ? '>' : '<';
  out += 'if ( ';
  if ($isData) {
    out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
  }
  out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
  var $errorKeyword = $keyword;
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should NOT have ';
      if ($keyword == 'maxProperties') {
        out += 'more';
      } else {
        out += 'fewer';
      }
      out += ' than ';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + ($schema);
      }
      out += ' properties\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_allOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $allSchemasEmpty = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
        $allSchemasEmpty = false;
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($breakOnError) {
    if ($allSchemasEmpty) {
      out += ' if (true) { ';
    } else {
      out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
    }
  }
  return out;
}
'use strict';
module.exports = function generate_anyOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $noEmptySchema = $schema.every(function($sch) {
    return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all));
  });
  if ($noEmptySchema) {
    var $currentBaseId = $it.baseId;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
        out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
        $closingBraces += '}';
      }
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match some schema in anyOf\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}
'use strict';
module.exports = function generate_comment(it, $keyword, $ruleType) {
  var out = ' ';
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $comment = it.util.toQuotedString($schema);
  if (it.opts.$comment === true) {
    out += ' console.log(' + ($comment) + ');';
  } else if (typeof it.opts.$comment == 'function') {
    out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
  }
  return out;
}
'use strict';
module.exports = function generate_const(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!$isData) {
    out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to constant\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_contains(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId,
    $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all));
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($nonEmptySchema) {
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    out += ' if (' + ($nextValid) + ') break; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
  } else {
    out += ' if (' + ($data) + '.length == 0) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should contain a valid item\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } else { ';
  if ($nonEmptySchema) {
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
  }
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}
'use strict';
module.exports = function generate_custom(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $errorKeyword;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $rule = this,
    $definition = 'definition' + $lvl,
    $rDef = $rule.definition,
    $closingBraces = '';
  var $compile, $inline, $macro, $ruleValidate, $validateCode;
  if ($isData && $rDef.$data) {
    $validateCode = 'keywordValidate' + $lvl;
    var $validateSchema = $rDef.validateSchema;
    out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
  } else {
    $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
    if (!$ruleValidate) return;
    $schemaValue = 'validate.schema' + $schemaPath;
    $validateCode = $ruleValidate.code;
    $compile = $rDef.compile;
    $inline = $rDef.inline;
    $macro = $rDef.macro;
  }
  var $ruleErrs = $validateCode + '.errors',
    $i = 'i' + $lvl,
    $ruleErr = 'ruleErr' + $lvl,
    $asyncKeyword = $rDef.async;
  if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
  if (!($inline || $macro)) {
    out += '' + ($ruleErrs) + ' = null;';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if ($isData && $rDef.$data) {
    $closingBraces += '}';
    out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
    if ($validateSchema) {
      $closingBraces += '}';
      out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
    }
  }
  if ($inline) {
    if ($rDef.statements) {
      out += ' ' + ($ruleValidate.validate) + ' ';
    } else {
      out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
    }
  } else if ($macro) {
    var $it = it.util.copy(it);
    var $closingBraces = '';
    $it.level++;
    var $nextValid = 'valid' + $it.level;
    $it.schema = $ruleValidate.validate;
    $it.schemaPath = '';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' ' + ($code);
  } else {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    out += '  ' + ($validateCode) + '.call( ';
    if (it.opts.passContext) {
      out += 'this';
    } else {
      out += 'self';
    }
    if ($compile || $rDef.schema === false) {
      out += ' , ' + ($data) + ' ';
    } else {
      out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
    }
    out += ' , (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData )  ';
    var def_callRuleValidate = out;
    out = $$outStack.pop();
    if ($rDef.errors === false) {
      out += ' ' + ($valid) + ' = ';
      if ($asyncKeyword) {
        out += 'await ';
      }
      out += '' + (def_callRuleValidate) + '; ';
    } else {
      if ($asyncKeyword) {
        $ruleErrs = 'customErrors' + $lvl;
        out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
      } else {
        out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
      }
    }
  }
  if ($rDef.modifying) {
    out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
  }
  out += '' + ($closingBraces);
  if ($rDef.valid) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  } else {
    out += ' if ( ';
    if ($rDef.valid === undefined) {
      out += ' !';
      if ($macro) {
        out += '' + ($nextValid);
      } else {
        out += '' + ($valid);
      }
    } else {
      out += ' ' + (!$rDef.valid) + ' ';
    }
    out += ') { ';
    $errorKeyword = $rule.keyword;
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    var def_customError = out;
    out = $$outStack.pop();
    if ($inline) {
      if ($rDef.errors) {
        if ($rDef.errors != 'full') {
          out += '  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } ';
        }
      } else {
        if ($rDef.errors === false) {
          out += ' ' + (def_customError) + ' ';
        } else {
          out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else {  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
          if (it.opts.verbose) {
            out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
          }
          out += ' } } ';
        }
      }
    } else if ($macro) {
      out += '   var err =   '; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError(vErrors); ';
        } else {
          out += ' validate.errors = vErrors; return false; ';
        }
      }
    } else {
      if ($rDef.errors === false) {
        out += ' ' + (def_customError) + ' ';
      } else {
        out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length;  for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + ';  ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '";  ';
        if (it.opts.verbose) {
          out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
        }
        out += ' } } else { ' + (def_customError) + ' } ';
      }
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  }
  return out;
}
'use strict';
module.exports = function generate_dependencies(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $schemaDeps = {},
    $propertyDeps = {},
    $ownProperties = it.opts.ownProperties;
  for ($property in $schema) {
    if ($property == '__proto__') continue;
    var $sch = $schema[$property];
    var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
    $deps[$property] = $sch;
  }
  out += 'var ' + ($errs) + ' = errors;';
  var $currentErrorPath = it.errorPath;
  out += 'var missing' + ($lvl) + ';';
  for (var $property in $propertyDeps) {
    $deps = $propertyDeps[$property];
    if ($deps.length) {
      out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      if ($breakOnError) {
        out += ' && ( ';
        var arr1 = $deps;
        if (arr1) {
          var $propertyKey, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $propertyKey = arr1[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ')) {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should have ';
            if ($deps.length == 1) {
              out += 'property ' + (it.util.escapeQuotes($deps[0]));
            } else {
              out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
            }
            out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      } else {
        out += ' ) { ';
        var arr2 = $deps;
        if (arr2) {
          var $propertyKey, i2 = -1,
            l2 = arr2.length - 1;
          while (i2 < l2) {
            $propertyKey = arr2[i2 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'should have ';
                if ($deps.length == 1) {
                  out += 'property ' + (it.util.escapeQuotes($deps[0]));
                } else {
                  out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
                }
                out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
      out += ' }   ';
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
  }
  it.errorPath = $currentErrorPath;
  var $currentBaseId = $it.baseId;
  for (var $property in $schemaDeps) {
    var $sch = $schemaDeps[$property];
    if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
      out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
      if ($ownProperties) {
        out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
      }
      out += ') { ';
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + it.util.getProperty($property);
      $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  }
  if ($breakOnError) {
    out += '   ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}
'use strict';
module.exports = function generate_enum(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $i = 'i' + $lvl,
    $vSchema = 'schema' + $lvl;
  if (!$isData) {
    out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
  }
  out += 'var ' + ($valid) + ';';
  if ($isData) {
    out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
  }
  out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
  if ($isData) {
    out += '  }  ';
  }
  out += ' if (!' + ($valid) + ') {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be equal to one of the allowed values\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' }';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_format(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  if (it.opts.format === false) {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
    return out;
  }
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $unknownFormats = it.opts.unknownFormats,
    $allowUnknown = Array.isArray($unknownFormats);
  if ($isData) {
    var $format = 'format' + $lvl,
      $isObject = 'isObject' + $lvl,
      $formatType = 'formatType' + $lvl;
    out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
    if (it.async) {
      out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
    }
    out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if (  ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' (';
    if ($unknownFormats != 'ignore') {
      out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
      if ($allowUnknown) {
        out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
      }
      out += ') || ';
    }
    out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
    if (it.async) {
      out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
    } else {
      out += ' ' + ($format) + '(' + ($data) + ') ';
    }
    out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
  } else {
    var $format = it.formats[$schema];
    if (!$format) {
      if ($unknownFormats == 'ignore') {
        it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
        if ($breakOnError) {
          out += ' if (true) { ';
        }
        return out;
      } else {
        throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
      }
    }
    var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
    var $formatType = $isObject && $format.type || 'string';
    if ($isObject) {
      var $async = $format.async === true;
      $format = $format.validate;
    }
    if ($formatType != $ruleType) {
      if ($breakOnError) {
        out += ' if (true) { ';
      }
      return out;
    }
    if ($async) {
      if (!it.async) throw new Error('async format in sync schema');
      var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
      out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
    } else {
      out += ' if (! ';
      var $formatRef = 'formats' + it.util.getProperty($schema);
      if ($isObject) $formatRef += '.validate';
      if (typeof $format == 'function') {
        out += ' ' + ($formatRef) + '(' + ($data) + ') ';
      } else {
        out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
      }
      out += ') { ';
    }
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match format "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += ' } ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_if(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $thenSch = it.schema['then'],
    $elseSch = it.schema['else'],
    $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)),
    $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)),
    $currentBaseId = $it.baseId;
  if ($thenPresent || $elsePresent) {
    var $ifClause;
    $it.createErrors = false;
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    out += '  ' + (it.validate($it)) + ' ';
    $it.baseId = $currentBaseId;
    $it.createErrors = true;
    out += '  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }  ';
    it.compositeRule = $it.compositeRule = $wasComposite;
    if ($thenPresent) {
      out += ' if (' + ($nextValid) + ') {  ';
      $it.schema = it.schema['then'];
      $it.schemaPath = it.schemaPath + '.then';
      $it.errSchemaPath = it.errSchemaPath + '/then';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'then\'; ';
      } else {
        $ifClause = '\'then\'';
      }
      out += ' } ';
      if ($elsePresent) {
        out += ' else { ';
      }
    } else {
      out += ' if (!' + ($nextValid) + ') { ';
    }
    if ($elsePresent) {
      $it.schema = it.schema['else'];
      $it.schemaPath = it.schemaPath + '.else';
      $it.errSchemaPath = it.errSchemaPath + '/else';
      out += '  ' + (it.validate($it)) + ' ';
      $it.baseId = $currentBaseId;
      out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
      if ($thenPresent && $elsePresent) {
        $ifClause = 'ifClause' + $lvl;
        out += ' var ' + ($ifClause) + ' = \'else\'; ';
      } else {
        $ifClause = '\'else\'';
      }
      out += ' } ';
    }
    out += ' if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    out += ' }   ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}
'use strict';

//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
  '$ref': require('./ref'),
  allOf: require('./allOf'),
  anyOf: require('./anyOf'),
  '$comment': require('./comment'),
  const: require('./const'),
  contains: require('./contains'),
  dependencies: require('./dependencies'),
  'enum': require('./enum'),
  format: require('./format'),
  'if': require('./if'),
  items: require('./items'),
  maximum: require('./_limit'),
  minimum: require('./_limit'),
  maxItems: require('./_limitItems'),
  minItems: require('./_limitItems'),
  maxLength: require('./_limitLength'),
  minLength: require('./_limitLength'),
  maxProperties: require('./_limitProperties'),
  minProperties: require('./_limitProperties'),
  multipleOf: require('./multipleOf'),
  not: require('./not'),
  oneOf: require('./oneOf'),
  pattern: require('./pattern'),
  properties: require('./properties'),
  propertyNames: require('./propertyNames'),
  required: require('./required'),
  uniqueItems: require('./uniqueItems'),
  validate: require('./validate')
};
'use strict';
module.exports = function generate_items(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $idx = 'i' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $currentBaseId = it.baseId;
  out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
  if (Array.isArray($schema)) {
    var $additionalItems = it.schema.additionalItems;
    if ($additionalItems === false) {
      out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
      var $currErrSchemaPath = $errSchemaPath;
      $errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += '  if (!' + ($valid) + ') {   ';
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
        if (it.opts.messages !== false) {
          out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
      out += ' } ';
      $errSchemaPath = $currErrSchemaPath;
      if ($breakOnError) {
        $closingBraces += '}';
        out += ' else { ';
      }
    }
    var arr1 = $schema;
    if (arr1) {
      var $sch, $i = -1,
        l1 = arr1.length - 1;
      while ($i < l1) {
        $sch = arr1[$i += 1];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
          var $passData = $data + '[' + $i + ']';
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + '[' + $i + ']';
          $it.errSchemaPath = $errSchemaPath + '/' + $i;
          $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
          $it.dataPathArr[$dataNxt] = $i;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
    if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
      $it.schema = $additionalItems;
      $it.schemaPath = it.schemaPath + '.additionalItems';
      $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
      out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') {  for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
      $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
      var $passData = $data + '[' + $idx + ']';
      $it.dataPathArr[$dataNxt] = $idx;
      var $code = it.validate($it);
      $it.baseId = $currentBaseId;
      if (it.util.varOccurences($code, $nextData) < 2) {
        out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
      } else {
        out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
      }
      if ($breakOnError) {
        out += ' if (!' + ($nextValid) + ') break; ';
      }
      out += ' } }  ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
        $closingBraces += '}';
      }
    }
  } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += '  for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
    $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
    var $passData = $data + '[' + $idx + ']';
    $it.dataPathArr[$dataNxt] = $idx;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    if ($breakOnError) {
      out += ' if (!' + ($nextValid) + ') break; ';
    }
    out += ' }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}
'use strict';
module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (!($isData || typeof $schema == 'number')) {
    throw new Error($keyword + ' must be number');
  }
  out += 'var division' + ($lvl) + ';if (';
  if ($isData) {
    out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
  }
  out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
  if (it.opts.multipleOfPrecision) {
    out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
  } else {
    out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
  }
  out += ' ) ';
  if ($isData) {
    out += '  )  ';
  }
  out += ' ) {   ';
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should be multiple of ';
      if ($isData) {
        out += '\' + ' + ($schemaValue);
      } else {
        out += '' + ($schemaValue) + '\'';
      }
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + ($schema);
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_not(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    out += ' var ' + ($errs) + ' = errors;  ';
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    $it.createErrors = false;
    var $allErrorsOption;
    if ($it.opts.allErrors) {
      $allErrorsOption = $it.opts.allErrors;
      $it.opts.allErrors = false;
    }
    out += ' ' + (it.validate($it)) + ' ';
    $it.createErrors = true;
    if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (' + ($nextValid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
    if (it.opts.allErrors) {
      out += ' } ';
    }
  } else {
    out += '  var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT be valid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if ($breakOnError) {
      out += ' if (false) { ';
    }
  }
  return out;
}
'use strict';
module.exports = function generate_oneOf(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $currentBaseId = $it.baseId,
    $prevValid = 'prevValid' + $lvl,
    $passingSchemas = 'passingSchemas' + $lvl;
  out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
  var $wasComposite = it.compositeRule;
  it.compositeRule = $it.compositeRule = true;
  var arr1 = $schema;
  if (arr1) {
    var $sch, $i = -1,
      l1 = arr1.length - 1;
    while ($i < l1) {
      $sch = arr1[$i += 1];
      if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
        $it.schema = $sch;
        $it.schemaPath = $schemaPath + '[' + $i + ']';
        $it.errSchemaPath = $errSchemaPath + '/' + $i;
        out += '  ' + (it.validate($it)) + ' ';
        $it.baseId = $currentBaseId;
      } else {
        out += ' var ' + ($nextValid) + ' = true; ';
      }
      if ($i) {
        out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
        $closingBraces += '}';
      }
      out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
    }
  }
  it.compositeRule = $it.compositeRule = $wasComposite;
  out += '' + ($closingBraces) + 'if (!' + ($valid) + ') {   var err =   '; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match exactly one schema in oneOf\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; return false; ';
    }
  }
  out += '} else {  errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
  if (it.opts.allErrors) {
    out += ' } ';
  }
  return out;
}
'use strict';
module.exports = function generate_pattern(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $regExpCode = it.opts.regExp ? 'regExp' : 'new RegExp';
  if ($isData) {
    out += ' var ' + ($valid) + ' = true; try { ' + ($valid) + ' = ' + ($regExpCode) + '(' + ($schemaValue) + ').test(' + ($data) + '); } catch(e) { ' + ($valid) + ' = false; } if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' !' + ($valid) + ') {';
  } else {
    var $regexp = it.usePattern($schema);
    out += ' if ( ';
    if ($isData) {
      out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
    }
    out += ' !' + ($regexp) + '.test(' + ($data) + ') ) {';
  }
  var $$outStack = $$outStack || [];
  $$outStack.push(out);
  out = ''; /* istanbul ignore else */
  if (it.createErrors !== false) {
    out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern:  ';
    if ($isData) {
      out += '' + ($schemaValue);
    } else {
      out += '' + (it.util.toQuotedString($schema));
    }
    out += '  } ';
    if (it.opts.messages !== false) {
      out += ' , message: \'should match pattern "';
      if ($isData) {
        out += '\' + ' + ($schemaValue) + ' + \'';
      } else {
        out += '' + (it.util.escapeQuotes($schema));
      }
      out += '"\' ';
    }
    if (it.opts.verbose) {
      out += ' , schema:  ';
      if ($isData) {
        out += 'validate.schema' + ($schemaPath);
      } else {
        out += '' + (it.util.toQuotedString($schema));
      }
      out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
    }
    out += ' } ';
  } else {
    out += ' {} ';
  }
  var __err = out;
  out = $$outStack.pop();
  if (!it.compositeRule && $breakOnError) {
    /* istanbul ignore if */
    if (it.async) {
      out += ' throw new ValidationError([' + (__err) + ']); ';
    } else {
      out += ' validate.errors = [' + (__err) + ']; return false; ';
    }
  } else {
    out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
  }
  out += '} ';
  if ($breakOnError) {
    out += ' else { ';
  }
  return out;
}
'use strict';
module.exports = function generate_properties(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  var $key = 'key' + $lvl,
    $idx = 'idx' + $lvl,
    $dataNxt = $it.dataLevel = it.dataLevel + 1,
    $nextData = 'data' + $dataNxt,
    $dataProperties = 'dataProperties' + $lvl;
  var $schemaKeys = Object.keys($schema || {}).filter(notProto),
    $pProperties = it.schema.patternProperties || {},
    $pPropertyKeys = Object.keys($pProperties).filter(notProto),
    $aProperties = it.schema.additionalProperties,
    $someProperties = $schemaKeys.length || $pPropertyKeys.length,
    $noAdditional = $aProperties === false,
    $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
    $removeAdditional = it.opts.removeAdditional,
    $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
    $ownProperties = it.opts.ownProperties,
    $currentBaseId = it.baseId;
  var $required = it.schema.required;
  if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {
    var $requiredHash = it.util.toHash($required);
  }

  function notProto(p) {
    return p !== '__proto__';
  }
  out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
  if ($ownProperties) {
    out += ' var ' + ($dataProperties) + ' = undefined;';
  }
  if ($checkAdditional) {
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    if ($someProperties) {
      out += ' var isAdditional' + ($lvl) + ' = !(false ';
      if ($schemaKeys.length) {
        if ($schemaKeys.length > 8) {
          out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
        } else {
          var arr1 = $schemaKeys;
          if (arr1) {
            var $propertyKey, i1 = -1,
              l1 = arr1.length - 1;
            while (i1 < l1) {
              $propertyKey = arr1[i1 += 1];
              out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
            }
          }
        }
      }
      if ($pPropertyKeys.length) {
        var arr2 = $pPropertyKeys;
        if (arr2) {
          var $pProperty, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $pProperty = arr2[$i += 1];
            out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
          }
        }
      }
      out += ' ); if (isAdditional' + ($lvl) + ') { ';
    }
    if ($removeAdditional == 'all') {
      out += ' delete ' + ($data) + '[' + ($key) + ']; ';
    } else {
      var $currentErrorPath = it.errorPath;
      var $additionalProperty = '\' + ' + $key + ' + \'';
      if (it.opts._errorDataPathProperty) {
        it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
      }
      if ($noAdditional) {
        if ($removeAdditional) {
          out += ' delete ' + ($data) + '[' + ($key) + ']; ';
        } else {
          out += ' ' + ($nextValid) + ' = false; ';
          var $currErrSchemaPath = $errSchemaPath;
          $errSchemaPath = it.errSchemaPath + '/additionalProperties';
          var $$outStack = $$outStack || [];
          $$outStack.push(out);
          out = ''; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is an invalid additional property';
              } else {
                out += 'should NOT have additional properties';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          var __err = out;
          out = $$outStack.pop();
          if (!it.compositeRule && $breakOnError) {
            /* istanbul ignore if */
            if (it.async) {
              out += ' throw new ValidationError([' + (__err) + ']); ';
            } else {
              out += ' validate.errors = [' + (__err) + ']; return false; ';
            }
          } else {
            out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
          }
          $errSchemaPath = $currErrSchemaPath;
          if ($breakOnError) {
            out += ' break; ';
          }
        }
      } else if ($additionalIsSchema) {
        if ($removeAdditional == 'failing') {
          out += ' var ' + ($errs) + ' = errors;  ';
          var $wasComposite = it.compositeRule;
          it.compositeRule = $it.compositeRule = true;
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; }  ';
          it.compositeRule = $it.compositeRule = $wasComposite;
        } else {
          $it.schema = $aProperties;
          $it.schemaPath = it.schemaPath + '.additionalProperties';
          $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
          $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
        }
      }
      it.errorPath = $currentErrorPath;
    }
    if ($someProperties) {
      out += ' } ';
    }
    out += ' }  ';
    if ($breakOnError) {
      out += ' if (' + ($nextValid) + ') { ';
      $closingBraces += '}';
    }
  }
  var $useDefaults = it.opts.useDefaults && !it.compositeRule;
  if ($schemaKeys.length) {
    var arr3 = $schemaKeys;
    if (arr3) {
      var $propertyKey, i3 = -1,
        l3 = arr3.length - 1;
      while (i3 < l3) {
        $propertyKey = arr3[i3 += 1];
        var $sch = $schema[$propertyKey];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          var $prop = it.util.getProperty($propertyKey),
            $passData = $data + $prop,
            $hasDefault = $useDefaults && $sch.default !== undefined;
          $it.schema = $sch;
          $it.schemaPath = $schemaPath + $prop;
          $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
          $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
          $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            $code = it.util.varReplace($code, $nextData, $passData);
            var $useData = $passData;
          } else {
            var $useData = $nextData;
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
          }
          if ($hasDefault) {
            out += ' ' + ($code) + ' ';
          } else {
            if ($requiredHash && $requiredHash[$propertyKey]) {
              out += ' if ( ' + ($useData) + ' === undefined ';
              if ($ownProperties) {
                out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
              }
              out += ') { ' + ($nextValid) + ' = false; ';
              var $currentErrorPath = it.errorPath,
                $currErrSchemaPath = $errSchemaPath,
                $missingProperty = it.util.escapeQuotes($propertyKey);
              if (it.opts._errorDataPathProperty) {
                it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
              }
              $errSchemaPath = it.errSchemaPath + '/required';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'';
                  if (it.opts._errorDataPathProperty) {
                    out += 'is a required property';
                  } else {
                    out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              $errSchemaPath = $currErrSchemaPath;
              it.errorPath = $currentErrorPath;
              out += ' } else { ';
            } else {
              if ($breakOnError) {
                out += ' if ( ' + ($useData) + ' === undefined ';
                if ($ownProperties) {
                  out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ') { ' + ($nextValid) + ' = true; } else { ';
              } else {
                out += ' if (' + ($useData) + ' !== undefined ';
                if ($ownProperties) {
                  out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
                }
                out += ' ) { ';
              }
            }
            out += ' ' + ($code) + ' } ';
          }
        }
        if ($breakOnError) {
          out += ' if (' + ($nextValid) + ') { ';
          $closingBraces += '}';
        }
      }
    }
  }
  if ($pPropertyKeys.length) {
    var arr4 = $pPropertyKeys;
    if (arr4) {
      var $pProperty, i4 = -1,
        l4 = arr4.length - 1;
      while (i4 < l4) {
        $pProperty = arr4[i4 += 1];
        var $sch = $pProperties[$pProperty];
        if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {
          $it.schema = $sch;
          $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
          $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
          if ($ownProperties) {
            out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
          } else {
            out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
          }
          out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
          $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
          var $passData = $data + '[' + $key + ']';
          $it.dataPathArr[$dataNxt] = $key;
          var $code = it.validate($it);
          $it.baseId = $currentBaseId;
          if (it.util.varOccurences($code, $nextData) < 2) {
            out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
          } else {
            out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
          }
          if ($breakOnError) {
            out += ' if (!' + ($nextValid) + ') break; ';
          }
          out += ' } ';
          if ($breakOnError) {
            out += ' else ' + ($nextValid) + ' = true; ';
          }
          out += ' }  ';
          if ($breakOnError) {
            out += ' if (' + ($nextValid) + ') { ';
            $closingBraces += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}
'use strict';
module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $errs = 'errs__' + $lvl;
  var $it = it.util.copy(it);
  var $closingBraces = '';
  $it.level++;
  var $nextValid = 'valid' + $it.level;
  out += 'var ' + ($errs) + ' = errors;';
  if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
    $it.schema = $schema;
    $it.schemaPath = $schemaPath;
    $it.errSchemaPath = $errSchemaPath;
    var $key = 'key' + $lvl,
      $idx = 'idx' + $lvl,
      $i = 'i' + $lvl,
      $invalidName = '\' + ' + $key + ' + \'',
      $dataNxt = $it.dataLevel = it.dataLevel + 1,
      $nextData = 'data' + $dataNxt,
      $dataProperties = 'dataProperties' + $lvl,
      $ownProperties = it.opts.ownProperties,
      $currentBaseId = it.baseId;
    if ($ownProperties) {
      out += ' var ' + ($dataProperties) + ' = undefined; ';
    }
    if ($ownProperties) {
      out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
    } else {
      out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
    }
    out += ' var startErrs' + ($lvl) + ' = errors; ';
    var $passData = $key;
    var $wasComposite = it.compositeRule;
    it.compositeRule = $it.compositeRule = true;
    var $code = it.validate($it);
    $it.baseId = $currentBaseId;
    if (it.util.varOccurences($code, $nextData) < 2) {
      out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
    } else {
      out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
    }
    it.compositeRule = $it.compositeRule = $wasComposite;
    out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; }   var err =   '; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError(vErrors); ';
      } else {
        out += ' validate.errors = vErrors; return false; ';
      }
    }
    if ($breakOnError) {
      out += ' break; ';
    }
    out += ' } }';
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
  }
  return out;
}
'use strict';
module.exports = function generate_ref(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $async, $refCode;
  if ($schema == '#' || $schema == '#/') {
    if (it.isRoot) {
      $async = it.async;
      $refCode = 'validate';
    } else {
      $async = it.root.schema.$async === true;
      $refCode = 'root.refVal[0]';
    }
  } else {
    var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
    if ($refVal === undefined) {
      var $message = it.MissingRefError.message(it.baseId, $schema);
      if (it.opts.missingRefs == 'fail') {
        it.logger.error($message);
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        if ($breakOnError) {
          out += ' if (false) { ';
        }
      } else if (it.opts.missingRefs == 'ignore') {
        it.logger.warn($message);
        if ($breakOnError) {
          out += ' if (true) { ';
        }
      } else {
        throw new it.MissingRefError(it.baseId, $schema, $message);
      }
    } else if ($refVal.inline) {
      var $it = it.util.copy(it);
      $it.level++;
      var $nextValid = 'valid' + $it.level;
      $it.schema = $refVal.schema;
      $it.schemaPath = '';
      $it.errSchemaPath = $schema;
      var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
      out += ' ' + ($code) + ' ';
      if ($breakOnError) {
        out += ' if (' + ($nextValid) + ') { ';
      }
    } else {
      $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
      $refCode = $refVal.code;
    }
  }
  if ($refCode) {
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = '';
    if (it.opts.passContext) {
      out += ' ' + ($refCode) + '.call(this, ';
    } else {
      out += ' ' + ($refCode) + '( ';
    }
    out += ' ' + ($data) + ', (dataPath || \'\')';
    if (it.errorPath != '""') {
      out += ' + ' + (it.errorPath);
    }
    var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
      $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
    out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData)  ';
    var __callValidate = out;
    out = $$outStack.pop();
    if ($async) {
      if (!it.async) throw new Error('async schema referenced by sync schema');
      if ($breakOnError) {
        out += ' var ' + ($valid) + '; ';
      }
      out += ' try { await ' + (__callValidate) + '; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = true; ';
      }
      out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
      if ($breakOnError) {
        out += ' ' + ($valid) + ' = false; ';
      }
      out += ' } ';
      if ($breakOnError) {
        out += ' if (' + ($valid) + ') { ';
      }
    } else {
      out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
      if ($breakOnError) {
        out += ' else { ';
      }
    }
  }
  return out;
}
'use strict';
module.exports = function generate_required(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  var $vSchema = 'schema' + $lvl;
  if (!$isData) {
    if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
      var $required = [];
      var arr1 = $schema;
      if (arr1) {
        var $property, i1 = -1,
          l1 = arr1.length - 1;
        while (i1 < l1) {
          $property = arr1[i1 += 1];
          var $propertySch = it.schema.properties[$property];
          if (!($propertySch && (it.opts.strictKeywords ? (typeof $propertySch == 'object' && Object.keys($propertySch).length > 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
            $required[$required.length] = $property;
          }
        }
      }
    } else {
      var $required = $schema;
    }
  }
  if ($isData || $required.length) {
    var $currentErrorPath = it.errorPath,
      $loopRequired = $isData || $required.length >= it.opts.loopRequired,
      $ownProperties = it.opts.ownProperties;
    if ($breakOnError) {
      out += ' var missing' + ($lvl) + '; ';
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        out += ' var ' + ($valid) + ' = true; ';
        if ($isData) {
          out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
        if ($ownProperties) {
          out += ' &&   Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += '; if (!' + ($valid) + ') break; } ';
        if ($isData) {
          out += '  }  ';
        }
        out += '  if (!' + ($valid) + ') {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      } else {
        out += ' if ( ';
        var arr2 = $required;
        if (arr2) {
          var $propertyKey, $i = -1,
            l2 = arr2.length - 1;
          while ($i < l2) {
            $propertyKey = arr2[$i += 1];
            if ($i) {
              out += ' || ';
            }
            var $prop = it.util.getProperty($propertyKey),
              $useData = $data + $prop;
            out += ' ( ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
          }
        }
        out += ') {  ';
        var $propertyPath = 'missing' + $lvl,
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
        }
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } else { ';
      }
    } else {
      if ($loopRequired) {
        if (!$isData) {
          out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
        }
        var $i = 'i' + $lvl,
          $propertyPath = 'schema' + $lvl + '[' + $i + ']',
          $missingProperty = '\' + ' + $propertyPath + ' + \'';
        if (it.opts._errorDataPathProperty) {
          it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
        }
        if ($isData) {
          out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) {  var err =   '; /* istanbul ignore else */
          if (it.createErrors !== false) {
            out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
            if (it.opts.messages !== false) {
              out += ' , message: \'';
              if (it.opts._errorDataPathProperty) {
                out += 'is a required property';
              } else {
                out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
              }
              out += '\' ';
            }
            if (it.opts.verbose) {
              out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
            }
            out += ' } ';
          } else {
            out += ' {} ';
          }
          out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
        }
        out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
        if ($ownProperties) {
          out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
        }
        out += ') {  var err =   '; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'';
            if (it.opts._errorDataPathProperty) {
              out += 'is a required property';
            } else {
              out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
        if ($isData) {
          out += '  }  ';
        }
      } else {
        var arr3 = $required;
        if (arr3) {
          var $propertyKey, i3 = -1,
            l3 = arr3.length - 1;
          while (i3 < l3) {
            $propertyKey = arr3[i3 += 1];
            var $prop = it.util.getProperty($propertyKey),
              $missingProperty = it.util.escapeQuotes($propertyKey),
              $useData = $data + $prop;
            if (it.opts._errorDataPathProperty) {
              it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
            }
            out += ' if ( ' + ($useData) + ' === undefined ';
            if ($ownProperties) {
              out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
            }
            out += ') {  var err =   '; /* istanbul ignore else */
            if (it.createErrors !== false) {
              out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
              if (it.opts.messages !== false) {
                out += ' , message: \'';
                if (it.opts._errorDataPathProperty) {
                  out += 'is a required property';
                } else {
                  out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
                }
                out += '\' ';
              }
              if (it.opts.verbose) {
                out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
              }
              out += ' } ';
            } else {
              out += ' {} ';
            }
            out += ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
          }
        }
      }
    }
    it.errorPath = $currentErrorPath;
  } else if ($breakOnError) {
    out += ' if (true) {';
  }
  return out;
}
'use strict';
module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
  var out = ' ';
  var $lvl = it.level;
  var $dataLvl = it.dataLevel;
  var $schema = it.schema[$keyword];
  var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
  var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
  var $breakOnError = !it.opts.allErrors;
  var $data = 'data' + ($dataLvl || '');
  var $valid = 'valid' + $lvl;
  var $isData = it.opts.$data && $schema && $schema.$data,
    $schemaValue;
  if ($isData) {
    out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
    $schemaValue = 'schema' + $lvl;
  } else {
    $schemaValue = $schema;
  }
  if (($schema || $isData) && it.opts.uniqueItems !== false) {
    if ($isData) {
      out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
    }
    out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
    var $itemType = it.schema.items && it.schema.items.type,
      $typeIsArray = Array.isArray($itemType);
    if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
      out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
    } else {
      out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
      var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
      out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';
      if ($typeIsArray) {
        out += ' if (typeof item == \'string\') item = \'"\' + item; ';
      }
      out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
    }
    out += ' } ';
    if ($isData) {
      out += '  }  ';
    }
    out += ' if (!' + ($valid) + ') {   ';
    var $$outStack = $$outStack || [];
    $$outStack.push(out);
    out = ''; /* istanbul ignore else */
    if (it.createErrors !== false) {
      out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
      if (it.opts.messages !== false) {
        out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
      }
      if (it.opts.verbose) {
        out += ' , schema:  ';
        if ($isData) {
          out += 'validate.schema' + ($schemaPath);
        } else {
          out += '' + ($schema);
        }
        out += '         , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
      }
      out += ' } ';
    } else {
      out += ' {} ';
    }
    var __err = out;
    out = $$outStack.pop();
    if (!it.compositeRule && $breakOnError) {
      /* istanbul ignore if */
      if (it.async) {
        out += ' throw new ValidationError([' + (__err) + ']); ';
      } else {
        out += ' validate.errors = [' + (__err) + ']; return false; ';
      }
    } else {
      out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
    }
    out += ' } ';
    if ($breakOnError) {
      out += ' else { ';
    }
  } else {
    if ($breakOnError) {
      out += ' if (true) { ';
    }
  }
  return out;
}
'use strict';
module.exports = function generate_validate(it, $keyword, $ruleType) {
  var out = '';
  var $async = it.schema.$async === true,
    $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
    $id = it.self._getId(it.schema);
  if (it.opts.strictKeywords) {
    var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
    if ($unknownKwd) {
      var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
      if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
      else throw new Error($keywordsMsg);
    }
  }
  if (it.isTop) {
    out += ' var validate = ';
    if ($async) {
      it.async = true;
      out += 'async ';
    }
    out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
    if ($id && (it.opts.sourceCode || it.opts.processCode)) {
      out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
    }
  }
  if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
    var $keyword = 'false schema';
    var $lvl = it.level;
    var $dataLvl = it.dataLevel;
    var $schema = it.schema[$keyword];
    var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
    var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
    var $breakOnError = !it.opts.allErrors;
    var $errorKeyword;
    var $data = 'data' + ($dataLvl || '');
    var $valid = 'valid' + $lvl;
    if (it.schema === false) {
      if (it.isTop) {
        $breakOnError = true;
      } else {
        out += ' var ' + ($valid) + ' = false; ';
      }
      var $$outStack = $$outStack || [];
      $$outStack.push(out);
      out = ''; /* istanbul ignore else */
      if (it.createErrors !== false) {
        out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
        if (it.opts.messages !== false) {
          out += ' , message: \'boolean schema is false\' ';
        }
        if (it.opts.verbose) {
          out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
        }
        out += ' } ';
      } else {
        out += ' {} ';
      }
      var __err = out;
      out = $$outStack.pop();
      if (!it.compositeRule && $breakOnError) {
        /* istanbul ignore if */
        if (it.async) {
          out += ' throw new ValidationError([' + (__err) + ']); ';
        } else {
          out += ' validate.errors = [' + (__err) + ']; return false; ';
        }
      } else {
        out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
      }
    } else {
      if (it.isTop) {
        if ($async) {
          out += ' return data; ';
        } else {
          out += ' validate.errors = null; return true; ';
        }
      } else {
        out += ' var ' + ($valid) + ' = true; ';
      }
    }
    if (it.isTop) {
      out += ' }; return validate; ';
    }
    return out;
  }
  if (it.isTop) {
    var $top = it.isTop,
      $lvl = it.level = 0,
      $dataLvl = it.dataLevel = 0,
      $data = 'data';
    it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
    it.baseId = it.baseId || it.rootId;
    delete it.isTop;
    it.dataPathArr = [""];
    if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
      var $defaultMsg = 'default is ignored in the schema root';
      if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
      else throw new Error($defaultMsg);
    }
    out += ' var vErrors = null; ';
    out += ' var errors = 0;     ';
    out += ' if (rootData === undefined) rootData = data; ';
  } else {
    var $lvl = it.level,
      $dataLvl = it.dataLevel,
      $data = 'data' + ($dataLvl || '');
    if ($id) it.baseId = it.resolve.url(it.baseId, $id);
    if ($async && !it.async) throw new Error('async schema in sync schema');
    out += ' var errs_' + ($lvl) + ' = errors;';
  }
  var $valid = 'valid' + $lvl,
    $breakOnError = !it.opts.allErrors,
    $closingBraces1 = '',
    $closingBraces2 = '';
  var $errorKeyword;
  var $typeSchema = it.schema.type,
    $typeIsArray = Array.isArray($typeSchema);
  if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
    if ($typeIsArray) {
      if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
    } else if ($typeSchema != 'null') {
      $typeSchema = [$typeSchema, 'null'];
      $typeIsArray = true;
    }
  }
  if ($typeIsArray && $typeSchema.length == 1) {
    $typeSchema = $typeSchema[0];
    $typeIsArray = false;
  }
  if (it.schema.$ref && $refKeywords) {
    if (it.opts.extendRefs == 'fail') {
      throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
    } else if (it.opts.extendRefs !== true) {
      $refKeywords = false;
      it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
    }
  }
  if (it.schema.$comment && it.opts.$comment) {
    out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
  }
  if ($typeSchema) {
    if (it.opts.coerceTypes) {
      var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
    }
    var $rulesGroup = it.RULES.types[$typeSchema];
    if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type';
      var $schemaPath = it.schemaPath + '.type',
        $errSchemaPath = it.errSchemaPath + '/type',
        $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
      out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';
      if ($coerceToTypes) {
        var $dataType = 'dataType' + $lvl,
          $coerced = 'coerced' + $lvl;
        out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';
        if (it.opts.coerceTypes == 'array') {
          out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';
        }
        out += ' if (' + ($coerced) + ' !== undefined) ; ';
        var arr1 = $coerceToTypes;
        if (arr1) {
          var $type, $i = -1,
            l1 = arr1.length - 1;
          while ($i < l1) {
            $type = arr1[$i += 1];
            if ($type == 'string') {
              out += ' else if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
            } else if ($type == 'number' || $type == 'integer') {
              out += ' else if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
              if ($type == 'integer') {
                out += ' && !(' + ($data) + ' % 1)';
              }
              out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
            } else if ($type == 'boolean') {
              out += ' else if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
            } else if ($type == 'null') {
              out += ' else if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
            } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
              out += ' else if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
            }
          }
        }
        out += ' else {   ';
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
        out += ' } if (' + ($coerced) + ' !== undefined) {  ';
        var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
          $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
        out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
        if (!$dataLvl) {
          out += 'if (' + ($parentData) + ' !== undefined)';
        }
        out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
      } else {
        var $$outStack = $$outStack || [];
        $$outStack.push(out);
        out = ''; /* istanbul ignore else */
        if (it.createErrors !== false) {
          out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
          if ($typeIsArray) {
            out += '' + ($typeSchema.join(","));
          } else {
            out += '' + ($typeSchema);
          }
          out += '\' } ';
          if (it.opts.messages !== false) {
            out += ' , message: \'should be ';
            if ($typeIsArray) {
              out += '' + ($typeSchema.join(","));
            } else {
              out += '' + ($typeSchema);
            }
            out += '\' ';
          }
          if (it.opts.verbose) {
            out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
          }
          out += ' } ';
        } else {
          out += ' {} ';
        }
        var __err = out;
        out = $$outStack.pop();
        if (!it.compositeRule && $breakOnError) {
          /* istanbul ignore if */
          if (it.async) {
            out += ' throw new ValidationError([' + (__err) + ']); ';
          } else {
            out += ' validate.errors = [' + (__err) + ']; return false; ';
          }
        } else {
          out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
        }
      }
      out += ' } ';
    }
  }
  if (it.schema.$ref && !$refKeywords) {
    out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
    if ($breakOnError) {
      out += ' } if (errors === ';
      if ($top) {
        out += '0';
      } else {
        out += 'errs_' + ($lvl);
      }
      out += ') { ';
      $closingBraces2 += '}';
    }
  } else {
    var arr2 = it.RULES;
    if (arr2) {
      var $rulesGroup, i2 = -1,
        l2 = arr2.length - 1;
      while (i2 < l2) {
        $rulesGroup = arr2[i2 += 1];
        if ($shouldUseGroup($rulesGroup)) {
          if ($rulesGroup.type) {
            out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';
          }
          if (it.opts.useDefaults) {
            if ($rulesGroup.type == 'object' && it.schema.properties) {
              var $schema = it.schema.properties,
                $schemaKeys = Object.keys($schema);
              var arr3 = $schemaKeys;
              if (arr3) {
                var $propertyKey, i3 = -1,
                  l3 = arr3.length - 1;
                while (i3 < l3) {
                  $propertyKey = arr3[i3 += 1];
                  var $sch = $schema[$propertyKey];
                  if ($sch.default !== undefined) {
                    var $passData = $data + it.util.getProperty($propertyKey);
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
              var arr4 = it.schema.items;
              if (arr4) {
                var $sch, $i = -1,
                  l4 = arr4.length - 1;
                while ($i < l4) {
                  $sch = arr4[$i += 1];
                  if ($sch.default !== undefined) {
                    var $passData = $data + '[' + $i + ']';
                    if (it.compositeRule) {
                      if (it.opts.strictDefaults) {
                        var $defaultMsg = 'default is ignored for: ' + $passData;
                        if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
                        else throw new Error($defaultMsg);
                      }
                    } else {
                      out += ' if (' + ($passData) + ' === undefined ';
                      if (it.opts.useDefaults == 'empty') {
                        out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
                      }
                      out += ' ) ' + ($passData) + ' = ';
                      if (it.opts.useDefaults == 'shared') {
                        out += ' ' + (it.useDefault($sch.default)) + ' ';
                      } else {
                        out += ' ' + (JSON.stringify($sch.default)) + ' ';
                      }
                      out += '; ';
                    }
                  }
                }
              }
            }
          }
          var arr5 = $rulesGroup.rules;
          if (arr5) {
            var $rule, i5 = -1,
              l5 = arr5.length - 1;
            while (i5 < l5) {
              $rule = arr5[i5 += 1];
              if ($shouldUseRule($rule)) {
                var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
                if ($code) {
                  out += ' ' + ($code) + ' ';
                  if ($breakOnError) {
                    $closingBraces1 += '}';
                  }
                }
              }
            }
          }
          if ($breakOnError) {
            out += ' ' + ($closingBraces1) + ' ';
            $closingBraces1 = '';
          }
          if ($rulesGroup.type) {
            out += ' } ';
            if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
              out += ' else { ';
              var $schemaPath = it.schemaPath + '.type',
                $errSchemaPath = it.errSchemaPath + '/type';
              var $$outStack = $$outStack || [];
              $$outStack.push(out);
              out = ''; /* istanbul ignore else */
              if (it.createErrors !== false) {
                out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
                if ($typeIsArray) {
                  out += '' + ($typeSchema.join(","));
                } else {
                  out += '' + ($typeSchema);
                }
                out += '\' } ';
                if (it.opts.messages !== false) {
                  out += ' , message: \'should be ';
                  if ($typeIsArray) {
                    out += '' + ($typeSchema.join(","));
                  } else {
                    out += '' + ($typeSchema);
                  }
                  out += '\' ';
                }
                if (it.opts.verbose) {
                  out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
                }
                out += ' } ';
              } else {
                out += ' {} ';
              }
              var __err = out;
              out = $$outStack.pop();
              if (!it.compositeRule && $breakOnError) {
                /* istanbul ignore if */
                if (it.async) {
                  out += ' throw new ValidationError([' + (__err) + ']); ';
                } else {
                  out += ' validate.errors = [' + (__err) + ']; return false; ';
                }
              } else {
                out += ' var err = ' + (__err) + ';  if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
              }
              out += ' } ';
            }
          }
          if ($breakOnError) {
            out += ' if (errors === ';
            if ($top) {
              out += '0';
            } else {
              out += 'errs_' + ($lvl);
            }
            out += ') { ';
            $closingBraces2 += '}';
          }
        }
      }
    }
  }
  if ($breakOnError) {
    out += ' ' + ($closingBraces2) + ' ';
  }
  if ($top) {
    if ($async) {
      out += ' if (errors === 0) return data;           ';
      out += ' else throw new ValidationError(vErrors); ';
    } else {
      out += ' validate.errors = vErrors; ';
      out += ' return errors === 0;       ';
    }
    out += ' }; return validate;';
  } else {
    out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
  }

  function $shouldUseGroup($rulesGroup) {
    var rules = $rulesGroup.rules;
    for (var i = 0; i < rules.length; i++)
      if ($shouldUseRule(rules[i])) return true;
  }

  function $shouldUseRule($rule) {
    return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
  }

  function $ruleImplementsSomeKeyword($rule) {
    var impl = $rule.implements;
    for (var i = 0; i < impl.length; i++)
      if (it.schema[impl[i]] !== undefined) return true;
  }
  return out;
}
'use strict';

var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
var customRuleCode = require('./dotjs/custom');
var definitionSchema = require('./definition_schema');

module.exports = {
  add: addKeyword,
  get: getKeyword,
  remove: removeKeyword,
  validate: validateKeyword
};


/**
 * Define custom keyword
 * @this  Ajv
 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
 * @return {Ajv} this for method chaining
 */
function addKeyword(keyword, definition) {
  /* jshint validthis: true */
  /* eslint no-shadow: 0 */
  var RULES = this.RULES;
  if (RULES.keywords[keyword])
    throw new Error('Keyword ' + keyword + ' is already defined');

  if (!IDENTIFIER.test(keyword))
    throw new Error('Keyword ' + keyword + ' is not a valid identifier');

  if (definition) {
    this.validateKeyword(definition, true);

    var dataType = definition.type;
    if (Array.isArray(dataType)) {
      for (var i=0; i<dataType.length; i++)
        _addRule(keyword, dataType[i], definition);
    } else {
      _addRule(keyword, dataType, definition);
    }

    var metaSchema = definition.metaSchema;
    if (metaSchema) {
      if (definition.$data && this._opts.$data) {
        metaSchema = {
          anyOf: [
            metaSchema,
            { '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' }
          ]
        };
      }
      definition.validateSchema = this.compile(metaSchema, true);
    }
  }

  RULES.keywords[keyword] = RULES.all[keyword] = true;


  function _addRule(keyword, dataType, definition) {
    var ruleGroup;
    for (var i=0; i<RULES.length; i++) {
      var rg = RULES[i];
      if (rg.type == dataType) {
        ruleGroup = rg;
        break;
      }
    }

    if (!ruleGroup) {
      ruleGroup = { type: dataType, rules: [] };
      RULES.push(ruleGroup);
    }

    var rule = {
      keyword: keyword,
      definition: definition,
      custom: true,
      code: customRuleCode,
      implements: definition.implements
    };
    ruleGroup.rules.push(rule);
    RULES.custom[keyword] = rule;
  }

  return this;
}


/**
 * Get keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
 */
function getKeyword(keyword) {
  /* jshint validthis: true */
  var rule = this.RULES.custom[keyword];
  return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}


/**
 * Remove keyword
 * @this  Ajv
 * @param {String} keyword pre-defined or custom keyword.
 * @return {Ajv} this for method chaining
 */
function removeKeyword(keyword) {
  /* jshint validthis: true */
  var RULES = this.RULES;
  delete RULES.keywords[keyword];
  delete RULES.all[keyword];
  delete RULES.custom[keyword];
  for (var i=0; i<RULES.length; i++) {
    var rules = RULES[i].rules;
    for (var j=0; j<rules.length; j++) {
      if (rules[j].keyword == keyword) {
        rules.splice(j, 1);
        break;
      }
    }
  }
  return this;
}


/**
 * Validate keyword definition
 * @this  Ajv
 * @param {Object} definition keyword definition object.
 * @param {Boolean} throwError true to throw exception if definition is invalid
 * @return {boolean} validation result
 */
function validateKeyword(definition, throwError) {
  validateKeyword.errors = null;
  var v = this._validateKeyword = this._validateKeyword
                                  || this.compile(definitionSchema, true);

  if (v(definition)) return true;
  validateKeyword.errors = v.errors;
  if (throwError)
    throw new Error('custom keyword definition is invalid: '  + this.errorsText(v.errors));
  else
    return false;
}
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
    "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
    "type": "object",
    "required": [ "$data" ],
    "properties": {
        "$data": {
            "type": "string",
            "anyOf": [
                { "format": "relative-json-pointer" }, 
                { "format": "json-pointer" }
            ]
        }
    },
    "additionalProperties": false
}
{
    "id": "http://json-schema.org/draft-04/schema#",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "description": "Core schema meta-schema",
    "definitions": {
        "schemaArray": {
            "type": "array",
            "minItems": 1,
            "items": { "$ref": "#" }
        },
        "positiveInteger": {
            "type": "integer",
            "minimum": 0
        },
        "positiveIntegerDefault0": {
            "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
        },
        "simpleTypes": {
            "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
        },
        "stringArray": {
            "type": "array",
            "items": { "type": "string" },
            "minItems": 1,
            "uniqueItems": true
        }
    },
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        },
        "$schema": {
            "type": "string"
        },
        "title": {
            "type": "string"
        },
        "description": {
            "type": "string"
        },
        "default": {},
        "multipleOf": {
            "type": "number",
            "minimum": 0,
            "exclusiveMinimum": true
        },
        "maximum": {
            "type": "number"
        },
        "exclusiveMaximum": {
            "type": "boolean",
            "default": false
        },
        "minimum": {
            "type": "number"
        },
        "exclusiveMinimum": {
            "type": "boolean",
            "default": false
        },
        "maxLength": { "$ref": "#/definitions/positiveInteger" },
        "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
        "pattern": {
            "type": "string",
            "format": "regex"
        },
        "additionalItems": {
            "anyOf": [
                { "type": "boolean" },
                { "$ref": "#" }
            ],
            "default": {}
        },
        "items": {
            "anyOf": [
                { "$ref": "#" },
                { "$ref": "#/definitions/schemaArray" }
            ],
            "default": {}
        },
        "maxItems": { "$ref": "#/definitions/positiveInteger" },
        "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
        "uniqueItems": {
            "type": "boolean",
            "default": false
        },
        "maxProperties": { "$ref": "#/definitions/positiveInteger" },
        "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
        "required": { "$ref": "#/definitions/stringArray" },
        "additionalProperties": {
            "anyOf": [
                { "type": "boolean" },
                { "$ref": "#" }
            ],
            "default": {}
        },
        "definitions": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "properties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "patternProperties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "dependencies": {
            "type": "object",
            "additionalProperties": {
                "anyOf": [
                    { "$ref": "#" },
                    { "$ref": "#/definitions/stringArray" }
                ]
            }
        },
        "enum": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true
        },
        "type": {
            "anyOf": [
                { "$ref": "#/definitions/simpleTypes" },
                {
                    "type": "array",
                    "items": { "$ref": "#/definitions/simpleTypes" },
                    "minItems": 1,
                    "uniqueItems": true
                }
            ]
        },
        "format": { "type": "string" },
        "allOf": { "$ref": "#/definitions/schemaArray" },
        "anyOf": { "$ref": "#/definitions/schemaArray" },
        "oneOf": { "$ref": "#/definitions/schemaArray" },
        "not": { "$ref": "#" }
    },
    "dependencies": {
        "exclusiveMaximum": [ "maximum" ],
        "exclusiveMinimum": [ "minimum" ]
    },
    "default": {}
}
{
    "$schema": "http://json-schema.org/draft-06/schema#",
    "$id": "http://json-schema.org/draft-06/schema#",
    "title": "Core schema meta-schema",
    "definitions": {
        "schemaArray": {
            "type": "array",
            "minItems": 1,
            "items": { "$ref": "#" }
        },
        "nonNegativeInteger": {
            "type": "integer",
            "minimum": 0
        },
        "nonNegativeIntegerDefault0": {
            "allOf": [
                { "$ref": "#/definitions/nonNegativeInteger" },
                { "default": 0 }
            ]
        },
        "simpleTypes": {
            "enum": [
                "array",
                "boolean",
                "integer",
                "null",
                "number",
                "object",
                "string"
            ]
        },
        "stringArray": {
            "type": "array",
            "items": { "type": "string" },
            "uniqueItems": true,
            "default": []
        }
    },
    "type": ["object", "boolean"],
    "properties": {
        "$id": {
            "type": "string",
            "format": "uri-reference"
        },
        "$schema": {
            "type": "string",
            "format": "uri"
        },
        "$ref": {
            "type": "string",
            "format": "uri-reference"
        },
        "title": {
            "type": "string"
        },
        "description": {
            "type": "string"
        },
        "default": {},
        "examples": {
            "type": "array",
            "items": {}
        },
        "multipleOf": {
            "type": "number",
            "exclusiveMinimum": 0
        },
        "maximum": {
            "type": "number"
        },
        "exclusiveMaximum": {
            "type": "number"
        },
        "minimum": {
            "type": "number"
        },
        "exclusiveMinimum": {
            "type": "number"
        },
        "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
        "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "pattern": {
            "type": "string",
            "format": "regex"
        },
        "additionalItems": { "$ref": "#" },
        "items": {
            "anyOf": [
                { "$ref": "#" },
                { "$ref": "#/definitions/schemaArray" }
            ],
            "default": {}
        },
        "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
        "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "uniqueItems": {
            "type": "boolean",
            "default": false
        },
        "contains": { "$ref": "#" },
        "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
        "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "required": { "$ref": "#/definitions/stringArray" },
        "additionalProperties": { "$ref": "#" },
        "definitions": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "properties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "patternProperties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "dependencies": {
            "type": "object",
            "additionalProperties": {
                "anyOf": [
                    { "$ref": "#" },
                    { "$ref": "#/definitions/stringArray" }
                ]
            }
        },
        "propertyNames": { "$ref": "#" },
        "const": {},
        "enum": {
            "type": "array",
            "minItems": 1,
            "uniqueItems": true
        },
        "type": {
            "anyOf": [
                { "$ref": "#/definitions/simpleTypes" },
                {
                    "type": "array",
                    "items": { "$ref": "#/definitions/simpleTypes" },
                    "minItems": 1,
                    "uniqueItems": true
                }
            ]
        },
        "format": { "type": "string" },
        "allOf": { "$ref": "#/definitions/schemaArray" },
        "anyOf": { "$ref": "#/definitions/schemaArray" },
        "oneOf": { "$ref": "#/definitions/schemaArray" },
        "not": { "$ref": "#" }
    },
    "default": {}
}
{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://json-schema.org/draft-07/schema#",
    "title": "Core schema meta-schema",
    "definitions": {
        "schemaArray": {
            "type": "array",
            "minItems": 1,
            "items": { "$ref": "#" }
        },
        "nonNegativeInteger": {
            "type": "integer",
            "minimum": 0
        },
        "nonNegativeIntegerDefault0": {
            "allOf": [
                { "$ref": "#/definitions/nonNegativeInteger" },
                { "default": 0 }
            ]
        },
        "simpleTypes": {
            "enum": [
                "array",
                "boolean",
                "integer",
                "null",
                "number",
                "object",
                "string"
            ]
        },
        "stringArray": {
            "type": "array",
            "items": { "type": "string" },
            "uniqueItems": true,
            "default": []
        }
    },
    "type": ["object", "boolean"],
    "properties": {
        "$id": {
            "type": "string",
            "format": "uri-reference"
        },
        "$schema": {
            "type": "string",
            "format": "uri"
        },
        "$ref": {
            "type": "string",
            "format": "uri-reference"
        },
        "$comment": {
            "type": "string"
        },
        "title": {
            "type": "string"
        },
        "description": {
            "type": "string"
        },
        "default": true,
        "readOnly": {
            "type": "boolean",
            "default": false
        },
        "examples": {
            "type": "array",
            "items": true
        },
        "multipleOf": {
            "type": "number",
            "exclusiveMinimum": 0
        },
        "maximum": {
            "type": "number"
        },
        "exclusiveMaximum": {
            "type": "number"
        },
        "minimum": {
            "type": "number"
        },
        "exclusiveMinimum": {
            "type": "number"
        },
        "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
        "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "pattern": {
            "type": "string",
            "format": "regex"
        },
        "additionalItems": { "$ref": "#" },
        "items": {
            "anyOf": [
                { "$ref": "#" },
                { "$ref": "#/definitions/schemaArray" }
            ],
            "default": true
        },
        "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
        "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "uniqueItems": {
            "type": "boolean",
            "default": false
        },
        "contains": { "$ref": "#" },
        "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
        "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
        "required": { "$ref": "#/definitions/stringArray" },
        "additionalProperties": { "$ref": "#" },
        "definitions": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "properties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "default": {}
        },
        "patternProperties": {
            "type": "object",
            "additionalProperties": { "$ref": "#" },
            "propertyNames": { "format": "regex" },
            "default": {}
        },
        "dependencies": {
            "type": "object",
            "additionalProperties": {
                "anyOf": [
                    { "$ref": "#" },
                    { "$ref": "#/definitions/stringArray" }
                ]
            }
        },
        "propertyNames": { "$ref": "#" },
        "const": true,
        "enum": {
            "type": "array",
            "items": true,
            "minItems": 1,
            "uniqueItems": true
        },
        "type": {
            "anyOf": [
                { "$ref": "#/definitions/simpleTypes" },
                {
                    "type": "array",
                    "items": { "$ref": "#/definitions/simpleTypes" },
                    "minItems": 1,
                    "uniqueItems": true
                }
            ]
        },
        "format": { "type": "string" },
        "contentMediaType": { "type": "string" },
        "contentEncoding": { "type": "string" },
        "if": {"$ref": "#"},
        "then": {"$ref": "#"},
        "else": {"$ref": "#"},
        "allOf": { "$ref": "#/definitions/schemaArray" },
        "anyOf": { "$ref": "#/definitions/schemaArray" },
        "oneOf": { "$ref": "#/definitions/schemaArray" },
        "not": { "$ref": "#" }
    },
    "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON Schema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [
          {"type": "array"},
          {"$ref": "#"}
        ]
      }
    },
    "items": {
      "anyOf": [
        {"$ref": "#"},
        {"$ref": "#/definitions/schemaArray"}
      ]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
{
  "name": "ajv",
  "version": "6.14.0",
  "description": "Another JSON Schema Validator",
  "main": "lib/ajv.js",
  "typings": "lib/ajv.d.ts",
  "files": [
    "lib/",
    "dist/",
    "scripts/",
    "LICENSE",
    ".tonic_example.js"
  ],
  "scripts": {
    "eslint": "eslint lib/{compile/,}*.js spec/{**/,}*.js scripts --ignore-pattern spec/JSON-Schema-Test-Suite",
    "jshint": "jshint lib/{compile/,}*.js",
    "lint": "npm run jshint && npm run eslint",
    "test-spec": "mocha spec/{**/,}*.spec.js -R spec",
    "test-fast": "AJV_FAST_TEST=true npm run test-spec",
    "test-debug": "npm run test-spec -- --inspect-brk",
    "test-cov": "nyc npm run test-spec",
    "test-ts": "tsc --target ES5 --noImplicitAny --noEmit spec/typescript/index.ts",
    "bundle": "del-cli dist && node ./scripts/bundle.js . Ajv pure_getters",
    "bundle-beautify": "node ./scripts/bundle.js js-beautify",
    "build": "del-cli lib/dotjs/*.js \"!lib/dotjs/index.js\" && node scripts/compile-dots.js",
    "test-karma": "karma start",
    "test-browser": "del-cli .browser && npm run bundle && scripts/prepare-tests && npm run test-karma",
    "test-all": "npm run test-cov && if-node-version 10 npm run test-browser",
    "test": "npm run lint && npm run build && npm run test-all",
    "prepublish": "npm run build && npm run bundle",
    "watch": "watch \"npm run build\" ./lib/dot"
  },
  "nyc": {
    "exclude": [
      "**/spec/**",
      "node_modules"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ]
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/ajv-validator/ajv.git"
  },
  "keywords": [
    "JSON",
    "schema",
    "validator",
    "validation",
    "jsonschema",
    "json-schema",
    "json-schema-validator",
    "json-schema-validation"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/ajv-validator/ajv/issues"
  },
  "homepage": "https://github.com/ajv-validator/ajv",
  "tonicExampleFilename": ".tonic_example.js",
  "dependencies": {
    "fast-deep-equal": "^3.1.1",
    "fast-json-stable-stringify": "^2.0.0",
    "json-schema-traverse": "^0.4.1",
    "uri-js": "^4.2.2"
  },
  "devDependencies": {
    "ajv-async": "^1.0.0",
    "bluebird": "^3.5.3",
    "brfs": "^2.0.0",
    "browserify": "^16.2.0",
    "chai": "^4.0.1",
    "coveralls": "^3.0.1",
    "del-cli": "^3.0.0",
    "dot": "^1.0.3",
    "eslint": "^7.3.1",
    "gh-pages-generator": "^0.2.3",
    "glob": "^7.0.0",
    "if-node-version": "^1.0.0",
    "js-beautify": "^1.7.3",
    "jshint": "^2.10.2",
    "json-schema-test": "^2.0.0",
    "karma": "^5.0.0",
    "karma-chrome-launcher": "^3.0.0",
    "karma-mocha": "^2.0.0",
    "karma-sauce-launcher": "^4.1.3",
    "mocha": "^8.0.1",
    "nyc": "^15.0.0",
    "pre-commit": "^1.1.1",
    "re2": "^1.21.4",
    "require-globify": "^1.3.0",
    "typescript": "^3.9.5",
    "uglify-js": "^3.6.9",
    "watch": "^1.0.0"
  },
  "collective": {
    "type": "opencollective",
    "url": "https://opencollective.com/ajv"
  },
  "funding": {
    "type": "github",
    "url": "https://github.com/sponsors/epoberezkin"
  }
}
rules:
  no-console: 0
  no-empty: [2, allowEmptyCatch: true]
'use strict';

var fs = require('fs')
  , path = require('path')
  , browserify = require('browserify')
  , uglify = require('uglify-js');

var pkg = process.argv[2]
  , standalone = process.argv[3]
  , compress = process.argv[4];

var packageDir = path.join(__dirname, '..');
if (pkg != '.') packageDir = path.join(packageDir, 'node_modules', pkg);

var json = require(path.join(packageDir, 'package.json'));

var distDir = path.join(__dirname, '..', 'dist');
if (!fs.existsSync(distDir)) fs.mkdirSync(distDir);

var bOpts = {};
if (standalone) bOpts.standalone = standalone;

browserify(bOpts)
.require(path.join(packageDir, json.main), {expose: json.name})
.bundle(function (err, buf) {
  if (err) {
    console.error('browserify error:', err);
    process.exit(1);
  }

  var outputFile = path.join(distDir, json.name);
  var uglifyOpts = {
    warnings: true,
    compress: {},
    output: {
      preamble: '/* ' + json.name + ' ' + json.version + ': ' + json.description + ' */'
    }
  };
  if (compress) {
    var compressOpts = compress.split(',');
    for (var i=0, il = compressOpts.length; i<il; ++i) {
      var pair = compressOpts[i].split('=');
      uglifyOpts.compress[pair[0]] = pair.length < 1 || pair[1] != 'false';
    }
  }
  if (standalone) {
    uglifyOpts.sourceMap = {
      filename: json.name + '.min.js',
      url: json.name + '.min.js.map'
    };
  }

  var result = uglify.minify(buf.toString(), uglifyOpts);
  fs.writeFileSync(outputFile + '.min.js', result.code);
  if (result.map) fs.writeFileSync(outputFile + '.min.js.map', result.map);
  if (standalone) fs.writeFileSync(outputFile + '.bundle.js', buf);
  if (result.warnings) {
    for (var j=0, jl = result.warnings.length; j<jl; ++j)
      console.warn('UglifyJS warning:', result.warnings[j]);
  }
});
//compile doT templates to js functions
'use strict';

var glob = require('glob')
  , fs = require('fs')
  , path = require('path')
  , doT = require('dot')
  , beautify = require('js-beautify').js_beautify;

var defsRootPath = process.argv[2] || path.join(__dirname, '../lib');

var defs = {};
var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath });
defFiles.forEach(function (f) {
  var name = path.basename(f, '.def');
  defs[name] = fs.readFileSync(path.join(defsRootPath, f));
});

var filesRootPath = process.argv[3] || path.join(__dirname, '../lib');
var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath });

var dotjsPath = path.join(filesRootPath, './dotjs');
try { fs.mkdirSync(dotjsPath); } catch(e) {}

console.log('\n\nCompiling:');

var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/;
var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g;
var ISTANBUL = /'(istanbul[^']+)';/g;
var ERROR_KEYWORD = /\$errorKeyword/g;
var ERROR_KEYWORD_OR = /\$errorKeyword\s+\|\|/g;
var VARS = [
  '$errs', '$valid', '$lvl', '$data', '$dataLvl',
  '$errorKeyword', '$closingBraces', '$schemaPath',
  '$validate'
];

files.forEach(function (f) {
  var keyword = path.basename(f, '.jst');
  var targetPath = path.join(dotjsPath, keyword + '.js');
  var template = fs.readFileSync(path.join(filesRootPath, f));
  var code = doT.compile(template, defs);
  code = code.toString()
             .replace(OUT_EMPTY_STRING, '')
             .replace(FUNCTION_NAME, 'function generate_' + keyword + '(it, $keyword, $ruleType) {')
             .replace(ISTANBUL, '/* $1 */');
  removeAlwaysFalsyInOr();
  VARS.forEach(removeUnusedVar);
  code = "'use strict';\nmodule.exports = " + code;
  code = beautify(code, { indent_size: 2 }) + '\n';
  fs.writeFileSync(targetPath, code);
  console.log('compiled', keyword);

  function removeUnusedVar(v) {
    v = v.replace(/\$/g, '\\$$');
    var regexp = new RegExp(v + '[^A-Za-z0-9_$]', 'g');
    var count = occurrences(regexp);
    if (count == 1) {
      regexp = new RegExp('var\\s+' + v + '\\s*=[^;]+;|var\\s+' + v + ';');
      code = code.replace(regexp, '');
    }
  }

  function removeAlwaysFalsyInOr() {
    var countUsed = occurrences(ERROR_KEYWORD);
    var countOr = occurrences(ERROR_KEYWORD_OR);
    if (countUsed == countOr + 1) code = code.replace(ERROR_KEYWORD_OR, '');
  }

  function occurrences(regexp) {
    return (code.match(regexp) || []).length;
  }
});
#!/usr/bin/env node

'use strict';

var fs = require('fs');
var name = process.argv[2] || '.';
var property = process.argv[3] || 'version';
if (name != '.') name = 'node_modules/' + name;
var json = JSON.parse(fs.readFileSync(name + '/package.json', 'utf8'));
console.log(json[property]);
#!/usr/bin/env sh

set -e

mkdir -p .browser

echo
echo Preparing browser tests:

find spec -type f -name '*.spec.js' | \
xargs -I {} sh -c \
'export f="{}"; echo $f; browserify $f -t require-globify -t brfs -x ajv -u buffer -o $(echo $f | sed -e "s/spec/.browser/");'
#!/usr/bin/env bash

set -e

if [[ -n $TRAVIS_TAG && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then
  echo "About to publish $TRAVIS_TAG to ajv-dist..."

  git config user.email "$GIT_USER_EMAIL"
  git config user.name "$GIT_USER_NAME"

  git clone https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv-dist.git ../ajv-dist

  rm -rf ../ajv-dist/dist
  mkdir ../ajv-dist/dist
  cp ./dist/ajv.* ../ajv-dist/dist
  cat bower.json | sed 's/"name": "ajv"/"name": "ajv-dist"/' > ../ajv-dist/bower.json
  cd ../ajv-dist

  if [[ `git status --porcelain` ]]; then
    echo "Changes detected. Updating master branch..."
    git add -A
    git commit -m "updated by travis build #$TRAVIS_BUILD_NUMBER"
    git push --quiet origin master > /dev/null 2>&1
  fi

  echo "Publishing tag..."

  git tag $TRAVIS_TAG
  git push --tags > /dev/null 2>&1

  echo "Done"
fi
#!/usr/bin/env bash

set -e

if [[ "$TRAVIS_BRANCH" == "master" && "$TRAVIS_PULL_REQUEST" == "false" && $TRAVIS_JOB_NUMBER =~ ".3" ]]; then
  git diff --name-only $TRAVIS_COMMIT_RANGE | grep -qE '\.md$|^LICENSE$|travis-gh-pages$' && {
    rm -rf ../gh-pages
    git clone -b gh-pages --single-branch https://${GITHUB_TOKEN}@github.com/ajv-validator/ajv.git ../gh-pages
    mkdir -p ../gh-pages/_source
    cp *.md ../gh-pages/_source
    cp LICENSE ../gh-pages/_source
    currentDir=$(pwd)
    cd ../gh-pages
    $currentDir/node_modules/.bin/gh-pages-generator
    # remove logo from README
    sed -i -E "s/<img[^>]+ajv_logo[^>]+>//" index.md
    git config user.email "$GIT_USER_EMAIL"
    git config user.name "$GIT_USER_NAME"
    git add .
    git commit -am "updated by travis build #$TRAVIS_BUILD_NUMBER"
    git push --quiet origin gh-pages > /dev/null 2>&1
  }
fi

root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
v10.12.0
The MIT License (MIT)

Copyright (c) 2020-present Fabio Spampinato

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
# Atomically

Read and write files atomically and reliably.

## Features

- Overview:
  - This library is a rewrite of [`write-file-atomic`](https://github.com/npm/write-file-atomic), with some important enhancements on top, you can largely use this as a drop-in replacement.
  - This library is written in TypeScript, so types aren't an afterthought but come with library.
  - This library is slightly faster than [`write-file-atomic`](https://github.com/npm/write-file-atomic), and it can be 10x faster, while being essentially just as safe, by using the `fsyncWait` option.
  - This library has 0 dependencies, so there's less code to vet and the entire thing is roughly 20% smaller than [`write-file-atomic`](https://github.com/npm/write-file-atomic).
  - This library tries harder to write files on disk than [`write-file-atomic`](https://github.com/npm/write-file-atomic) does, by default retrying some failed operations and handling some more errors.
- Reliability:
  - Reads are retried, when appropriate, until they succeed or the timeout is reached.
  - Writes are atomic, meaning that first a temporary file containing the new content is written, then this file is renamed to the final path, this way it's impossible to get a corrupt/partially-written file.
  - Writes happening to the same path are queued, ensuring they don't interfere with each other.
  - Temporary files can be configured to not be purged from disk if the write operation fails, which is useful for when keeping the temporary file is better than just losing data.
  - Any needed missing parent folder will be created automatically.
  - Symlinks are resolved automatically.
  - `ENOSYS` errors on `chmod`/`chown` operations are ignored.
  - `EINVAL`/`EPERM` errors on `chmod`/`chown` operations, in POSIX systems where the user is not root, are ignored.
  - `EMFILE`/`ENFILE`/`EAGAIN`/`EBUSY`/`EACCESS`/`EACCS`/`EPERM` errors happening during necessary operations are caught and the operations are retried until they succeed or the timeout is reached.
  - `ENAMETOOLONG` errors, both appening because of the final path or the temporary path, are attempted to be worked around by smartly truncating paths.
- Temporary files:
  - By default they are purged automatically once the write operation is completed or if the process exits (cleanly or not).
  - By default they are created by appending a `.tmp-[timestamp][randomness]` suffix to destination paths:
    - The `tmp-` part gives users a hint about the nature of these files, if they happen to see them.
    - The `[timestamp]` part consists of the 10 least significant digits of a milliseconds-precise timestamp, making it likely that if more than one of these files are kept on disk the user will see them in chronological order.
    - The `[randomness]` part consists of 6 random hex characters.
    - If by any chance a collision is found then another suffix is generated.
- Custom options:
  - `chown`: it allows you to specify custom group and user ids:
    - by default the old file's ids are copied over.
    - if custom ids are provided they will be used.
    - if `false` the default ids are used.
  - `encoding`: it allows you to specify the encoding of the file content:
    - by default when reading no encoding is specified and a raw buffer is returned.
    - by default when writing `utf8` is used when.
  - `fsync`: it allows you to control whether the `fsync` syscall is triggered right after writing the file or not:
    - by default the syscall is triggered immediately after writing the file, increasing the chances that the file will actually be written to disk in case of imminent catastrophic failures, like power outages.
    - if `false` the syscall won't be triggered.
  - `fsyncWait`: it allows you to control whether the triggered `fsync` is waited or not:
    - by default the syscall is waited.
    - if `false` the syscall will still be triggered but not be waited.
      - this increases performance 10x in some cases, and at the end of the day often there's no plan B if `fsync` fails anyway.
  - `mode`: it allows you to specify the mode for the file:
    - by default the old file's mode is copied over.
    - if `false` then `0o666` is used.
  - `schedule`: it's a function that returns a promise that resolves to a disposer function, basically it allows you to provide some custom queueing logic for the writing operation, allowing you to perhaps wire `atomically` with your app's main filesystem job scheduler:
    - even when a custom `schedule` function is provided write operations will still be queued internally by the library too.
  - `timeout`: it allows you to specify the amount of maximum milliseconds within which the library will retry some failed operations:
    - when writing asynchronously by default it will keep retrying for 5000 milliseconds.
    - when writing synchronously by default it will keep retrying for 100 milliseconds.
    - if `0` or `-1` no failed operations will be retried.
    - if another number is provided that will be the timeout interval.
  - `tmpCreate`: it's a function that will be used to create the custom temporary file path in place of the default one:
    - even when a custom function is provided the final temporary path will still be truncated if the library thinks that it may lead to `ENAMETOOLONG` errors.
    - paths by default are truncated in a way that preserves an eventual existing leading dot and trailing extension.
  - `tmpCreated`: it's a function that will be called with the newly created temporary file path.
  - `tmpPurge`: it allows you to control whether the temporary file will be purged from the filesystem or not if the write fails:
    - by default it will be purged.
    - if `false` it will be kept on disk.

## Install

```sh
npm install --save atomically
```

## Usage

This is the shape of the optional options object:

```ts
type Disposer = () => void;

type ReadOptions = string | {
  encoding?: string | null,
  mode?: string | number | false,
  timeout?: number
};

type WriteOptions = string | {
  chown?: { gid: number, uid: number } | false,
  encoding?: string | null,
  fsync?: boolean,
  fsyncWait?: boolean,
  mode?: string | number | false,
  schedule?: ( filePath: string ) => Promise<Disposer>,
  timeout?: number,
  tmpCreate?: ( filePath: string ) => string,
  tmpCreated?: ( filePath: string ) => any,
  tmpPurge?: boolean
};
```

This is the shape of the provided functions:

```ts
function readFile ( filePath: string, options?: ReadOptions ): Promise<Buffer | string>;
function readFileSync ( filePath: string, options?: ReadOptions ): Buffer | string;
function writeFile ( filePath: string, data: Buffer | string | undefined, options?: WriteOptions ): Promise<void>;
function writeFileSync ( filePath: string, data: Buffer | string | undefined, options?: WriteOptions ): void;
```

This is how to use the library:

```ts
import {readFile, readFileSync, writeFile, writeFileSync} from 'atomically';

// Asynchronous read with default option
const buffer = await readFile ( '/foo.txt' );

// Synchronous read assuming the encoding is "utf8"
const string = readFileSync ( '/foo.txt', 'utf8' );

// Asynchronous write with default options
await writeFile ( '/foo.txt', 'my_data' );

// Asynchronous write that doesn't prod the old file for a stat object at all
await writeFile ( '/foo.txt', 'my_data', { chown: false, mode: false } );

// 10x faster asynchronous write that's less resilient against imminent catastrophies
await writeFile ( '/foo.txt', 'my_data', { fsync: false } );

// 10x faster asynchronous write that's essentially still as resilient against imminent catastrophies
await writeFile ( '/foo.txt', 'my_data', { fsyncWait: false } );

// Asynchronous write with a custom schedule function
await writeFile ( '/foo.txt', 'my_data', {
  schedule: filePath => {
    return new Promise ( resolve => { // When this returned promise will resolve the write operation will begin
      MyScheduler.schedule ( filePath, () => { // Hypothetical scheduler function that will eventually tell us to go on with this write operation
        const disposer = () => {}; // Hypothetical function that contains eventual clean-up logic, it will be called after the write operation has been completed (successfully or not)
        resolve ( disposer ); // Resolving the promise with a disposer, beginning the write operation
      })
    });
  }
});

// Synchronous write with default options
writeFileSync ( '/foo.txt', 'my_data' );
```

## License

MIT © Fabio Spampinato
"use strict";
/* CONSTS */
Object.defineProperty(exports, "__esModule", { value: true });
exports.NOOP = exports.LIMIT_FILES_DESCRIPTORS = exports.LIMIT_BASENAME_LENGTH = exports.IS_USER_ROOT = exports.IS_POSIX = exports.DEFAULT_TIMEOUT_SYNC = exports.DEFAULT_TIMEOUT_ASYNC = exports.DEFAULT_WRITE_OPTIONS = exports.DEFAULT_READ_OPTIONS = exports.DEFAULT_FOLDER_MODE = exports.DEFAULT_FILE_MODE = exports.DEFAULT_ENCODING = void 0;
const DEFAULT_ENCODING = 'utf8';
exports.DEFAULT_ENCODING = DEFAULT_ENCODING;
const DEFAULT_FILE_MODE = 0o666;
exports.DEFAULT_FILE_MODE = DEFAULT_FILE_MODE;
const DEFAULT_FOLDER_MODE = 0o777;
exports.DEFAULT_FOLDER_MODE = DEFAULT_FOLDER_MODE;
const DEFAULT_READ_OPTIONS = {};
exports.DEFAULT_READ_OPTIONS = DEFAULT_READ_OPTIONS;
const DEFAULT_WRITE_OPTIONS = {};
exports.DEFAULT_WRITE_OPTIONS = DEFAULT_WRITE_OPTIONS;
const DEFAULT_TIMEOUT_ASYNC = 5000;
exports.DEFAULT_TIMEOUT_ASYNC = DEFAULT_TIMEOUT_ASYNC;
const DEFAULT_TIMEOUT_SYNC = 100;
exports.DEFAULT_TIMEOUT_SYNC = DEFAULT_TIMEOUT_SYNC;
const IS_POSIX = !!process.getuid;
exports.IS_POSIX = IS_POSIX;
const IS_USER_ROOT = process.getuid ? !process.getuid() : false;
exports.IS_USER_ROOT = IS_USER_ROOT;
const LIMIT_BASENAME_LENGTH = 128; //TODO: fetch the real limit from the filesystem //TODO: fetch the whole-path length limit too
exports.LIMIT_BASENAME_LENGTH = LIMIT_BASENAME_LENGTH;
const LIMIT_FILES_DESCRIPTORS = 10000; //TODO: fetch the real limit from the filesystem
exports.LIMIT_FILES_DESCRIPTORS = LIMIT_FILES_DESCRIPTORS;
const NOOP = () => { };
exports.NOOP = NOOP;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeFileSync = exports.writeFile = exports.readFileSync = exports.readFile = void 0;
const path = require("path");
const consts_1 = require("./consts");
const fs_1 = require("./utils/fs");
const lang_1 = require("./utils/lang");
const scheduler_1 = require("./utils/scheduler");
const temp_1 = require("./utils/temp");
function readFile(filePath, options = consts_1.DEFAULT_READ_OPTIONS) {
    var _a;
    if (lang_1.default.isString(options))
        return readFile(filePath, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_ASYNC);
    return fs_1.default.readFileRetry(timeout)(filePath, options);
}
exports.readFile = readFile;
;
function readFileSync(filePath, options = consts_1.DEFAULT_READ_OPTIONS) {
    var _a;
    if (lang_1.default.isString(options))
        return readFileSync(filePath, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_SYNC);
    return fs_1.default.readFileSyncRetry(timeout)(filePath, options);
}
exports.readFileSync = readFileSync;
;
const writeFile = (filePath, data, options, callback) => {
    if (lang_1.default.isFunction(options))
        return writeFile(filePath, data, consts_1.DEFAULT_WRITE_OPTIONS, options);
    const promise = writeFileAsync(filePath, data, options);
    if (callback)
        promise.then(callback, callback);
    return promise;
};
exports.writeFile = writeFile;
const writeFileAsync = async (filePath, data, options = consts_1.DEFAULT_WRITE_OPTIONS) => {
    var _a;
    if (lang_1.default.isString(options))
        return writeFileAsync(filePath, data, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_ASYNC);
    let schedulerCustomDisposer = null, schedulerDisposer = null, tempDisposer = null, tempPath = null, fd = null;
    try {
        if (options.schedule)
            schedulerCustomDisposer = await options.schedule(filePath);
        schedulerDisposer = await scheduler_1.default.schedule(filePath);
        filePath = await fs_1.default.realpathAttempt(filePath) || filePath;
        [tempPath, tempDisposer] = temp_1.default.get(filePath, options.tmpCreate || temp_1.default.create, !(options.tmpPurge === false));
        const useStatChown = consts_1.IS_POSIX && lang_1.default.isUndefined(options.chown), useStatMode = lang_1.default.isUndefined(options.mode);
        if (useStatChown || useStatMode) {
            const stat = await fs_1.default.statAttempt(filePath);
            if (stat) {
                options = { ...options };
                if (useStatChown)
                    options.chown = { uid: stat.uid, gid: stat.gid };
                if (useStatMode)
                    options.mode = stat.mode;
            }
        }
        const parentPath = path.dirname(filePath);
        await fs_1.default.mkdirAttempt(parentPath, {
            mode: consts_1.DEFAULT_FOLDER_MODE,
            recursive: true
        });
        fd = await fs_1.default.openRetry(timeout)(tempPath, 'w', options.mode || consts_1.DEFAULT_FILE_MODE);
        if (options.tmpCreated)
            options.tmpCreated(tempPath);
        if (lang_1.default.isString(data)) {
            await fs_1.default.writeRetry(timeout)(fd, data, 0, options.encoding || consts_1.DEFAULT_ENCODING);
        }
        else if (!lang_1.default.isUndefined(data)) {
            await fs_1.default.writeRetry(timeout)(fd, data, 0, data.length, 0);
        }
        if (options.fsync !== false) {
            if (options.fsyncWait !== false) {
                await fs_1.default.fsyncRetry(timeout)(fd);
            }
            else {
                fs_1.default.fsyncAttempt(fd);
            }
        }
        await fs_1.default.closeRetry(timeout)(fd);
        fd = null;
        if (options.chown)
            await fs_1.default.chownAttempt(tempPath, options.chown.uid, options.chown.gid);
        if (options.mode)
            await fs_1.default.chmodAttempt(tempPath, options.mode);
        try {
            await fs_1.default.renameRetry(timeout)(tempPath, filePath);
        }
        catch (error) {
            if (error.code !== 'ENAMETOOLONG')
                throw error;
            await fs_1.default.renameRetry(timeout)(tempPath, temp_1.default.truncate(filePath));
        }
        tempDisposer();
        tempPath = null;
    }
    finally {
        if (fd)
            await fs_1.default.closeAttempt(fd);
        if (tempPath)
            temp_1.default.purge(tempPath);
        if (schedulerCustomDisposer)
            schedulerCustomDisposer();
        if (schedulerDisposer)
            schedulerDisposer();
    }
};
const writeFileSync = (filePath, data, options = consts_1.DEFAULT_WRITE_OPTIONS) => {
    var _a;
    if (lang_1.default.isString(options))
        return writeFileSync(filePath, data, { encoding: options });
    const timeout = Date.now() + ((_a = options.timeout) !== null && _a !== void 0 ? _a : consts_1.DEFAULT_TIMEOUT_SYNC);
    let tempDisposer = null, tempPath = null, fd = null;
    try {
        filePath = fs_1.default.realpathSyncAttempt(filePath) || filePath;
        [tempPath, tempDisposer] = temp_1.default.get(filePath, options.tmpCreate || temp_1.default.create, !(options.tmpPurge === false));
        const useStatChown = consts_1.IS_POSIX && lang_1.default.isUndefined(options.chown), useStatMode = lang_1.default.isUndefined(options.mode);
        if (useStatChown || useStatMode) {
            const stat = fs_1.default.statSyncAttempt(filePath);
            if (stat) {
                options = { ...options };
                if (useStatChown)
                    options.chown = { uid: stat.uid, gid: stat.gid };
                if (useStatMode)
                    options.mode = stat.mode;
            }
        }
        const parentPath = path.dirname(filePath);
        fs_1.default.mkdirSyncAttempt(parentPath, {
            mode: consts_1.DEFAULT_FOLDER_MODE,
            recursive: true
        });
        fd = fs_1.default.openSyncRetry(timeout)(tempPath, 'w', options.mode || consts_1.DEFAULT_FILE_MODE);
        if (options.tmpCreated)
            options.tmpCreated(tempPath);
        if (lang_1.default.isString(data)) {
            fs_1.default.writeSyncRetry(timeout)(fd, data, 0, options.encoding || consts_1.DEFAULT_ENCODING);
        }
        else if (!lang_1.default.isUndefined(data)) {
            fs_1.default.writeSyncRetry(timeout)(fd, data, 0, data.length, 0);
        }
        if (options.fsync !== false) {
            if (options.fsyncWait !== false) {
                fs_1.default.fsyncSyncRetry(timeout)(fd);
            }
            else {
                fs_1.default.fsyncAttempt(fd);
            }
        }
        fs_1.default.closeSyncRetry(timeout)(fd);
        fd = null;
        if (options.chown)
            fs_1.default.chownSyncAttempt(tempPath, options.chown.uid, options.chown.gid);
        if (options.mode)
            fs_1.default.chmodSyncAttempt(tempPath, options.mode);
        try {
            fs_1.default.renameSyncRetry(timeout)(tempPath, filePath);
        }
        catch (error) {
            if (error.code !== 'ENAMETOOLONG')
                throw error;
            fs_1.default.renameSyncRetry(timeout)(tempPath, temp_1.default.truncate(filePath));
        }
        tempDisposer();
        tempPath = null;
    }
    finally {
        if (fd)
            fs_1.default.closeSyncAttempt(fd);
        if (tempPath)
            temp_1.default.purge(tempPath);
    }
};
exports.writeFileSync = writeFileSync;
"use strict";
/* TYPES */
Object.defineProperty(exports, "__esModule", { value: true });
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.attemptifySync = exports.attemptifyAsync = void 0;
const consts_1 = require("../consts");
/* ATTEMPTIFY */
//TODO: Maybe publish this as a standalone package
//FIXME: The type castings here aren't exactly correct
const attemptifyAsync = (fn, onError = consts_1.NOOP) => {
    return function () {
        return fn.apply(undefined, arguments).catch(onError);
    };
};
exports.attemptifyAsync = attemptifyAsync;
const attemptifySync = (fn, onError = consts_1.NOOP) => {
    return function () {
        try {
            return fn.apply(undefined, arguments);
        }
        catch (error) {
            return onError(error);
        }
    };
};
exports.attemptifySync = attemptifySync;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("fs");
const util_1 = require("util");
const attemptify_1 = require("./attemptify");
const fs_handlers_1 = require("./fs_handlers");
const retryify_1 = require("./retryify");
/* FS */
const FS = {
    chmodAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.chmod), fs_handlers_1.default.onChangeError),
    chownAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.chown), fs_handlers_1.default.onChangeError),
    closeAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.close)),
    fsyncAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.fsync)),
    mkdirAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.mkdir)),
    realpathAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.realpath)),
    statAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.stat)),
    unlinkAttempt: attemptify_1.attemptifyAsync(util_1.promisify(fs.unlink)),
    closeRetry: retryify_1.retryifyAsync(util_1.promisify(fs.close), fs_handlers_1.default.isRetriableError),
    fsyncRetry: retryify_1.retryifyAsync(util_1.promisify(fs.fsync), fs_handlers_1.default.isRetriableError),
    openRetry: retryify_1.retryifyAsync(util_1.promisify(fs.open), fs_handlers_1.default.isRetriableError),
    readFileRetry: retryify_1.retryifyAsync(util_1.promisify(fs.readFile), fs_handlers_1.default.isRetriableError),
    renameRetry: retryify_1.retryifyAsync(util_1.promisify(fs.rename), fs_handlers_1.default.isRetriableError),
    statRetry: retryify_1.retryifyAsync(util_1.promisify(fs.stat), fs_handlers_1.default.isRetriableError),
    writeRetry: retryify_1.retryifyAsync(util_1.promisify(fs.write), fs_handlers_1.default.isRetriableError),
    chmodSyncAttempt: attemptify_1.attemptifySync(fs.chmodSync, fs_handlers_1.default.onChangeError),
    chownSyncAttempt: attemptify_1.attemptifySync(fs.chownSync, fs_handlers_1.default.onChangeError),
    closeSyncAttempt: attemptify_1.attemptifySync(fs.closeSync),
    mkdirSyncAttempt: attemptify_1.attemptifySync(fs.mkdirSync),
    realpathSyncAttempt: attemptify_1.attemptifySync(fs.realpathSync),
    statSyncAttempt: attemptify_1.attemptifySync(fs.statSync),
    unlinkSyncAttempt: attemptify_1.attemptifySync(fs.unlinkSync),
    closeSyncRetry: retryify_1.retryifySync(fs.closeSync, fs_handlers_1.default.isRetriableError),
    fsyncSyncRetry: retryify_1.retryifySync(fs.fsyncSync, fs_handlers_1.default.isRetriableError),
    openSyncRetry: retryify_1.retryifySync(fs.openSync, fs_handlers_1.default.isRetriableError),
    readFileSyncRetry: retryify_1.retryifySync(fs.readFileSync, fs_handlers_1.default.isRetriableError),
    renameSyncRetry: retryify_1.retryifySync(fs.renameSync, fs_handlers_1.default.isRetriableError),
    statSyncRetry: retryify_1.retryifySync(fs.statSync, fs_handlers_1.default.isRetriableError),
    writeSyncRetry: retryify_1.retryifySync(fs.writeSync, fs_handlers_1.default.isRetriableError)
};
/* EXPORT */
exports.default = FS;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const consts_1 = require("../consts");
/* FS HANDLERS */
const Handlers = {
    isChangeErrorOk: (error) => {
        const { code } = error;
        if (code === 'ENOSYS')
            return true;
        if (!consts_1.IS_USER_ROOT && (code === 'EINVAL' || code === 'EPERM'))
            return true;
        return false;
    },
    isRetriableError: (error) => {
        const { code } = error;
        if (code === 'EMFILE' || code === 'ENFILE' || code === 'EAGAIN' || code === 'EBUSY' || code === 'EACCESS' || code === 'EACCS' || code === 'EPERM')
            return true;
        return false;
    },
    onChangeError: (error) => {
        if (Handlers.isChangeErrorOk(error))
            return;
        throw error;
    }
};
/* EXPORT */
exports.default = Handlers;
"use strict";
/* LANG */
Object.defineProperty(exports, "__esModule", { value: true });
const Lang = {
    isFunction: (x) => {
        return typeof x === 'function';
    },
    isString: (x) => {
        return typeof x === 'string';
    },
    isUndefined: (x) => {
        return typeof x === 'undefined';
    }
};
/* EXPORT */
exports.default = Lang;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryifySync = exports.retryifyAsync = void 0;
const retryify_queue_1 = require("./retryify_queue");
/* RETRYIFY */
const retryifyAsync = (fn, isRetriableError) => {
    return function (timestamp) {
        return function attempt() {
            return retryify_queue_1.default.schedule().then(cleanup => {
                return fn.apply(undefined, arguments).then(result => {
                    cleanup();
                    return result;
                }, error => {
                    cleanup();
                    if (Date.now() >= timestamp)
                        throw error;
                    if (isRetriableError(error)) {
                        const delay = Math.round(100 + (400 * Math.random())), delayPromise = new Promise(resolve => setTimeout(resolve, delay));
                        return delayPromise.then(() => attempt.apply(undefined, arguments));
                    }
                    throw error;
                });
            });
        };
    };
};
exports.retryifyAsync = retryifyAsync;
const retryifySync = (fn, isRetriableError) => {
    return function (timestamp) {
        return function attempt() {
            try {
                return fn.apply(undefined, arguments);
            }
            catch (error) {
                if (Date.now() > timestamp)
                    throw error;
                if (isRetriableError(error))
                    return attempt.apply(undefined, arguments);
                throw error;
            }
        };
    };
};
exports.retryifySync = retryifySync;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const consts_1 = require("../consts");
/* RETRYIFY QUEUE */
const RetryfyQueue = {
    interval: 25,
    intervalId: undefined,
    limit: consts_1.LIMIT_FILES_DESCRIPTORS,
    queueActive: new Set(),
    queueWaiting: new Set(),
    init: () => {
        if (RetryfyQueue.intervalId)
            return;
        RetryfyQueue.intervalId = setInterval(RetryfyQueue.tick, RetryfyQueue.interval);
    },
    reset: () => {
        if (!RetryfyQueue.intervalId)
            return;
        clearInterval(RetryfyQueue.intervalId);
        delete RetryfyQueue.intervalId;
    },
    add: (fn) => {
        RetryfyQueue.queueWaiting.add(fn);
        if (RetryfyQueue.queueActive.size < (RetryfyQueue.limit / 2)) { // Active queue not under preassure, executing immediately
            RetryfyQueue.tick();
        }
        else {
            RetryfyQueue.init();
        }
    },
    remove: (fn) => {
        RetryfyQueue.queueWaiting.delete(fn);
        RetryfyQueue.queueActive.delete(fn);
    },
    schedule: () => {
        return new Promise(resolve => {
            const cleanup = () => RetryfyQueue.remove(resolver);
            const resolver = () => resolve(cleanup);
            RetryfyQueue.add(resolver);
        });
    },
    tick: () => {
        if (RetryfyQueue.queueActive.size >= RetryfyQueue.limit)
            return;
        if (!RetryfyQueue.queueWaiting.size)
            return RetryfyQueue.reset();
        for (const fn of RetryfyQueue.queueWaiting) {
            if (RetryfyQueue.queueActive.size >= RetryfyQueue.limit)
                break;
            RetryfyQueue.queueWaiting.delete(fn);
            RetryfyQueue.queueActive.add(fn);
            fn();
        }
    }
};
/* EXPORT */
exports.default = RetryfyQueue;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
/* VARIABLES */
const Queues = {};
/* SCHEDULER */
//TODO: Maybe publish this as a standalone package
const Scheduler = {
    next: (id) => {
        const queue = Queues[id];
        if (!queue)
            return;
        queue.shift();
        const job = queue[0];
        if (job) {
            job(() => Scheduler.next(id));
        }
        else {
            delete Queues[id];
        }
    },
    schedule: (id) => {
        return new Promise(resolve => {
            let queue = Queues[id];
            if (!queue)
                queue = Queues[id] = [];
            queue.push(resolve);
            if (queue.length > 1)
                return;
            resolve(() => Scheduler.next(id));
        });
    }
};
/* EXPORT */
exports.default = Scheduler;
"use strict";
/* IMPORT */
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const consts_1 = require("../consts");
const fs_1 = require("./fs");
/* TEMP */
//TODO: Maybe publish this as a standalone package
const Temp = {
    store: {},
    create: (filePath) => {
        const randomness = `000000${Math.floor(Math.random() * 16777215).toString(16)}`.slice(-6), // 6 random-enough hex characters
        timestamp = Date.now().toString().slice(-10), // 10 precise timestamp digits
        prefix = 'tmp-', suffix = `.${prefix}${timestamp}${randomness}`, tempPath = `${filePath}${suffix}`;
        return tempPath;
    },
    get: (filePath, creator, purge = true) => {
        const tempPath = Temp.truncate(creator(filePath));
        if (tempPath in Temp.store)
            return Temp.get(filePath, creator, purge); // Collision found, try again
        Temp.store[tempPath] = purge;
        const disposer = () => delete Temp.store[tempPath];
        return [tempPath, disposer];
    },
    purge: (filePath) => {
        if (!Temp.store[filePath])
            return;
        delete Temp.store[filePath];
        fs_1.default.unlinkAttempt(filePath);
    },
    purgeSync: (filePath) => {
        if (!Temp.store[filePath])
            return;
        delete Temp.store[filePath];
        fs_1.default.unlinkSyncAttempt(filePath);
    },
    purgeSyncAll: () => {
        for (const filePath in Temp.store) {
            Temp.purgeSync(filePath);
        }
    },
    truncate: (filePath) => {
        const basename = path.basename(filePath);
        if (basename.length <= consts_1.LIMIT_BASENAME_LENGTH)
            return filePath; //FIXME: Rough and quick attempt at detecting ok lengths
        const truncable = /^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(basename);
        if (!truncable)
            return filePath; //FIXME: No truncable part detected, can't really do much without also changing the parent path, which is unsafe, hoping for the best here
        const truncationLength = basename.length - consts_1.LIMIT_BASENAME_LENGTH;
        return `${filePath.slice(0, -basename.length)}${truncable[1]}${truncable[2].slice(0, -truncationLength)}${truncable[3]}`; //FIXME: The truncable part might be shorter than needed here
    }
};
/* INIT */
process.on('exit', Temp.purgeSyncAll); // Ensuring purgeable temp files are purged on exit
/* EXPORT */
exports.default = Temp;
{
  "name": "atomically",
  "description": "Read and write files atomically and reliably.",
  "version": "1.7.0",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "benchmark": "node ./tasks/benchmark.js",
    "clean": "rimraf dist",
    "compile": "tsc --skipLibCheck && tstei",
    "compile:watch": "tsc --skipLibCheck --watch",
    "test": "tap --no-coverage-report",
    "test:watch": "tap --no-coverage-report --watch",
    "prepublishOnly": "npm run clean && npm run compile && npm run test"
  },
  "bugs": {
    "url": "https://github.com/fabiospampinato/atomically/issues"
  },
  "license": "MIT",
  "author": {
    "name": "Fabio Spampinato",
    "email": "spampinabio@gmail.com"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/fabiospampinato/atomically.git"
  },
  "keywords": [
    "atomic",
    "read",
    "write",
    "file",
    "reliable"
  ],
  "engines": {
    "node": ">=10.12.0"
  },
  "dependencies": {},
  "devDependencies": {
    "@types/node": "^12.7.2",
    "lodash": "^4.17.19",
    "mkdirp": "^1.0.4",
    "promise-resolve-timeout": "^1.2.1",
    "require-inject": "^1.4.4",
    "rimraf": "^3.0.2",
    "tap": "^14.10.7",
    "typescript": "^3.5.3",
    "typescript-transform-export-interop": "^1.0.2",
    "write-file-atomic": "^3.0.3"
  }
}

/* IMPORT */

const fs = require ( 'fs' ),
      os = require ( 'os' ),
      path = require ( 'path' ),
      delay = require ( 'promise-resolve-timeout' ),
      writeFileAtomic = require ( 'write-file-atomic' ),
      {writeFile, writeFileSync} = require ( '../dist' );

/* BENCHMARK */

const TEMP = os.tmpdir (),
      DST = i => path.join ( TEMP, `atomically-temp-${i}.txt` ),
      ITERATIONS = 250;

const runSingleAsync = async ( name, fn, buffer, options ) => {
  console.time ( name );
  for ( let i = 0; i < ITERATIONS; i++ ) {
    await fn ( DST ( i ), buffer, options );
  }
  console.timeEnd ( name );
  await delay ( 1000 );
};

const runSingleSync = async ( name, fn, buffer, options ) => {
  console.time ( name );
  for ( let i = 0; i < ITERATIONS; i++ ) {
    fn ( DST ( i ), buffer, options );
  }
  console.timeEnd ( name );
  await delay ( 1000 );
};

const runAllDummy = () => { // Preparation run
  runSingleSync ( 'dummy', fs.writeFileSync, '' );
};

const runAllAsync = async ( name, buffer ) => {
  await runSingleAsync ( `${name} -> async -> write-file-atomic`, writeFileAtomic, buffer );
  await runSingleAsync ( `${name} -> async -> write-file-atomic (fastest)`, writeFileAtomic, buffer, { fsync: false } );
  await runSingleAsync ( `${name} -> async -> atomically`, writeFile, buffer );
  await runSingleAsync ( `${name} -> async -> atomically (faster)`, writeFile, buffer, { mode: false, chown: false, fsyncWait: false } );
  await runSingleAsync ( `${name} -> async -> atomically (fastest)`, writeFile, buffer, { mode: false, chown: false, fsync: false } );
};

const runAllSync = ( name, buffer ) => {
  runSingleSync ( `${name} -> sync -> write-file-atomic`, writeFileAtomic.sync, buffer );
  runSingleSync ( `${name} -> sync -> write-file-atomic (fastest)`, writeFileAtomic.sync, buffer, { fsync: false } );
  runSingleSync ( `${name} -> sync -> atomically`, writeFileSync, buffer );
  runSingleSync ( `${name} -> sync -> atomically (faster)`, writeFileSync, buffer, { mode: false, chown: false, fsyncWait: false } );
  runSingleSync ( `${name} -> sync -> atomically (fastest)`, writeFileSync, buffer, { mode: false, chown: false, fsync: false } );
};

const runAll = async ( name, buffer ) => {
  await runAllAsync ( name, buffer );
  console.log ( '-------------------' );
  runAllSync ( name, buffer );
};

const run = async () => {
  runAllDummy ();
  console.log ( '===================' );
  await runAll ( '100kb', Buffer.allocUnsafe ( 100 * 1024 ) );
  console.log ( '===================' );
  await runAll ( '10kb', Buffer.allocUnsafe ( 10 * 1024 ) );
  console.log ( '===================' );
  await runAll ( '1kb', Buffer.allocUnsafe ( 1024 ) );
  console.log ( '===================' );
};

run ();
'use strict'

process.setMaxListeners(1000000);

const _ = require('lodash')
const fs = require('fs')
const os = require('os')
const path = require('path')
const {test} = require('tap')
const requireInject = require('require-inject')

let expectClose = 0
let closeCalled = 0
let expectCloseSync = 0
let closeSyncCalled = 0
const createErr = code => Object.assign(new Error(code), { code })

let unlinked = []

const fsMock = Object.assign ( {}, fs, {
  /* ASYNC */
  mkdir (filename, opts, cb) {
    return cb(null);
  },
  realpath (filename, cb) {
    return cb(null, filename)
  },
  open (tmpfile, options, mode, cb) {
    if (/noopen/.test(tmpfile)) return cb(createErr('ENOOPEN'))
    expectClose++
    cb(null, tmpfile)
  },
  write (fd) {
    const cb = arguments[arguments.length - 1]
    if (/nowrite/.test(fd)) return cb(createErr('ENOWRITE'))
    cb()
  },
  fsync (fd, cb) {
    if (/nofsync/.test(fd)) return cb(createErr('ENOFSYNC'))
    cb()
  },
  close (fd, cb) {
    closeCalled++
    cb()
  },
  chown (tmpfile, uid, gid, cb) {
    if (/nochown/.test(tmpfile)) return cb(createErr('ENOCHOWN'))
    if (/enosys/.test(tmpfile)) return cb(createErr('ENOSYS'))
    if (/einval/.test(tmpfile)) return cb(createErr('EINVAL'))
    if (/eperm/.test(tmpfile)) return cb(createErr('EPERM'))
    cb()
  },
  chmod (tmpfile, mode, cb) {
    if (/nochmod/.test(tmpfile)) return cb(createErr('ENOCHMOD'))
    if (/enosys/.test(tmpfile)) return cb(createErr('ENOSYS'))
    if (/eperm/.test(tmpfile)) return cb(createErr('EPERM'))
    if (/einval/.test(tmpfile)) return cb(createErr('EINVAL'))
    cb()
  },
  rename (tmpfile, filename, cb) {
    if (/norename/.test(tmpfile)) return cb(createErr('ENORENAME'))
    cb()
  },
  unlink (tmpfile, cb) {
    if (/nounlink/.test(tmpfile)) return cb(createErr('ENOUNLINK'))
    cb()
  },
  stat (tmpfile, cb) {
    if (/nostat/.test(tmpfile)) return cb(createErr('ENOSTAT'))
    if (/statful/.test(tmpfile)) return cb(null, fs.statSync('/'));
    cb()
  },
  /* SYNC */
  mkdirSync (filename) {},
  realpathSync (filename, cb) {
    return filename
  },
  openSync (tmpfile, options) {
    if (/noopen/.test(tmpfile)) throw createErr('ENOOPEN')
    expectCloseSync++
    return tmpfile
  },
  writeSync (fd) {
    if (/nowrite/.test(fd)) throw createErr('ENOWRITE')
  },
  fsyncSync (fd) {
    if (/nofsync/.test(fd)) throw createErr('ENOFSYNC')
  },
  closeSync (fd) {
    closeSyncCalled++
  },
  chownSync (tmpfile, uid, gid) {
    if (/nochown/.test(tmpfile)) throw createErr('ENOCHOWN')
    if (/enosys/.test(tmpfile)) throw createErr('ENOSYS')
    if (/einval/.test(tmpfile)) throw createErr('EINVAL')
    if (/eperm/.test(tmpfile)) throw createErr('EPERM')
  },
  chmodSync (tmpfile, mode) {
    if (/nochmod/.test(tmpfile)) throw createErr('ENOCHMOD')
    if (/enosys/.test(tmpfile)) throw createErr('ENOSYS')
    if (/einval/.test(tmpfile)) throw createErr('EINVAL')
    if (/eperm/.test(tmpfile)) throw createErr('EPERM')
  },
  renameSync (tmpfile, filename) {
    if (/norename/.test(tmpfile)) throw createErr('ENORENAME')
  },
  unlinkSync (tmpfile) {
    if (/nounlink/.test(tmpfile)) throw createErr('ENOUNLINK')
    unlinked.push(tmpfile)
  },
  statSync (tmpfile) {
    if (/nostat/.test(tmpfile)) throw createErr('ENOSTAT')
    if (/statful/.test(tmpfile)) return fs.statSync('/');
  }
});

const makeUnstableAsyncFn = function () {
  return function () {
    if ( Math.random () <= .75 ) {
      const code = _.shuffle ([ 'EMFILE', 'ENFILE', 'EAGAIN', 'EBUSY', 'EACCESS', 'EPERM' ])[0];
      throw createErr ( code );
    }
    return arguments[arguments.length -1](null, arguments[0]);
  };
};

const makeUnstableSyncFn = function ( fn ) {
  return function () {
    if ( Math.random () <= .75 ) {
      const code = _.shuffle ([ 'EMFILE', 'ENFILE', 'EAGAIN', 'EBUSY', 'EACCESS', 'EPERM' ])[0];
      throw createErr ( code );
    }
    return fn.apply(undefined, arguments)
  };
};

const fsMockUnstable = Object.assign ( {}, fsMock, {
  open: makeUnstableAsyncFn (),
  write: makeUnstableAsyncFn (),
  fsync: makeUnstableAsyncFn (),
  close: makeUnstableAsyncFn (),
  rename: makeUnstableAsyncFn (),
  openSync: makeUnstableSyncFn ( _.identity ),
  writeSync: makeUnstableSyncFn ( _.noop ),
  fsyncSync: makeUnstableSyncFn ( _.noop ),
  closeSync: makeUnstableSyncFn ( _.noop ),
  renameSync: makeUnstableSyncFn ( _.noop )
});

const {writeFile: writeFileAtomic, writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: fsMock });

test('async tests', t => {
  t.plan(2)

  expectClose = 0
  closeCalled = 0
  t.teardown(() => {
    t.parent.equal(closeCalled, expectClose, 'async tests closed all files')
    expectClose = 0
    closeCalled = 0
  })

  t.test('non-root tests', t => {
    t.plan(28)

    writeFileAtomic('good', 'test', { mode: '0777' }, err => {
      t.notOk(err, 'No errors occur when passing in options')
    })
    writeFileAtomic('good', 'test', 'utf8', err => {
      t.notOk(err, 'No errors occur when passing in options as string')
    })
    writeFileAtomic('good', 'test', undefined, err => {
      t.notOk(err, 'No errors occur when NOT passing in options')
    })
    writeFileAtomic('good', 'test', err => {
      t.notOk(err)
    })
    writeFileAtomic('noopen', 'test', err => {
      t.is(err && err.message, 'ENOOPEN', 'fs.open failures propagate')
    })
    writeFileAtomic('nowrite', 'test', err => {
      t.is(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate')
    })
    writeFileAtomic('nowrite', Buffer.from('test', 'utf8'), err => {
      t.is(err && err.message, 'ENOWRITE', 'fs.writewrite failures propagate for buffers')
    })
    writeFileAtomic('nochown', 'test', { chown: { uid: 100, gid: 100 } }, err => {
      t.is(err && err.message, 'ENOCHOWN', 'Chown failures propagate')
    })
    writeFileAtomic('nochown', 'test', err => {
      t.notOk(err, 'No attempt to chown when no uid/gid passed in')
    })
    writeFileAtomic('nochmod', 'test', { mode: parseInt('741', 8) }, err => {
      t.is(err && err.message, 'ENOCHMOD', 'Chmod failures propagate')
    })
    writeFileAtomic('nofsyncopt', 'test', { fsync: false }, err => {
      t.notOk(err, 'fsync skipped if options.fsync is false')
    })
    writeFileAtomic('norename', 'test', err => {
      t.is(err && err.message, 'ENORENAME', 'Rename errors propagate')
    })
    writeFileAtomic('norename nounlink', 'test', err => {
      t.is(err && err.message, 'ENORENAME', 'Failure to unlink the temp file does not clobber the original error')
    })
    writeFileAtomic('nofsync', 'test', err => {
      t.is(err && err.message, 'ENOFSYNC', 'Fsync failures propagate')
    })
    writeFileAtomic('enosys', 'test', err => {
      t.notOk(err, 'No errors on ENOSYS')
    })
    writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
      t.notOk(err, 'No errors on EINVAL for non root')
    })
    writeFileAtomic('eperm', 'test', { mode: 0o741 }, err => {
      t.notOk(err, 'No errors on EPERM for non root')
    })
    writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
      t.notOk(err, 'No errors on EINVAL for non root')
    })
    writeFileAtomic('eperm', 'test', { chown: { uid: 100, gid: 100 } }, err => {
      t.notOk(err, 'No errors on EPERM for non root')
    })
    const optionsImmutable = {};
    writeFileAtomic('statful', 'test', optionsImmutable, err => {
      t.notOk(err);
      t.deepEquals(optionsImmutable, {});
    });
    const schedule = filePath => {
      t.is(filePath, 'good');
      return new Promise ( resolve => {
        resolve ( () => {
          t.is(true,true);
        });
      });
    };
    writeFileAtomic('good','test', {schedule}, err => {
      t.notOk(err);
    });
    const tmpCreate = filePath => `.${filePath}.custom`;
    const tmpCreated = filePath => t.is ( filePath, '.good.custom' );
    writeFileAtomic('good','test', {tmpCreate, tmpCreated}, err => {
      t.notOk(err)
    })
    const longPath = path.join(os.tmpdir(),'.012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt');
    const {writeFile: writeFileAtomicNative} = requireInject('../dist', { fs });
    writeFileAtomicNative(longPath,'test', err => {
      t.notOk(err)
    })
    const pathMissingFolders = path.join(os.tmpdir(),String(Math.random()),String(Math.random()),String(Math.random()),'foo.txt');
    writeFileAtomicNative(pathMissingFolders,'test', err => {
      t.notOk(err)
    })
  })

  t.test('errors for root', t => {
    const { getuid } = process
    process.getuid = () => 0
    t.teardown(() => {
      process.getuid = getuid
    })
    const {writeFile: writeFileAtomic} = requireInject('../dist', { fs: fsMock });
    t.plan(2)
    writeFileAtomic('einval', 'test', { chown: { uid: 100, gid: 100 } }, err => {
      t.match(err, { code: 'EINVAL' })
    })
    writeFileAtomic('einval', 'test', { mode: 0o741 }, err => {
      t.match(err, { code: 'EINVAL' })
    })
  })
})

test('unstable async tests', t => {
  t.plan(2);
  const {writeFile: writeFileAtomic} = requireInject('../dist', { fs: fsMockUnstable });
  writeFileAtomic('good', 'test', err => {
    t.notOk(err, 'No errors occur when retryable errors are thrown')
  })
  writeFileAtomic('good', 'test', { timeout: 0 }, err => {
    t.is(!!err.code, true, 'Retrying can be disabled')
  })
});

test('sync tests', t => {
  t.plan(2)
  closeSyncCalled = 0
  expectCloseSync = 0
  t.teardown(() => {
    t.parent.equal(closeSyncCalled, expectCloseSync, 'sync closed all files')
    expectCloseSync = 0
    closeSyncCalled = 0
  })

  const throws = function (t, shouldthrow, msg, todo) {
    let err
    try { todo() } catch (e) { err = e }
    t.is(shouldthrow, err && err.message, msg)
  }
  const noexception = function (t, msg, todo) {
    let err
    try { todo() } catch (e) { err = e }
    t.ifError(err, msg)
  }
  let tmpfile

  t.test('non-root', t => {
    t.plan(38)
    noexception(t, 'No errors occur when passing in options', () => {
      writeFileAtomicSync('good', 'test', { mode: '0777' })
    })
    noexception(t, 'No errors occur when passing in options as string', () => {
      writeFileAtomicSync('good', 'test', 'utf8')
    })
    noexception(t, 'No errors occur when NOT passing in options', () => {
      writeFileAtomicSync('good', 'test')
    })
    noexception(t, 'fsync never called if options.fsync is falsy', () => {
      writeFileAtomicSync('good', 'test', { fsync: false })
    })
    noexception(t, 'tmpCreated is called on success', () => {
      writeFileAtomicSync('good', 'test', {
        tmpCreated (gottmpfile) {
          tmpfile = gottmpfile
        }
      })
      t.match(tmpfile, /^good\.tmp-\w+$/, 'tmpCreated called for success')
      t.match(tmpfile, /^good\.tmp-\d{10}[a-f0-9]{6}$/, 'tmpCreated format')
    })

    tmpfile = undefined
    throws(t, 'ENOOPEN', 'fs.openSync failures propagate', () => {
      writeFileAtomicSync('noopen', 'test', {
        tmpCreated (gottmpfile) {
          tmpfile = gottmpfile
        }
      })
    })
    t.is(tmpfile, undefined, 'tmpCreated not called for open failure')

    throws(t, 'ENOWRITE', 'fs.writeSync failures propagate', () => {
      writeFileAtomicSync('nowrite', 'test', {
        tmpCreated (gottmpfile) {
          tmpfile = gottmpfile
        }
      })
    })
    t.match(tmpfile, /^nowrite\.tmp-\w+$/, 'tmpCreated called for failure after open')

    throws(t, 'ENOCHOWN', 'Chown failures propagate', () => {
      writeFileAtomicSync('nochown', 'test', { chown: { uid: 100, gid: 100 } })
    })
    noexception(t, 'No attempt to chown when false passed in', () => {
      writeFileAtomicSync('nochown', 'test', { chown: false })
    })
    noexception(t, 'No errors occured when chown is undefined and original file owner used', () => {
      writeFileAtomicSync('chowncopy', 'test', { chown: undefined })
    })
    throws(t, 'ENORENAME', 'Rename errors propagate', () => {
      writeFileAtomicSync('norename', 'test')
    })
    throws(t, 'ENORENAME', 'Failure to unlink the temp file does not clobber the original error', () => {
      writeFileAtomicSync('norename nounlink', 'test')
    })
    throws(t, 'ENOFSYNC', 'Fsync errors propagate', () => {
      writeFileAtomicSync('nofsync', 'test')
    })
    noexception(t, 'No errors on ENOSYS', () => {
      writeFileAtomicSync('enosys', 'test', { chown: { uid: 100, gid: 100 } })
    })
    noexception(t, 'No errors on EINVAL for non root', () => {
      writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
    })
    noexception(t, 'No errors on EPERM for non root', () => {
      writeFileAtomicSync('eperm', 'test', { chown: { uid: 100, gid: 100 } })
    })

    throws(t, 'ENOCHMOD', 'Chmod failures propagate', () => {
      writeFileAtomicSync('nochmod', 'test', { mode: 0o741 })
    })
    noexception(t, 'No errors on EPERM for non root', () => {
      writeFileAtomicSync('eperm', 'test', { mode: 0o741 })
    })
    noexception(t, 'No attempt to chmod when no mode provided', () => {
      writeFileAtomicSync('nochmod', 'test', { mode: false })
    })
    const optionsImmutable = {};
    noexception(t, 'options are immutable', () => {
      writeFileAtomicSync('statful', 'test', optionsImmutable)
    })
    t.deepEquals(optionsImmutable, {});
    const tmpCreate = filePath => `.${filePath}.custom`;
    const tmpCreated = filePath => t.is ( filePath, '.good.custom' );
    noexception(t, 'custom temp creator', () => {
      writeFileAtomicSync('good', 'test', {tmpCreate, tmpCreated})
    })
    const path0 = path.join(os.tmpdir(),'atomically-test-0');
    const tmpPath0 = path0 + '.temp';
    noexception(t, 'temp files are purged on success', () => {
      const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs });
      writeFileAtomicSync(path0, 'test', {tmpCreate: () => tmpPath0})
    })
    t.is(true,fs.existsSync(path0));
    t.is(false,fs.existsSync(tmpPath0));
    const path1 = path.join(os.tmpdir(),'atomically-test-norename-1');
    const tmpPath1 = path1 + '.temp';
    throws(t, 'ENORENAME', 'temp files are purged on error', () => {
      const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: Object.assign ( {}, fs, { renameSync: fsMock.renameSync })});
      writeFileAtomicSync(path1, 'test', {tmpCreate: () => tmpPath1})
    })
    t.is(false,fs.existsSync(path1));
    t.is(false,fs.existsSync(tmpPath1));
    const path2 = path.join(os.tmpdir(),'atomically-test-norename-2');
    const tmpPath2 = path2 + '.temp';
    throws(t, 'ENORENAME', 'temp files can also not be purged on error', () => {
      const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: Object.assign ( {}, fs, { renameSync: fsMock.renameSync })});
      writeFileAtomicSync(path2, 'test', {tmpCreate: () => tmpPath2,tmpPurge: false})
    })
    t.is(false,fs.existsSync(path2));
    t.is(true,fs.existsSync(tmpPath2));
    const longPath = path.join(os.tmpdir(),'.012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789.txt');
    noexception(t, 'temp files are truncated', () => {
      const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs });
      writeFileAtomicSync(longPath, 'test')
    })
    const pathMissingFolders = path.join(os.tmpdir(),String(Math.random()),String(Math.random()),String(Math.random()),'foo.txt');
    noexception(t, 'parent folders are created', () => {
      const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs });
      writeFileAtomicSync(pathMissingFolders, 'test')
    })
  })

  t.test('errors for root', t => {
    const { getuid } = process
    process.getuid = () => 0
    t.teardown(() => {
      process.getuid = getuid
    })
    const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: fsMock });
    t.plan(2)
    throws(t, 'EINVAL', 'Chown error as root user', () => {
      writeFileAtomicSync('einval', 'test', { chown: { uid: 100, gid: 100 } })
    })
    throws(t, 'EINVAL', 'Chmod error as root user', () => {
      writeFileAtomicSync('einval', 'test', { mode: 0o741 })
    })
  })
})

test('unstable sync tests', t => {
  t.plan(2);

  const throws = function (t, msg, todo) {
    let err
    try { todo() } catch (e) { err = e }
    t.is(!!err.code, true, msg)
  }
  const noexception = function (t, msg, todo) {
    let err
    try { todo() } catch (e) { err = e }
    t.ifError(err, msg)
  }

  noexception(t, 'No errors occur when retryable errors are thrown', () => {
    const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: fsMockUnstable });
    writeFileAtomicSync('good', 'test')
  })

  throws(t, 'retrying can be disabled', () => {
    const {writeFileSync: writeFileAtomicSync} = requireInject('../dist', { fs: fsMockUnstable });
    writeFileAtomicSync('good', 'test', { timeout: 0 })
  })
});

test('promises', async t => {
  let tmpfile
  closeCalled = 0
  expectClose = 0
  t.teardown(() => {
    t.parent.equal(closeCalled, expectClose, 'promises closed all files')
    closeCalled = 0
    expectClose = 0
  })

  await writeFileAtomic('good', 'test', {
    tmpCreated (gottmpfile) {
      tmpfile = gottmpfile
    }
  })
  t.match(tmpfile, /^good\.tmp-\w+$/, 'tmpCreated is called for success')

  await writeFileAtomic('good', 'test', {
    tmpCreated (gottmpfile) {
      return Promise.resolve()
    }
  })

  tmpfile = undefined
  await t.rejects(writeFileAtomic('noopen', 'test', {
    tmpCreated (gottmpfile) {
      tmpfile = gottmpfile
    }
  }))
  t.is(tmpfile, undefined, 'tmpCreated is not called on open failure')

  await t.rejects(writeFileAtomic('nowrite', 'test', {
    tmpCreated (gottmpfile) {
      tmpfile = gottmpfile
    }
  }))
  t.match(tmpfile, /^nowrite\.tmp-\w+$/, 'tmpCreated is called if failure is after open')
})
'use strict'

process.setMaxListeners(1000000);

const fs = require('fs')
const {test} = require('tap')
const requireInject = require('require-inject')

// defining mock for fs so its functions can be modified
const fsMock = Object.assign ( {}, fs, {
  /* ASYNC */
  mkdir (filename, opts, cb) {
    return cb(null);
  },
  realpath (filename, cb) {
    return cb(null, filename)
  },
  open (tmpfile, options, mode, cb) {
    if (/noopen/.test(tmpfile)) return cb(new Error('ENOOPEN'))
    cb(null, tmpfile)
  },
  write (fd) {
    const cb = arguments[arguments.length - 1]
    if (/nowrite/.test(fd)) return cb(new Error('ENOWRITE'))
    cb()
  },
  fsync (fd, cb) {
    if (/nofsync/.test(fd)) return cb(new Error('ENOFSYNC'))
    cb()
  },
  close (fd, cb) {
    cb()
  },
  chown (tmpfile, uid, gid, cb) {
    if (/nochown/.test(tmpfile)) return cb(new Error('ENOCHOWN'))
    cb()
  },
  chmod (tmpfile, mode, cb) {
    if (/nochmod/.test(tmpfile)) return cb(new Error('ENOCHMOD'))
    cb()
  },
  rename (tmpfile, filename, cb) {
    if (/norename/.test(tmpfile)) return cb(new Error('ENORENAME'))
    cb()
  },
  unlink (tmpfile, cb) {
    if (/nounlink/.test(tmpfile)) return cb(new Error('ENOUNLINK'))
    cb()
  },
  stat (tmpfile, cb) {
    if (/nostat/.test(tmpfile)) return cb(new Error('ENOSTAT'))
    cb()
  },
  /* SYNC */
  mkdirSync (filename) {},
  realpathSync (filename, cb) {
    return filename
  },
  openSync (tmpfile, options) {
    if (/noopen/.test(tmpfile)) throw new Error('ENOOPEN')
    return tmpfile
  },
  writeSync (fd) {
    if (/nowrite/.test(fd)) throw new Error('ENOWRITE')
  },
  fsyncSync (fd) {
    if (/nofsync/.test(fd)) throw new Error('ENOFSYNC')
  },
  closeSync () {},
  chownSync (tmpfile, uid, gid) {
    if (/nochown/.test(tmpfile)) throw new Error('ENOCHOWN')
  },
  chmodSync (tmpfile, mode) {
    if (/nochmod/.test(tmpfile)) throw new Error('ENOCHMOD')
  },
  renameSync (tmpfile, filename) {
    if (/norename/.test(tmpfile)) throw new Error('ENORENAME')
  },
  unlinkSync (tmpfile) {
    if (/nounlink/.test(tmpfile)) throw new Error('ENOUNLINK')
  },
  statSync (tmpfile) {
    if (/nostat/.test(tmpfile)) throw new Error('ENOSTAT')
  }
})

const {writeFile: writeFileAtomic} = requireInject('../dist', { fs: fsMock });

// preserve original functions
const oldRealPath = fsMock.realpath
const oldRename = fsMock.rename

test('ensure writes to the same file are serial', t => {
  let fileInUse = false
  const ops = 5 // count for how many concurrent write ops to request
  t.plan(ops * 3 + 3)
  fsMock.realpath = (...args) => {
    t.false(fileInUse, 'file not in use')
    fileInUse = true
    oldRealPath(...args)
  }
  fsMock.rename = (...args) => {
    t.true(fileInUse, 'file in use')
    fileInUse = false
    oldRename(...args)
  }
  const {writeFile: writeFileAtomic} = requireInject('../dist', { fs: fsMock });
  for (let i = 0; i < ops; i++) {
    writeFileAtomic('test', 'test', err => {
      if (err) t.fail(err)
      else t.pass('wrote without error')
    })
  }
  setTimeout(() => {
    writeFileAtomic('test', 'test', err => {
      if (err) t.fail(err)
      else t.pass('successive writes after delay')
    })
  }, 500)
})

test('allow write to multiple files in parallel, but same file writes are serial', t => {
  const filesInUse = []
  const ops = 5
  let wasParallel = false
  fsMock.realpath = (filename, ...args) => {
    filesInUse.push(filename)
    const firstOccurence = filesInUse.indexOf(filename)
    t.equal(filesInUse.indexOf(filename, firstOccurence + 1), -1, 'serial writes') // check for another occurence after the first
    if (filesInUse.length > 1) wasParallel = true // remember that a parallel operation took place
    oldRealPath(filename, ...args)
  }
  fsMock.rename = (filename, ...args) => {
    filesInUse.splice(filesInUse.indexOf(filename), 1)
    oldRename(filename, ...args)
  }
  const {writeFile: writeFileAtomic} = requireInject('../dist', { fs: fsMock });
  t.plan(ops * 2 * 2 + 1)
  let opCount = 0
  for (let i = 0; i < ops; i++) {
    writeFileAtomic('test', 'test', err => {
      if (err) t.fail(err, 'wrote without error')
      else t.pass('wrote without error')
    })
    writeFileAtomic('test2', 'test', err => {
      opCount++
      if (opCount === ops) t.true(wasParallel, 'parallel writes')

      if (err) t.fail(err, 'wrote without error')
      else t.pass('wrote without error')
    })
  }
})
'use strict'

process.setMaxListeners(1000000);

const fs = require('fs')
const path = require('path')
const {test} = require('tap')
const rimraf = require('rimraf')
const requireInject = require('require-inject')

const workdir = path.join(__dirname, path.basename(__filename, '.js'))
let testfiles = 0
function tmpFile () {
  return path.join(workdir, 'test-' + (++testfiles))
}

function readFile (path) {
  return fs.readFileSync(path).toString()
}

function didWriteFileAtomic (t, expected, filename, data, options, callback) {
  if (options instanceof Function) {
    callback = options
    options = null
  }
  if (!options) options = {}
  const actual = {}
  const {writeFile: writeFileAtomic} = requireInject('../dist', {
    fs: Object.assign({}, fs, {
      chown (filename, uid, gid, cb) {
        actual.uid = uid
        actual.gid = gid
        process.nextTick(cb)
      },
      stat (filename, cb) {
        fs.stat(filename, (err, stats) => {
          if (err) return cb(err)
          cb(null, Object.assign(stats, expected || {}))
        })
      }
    })
  })
  return writeFileAtomic(filename, data, options, err => {
    t.isDeeply(actual, expected, 'ownership is as expected')
    callback(err)
  })
}

function didWriteFileAtomicSync (t, expected, filename, data, options) {
  const actual = {}
  const {writeFileSync} = requireInject('../dist', {
    fs: Object.assign({}, fs, {
      chownSync (filename, uid, gid) {
        actual.uid = uid
        actual.gid = gid
      },
      statSync (filename) {
        const stats = fs.statSync(filename)
        return Object.assign(stats, expected || {})
      }
    })
  })
  writeFileSync(filename, data, options)
  t.isDeeply(actual, expected)
}

function currentUser () {
  return {
    uid: process.getuid(),
    gid: process.getgid()
  }
}

test('setup', t => {
  rimraf.sync(workdir)
  fs.mkdirSync(workdir, {recursive: true})
  t.done()
})

test('writes simple file (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, '42', err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '42', 'content ok')
  })
})

test('writes simple file with encoding (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, 'foo', 'utf16le', err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), 'f\u0000o\u0000o\u0000', 'content ok')
  })
})

test('writes buffers to simple file (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, Buffer.from('42'), err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '42', 'content ok')
  })
})

test('writes undefined to simple file (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, undefined, err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '', 'content ok')
  })
})

test('writes to symlinks without clobbering (async)', t => {
  t.plan(5)
  const file = tmpFile()
  const link = tmpFile()
  fs.writeFileSync(file, '42')
  fs.symlinkSync(file, link)
  didWriteFileAtomic(t, currentUser(), link, '43', err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '43', 'target content ok')
    t.is(readFile(link), '43', 'link content ok')
    t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
  })
})

test('runs chown on given file (async)', t => {
  const file = tmpFile()
  didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } }, err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '42', 'content ok')
    t.done()
  })
})

test('writes simple file with no chown (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, '42', { chown: false }, err => {
    t.ifError(err, 'no error')
    t.is(readFile(file), '42', 'content ok')
    t.done()
  })
})

test('runs chmod on given file (async)', t => {
  t.plan(5)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
    t.ifError(err, 'no error')
    const stat = fs.statSync(file)
    t.is(stat.mode, parseInt('100741', 8))
    didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '23', { chown: { uid: 42, gid: 43 } }, err => {
      t.ifError(err, 'no error')
    })
  })
})

test('run chmod AND chown (async)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42', { mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } }, err => {
    t.ifError(err, 'no error')
    const stat = fs.statSync(file)
    t.is(stat.mode, parseInt('100741', 8))
  })
})

test('does not change chmod by default (async)', t => {
  t.plan(5)
  const file = tmpFile()
  didWriteFileAtomic(t, {}, file, '42', { mode: parseInt('741', 8) }, err => {
    t.ifError(err, 'no error')

    didWriteFileAtomic(t, currentUser(), file, '43', err => {
      t.ifError(err, 'no error')
      const stat = fs.statSync(file)
      t.is(stat.mode, parseInt('100741', 8))
    })
  })
})

test('does not change chown by default (async)', t => {
  t.plan(6)
  const file = tmpFile()
  didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } }, _setModeOnly)

  function _setModeOnly (err) {
    t.ifError(err, 'no error')

    didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43', { mode: parseInt('741', 8) }, _allDefault)
  }

  function _allDefault (err) {
    t.ifError(err, 'no error')

    didWriteFileAtomic(t, { uid: 42, gid: 43 }, file, '43', _noError)
  }

  function _noError (err) {
    t.ifError(err, 'no error')
  }
})

test('writes simple file (sync)', t => {
  t.plan(2)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, '42')
  t.is(readFile(file), '42')
})

test('writes simple file with encoding (sync)', t => {
  t.plan(2)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, 'foo', 'utf16le')
  t.is(readFile(file), 'f\u0000o\u0000o\u0000')
})

test('writes simple buffer file (sync)', t => {
  t.plan(2)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, Buffer.from('42'))
  t.is(readFile(file), '42')
})

test('writes undefined file (sync)', t => {
  t.plan(2)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, undefined)
  t.is(readFile(file), '')
})

test('writes to symlinks without clobbering (sync)', t => {
  t.plan(4)
  const file = tmpFile()
  const link = tmpFile()
  fs.writeFileSync(file, '42')
  fs.symlinkSync(file, link)
  didWriteFileAtomicSync(t, currentUser(), link, '43')
  t.is(readFile(file), '43', 'target content ok')
  t.is(readFile(link), '43', 'link content ok')
  t.ok(fs.lstatSync(link).isSymbolicLink(), 'link is link')
})

test('runs chown on given file (sync)', t => {
  t.plan(1)
  const file = tmpFile()
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
})

test('runs chmod on given file (sync)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
  const stat = fs.statSync(file)
  t.is(stat.mode, parseInt('100741', 8))
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '23', { chown: { uid: 42, gid: 43 } })
})

test('runs chown and chmod (sync)', t => {
  t.plan(2)
  const file = tmpFile()
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { mode: parseInt('741', 8), chown: { uid: 42, gid: 43 } })
  const stat = fs.statSync(file)
  t.is(stat.mode, parseInt('100741', 8))
})

test('does not change chmod by default (sync)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomicSync(t, {}, file, '42', { mode: parseInt('741', 8) })
  didWriteFileAtomicSync(t, currentUser(), file, '43')
  const stat = fs.statSync(file)
  t.is(stat.mode, parseInt('100741', 8))
})

test('does not change chown by default (sync)', t => {
  t.plan(3)
  const file = tmpFile()
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '42', { chown: { uid: 42, gid: 43 } })
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '43', { mode: parseInt('741', 8) })
  didWriteFileAtomicSync(t, { uid: 42, gid: 43 }, file, '44')
})

test('cleanup', t => {
  rimraf.sync(workdir)
  t.done()
})
{
  "compilerOptions": {
    "alwaysStrict": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "inlineSourceMap": false,
    "jsx": "react",
    "lib": ["dom", "scripthost", "es2015", "es2016", "es2017", "es2018", "es2019", "es2020"],
    "module": "commonjs",
    "moduleResolution": "node",
    "newLine": "LF",
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "outDir": "dist",
    "pretty": true,
    "strictNullChecks": true,
    "target": "es2018"
  },
  "include": [
    "src"
  ],
  "exclude": [
    "node_modules"
  ]
}
"use strict";
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _a, _b;
var _Conf_validator, _Conf_encryptionKey, _Conf_options, _Conf_defaultValues;
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("util");
const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const assert = require("assert");
const events_1 = require("events");
const dotProp = require("dot-prop");
const pkgUp = require("pkg-up");
const envPaths = require("env-paths");
const atomically = require("atomically");
const ajv_1 = require("ajv");
const ajv_formats_1 = require("ajv-formats");
const debounceFn = require("debounce-fn");
const semver = require("semver");
const onetime = require("onetime");
const encryptionAlgorithm = 'aes-256-cbc';
const createPlainObject = () => {
    return Object.create(null);
};
const isExist = (data) => {
    return data !== undefined && data !== null;
};
let parentDir = '';
try {
    // Prevent caching of this module so module.parent is always accurate.
    // Note: This trick won't work with ESM or inside a webworker
    // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
    delete require.cache[__filename];
    parentDir = path.dirname((_b = (_a = module.parent) === null || _a === void 0 ? void 0 : _a.filename) !== null && _b !== void 0 ? _b : '.');
}
catch (_c) { }
const checkValueType = (key, value) => {
    const nonJsonTypes = new Set([
        'undefined',
        'symbol',
        'function'
    ]);
    const type = typeof value;
    if (nonJsonTypes.has(type)) {
        throw new TypeError(`Setting a value of type \`${type}\` for key \`${key}\` is not allowed as it's not supported by JSON`);
    }
};
const INTERNAL_KEY = '__internal__';
const MIGRATION_KEY = `${INTERNAL_KEY}.migrations.version`;
class Conf {
    constructor(partialOptions = {}) {
        var _a;
        _Conf_validator.set(this, void 0);
        _Conf_encryptionKey.set(this, void 0);
        _Conf_options.set(this, void 0);
        _Conf_defaultValues.set(this, {});
        this._deserialize = value => JSON.parse(value);
        this._serialize = value => JSON.stringify(value, undefined, '\t');
        const options = {
            configName: 'config',
            fileExtension: 'json',
            projectSuffix: 'nodejs',
            clearInvalidConfig: false,
            accessPropertiesByDotNotation: true,
            configFileMode: 0o666,
            ...partialOptions
        };
        const getPackageData = onetime(() => {
            const packagePath = pkgUp.sync({ cwd: parentDir });
            // Can't use `require` because of Webpack being annoying:
            // https://github.com/webpack/webpack/issues/196
            const packageData = packagePath && JSON.parse(fs.readFileSync(packagePath, 'utf8'));
            return packageData !== null && packageData !== void 0 ? packageData : {};
        });
        if (!options.cwd) {
            if (!options.projectName) {
                options.projectName = getPackageData().name;
            }
            if (!options.projectName) {
                throw new Error('Project name could not be inferred. Please specify the `projectName` option.');
            }
            options.cwd = envPaths(options.projectName, { suffix: options.projectSuffix }).config;
        }
        __classPrivateFieldSet(this, _Conf_options, options, "f");
        if (options.schema) {
            if (typeof options.schema !== 'object') {
                throw new TypeError('The `schema` option must be an object.');
            }
            const ajv = new ajv_1.default({
                allErrors: true,
                useDefaults: true
            });
            (0, ajv_formats_1.default)(ajv);
            const schema = {
                type: 'object',
                properties: options.schema
            };
            __classPrivateFieldSet(this, _Conf_validator, ajv.compile(schema), "f");
            for (const [key, value] of Object.entries(options.schema)) {
                if (value === null || value === void 0 ? void 0 : value.default) {
                    __classPrivateFieldGet(this, _Conf_defaultValues, "f")[key] = value.default;
                }
            }
        }
        if (options.defaults) {
            __classPrivateFieldSet(this, _Conf_defaultValues, {
                ...__classPrivateFieldGet(this, _Conf_defaultValues, "f"),
                ...options.defaults
            }, "f");
        }
        if (options.serialize) {
            this._serialize = options.serialize;
        }
        if (options.deserialize) {
            this._deserialize = options.deserialize;
        }
        this.events = new events_1.EventEmitter();
        __classPrivateFieldSet(this, _Conf_encryptionKey, options.encryptionKey, "f");
        const fileExtension = options.fileExtension ? `.${options.fileExtension}` : '';
        this.path = path.resolve(options.cwd, `${(_a = options.configName) !== null && _a !== void 0 ? _a : 'config'}${fileExtension}`);
        const fileStore = this.store;
        const store = Object.assign(createPlainObject(), options.defaults, fileStore);
        this._validate(store);
        try {
            assert.deepEqual(fileStore, store);
        }
        catch (_b) {
            this.store = store;
        }
        if (options.watch) {
            this._watch();
        }
        if (options.migrations) {
            if (!options.projectVersion) {
                options.projectVersion = getPackageData().version;
            }
            if (!options.projectVersion) {
                throw new Error('Project version could not be inferred. Please specify the `projectVersion` option.');
            }
            this._migrate(options.migrations, options.projectVersion, options.beforeEachMigration);
        }
    }
    get(key, defaultValue) {
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            return this._get(key, defaultValue);
        }
        const { store } = this;
        return key in store ? store[key] : defaultValue;
    }
    set(key, value) {
        if (typeof key !== 'string' && typeof key !== 'object') {
            throw new TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof key}`);
        }
        if (typeof key !== 'object' && value === undefined) {
            throw new TypeError('Use `delete()` to clear values');
        }
        if (this._containsReservedKey(key)) {
            throw new TypeError(`Please don't use the ${INTERNAL_KEY} key, as it's used to manage this module internal operations.`);
        }
        const { store } = this;
        const set = (key, value) => {
            checkValueType(key, value);
            if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
                dotProp.set(store, key, value);
            }
            else {
                store[key] = value;
            }
        };
        if (typeof key === 'object') {
            const object = key;
            for (const [key, value] of Object.entries(object)) {
                set(key, value);
            }
        }
        else {
            set(key, value);
        }
        this.store = store;
    }
    /**
    Check if an item exists.

    @param key - The key of the item to check.
    */
    has(key) {
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            return dotProp.has(this.store, key);
        }
        return key in this.store;
    }
    /**
    Reset items to their default values, as defined by the `defaults` or `schema` option.

    @see `clear()` to reset all items.

    @param keys - The keys of the items to reset.
    */
    reset(...keys) {
        for (const key of keys) {
            if (isExist(__classPrivateFieldGet(this, _Conf_defaultValues, "f")[key])) {
                this.set(key, __classPrivateFieldGet(this, _Conf_defaultValues, "f")[key]);
            }
        }
    }
    /**
    Delete an item.

    @param key - The key of the item to delete.
    */
    delete(key) {
        const { store } = this;
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            dotProp.delete(store, key);
        }
        else {
            // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
            delete store[key];
        }
        this.store = store;
    }
    /**
    Delete all items.

    This resets known items to their default values, if defined by the `defaults` or `schema` option.
    */
    clear() {
        this.store = createPlainObject();
        for (const key of Object.keys(__classPrivateFieldGet(this, _Conf_defaultValues, "f"))) {
            this.reset(key);
        }
    }
    /**
    Watches the given `key`, calling `callback` on any changes.

    @param key - The key wo watch.
    @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
    @returns A function, that when called, will unsubscribe.
    */
    onDidChange(key, callback) {
        if (typeof key !== 'string') {
            throw new TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof key}`);
        }
        if (typeof callback !== 'function') {
            throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
        }
        return this._handleChange(() => this.get(key), callback);
    }
    /**
    Watches the whole config object, calling `callback` on any changes.

    @param callback - A callback function that is called on any changes. When a `key` is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.
    @returns A function, that when called, will unsubscribe.
    */
    onDidAnyChange(callback) {
        if (typeof callback !== 'function') {
            throw new TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof callback}`);
        }
        return this._handleChange(() => this.store, callback);
    }
    get size() {
        return Object.keys(this.store).length;
    }
    get store() {
        try {
            const data = fs.readFileSync(this.path, __classPrivateFieldGet(this, _Conf_encryptionKey, "f") ? null : 'utf8');
            const dataString = this._encryptData(data);
            const deserializedData = this._deserialize(dataString);
            this._validate(deserializedData);
            return Object.assign(createPlainObject(), deserializedData);
        }
        catch (error) {
            if ((error === null || error === void 0 ? void 0 : error.code) === 'ENOENT') {
                this._ensureDirectory();
                return createPlainObject();
            }
            if (__classPrivateFieldGet(this, _Conf_options, "f").clearInvalidConfig && error.name === 'SyntaxError') {
                return createPlainObject();
            }
            throw error;
        }
    }
    set store(value) {
        this._ensureDirectory();
        this._validate(value);
        this._write(value);
        this.events.emit('change');
    }
    *[(_Conf_validator = new WeakMap(), _Conf_encryptionKey = new WeakMap(), _Conf_options = new WeakMap(), _Conf_defaultValues = new WeakMap(), Symbol.iterator)]() {
        for (const [key, value] of Object.entries(this.store)) {
            yield [key, value];
        }
    }
    _encryptData(data) {
        if (!__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
            return data.toString();
        }
        try {
            // Check if an initialization vector has been used to encrypt the data
            if (__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
                try {
                    if (data.slice(16, 17).toString() === ':') {
                        const initializationVector = data.slice(0, 16);
                        const password = crypto.pbkdf2Sync(__classPrivateFieldGet(this, _Conf_encryptionKey, "f"), initializationVector.toString(), 10000, 32, 'sha512');
                        const decipher = crypto.createDecipheriv(encryptionAlgorithm, password, initializationVector);
                        data = Buffer.concat([decipher.update(Buffer.from(data.slice(17))), decipher.final()]).toString('utf8');
                    }
                    else {
                        // TODO: Remove this in the next major version.
                        const decipher = crypto.createDecipher(encryptionAlgorithm, __classPrivateFieldGet(this, _Conf_encryptionKey, "f"));
                        data = Buffer.concat([decipher.update(Buffer.from(data)), decipher.final()]).toString('utf8');
                    }
                }
                catch (_a) { }
            }
        }
        catch (_b) { }
        return data.toString();
    }
    _handleChange(getter, callback) {
        let currentValue = getter();
        const onChange = () => {
            const oldValue = currentValue;
            const newValue = getter();
            if ((0, util_1.isDeepStrictEqual)(newValue, oldValue)) {
                return;
            }
            currentValue = newValue;
            callback.call(this, newValue, oldValue);
        };
        this.events.on('change', onChange);
        return () => this.events.removeListener('change', onChange);
    }
    _validate(data) {
        if (!__classPrivateFieldGet(this, _Conf_validator, "f")) {
            return;
        }
        const valid = __classPrivateFieldGet(this, _Conf_validator, "f").call(this, data);
        if (valid || !__classPrivateFieldGet(this, _Conf_validator, "f").errors) {
            return;
        }
        const errors = __classPrivateFieldGet(this, _Conf_validator, "f").errors
            .map(({ instancePath, message = '' }) => `\`${instancePath.slice(1)}\` ${message}`);
        throw new Error('Config schema violation: ' + errors.join('; '));
    }
    _ensureDirectory() {
        // Ensure the directory exists as it could have been deleted in the meantime.
        fs.mkdirSync(path.dirname(this.path), { recursive: true });
    }
    _write(value) {
        let data = this._serialize(value);
        if (__classPrivateFieldGet(this, _Conf_encryptionKey, "f")) {
            const initializationVector = crypto.randomBytes(16);
            const password = crypto.pbkdf2Sync(__classPrivateFieldGet(this, _Conf_encryptionKey, "f"), initializationVector.toString(), 10000, 32, 'sha512');
            const cipher = crypto.createCipheriv(encryptionAlgorithm, password, initializationVector);
            data = Buffer.concat([initializationVector, Buffer.from(':'), cipher.update(Buffer.from(data)), cipher.final()]);
        }
        // Temporary workaround for Conf being packaged in a Ubuntu Snap app.
        // See https://github.com/sindresorhus/conf/pull/82
        if (process.env.SNAP) {
            fs.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
        }
        else {
            try {
                atomically.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
            }
            catch (error) {
                // Fix for https://github.com/sindresorhus/electron-store/issues/106
                // Sometimes on Windows, we will get an EXDEV error when atomic writing
                // (even though to the same directory), so we fall back to non atomic write
                if ((error === null || error === void 0 ? void 0 : error.code) === 'EXDEV') {
                    fs.writeFileSync(this.path, data, { mode: __classPrivateFieldGet(this, _Conf_options, "f").configFileMode });
                    return;
                }
                throw error;
            }
        }
    }
    _watch() {
        this._ensureDirectory();
        if (!fs.existsSync(this.path)) {
            this._write(createPlainObject());
        }
        if (process.platform === 'win32') {
            fs.watch(this.path, { persistent: false }, debounceFn(() => {
                // On Linux and Windows, writing to the config file emits a `rename` event, so we skip checking the event type.
                this.events.emit('change');
            }, { wait: 100 }));
        }
        else {
            fs.watchFile(this.path, { persistent: false }, debounceFn(() => {
                this.events.emit('change');
            }, { wait: 5000 }));
        }
    }
    _migrate(migrations, versionToMigrate, beforeEachMigration) {
        let previousMigratedVersion = this._get(MIGRATION_KEY, '0.0.0');
        const newerVersions = Object.keys(migrations)
            .filter(candidateVersion => this._shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate));
        let storeBackup = { ...this.store };
        for (const version of newerVersions) {
            try {
                if (beforeEachMigration) {
                    beforeEachMigration(this, {
                        fromVersion: previousMigratedVersion,
                        toVersion: version,
                        finalVersion: versionToMigrate,
                        versions: newerVersions
                    });
                }
                const migration = migrations[version];
                migration(this);
                this._set(MIGRATION_KEY, version);
                previousMigratedVersion = version;
                storeBackup = { ...this.store };
            }
            catch (error) {
                this.store = storeBackup;
                throw new Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${error}`);
            }
        }
        if (this._isVersionInRangeFormat(previousMigratedVersion) || !semver.eq(previousMigratedVersion, versionToMigrate)) {
            this._set(MIGRATION_KEY, versionToMigrate);
        }
    }
    _containsReservedKey(key) {
        if (typeof key === 'object') {
            const firsKey = Object.keys(key)[0];
            if (firsKey === INTERNAL_KEY) {
                return true;
            }
        }
        if (typeof key !== 'string') {
            return false;
        }
        if (__classPrivateFieldGet(this, _Conf_options, "f").accessPropertiesByDotNotation) {
            if (key.startsWith(`${INTERNAL_KEY}.`)) {
                return true;
            }
            return false;
        }
        return false;
    }
    _isVersionInRangeFormat(version) {
        return semver.clean(version) === null;
    }
    _shouldPerformMigration(candidateVersion, previousMigratedVersion, versionToMigrate) {
        if (this._isVersionInRangeFormat(candidateVersion)) {
            if (previousMigratedVersion !== '0.0.0' && semver.satisfies(previousMigratedVersion, candidateVersion)) {
                return false;
            }
            return semver.satisfies(versionToMigrate, candidateVersion);
        }
        if (semver.lte(candidateVersion, previousMigratedVersion)) {
            return false;
        }
        if (semver.gt(candidateVersion, versionToMigrate)) {
            return false;
        }
        return true;
    }
    _get(key, defaultValue) {
        return dotProp.get(this.store, key, defaultValue);
    }
    _set(key, value) {
        const { store } = this;
        dotProp.set(store, key, value);
        this.store = store;
    }
}
exports.default = Conf;
// For CommonJS default export support
module.exports = Conf;
module.exports.default = Conf;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})

const schema = {
  type: "object",
  properties: {
    foo: {type: "string"},
    bar: {type: "number", maximum: 3},
  },
  required: ["foo", "bar"],
  additionalProperties: false,
}

const validate = ajv.compile(schema)

test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})

function test(data) {
  const valid = validate(data)
  if (valid) console.log("Valid!")
  else console.log("Invalid: " + ajv.errorsText(validate.errors))
}
The MIT License (MIT)

Copyright (c) 2015-2021 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg">

&nbsp;

# Ajv JSON schema validator

The fastest JSON validator for Node.js and browser.

Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/).

[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild)
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master)
[![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-70F0F9)](https://simplex.chat/contact#/?v=1-2&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2F8KvvURM6J38Gdq9dCuPswMOkMny0xCOJ%23%2F%3Fv%3D1-2%26dh%3DMCowBQYDK2VuAyEAr8rPVRuMOXv6kwF2yUAap-eoVg-9ssOFCi1fIrxTUw0%253D%26srv%3Do5vmywmrnaxalvz6wi3zicyftgio6psuvyniis6gco6bp6ekl4cqj4id.onion&data=%7B%22type%22%3A%22group%22%2C%22groupLinkId%22%3A%224pwLRgWHU9tlroMWHz0uOg%3D%3D%22%7D)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)

## Ajv sponsors

[<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv)

[<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)

[<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv)

## Contributing

More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation.

Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html).

## Documentation

All documentation is available on the [Ajv website](https://ajv.js.org).

Some useful site links:

- [Getting started](https://ajv.js.org/guide/getting-started.html)
- [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html)
- [API reference](https://ajv.js.org/api.html)
- [Strict mode](https://ajv.js.org/strict-mode.html)
- [Standalone validation code](https://ajv.js.org/standalone.html)
- [Security considerations](https://ajv.js.org/security.html)
- [Command line interface](https://ajv.js.org/packages/ajv-cli.html)
- [Frequently Asked Questions](https://ajv.js.org/faq.html)

## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin)

Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!

Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.

Please sponsor Ajv via:

- [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it)
- [Ajv Open Collective](https://opencollective.com/ajv)

Thank you.

#### Open Collective sponsors

<a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a>

<a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/12/website"><img src="https://opencollective.com/ajv/organization/12/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/13/website"><img src="https://opencollective.com/ajv/organization/13/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/14/website"><img src="https://opencollective.com/ajv/organization/14/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/15/website"><img src="https://opencollective.com/ajv/organization/15/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/16/website"><img src="https://opencollective.com/ajv/organization/16/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/17/website"><img src="https://opencollective.com/ajv/organization/17/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/18/website"><img src="https://opencollective.com/ajv/organization/18/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/19/website"><img src="https://opencollective.com/ajv/organization/19/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/20/website"><img src="https://opencollective.com/ajv/organization/20/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/21/website"><img src="https://opencollective.com/ajv/organization/21/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/22/website"><img src="https://opencollective.com/ajv/organization/22/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/23/website"><img src="https://opencollective.com/ajv/organization/23/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/24/website"><img src="https://opencollective.com/ajv/organization/24/avatar.svg"></a>

## Performance

Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:

- [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place
- [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster
- [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html)
- [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html)

Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark):

[![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus/schemasafe|is-my-json-valid|djv|@cfworker/json-schema|jsonschema/=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance)

## Features

- Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6):
  - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html))
  - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions:
    - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator).
    - keyword [nullable](https://ajv.js.org/json-schema.html#nullable).
  - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available)
  - support of recursive references between schemas
  - correct string lengths for strings with unicode pairs
  - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin).
  - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema)
- NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/):
  - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html))
  - meta-schema for JTD schemas
  - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema)
- supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current
- [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation
- "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors)
- [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation
- i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package
- [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties)
- [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items
- [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords
- [user-defined keywords](https://ajv.js.org/guide/user-keywords.html)
- additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package
- [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords
- [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords

## Install

To install version 8:

```
npm install ajv
```

## <a name="usage"></a>Getting started

Try it in the Node.js REPL: https://runkit.com/npm/ajv

In JavaScript:

```javascript
// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv")

const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}

const schema = {
  type: "object",
  properties: {
    foo: {type: "integer"},
    bar: {type: "string"},
  },
  required: ["foo"],
  additionalProperties: false,
}

const data = {
  foo: 1,
  bar: "abc",
}

const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
```

Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html)

## Changes history

See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases)

**Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0)

[Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0)

[Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0).

## Code of conduct

Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md).

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.

## Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.

## Open-source software support

Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.

## License

[MIT](./LICENSE)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const dynamic_1 = require("./vocabularies/dynamic");
const next_1 = require("./vocabularies/next");
const unevaluated_1 = require("./vocabularies/unevaluated");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2019_09_1 = require("./refs/json-schema-2019-09");
const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema";
class Ajv2019 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(dynamic_1.default);
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        this.addVocabulary(next_1.default);
        this.addVocabulary(unevaluated_1.default);
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2019_09_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2019 = Ajv2019;
module.exports = exports = Ajv2019;
module.exports.Ajv2019 = Ajv2019;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2019;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2019.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0;
const core_1 = require("./core");
const draft2020_1 = require("./vocabularies/draft2020");
const discriminator_1 = require("./vocabularies/discriminator");
const json_schema_2020_12_1 = require("./refs/json-schema-2020-12");
const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
class Ajv2020 extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            dynamicRef: true,
            next: true,
            unevaluated: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        draft2020_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        const { $data, meta } = this.opts;
        if (!meta)
            return;
        json_schema_2020_12_1.default.call(this, $data);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv2020 = Ajv2020;
module.exports = exports = Ajv2020;
module.exports.Ajv2020 = Ajv2020;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv2020;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const draft7_1 = require("./vocabularies/draft7");
const discriminator_1 = require("./vocabularies/discriminator");
const draft7MetaSchema = require("./refs/json-schema-draft-07.json");
const META_SUPPORT_DATA = ["/properties"];
const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
class Ajv extends core_1.default {
    _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v) => this.addVocabulary(v));
        if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        const metaSchema = this.opts.$data
            ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA)
            : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=ajv.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
class _CodeOrName {
}
exports._CodeOrName = _CodeOrName;
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
class Name extends _CodeOrName {
    constructor(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        return false;
    }
    get names() {
        return { [this.str]: 1 };
    }
}
exports.Name = Name;
class _Code extends _CodeOrName {
    constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
    }
    toString() {
        return this.str;
    }
    emptyStr() {
        if (this._items.length > 1)
            return false;
        const item = this._items[0];
        return item === "" || item === '""';
    }
    get str() {
        var _a;
        return ((_a = this._str) !== null && _a !== void 0 ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
    }
    get names() {
        var _a;
        return ((_a = this._names) !== null && _a !== void 0 ? _a : (this._names = this._items.reduce((names, c) => {
            if (c instanceof Name)
                names[c.str] = (names[c.str] || 0) + 1;
            return names;
        }, {})));
    }
}
exports._Code = _Code;
exports.nil = new _Code("");
function _(strs, ...args) {
    const code = [strs[0]];
    let i = 0;
    while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
    }
    return new _Code(code);
}
exports._ = _;
const plus = new _Code("+");
function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
}
exports.str = str;
function addCodeArg(code, arg) {
    if (arg instanceof _Code)
        code.push(...arg._items);
    else if (arg instanceof Name)
        code.push(arg);
    else
        code.push(interpolate(arg));
}
exports.addCodeArg = addCodeArg;
function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
        if (expr[i] === plus) {
            const res = mergeExprItems(expr[i - 1], expr[i + 1]);
            if (res !== undefined) {
                expr.splice(i - 1, 3, res);
                continue;
            }
            expr[i++] = "+";
        }
        i++;
    }
}
function mergeExprItems(a, b) {
    if (b === '""')
        return a;
    if (a === '""')
        return b;
    if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
            return;
        if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
        return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.slice(1)}`;
    return;
}
function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str `${c1}${c2}`;
}
exports.strConcat = strConcat;
// TODO do not allow arrays here
function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null
        ? x
        : safeStringify(Array.isArray(x) ? x.join(",") : x);
}
function stringify(x) {
    return new _Code(safeStringify(x));
}
exports.stringify = stringify;
function safeStringify(x) {
    return JSON.stringify(x)
        .replace(/\u2028/g, "\\u2028")
        .replace(/\u2029/g, "\\u2029");
}
exports.safeStringify = safeStringify;
function getProperty(key) {
    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
}
exports.getProperty = getProperty;
//Does best effort to format the name properly
function getEsmExportName(key) {
    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
}
exports.getEsmExportName = getEsmExportName;
function regexpCode(rx) {
    return new _Code(rx.toString());
}
exports.regexpCode = regexpCode;
//# sourceMappingURL=code.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
const code_1 = require("./code");
const scope_1 = require("./scope");
var code_2 = require("./code");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
var scope_2 = require("./scope");
Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
exports.operators = {
    GT: new code_1._Code(">"),
    GTE: new code_1._Code(">="),
    LT: new code_1._Code("<"),
    LTE: new code_1._Code("<="),
    EQ: new code_1._Code("==="),
    NEQ: new code_1._Code("!=="),
    NOT: new code_1._Code("!"),
    OR: new code_1._Code("||"),
    AND: new code_1._Code("&&"),
    ADD: new code_1._Code("+"),
};
class Node {
    optimizeNodes() {
        return this;
    }
    optimizeNames(_names, _constants) {
        return this;
    }
}
class Def extends Node {
    constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
    }
    render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (!names[this.name.str])
            return;
        if (this.rhs)
            this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
    }
}
class Assign extends Node {
    constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
    }
    render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
    }
    optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
            return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
    }
    get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
    }
}
class AssignOp extends Assign {
    constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
    }
    render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
    }
}
class Label extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        return `${this.label}:` + _n;
    }
}
class Break extends Node {
    constructor(label) {
        super();
        this.label = label;
        this.names = {};
    }
    render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
    }
}
class Throw extends Node {
    constructor(error) {
        super();
        this.error = error;
    }
    render({ _n }) {
        return `throw ${this.error};` + _n;
    }
    get names() {
        return this.error.names;
    }
}
class AnyCode extends Node {
    constructor(code) {
        super();
        this.code = code;
    }
    render({ _n }) {
        return `${this.code};` + _n;
    }
    optimizeNodes() {
        return `${this.code}` ? this : undefined;
    }
    optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
    }
    get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
    }
}
class ParentNode extends Node {
    constructor(nodes = []) {
        super();
        this.nodes = nodes;
    }
    render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
    }
    optimizeNodes() {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            const n = nodes[i].optimizeNodes();
            if (Array.isArray(n))
                nodes.splice(i, 1, ...n);
            else if (n)
                nodes[i] = n;
            else
                nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    optimizeNames(names, constants) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
            // iterating backwards improves 1-pass optimization
            const n = nodes[i];
            if (n.optimizeNames(names, constants))
                continue;
            subtractNames(names, n.names);
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : undefined;
    }
    get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
    }
}
class BlockNode extends ParentNode {
    render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
    }
}
class Root extends ParentNode {
}
class Else extends BlockNode {
}
Else.kind = "else";
class If extends BlockNode {
    constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
    }
    render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
            code += "else " + this.else.render(opts);
        return code;
    }
    optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
            return this.nodes; // else is ignored here
        let e = this.else;
        if (e) {
            const ns = e.optimizeNodes();
            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e) {
            if (cond === false)
                return e instanceof If ? e : e.nodes;
            if (this.nodes.length)
                return this;
            return new If(not(cond), e instanceof If ? [e] : e.nodes);
        }
        if (cond === false || !this.nodes.length)
            return undefined;
        return this;
    }
    optimizeNames(names, constants) {
        var _a;
        this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
            return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
            addNames(names, this.else.names);
        return names;
    }
}
If.kind = "if";
class For extends BlockNode {
}
For.kind = "for";
class ForLoop extends For {
    constructor(iteration) {
        super();
        this.iteration = iteration;
    }
    render(opts) {
        return `for(${this.iteration})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iteration.names);
    }
}
class ForRange extends For {
    constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
    }
    render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
    }
    get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
    }
}
class ForIter extends For {
    constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
    }
    render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
    }
    optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
            return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
    }
    get names() {
        return addNames(super.names, this.iterable.names);
    }
}
class Func extends BlockNode {
    constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
    }
    render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
    }
}
Func.kind = "func";
class Return extends ParentNode {
    render(opts) {
        return "return " + super.render(opts);
    }
}
Return.kind = "return";
class Try extends BlockNode {
    render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
            code += this.catch.render(opts);
        if (this.finally)
            code += this.finally.render(opts);
        return code;
    }
    optimizeNodes() {
        var _a, _b;
        super.optimizeNodes();
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
        return this;
    }
    optimizeNames(names, constants) {
        var _a, _b;
        super.optimizeNames(names, constants);
        (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants);
        (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
        return this;
    }
    get names() {
        const names = super.names;
        if (this.catch)
            addNames(names, this.catch.names);
        if (this.finally)
            addNames(names, this.finally.names);
        return names;
    }
}
class Catch extends BlockNode {
    constructor(error) {
        super();
        this.error = error;
    }
    render(opts) {
        return `catch(${this.error})` + super.render(opts);
    }
}
Catch.kind = "catch";
class Finally extends BlockNode {
    render(opts) {
        return "finally" + super.render(opts);
    }
}
Finally.kind = "finally";
class CodeGen {
    constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
    }
    toString() {
        return this._root.render(this.opts);
    }
    // returns unique name in the internal scope
    name(prefix) {
        return this._scope.name(prefix);
    }
    // reserves unique name in the external scope
    scopeName(prefix) {
        return this._extScope.name(prefix);
    }
    // reserves unique name in the external scope and assigns value to it
    scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set());
        vs.add(name);
        return name;
    }
    getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
    }
    // return code that assigns values in the external scope to the names that are used internally
    // (same names that were returned by gen.scopeName or gen.scopeValue)
    scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
    }
    scopeCode() {
        return this._extScope.scopeCode(this._values);
    }
    _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== undefined && constant)
            this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
    }
    // `const` declaration (`var` in es5 mode)
    const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
    }
    // `let` declaration with optional assignment (`var` in es5 mode)
    let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
    }
    // `var` declaration with optional assignment
    var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
    }
    // assignment code
    assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
    }
    // `+=` code
    add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
    }
    // appends passed SafeExpr to code or executes Block
    code(c) {
        if (typeof c == "function")
            c();
        else if (c !== code_1.nil)
            this._leafNode(new AnyCode(c));
        return this;
    }
    // returns code for object literal for the passed argument list of key-value pairs
    object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
            if (code.length > 1)
                code.push(",");
            code.push(key);
            if (key !== value || this.opts.es5) {
                code.push(":");
                (0, code_1.addCodeArg)(code, value);
            }
        }
        code.push("}");
        return new code_1._Code(code);
    }
    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
    if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
            this.code(thenBody).else().code(elseBody).endIf();
        }
        else if (thenBody) {
            this.code(thenBody).endIf();
        }
        else if (elseBody) {
            throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
    }
    // `else if` clause - invalid without `if` or after `else` clauses
    elseIf(condition) {
        return this._elseNode(new If(condition));
    }
    // `else` clause - only valid after `if` or `else if` clauses
    else() {
        return this._elseNode(new Else());
    }
    // end `if` statement (needed if gen.if was used only with condition)
    endIf() {
        return this._endBlockNode(If, Else);
    }
    _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
            this.code(forBody).endFor();
        return this;
    }
    // a generic `for` clause (or statement if `forBody` is passed)
    for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
    }
    // `for` statement for a range of values
    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
    }
    // `for-of` statement (in es5 mode replace with a normal for loop)
    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
            return this.forRange("_i", 0, (0, code_1._) `${arr}.length`, (i) => {
                this.var(name, (0, code_1._) `${arr}[${i}]`);
                forBody(name);
            });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
    }
    // `for-in` statement.
    // With option `ownProperties` replaced with a `for-of` loop for object keys
    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
            return this.forOf(nameOrPrefix, (0, code_1._) `Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
    }
    // end `for` loop
    endFor() {
        return this._endBlockNode(For);
    }
    // `label` statement
    label(label) {
        return this._leafNode(new Label(label));
    }
    // `break` statement
    break(label) {
        return this._leafNode(new Break(label));
    }
    // `return` statement
    return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
            throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
    }
    // `try` statement
    try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
            throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
            const error = this.name("e");
            this._currNode = node.catch = new Catch(error);
            catchCode(error);
        }
        if (finallyCode) {
            this._currNode = node.finally = new Finally();
            this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
    }
    // `throw` statement
    throw(error) {
        return this._leafNode(new Throw(error));
    }
    // start self-balancing block
    block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
            this.code(body).endBlock(nodeCount);
        return this;
    }
    // end the current self-balancing block
    endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === undefined)
            throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
    }
    // `function` heading (or definition if funcBody is passed)
    func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
            this.code(funcBody).endFunc();
        return this;
    }
    // end function definition
    endFunc() {
        return this._endBlockNode(Func);
    }
    optimize(n = 1) {
        while (n-- > 0) {
            this._root.optimizeNodes();
            this._root.optimizeNames(this._root.names, this._constants);
        }
    }
    _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
    }
    _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
    }
    _endBlockNode(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || (N2 && n instanceof N2)) {
            this._nodes.pop();
            return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
    }
    _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
            throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
    }
    get _root() {
        return this._nodes[0];
    }
    get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
    }
    set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
    }
}
exports.CodeGen = CodeGen;
function addNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
    return names;
}
function addExprNames(names, from) {
    return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
}
function optimizeExpr(expr, names, constants) {
    if (expr instanceof code_1.Name)
        return replaceName(expr);
    if (!canOptimize(expr))
        return expr;
    return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
            c = replaceName(c);
        if (c instanceof code_1._Code)
            items.push(...c._items);
        else
            items.push(c);
        return items;
    }, []));
    function replaceName(n) {
        const c = constants[n.str];
        if (c === undefined || names[n.str] !== 1)
            return n;
        delete names[n.str];
        return c;
    }
    function canOptimize(e) {
        return (e instanceof code_1._Code &&
            e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined));
    }
}
function subtractNames(names, from) {
    for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
}
function not(x) {
    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._) `!${par(x)}`;
}
exports.not = not;
const andCode = mappend(exports.operators.AND);
// boolean AND (&&) expression with the passed arguments
function and(...args) {
    return args.reduce(andCode);
}
exports.and = and;
const orCode = mappend(exports.operators.OR);
// boolean OR (||) expression with the passed arguments
function or(...args) {
    return args.reduce(orCode);
}
exports.or = or;
function mappend(op) {
    return (x, y) => (x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._) `${par(x)} ${op} ${par(y)}`);
}
function par(x) {
    return x instanceof code_1.Name ? x : (0, code_1._) `(${x})`;
}
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
const code_1 = require("./code");
class ValueError extends Error {
    constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
    }
}
var UsedValueState;
(function (UsedValueState) {
    UsedValueState[UsedValueState["Started"] = 0] = "Started";
    UsedValueState[UsedValueState["Completed"] = 1] = "Completed";
})(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
exports.varKinds = {
    const: new code_1.Name("const"),
    let: new code_1.Name("let"),
    var: new code_1.Name("var"),
};
class Scope {
    constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
    }
    toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
    }
    name(prefix) {
        return new code_1.Name(this._newName(prefix));
    }
    _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
    }
    _nameGroup(prefix) {
        var _a, _b;
        if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || (this._prefixes && !this._prefixes.has(prefix))) {
            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return (this._names[prefix] = { prefix, index: 0 });
    }
}
exports.Scope = Scope;
class ValueScopeName extends code_1.Name {
    constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
    }
    setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._) `.${new code_1.Name(property)}[${itemIndex}]`;
    }
}
exports.ValueScopeName = ValueScopeName;
const line = (0, code_1._) `\n`;
class ValueScope extends Scope {
    constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
    }
    get() {
        return this._scope;
    }
    name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
    }
    value(nameOrPrefix, value) {
        var _a;
        if (value.ref === undefined)
            throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
        let vs = this._values[prefix];
        if (vs) {
            const _name = vs.get(valueKey);
            if (_name)
                return _name;
        }
        else {
            vs = this._values[prefix] = new Map();
        }
        vs.set(valueKey, name);
        const s = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s.length;
        s[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
    }
    getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
            return;
        return vs.get(keyOrRef);
    }
    scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
            if (name.scopePath === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return (0, code_1._) `${scopeName}${name.scopePath}`;
        });
    }
    scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
            if (name.value === undefined)
                throw new Error(`CodeGen: name "${name}" has no value`);
            return name.value.code;
        }, usedValues, getCode);
    }
    _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
            const vs = values[prefix];
            if (!vs)
                continue;
            const nameSet = (usedValues[prefix] = usedValues[prefix] || new Map());
            vs.forEach((name) => {
                if (nameSet.has(name))
                    return;
                nameSet.set(name, UsedValueState.Started);
                let c = valueCode(name);
                if (c) {
                    const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
                }
                else if ((c = getCode === null || getCode === void 0 ? void 0 : getCode(name))) {
                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
                }
                else {
                    throw new ValueError(name);
                }
                nameSet.set(name, UsedValueState.Completed);
            });
        }
        return code;
    }
}
exports.ValueScope = ValueScope;
//# sourceMappingURL=scope.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
const codegen_1 = require("./codegen");
const util_1 = require("./util");
const names_1 = require("./names");
exports.keywordError = {
    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
};
exports.keyword$DataError = {
    message: ({ keyword, schemaType }) => schemaType
        ? (0, codegen_1.str) `"${keyword}" keyword must be ${schemaType} ($data)`
        : (0, codegen_1.str) `"${keyword}" keyword is invalid ($data)`,
};
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : (compositeRule || allErrors)) {
        addError(gen, errObj);
    }
    else {
        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
    }
}
exports.reportError = reportError;
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error, errorPaths);
    addError(gen, errObj);
    if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
    }
}
exports.reportExtraError = reportExtraError;
function resetErrorsCount(gen, errsCount) {
    gen.assign(names_1.default.errors, errsCount);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._) `${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
}
exports.resetErrorsCount = resetErrorsCount;
function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
    /* istanbul ignore if */
    if (errsCount === undefined)
        throw new Error("ajv implementation error");
    const err = gen.name("err");
    gen.forRange("i", errsCount, names_1.default.errors, (i) => {
        gen.const(err, (0, codegen_1._) `${names_1.default.vErrors}[${i}]`);
        gen.if((0, codegen_1._) `${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._) `${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._) `${err}.schemaPath`, (0, codegen_1.str) `${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
            gen.assign((0, codegen_1._) `${err}.schema`, schemaValue);
            gen.assign((0, codegen_1._) `${err}.data`, data);
        }
    });
}
exports.extendErrors = extendErrors;
function addError(gen, errObj) {
    const err = gen.const("err", errObj);
    gen.if((0, codegen_1._) `${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._) `[${err}]`), (0, codegen_1._) `${names_1.default.vErrors}.push(${err})`);
    gen.code((0, codegen_1._) `${names_1.default.errors}++`);
}
function returnErrors(it, errs) {
    const { gen, validateName, schemaEnv } = it;
    if (schemaEnv.$async) {
        gen.throw((0, codegen_1._) `new ${it.ValidationError}(${errs})`);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, errs);
        gen.return(false);
    }
}
const E = {
    keyword: new codegen_1.Name("keyword"),
    schemaPath: new codegen_1.Name("schemaPath"), // also used in JTD errors
    params: new codegen_1.Name("params"),
    propertyName: new codegen_1.Name("propertyName"),
    message: new codegen_1.Name("message"),
    schema: new codegen_1.Name("schema"),
    parentSchema: new codegen_1.Name("parentSchema"),
};
function errorObjectCode(cxt, error, errorPaths) {
    const { createErrors } = cxt.it;
    if (createErrors === false)
        return (0, codegen_1._) `{}`;
    return errorObject(cxt, error, errorPaths);
}
function errorObject(cxt, error, errorPaths = {}) {
    const { gen, it } = cxt;
    const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths),
    ];
    extraErrorProps(cxt, error, keyValues);
    return gen.object(...keyValues);
}
function errorInstancePath({ errorPath }, { instancePath }) {
    const instPath = instancePath
        ? (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}`
        : errorPath;
    return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
}
function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
    let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str) `${errSchemaPath}/${keyword}`;
    if (schemaPath) {
        schPath = (0, codegen_1.str) `${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
    }
    return [E.schemaPath, schPath];
}
function extraErrorProps(cxt, { params, message }, keyValues) {
    const { keyword, data, schemaValue, it } = cxt;
    const { opts, propertyName, topSchemaRef, schemaPath } = it;
    keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._) `{}`]);
    if (opts.messages) {
        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
    }
    if (opts.verbose) {
        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._) `${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
    }
    if (propertyName)
        keyValues.push([E.propertyName, propertyName]);
}
//# sourceMappingURL=errors.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
const codegen_1 = require("./codegen");
const validation_error_1 = require("../runtime/validation_error");
const names_1 = require("./names");
const resolve_1 = require("./resolve");
const util_1 = require("./util");
const validate_1 = require("./validate");
class SchemaEnv {
    constructor(env) {
        var _a;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
            schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
    }
}
exports.SchemaEnv = SchemaEnv;
// let codeSize = 0
// let nodeCount = 0
// Compiles schema in SchemaEnv
function compileSchema(sch) {
    // TODO refactor - remove compilations
    const _sch = getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    let _ValidationError;
    if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
            ref: validation_error_1.default,
            code: (0, codegen_1._) `require("ajv/dist/runtime/validation_error").default`,
        });
    }
    const validateName = gen.scopeName("validate");
    sch.validateName = validateName;
    const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil], // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true
            ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) }
            : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._) `""`,
        opts: this.opts,
        self: this,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        // gen.optimize(1)
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
        if (this.opts.code.process)
            sourceCode = this.opts.code.process(sourceCode, sch);
        // console.log("\n\n\n *** \n", sourceCode)
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
            validate.$async = true;
        if (this.opts.code.source === true) {
            validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
            const { props, items } = schemaCxt;
            validate.evaluated = {
                props: props instanceof codegen_1.Name ? undefined : props,
                items: items instanceof codegen_1.Name ? undefined : items,
                dynamicProps: props instanceof codegen_1.Name,
                dynamicItems: items instanceof codegen_1.Name,
            };
            if (validate.source)
                validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
    }
    catch (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
            this.logger.error("Error compiling schema, function code:", sourceCode);
        // console.log("\n\n\n *** \n", sourceCode, this.opts)
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
}
exports.compileSchema = compileSchema;
function resolveRef(root, baseId, ref) {
    var _a;
    ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
    const schOrFunc = root.refs[ref];
    if (schOrFunc)
        return schOrFunc;
    let _sch = resolve.call(this, root, ref);
    if (_sch === undefined) {
        const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
        const { schemaId } = this.opts;
        if (schema)
            _sch = new SchemaEnv({ schema, schemaId, root, baseId });
    }
    if (_sch === undefined)
        return;
    return (root.refs[ref] = inlineOrCompile.call(this, _sch));
}
exports.resolveRef = resolveRef;
function inlineOrCompile(sch) {
    if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
    return sch.validate ? sch : compileSchema.call(this, sch);
}
// Index of schema compilation in the currently compiled list
function getCompilingSchema(schEnv) {
    for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
            return sch;
    }
}
exports.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
// resolve and compile the references ($ref)
// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
function resolve(root, // information about the root schema for the current schema
ref // reference to resolve
) {
    let sch;
    while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
}
// Resolve schema, its root and baseId
function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref // reference to resolve
) {
    const p = this.opts.uriResolver.parse(ref);
    const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
    let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, undefined);
    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
    if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
    }
    const id = (0, resolve_1.normalizeId)(refPath);
    const schOrRef = this.refs[id] || this.schemas[id];
    if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
            return;
        return getJsonPointer.call(this, p, sch);
    }
    if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
    if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
    if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
    }
    return getJsonPointer.call(this, p, schOrRef);
}
exports.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = new Set([
    "properties",
    "patternProperties",
    "enum",
    "dependencies",
    "definitions",
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
    var _a;
    if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
        return;
    for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
            return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === undefined)
            return;
        schema = partSchema;
        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
            baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
    }
    let env;
    if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
    }
    // even though resolution failed we need to return SchemaEnv to throw exception
    // so that compileAsync loads missing schema.
    const { schemaId } = this.opts;
    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
    if (env.schema !== env.root.schema)
        return env;
    return undefined;
}
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const type_1 = require("../../vocabularies/jtd/type");
const parseJson_1 = require("../../runtime/parseJson");
const util_1 = require("../util");
const timestamp_1 = require("../../runtime/timestamp");
const genParse = {
    elements: parseElements,
    values: parseValues,
    discriminator: parseDiscriminator,
    properties: parseProperties,
    optionalProperties: parseProperties,
    enum: parseEnum,
    type: parseType,
    ref: parseRef,
};
function compileParser(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const parseName = gen.scopeName("parse");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
        parseName,
        char: gen.name("c"),
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.parseName = parseName;
        parserFunction(cxt);
        gen.optimize(this.opts.code.optimize);
        const parseFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${parseFuncCode}`;
        const makeParse = new Function(`${names_1.default.scope}`, sourceCode);
        const parse = makeParse(this.scope.get());
        this.scope.value(parseName, { ref: parse });
        sch.parse = parse;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling parser, function code:", sourceCode);
        delete sch.parse;
        delete sch.parseName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileParser;
const undef = (0, codegen_1._) `undefined`;
function parserFunction(cxt) {
    const { gen, parseName, char } = cxt;
    gen.func(parseName, (0, codegen_1._) `${names_1.default.json}, ${names_1.default.jsonPos}, ${names_1.default.jsonPart}`, false, () => {
        gen.let(names_1.default.data);
        gen.let(char);
        gen.assign((0, codegen_1._) `${parseName}.message`, undef);
        gen.assign((0, codegen_1._) `${parseName}.position`, undef);
        gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${names_1.default.jsonPos} || 0`);
        gen.const(names_1.default.jsonLen, (0, codegen_1._) `${names_1.default.json}.length`);
        parseCode(cxt);
        skipWhitespace(cxt);
        gen.if(names_1.default.jsonPart, () => {
            gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
            gen.return(names_1.default.data);
        });
        gen.if((0, codegen_1._) `${names_1.default.jsonPos} === ${names_1.default.jsonLen}`, () => gen.return(names_1.default.data));
        jsonSyntaxError(cxt);
    });
}
function parseCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    if (form)
        parseNullable(cxt, genParse[form]);
    else
        parseEmpty(cxt);
}
const parseBoolean = parseBooleanToken(true, parseBooleanToken(false, jsonSyntaxError));
function parseNullable(cxt, parseForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return parseForm(cxt);
    tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null));
}
function parseElements(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "[");
    const ix = gen.let("i", 0);
    gen.assign(data, (0, codegen_1._) `[]`);
    parseItems(cxt, "]", () => {
        const el = gen.let("el");
        parseCode({ ...cxt, schema: schema.elements, data: el });
        gen.assign((0, codegen_1._) `${data}[${ix}++]`, el);
    });
}
function parseValues(cxt) {
    const { gen, schema, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values));
}
function parseItems(cxt, endToken, block) {
    tryParseItems(cxt, endToken, block);
    parseToken(cxt, endToken);
}
function tryParseItems(cxt, endToken, block) {
    const { gen } = cxt;
    gen.for((0, codegen_1._) `;${names_1.default.jsonPos}<${names_1.default.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => {
        block();
        tryParseToken(cxt, ",", () => gen.break(), hasItem);
    });
    function hasItem() {
        tryParseToken(cxt, endToken, () => { }, jsonSyntaxError);
    }
}
function parseKeyValue(cxt, schema) {
    const { gen } = cxt;
    const key = gen.let("key");
    parseString({ ...cxt, data: key });
    parseToken(cxt, ":");
    parsePropertyValue(cxt, key, schema);
}
function parseDiscriminator(cxt) {
    const { gen, data, schema } = cxt;
    const { discriminator, mapping } = schema;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    const startPos = gen.const("pos", names_1.default.jsonPos);
    const value = gen.let("value");
    const tag = gen.let("tag");
    tryParseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if((0, codegen_1._) `${key} === ${discriminator}`, () => {
            parseString({ ...cxt, data: tag });
            gen.assign((0, codegen_1._) `${data}[${key}]`, tag);
            gen.break();
        }, () => parseEmpty({ ...cxt, data: value }) // can be discarded/skipped
        );
    });
    gen.assign(names_1.default.jsonPos, startPos);
    gen.if((0, codegen_1._) `${tag} === undefined`);
    parsingError(cxt, (0, codegen_1.str) `discriminator tag not found`);
    for (const tagValue in mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        parseSchemaProperties({ ...cxt, schema: mapping[tagValue] }, discriminator);
    }
    gen.else();
    parsingError(cxt, (0, codegen_1.str) `discriminator value not in schema`);
    gen.endIf();
}
function parseProperties(cxt) {
    const { gen, data } = cxt;
    parseToken(cxt, "{");
    gen.assign(data, (0, codegen_1._) `{}`);
    parseSchemaProperties(cxt);
}
function parseSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties, additionalProperties } = schema;
    parseItems(cxt, "}", () => {
        const key = gen.let("key");
        parseString({ ...cxt, data: key });
        parseToken(cxt, ":");
        gen.if(false);
        parseDefinedProperty(cxt, key, properties);
        parseDefinedProperty(cxt, key, optionalProperties);
        if (discriminator) {
            gen.elseIf((0, codegen_1._) `${key} === ${discriminator}`);
            const tag = gen.let("tag");
            parseString({ ...cxt, data: tag }); // can be discarded, it is already assigned
        }
        gen.else();
        if (additionalProperties) {
            parseEmpty({ ...cxt, data: (0, codegen_1._) `${data}[${key}]` });
        }
        else {
            parsingError(cxt, (0, codegen_1.str) `property ${key} not allowed`);
        }
        gen.endIf();
    });
    if (properties) {
        const hasProp = (0, code_1.hasPropFunc)(gen);
        const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._) `${hasProp}.call(${data}, ${p})`));
        gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str) `missing required properties`));
    }
}
function parseDefinedProperty(cxt, key, schemas = {}) {
    const { gen } = cxt;
    for (const prop in schemas) {
        gen.elseIf((0, codegen_1._) `${key} === ${prop}`);
        parsePropertyValue(cxt, key, schemas[prop]);
    }
}
function parsePropertyValue(cxt, key, schema) {
    parseCode({ ...cxt, schema, data: (0, codegen_1._) `${cxt.data}[${key}]` });
}
function parseType(cxt) {
    const { gen, schema, data, self } = cxt;
    switch (schema.type) {
        case "boolean":
            parseBoolean(cxt);
            break;
        case "string":
            parseString(cxt);
            break;
        case "timestamp": {
            parseString(cxt);
            const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
            const { allowDate, parseDate } = self.opts;
            const notValid = allowDate ? (0, codegen_1._) `!${vts}(${data}, true)` : (0, codegen_1._) `!${vts}(${data})`;
            const fail = parseDate
                ? (0, codegen_1.or)(notValid, (0, codegen_1._) `(${data} = new Date(${data}), false)`, (0, codegen_1._) `isNaN(${data}.valueOf())`)
                : notValid;
            gen.if(fail, () => parsingError(cxt, (0, codegen_1.str) `invalid timestamp`));
            break;
        }
        case "float32":
        case "float64":
            parseNumber(cxt);
            break;
        default: {
            const t = schema.type;
            if (!self.opts.int32range && (t === "int32" || t === "uint32")) {
                parseNumber(cxt, 16); // 2 ** 53 - max safe integer
                if (t === "uint32") {
                    gen.if((0, codegen_1._) `${data} < 0`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
                }
            }
            else {
                const [min, max, maxDigits] = type_1.intRange[t];
                parseNumber(cxt, maxDigits);
                gen.if((0, codegen_1._) `${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, (0, codegen_1.str) `integer out of range`));
            }
        }
    }
}
function parseString(cxt) {
    parseToken(cxt, '"');
    parseWith(cxt, parseJson_1.parseJsonString);
}
function parseEnum(cxt) {
    const { gen, data, schema } = cxt;
    const enumSch = schema.enum;
    parseToken(cxt, '"');
    // TODO loopEnum
    gen.if(false);
    for (const value of enumSch) {
        const valueStr = JSON.stringify(value).slice(1); // remove starting quote
        gen.elseIf((0, codegen_1._) `${jsonSlice(valueStr.length)} === ${valueStr}`);
        gen.assign(data, (0, codegen_1.str) `${value}`);
        gen.add(names_1.default.jsonPos, valueStr.length);
    }
    gen.else();
    jsonSyntaxError(cxt);
    gen.endIf();
}
function parseNumber(cxt, maxDigits) {
    const { gen } = cxt;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJson_1.parseJsonNumber, maxDigits));
}
function parseBooleanToken(bool, fail) {
    return (cxt) => {
        const { gen, data } = cxt;
        tryParseToken(cxt, `${bool}`, () => fail(cxt), () => gen.assign(data, bool));
    };
}
function parseRef(cxt) {
    const { gen, self, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return parseCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileParser.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    partialParse(cxt, getParser(gen, sch), true);
}
function getParser(gen, sch) {
    return sch.parse
        ? gen.scopeValue("parse", { ref: sch.parse })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.parse`;
}
function parseEmpty(cxt) {
    parseWith(cxt, parseJson_1.parseJson);
}
function parseWith(cxt, parseFunc, args) {
    partialParse(cxt, (0, util_1.useFunc)(cxt.gen, parseFunc), args);
}
function partialParse(cxt, parseFunc, args) {
    const { gen, data } = cxt;
    gen.assign(data, (0, codegen_1._) `${parseFunc}(${names_1.default.json}, ${names_1.default.jsonPos}${args ? (0, codegen_1._) `, ${args}` : codegen_1.nil})`);
    gen.assign(names_1.default.jsonPos, (0, codegen_1._) `${parseFunc}.position`);
    gen.if((0, codegen_1._) `${data} === undefined`, () => parsingError(cxt, (0, codegen_1._) `${parseFunc}.message`));
}
function parseToken(cxt, tok) {
    tryParseToken(cxt, tok, jsonSyntaxError);
}
function tryParseToken(cxt, tok, fail, success) {
    const { gen } = cxt;
    const n = tok.length;
    skipWhitespace(cxt);
    gen.if((0, codegen_1._) `${jsonSlice(n)} === ${tok}`, () => {
        gen.add(names_1.default.jsonPos, n);
        success === null || success === void 0 ? void 0 : success(cxt);
    }, () => fail(cxt));
}
function skipWhitespace({ gen, char: c }) {
    gen.code((0, codegen_1._) `while((${c}=${names_1.default.json}[${names_1.default.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${names_1.default.jsonPos}++;`);
}
function jsonSlice(len) {
    return len === 1
        ? (0, codegen_1._) `${names_1.default.json}[${names_1.default.jsonPos}]`
        : (0, codegen_1._) `${names_1.default.json}.slice(${names_1.default.jsonPos}, ${names_1.default.jsonPos}+${len})`;
}
function jsonSyntaxError(cxt) {
    parsingError(cxt, (0, codegen_1._) `"unexpected token " + ${names_1.default.json}[${names_1.default.jsonPos}]`);
}
function parsingError({ gen, parseName }, msg) {
    gen.assign((0, codegen_1._) `${parseName}.message`, msg);
    gen.assign((0, codegen_1._) `${parseName}.position`, names_1.default.jsonPos);
    gen.return(undef);
}
//# sourceMappingURL=parse.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
const __1 = require("..");
const codegen_1 = require("../codegen");
const ref_error_1 = require("../ref_error");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const ref_1 = require("../../vocabularies/jtd/ref");
const util_1 = require("../util");
const quote_1 = require("../../runtime/quote");
const genSerialize = {
    elements: serializeElements,
    values: serializeValues,
    discriminator: serializeDiscriminator,
    properties: serializeProperties,
    optionalProperties: serializeProperties,
    enum: serializeString,
    type: serializeType,
    ref: serializeRef,
};
function compileSerializer(sch, definitions) {
    const _sch = __1.getCompilingSchema.call(this, sch);
    if (_sch)
        return _sch;
    const { es5, lines } = this.opts.code;
    const { ownProperties } = this.opts;
    const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
    const serializeName = gen.scopeName("serialize");
    const cxt = {
        self: this,
        gen,
        schema: sch.schema,
        schemaEnv: sch,
        definitions,
        data: names_1.default.data,
    };
    let sourceCode;
    try {
        this._compilations.add(sch);
        sch.serializeName = serializeName;
        gen.func(serializeName, names_1.default.data, false, () => {
            gen.let(names_1.default.json, (0, codegen_1.str) ``);
            serializeCode(cxt);
            gen.return(names_1.default.json);
        });
        gen.optimize(this.opts.code.optimize);
        const serializeFuncCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${serializeFuncCode}`;
        const makeSerialize = new Function(`${names_1.default.scope}`, sourceCode);
        const serialize = makeSerialize(this.scope.get());
        this.scope.value(serializeName, { ref: serialize });
        sch.serialize = serialize;
    }
    catch (e) {
        if (sourceCode)
            this.logger.error("Error compiling serializer, function code:", sourceCode);
        delete sch.serialize;
        delete sch.serializeName;
        throw e;
    }
    finally {
        this._compilations.delete(sch);
    }
    return sch;
}
exports.default = compileSerializer;
function serializeCode(cxt) {
    let form;
    for (const key of types_1.jtdForms) {
        if (key in cxt.schema) {
            form = key;
            break;
        }
    }
    serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty);
}
function serializeNullable(cxt, serializeForm) {
    const { gen, schema, data } = cxt;
    if (!schema.nullable)
        return serializeForm(cxt);
    gen.if((0, codegen_1._) `${data} === undefined || ${data} === null`, () => gen.add(names_1.default.json, (0, codegen_1._) `"null"`), () => serializeForm(cxt));
}
function serializeElements(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `[`);
    const first = gen.let("first", true);
    gen.forOf("el", data, (el) => {
        addComma(cxt, first);
        serializeCode({ ...cxt, schema: schema.elements, data: el });
    });
    gen.add(names_1.default.json, (0, codegen_1.str) `]`);
}
function serializeValues(cxt) {
    const { gen, schema, data } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    const first = gen.let("first", true);
    gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first));
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeKeyValue(cxt, key, schema, first) {
    const { gen, data } = cxt;
    addComma(cxt, first);
    serializeString({ ...cxt, data: key });
    gen.add(names_1.default.json, (0, codegen_1.str) `:`);
    const value = gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    serializeCode({ ...cxt, schema, data: value });
}
function serializeDiscriminator(cxt) {
    const { gen, schema, data } = cxt;
    const { discriminator } = schema;
    gen.add(names_1.default.json, (0, codegen_1.str) `{${JSON.stringify(discriminator)}:`);
    const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(discriminator)}`);
    serializeString({ ...cxt, data: tag });
    gen.if(false);
    for (const tagValue in schema.mapping) {
        gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
        const sch = schema.mapping[tagValue];
        serializeSchemaProperties({ ...cxt, schema: sch }, discriminator);
    }
    gen.endIf();
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeProperties(cxt) {
    const { gen } = cxt;
    gen.add(names_1.default.json, (0, codegen_1.str) `{`);
    serializeSchemaProperties(cxt);
    gen.add(names_1.default.json, (0, codegen_1.str) `}`);
}
function serializeSchemaProperties(cxt, discriminator) {
    const { gen, schema, data } = cxt;
    const { properties, optionalProperties } = schema;
    const props = keys(properties);
    const optProps = keys(optionalProperties);
    const allProps = allProperties(props.concat(optProps));
    let first = !discriminator;
    let firstProp;
    for (const key of props) {
        if (first)
            first = false;
        else
            gen.add(names_1.default.json, (0, codegen_1.str) `,`);
        serializeProperty(key, properties[key], keyValue(key));
    }
    if (first)
        firstProp = gen.let("first", true);
    for (const key of optProps) {
        const value = keyValue(key);
        gen.if((0, codegen_1.and)((0, codegen_1._) `${value} !== undefined`, (0, code_1.isOwnProperty)(gen, data, key)), () => {
            addComma(cxt, firstProp);
            serializeProperty(key, optionalProperties[key], value);
        });
    }
    if (schema.additionalProperties) {
        gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)));
    }
    function keys(ps) {
        return ps ? Object.keys(ps) : [];
    }
    function allProperties(ps) {
        if (discriminator)
            ps.push(discriminator);
        if (new Set(ps).size !== ps.length) {
            throw new Error("JTD: properties/optionalProperties/disciminator overlap");
        }
        return ps;
    }
    function keyValue(key) {
        return gen.const("value", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(key)}`);
    }
    function serializeProperty(key, propSchema, value) {
        gen.add(names_1.default.json, (0, codegen_1.str) `${JSON.stringify(key)}:`);
        serializeCode({ ...cxt, schema: propSchema, data: value });
    }
    function isAdditional(key, ps) {
        return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`)) : true;
    }
}
function serializeType(cxt) {
    const { gen, schema, data } = cxt;
    switch (schema.type) {
        case "boolean":
            gen.add(names_1.default.json, (0, codegen_1._) `${data} ? "true" : "false"`);
            break;
        case "string":
            serializeString(cxt);
            break;
        case "timestamp":
            gen.if((0, codegen_1._) `${data} instanceof Date`, () => gen.add(names_1.default.json, (0, codegen_1._) `'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt));
            break;
        default:
            serializeNumber(cxt);
    }
}
function serializeString({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `${(0, util_1.useFunc)(gen, quote_1.default)}(${data})`);
}
function serializeNumber({ gen, data, self }) {
    const condition = (0, codegen_1._) `${data} === Infinity || ${data} === -Infinity || ${data} !== ${data}`;
    if (self.opts.specialNumbers === undefined || self.opts.specialNumbers === "fast") {
        gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`);
    }
    else {
        // specialNumbers === "null"
        gen.if(condition, () => gen.add(names_1.default.json, (0, codegen_1._) `null`), () => gen.add(names_1.default.json, (0, codegen_1._) `"" + ${data}`));
    }
}
function serializeRef(cxt) {
    const { gen, self, data, definitions, schema, schemaEnv } = cxt;
    const { ref } = schema;
    const refSchema = definitions[ref];
    if (!refSchema)
        throw new ref_error_1.default(self.opts.uriResolver, "", ref, `No definition ${ref}`);
    if (!(0, ref_1.hasRef)(refSchema))
        return serializeCode({ ...cxt, schema: refSchema });
    const { root } = schemaEnv;
    const sch = compileSerializer.call(self, new __1.SchemaEnv({ schema: refSchema, root }), definitions);
    gen.add(names_1.default.json, (0, codegen_1._) `${getSerialize(gen, sch)}(${data})`);
}
function getSerialize(gen, sch) {
    return sch.serialize
        ? gen.scopeValue("serialize", { ref: sch.serialize })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.serialize`;
}
function serializeEmpty({ gen, data }) {
    gen.add(names_1.default.json, (0, codegen_1._) `JSON.stringify(${data})`);
}
function addComma({ gen }, first) {
    if (first) {
        gen.if(first, () => gen.assign(first, false), () => gen.add(names_1.default.json, (0, codegen_1.str) `,`));
    }
    else {
        gen.add(names_1.default.json, (0, codegen_1.str) `,`);
    }
}
//# sourceMappingURL=serialize.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jtdForms = void 0;
exports.jtdForms = [
    "elements",
    "values",
    "discriminator",
    "properties",
    "optionalProperties",
    "enum",
    "type",
    "ref",
];
//# sourceMappingURL=types.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("./codegen");
const names = {
    // validation function arguments
    data: new codegen_1.Name("data"), // data passed to validation function
    // args passed from referencing schema
    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
    instancePath: new codegen_1.Name("instancePath"),
    parentData: new codegen_1.Name("parentData"),
    parentDataProperty: new codegen_1.Name("parentDataProperty"),
    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
    // function scoped variables
    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
    errors: new codegen_1.Name("errors"), // counter of validation errors
    this: new codegen_1.Name("this"),
    // "globals"
    self: new codegen_1.Name("self"),
    scope: new codegen_1.Name("scope"),
    // JTD serialize/parse name for JSON string and position
    json: new codegen_1.Name("json"),
    jsonPos: new codegen_1.Name("jsonPos"),
    jsonLen: new codegen_1.Name("jsonLen"),
    jsonPart: new codegen_1.Name("jsonPart"),
};
exports.default = names;
//# sourceMappingURL=names.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const resolve_1 = require("./resolve");
class MissingRefError extends Error {
    constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
    }
}
exports.default = MissingRefError;
//# sourceMappingURL=ref_error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
const util_1 = require("./util");
const equal = require("fast-deep-equal");
const traverse = require("json-schema-traverse");
// TODO refactor to use keyword definitions
const SIMPLE_INLINED = new Set([
    "type",
    "format",
    "pattern",
    "maxLength",
    "minLength",
    "maxProperties",
    "minProperties",
    "maxItems",
    "minItems",
    "maximum",
    "minimum",
    "uniqueItems",
    "multipleOf",
    "required",
    "enum",
    "const",
]);
function inlineRef(schema, limit = true) {
    if (typeof schema == "boolean")
        return true;
    if (limit === true)
        return !hasRef(schema);
    if (!limit)
        return false;
    return countKeys(schema) <= limit;
}
exports.inlineRef = inlineRef;
const REF_KEYWORDS = new Set([
    "$ref",
    "$recursiveRef",
    "$recursiveAnchor",
    "$dynamicRef",
    "$dynamicAnchor",
]);
function hasRef(schema) {
    for (const key in schema) {
        if (REF_KEYWORDS.has(key))
            return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
            return true;
        if (typeof sch == "object" && hasRef(sch))
            return true;
    }
    return false;
}
function countKeys(schema) {
    let count = 0;
    for (const key in schema) {
        if (key === "$ref")
            return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
            continue;
        if (typeof schema[key] == "object") {
            (0, util_1.eachItem)(schema[key], (sch) => (count += countKeys(sch)));
        }
        if (count === Infinity)
            return Infinity;
    }
    return count;
}
function getFullPath(resolver, id = "", normalize) {
    if (normalize !== false)
        id = normalizeId(id);
    const p = resolver.parse(id);
    return _getFullPath(resolver, p);
}
exports.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
    const serialized = resolver.serialize(p);
    return serialized.split("#")[0] + "#";
}
exports._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
    return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
}
exports.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id) {
    id = normalizeId(id);
    return resolver.resolve(baseId, id);
}
exports.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
    if (typeof schema == "boolean")
        return {};
    const { schemaId, uriResolver } = this.opts;
    const schId = normalizeId(schema[schemaId] || baseId);
    const baseIds = { "": schId };
    const pathPrefix = getFullPath(uriResolver, schId, false);
    const localRefs = {};
    const schemaRefs = new Set();
    traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === undefined)
            return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
            innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
            // eslint-disable-next-line @typescript-eslint/unbound-method
            const _resolve = this.opts.uriResolver.resolve;
            ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
            if (schemaRefs.has(ref))
                throw ambiguos(ref);
            schemaRefs.add(ref);
            let schOrRef = this.refs[ref];
            if (typeof schOrRef == "string")
                schOrRef = this.refs[schOrRef];
            if (typeof schOrRef == "object") {
                checkAmbiguosRef(sch, schOrRef.schema, ref);
            }
            else if (ref !== normalizeId(fullPath)) {
                if (ref[0] === "#") {
                    checkAmbiguosRef(sch, localRefs[ref], ref);
                    localRefs[ref] = sch;
                }
                else {
                    this.refs[ref] = fullPath;
                }
            }
            return ref;
        }
        function addAnchor(anchor) {
            if (typeof anchor == "string") {
                if (!ANCHOR.test(anchor))
                    throw new Error(`invalid anchor "${anchor}"`);
                addRef.call(this, `#${anchor}`);
            }
        }
    });
    return localRefs;
    function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== undefined && !equal(sch1, sch2))
            throw ambiguos(ref);
    }
    function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
    }
}
exports.getSchemaRefs = getSchemaRefs;
//# sourceMappingURL=resolve.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRules = exports.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
    return typeof x == "string" && jsonTypes.has(x);
}
exports.isJSONType = isJSONType;
function getRules() {
    const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] },
    };
    return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {},
    };
}
exports.getRules = getRules;
//# sourceMappingURL=rules.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
const codegen_1 = require("./codegen");
const code_1 = require("./codegen/code");
// TODO refactor to use Set
function toHash(arr) {
    const hash = {};
    for (const item of arr)
        hash[item] = true;
    return hash;
}
exports.toHash = toHash;
function alwaysValidSchema(it, schema) {
    if (typeof schema == "boolean")
        return schema;
    if (Object.keys(schema).length === 0)
        return true;
    checkUnknownRules(it, schema);
    return !schemaHasRules(schema, it.self.RULES.all);
}
exports.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
    const { opts, self } = it;
    if (!opts.strictSchema)
        return;
    if (typeof schema === "boolean")
        return;
    const rules = self.RULES.keywords;
    for (const key in schema) {
        if (!rules[key])
            checkStrictMode(it, `unknown keyword: "${key}"`);
    }
}
exports.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (rules[key])
            return true;
    return false;
}
exports.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
            return true;
    return false;
}
exports.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
    if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
            return schema;
        if (typeof schema == "string")
            return (0, codegen_1._) `${schema}`;
    }
    return (0, codegen_1._) `${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
}
exports.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
    return unescapeJsonPointer(decodeURIComponent(str));
}
exports.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
    return encodeURIComponent(escapeJsonPointer(str));
}
exports.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
    if (typeof str == "number")
        return `${str}`;
    return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
exports.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
    return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
exports.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
    if (Array.isArray(xs)) {
        for (const x of xs)
            f(x);
    }
    else {
        f(xs);
    }
}
exports.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName, }) {
    return (gen, from, to, toName) => {
        const res = to === undefined
            ? from
            : to instanceof codegen_1.Name
                ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to)
                : from instanceof codegen_1.Name
                    ? (mergeToName(gen, to, from), from)
                    : mergeValues(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
    };
}
exports.mergeEvaluated = {
    props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => {
            gen.if((0, codegen_1._) `${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._) `${to} || {}`).code((0, codegen_1._) `Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => {
            if (from === true) {
                gen.assign(to, true);
            }
            else {
                gen.assign(to, (0, codegen_1._) `${to} || {}`);
                setEvaluated(gen, to, from);
            }
        }),
        mergeValues: (from, to) => (from === true ? true : { ...from, ...to }),
        resultToName: evaluatedPropsToName,
    }),
    items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._) `${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._) `${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._) `${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => (from === true ? true : Math.max(from, to)),
        resultToName: (gen, items) => gen.var("items", items),
    }),
};
function evaluatedPropsToName(gen, ps) {
    if (ps === true)
        return gen.var("props", true);
    const props = gen.var("props", (0, codegen_1._) `{}`);
    if (ps !== undefined)
        setEvaluated(gen, props, ps);
    return props;
}
exports.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
    Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._) `${props}${(0, codegen_1.getProperty)(p)}`, true));
}
exports.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
    return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)),
    });
}
exports.useFunc = useFunc;
var Type;
(function (Type) {
    Type[Type["Num"] = 0] = "Num";
    Type[Type["Str"] = 1] = "Str";
})(Type || (exports.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
    // let path
    if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax
            ? isNumber
                ? (0, codegen_1._) `"[" + ${dataProp} + "]"`
                : (0, codegen_1._) `"['" + ${dataProp} + "']"`
            : isNumber
                ? (0, codegen_1._) `"/" + ${dataProp}`
                : (0, codegen_1._) `"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; // TODO maybe use global escapePointer
    }
    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
exports.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
    if (!mode)
        return;
    msg = `strict mode: ${msg}`;
    if (mode === true)
        throw new Error(msg);
    it.self.logger.warn(msg);
}
exports.checkStrictMode = checkStrictMode;
//# sourceMappingURL=util.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self }, type) {
    const group = self.RULES.types[type];
    return group && group !== true && shouldUseGroup(schema, group);
}
exports.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
    return group.rules.some((rule) => shouldUseRule(schema, rule));
}
exports.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
    var _a;
    return (schema[rule.keyword] !== undefined ||
        ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== undefined)));
}
exports.shouldUseRule = shouldUseRule;
//# sourceMappingURL=applicability.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const boolError = {
    message: "boolean schema is false",
};
function topBoolOrEmptySchema(it) {
    const { gen, schema, validateName } = it;
    if (schema === false) {
        falseSchemaError(it, false);
    }
    else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, null);
        gen.return(true);
    }
}
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
    const { gen, schema } = it;
    if (schema === false) {
        gen.var(valid, false); // TODO var
        falseSchemaError(it);
    }
    else {
        gen.var(valid, true); // TODO var
    }
}
exports.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
    const { gen, data } = it;
    // TODO maybe some other interface should be used for non-keyword validation errors...
    const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it,
    };
    (0, errors_1.reportError)(cxt, boolError, undefined, overrideAllErrors);
}
//# sourceMappingURL=boolSchema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
const rules_1 = require("../rules");
const applicability_1 = require("./applicability");
const errors_1 = require("../errors");
const codegen_1 = require("../codegen");
const util_1 = require("../util");
var DataType;
(function (DataType) {
    DataType[DataType["Correct"] = 0] = "Correct";
    DataType[DataType["Wrong"] = 1] = "Wrong";
})(DataType || (exports.DataType = DataType = {}));
function getSchemaTypes(schema) {
    const types = getJSONTypes(schema.type);
    const hasNull = types.includes("null");
    if (hasNull) {
        if (schema.nullable === false)
            throw new Error("type: null contradicts nullable: false");
    }
    else {
        if (!types.length && schema.nullable !== undefined) {
            throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
            types.push("null");
    }
    return types;
}
exports.getSchemaTypes = getSchemaTypes;
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
function getJSONTypes(ts) {
    const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
    if (types.every(rules_1.isJSONType))
        return types;
    throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
}
exports.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types) {
    const { gen, data, opts } = it;
    const coerceTo = coerceToTypes(types, opts.coerceTypes);
    const checkTypes = types.length > 0 &&
        !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
    if (checkTypes) {
        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
            if (coerceTo.length)
                coerceData(it, types, coerceTo);
            else
                reportTypeError(it);
        });
    }
    return checkTypes;
}
exports.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types, coerceTypes) {
    return coerceTypes
        ? types.filter((t) => COERCIBLE.has(t) || (coerceTypes === "array" && t === "array"))
        : [];
}
function coerceData(it, types, coerceTo) {
    const { gen, data, opts } = it;
    const dataType = gen.let("dataType", (0, codegen_1._) `typeof ${data}`);
    const coerced = gen.let("coerced", (0, codegen_1._) `undefined`);
    if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._) `${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen
            .assign(data, (0, codegen_1._) `${data}[0]`)
            .assign(dataType, (0, codegen_1._) `typeof ${data}`)
            .if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
    }
    gen.if((0, codegen_1._) `${coerced} !== undefined`);
    for (const t of coerceTo) {
        if (COERCIBLE.has(t) || (t === "array" && opts.coerceTypes === "array")) {
            coerceSpecificType(t);
        }
    }
    gen.else();
    reportTypeError(it);
    gen.endIf();
    gen.if((0, codegen_1._) `${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
    });
    function coerceSpecificType(t) {
        switch (t) {
            case "string":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "number" || ${dataType} == "boolean"`)
                    .assign(coerced, (0, codegen_1._) `"" + ${data}`)
                    .elseIf((0, codegen_1._) `${data} === null`)
                    .assign(coerced, (0, codegen_1._) `""`);
                return;
            case "number":
                gen
                    .elseIf((0, codegen_1._) `${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "integer":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`)
                    .assign(coerced, (0, codegen_1._) `+${data}`);
                return;
            case "boolean":
                gen
                    .elseIf((0, codegen_1._) `${data} === "false" || ${data} === 0 || ${data} === null`)
                    .assign(coerced, false)
                    .elseIf((0, codegen_1._) `${data} === "true" || ${data} === 1`)
                    .assign(coerced, true);
                return;
            case "null":
                gen.elseIf((0, codegen_1._) `${data} === "" || ${data} === 0 || ${data} === false`);
                gen.assign(coerced, null);
                return;
            case "array":
                gen
                    .elseIf((0, codegen_1._) `${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`)
                    .assign(coerced, (0, codegen_1._) `[${data}]`);
        }
    }
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
    // TODO use gen.property
    gen.if((0, codegen_1._) `${parentData} !== undefined`, () => gen.assign((0, codegen_1._) `${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
    const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
    let cond;
    switch (dataType) {
        case "null":
            return (0, codegen_1._) `${data} ${EQ} null`;
        case "array":
            cond = (0, codegen_1._) `Array.isArray(${data})`;
            break;
        case "object":
            cond = (0, codegen_1._) `${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
            break;
        case "integer":
            cond = numCond((0, codegen_1._) `!(${data} % 1) && !isNaN(${data})`);
            break;
        case "number":
            cond = numCond();
            break;
        default:
            return (0, codegen_1._) `typeof ${data} ${EQ} ${dataType}`;
    }
    return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
    function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._) `typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._) `isFinite(${data})` : codegen_1.nil);
    }
}
exports.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
    if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
    }
    let cond;
    const types = (0, util_1.toHash)(dataTypes);
    if (types.array && types.object) {
        const notObj = (0, codegen_1._) `typeof ${data} != "object"`;
        cond = types.null ? notObj : (0, codegen_1._) `!${data} || ${notObj}`;
        delete types.null;
        delete types.array;
        delete types.object;
    }
    else {
        cond = codegen_1.nil;
    }
    if (types.number)
        delete types.integer;
    for (const t in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
    return cond;
}
exports.checkDataTypes = checkDataTypes;
const typeError = {
    message: ({ schema }) => `must be ${schema}`,
    params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._) `{type: ${schema}}` : (0, codegen_1._) `{type: ${schemaValue}}`,
};
function reportTypeError(it) {
    const cxt = getTypeErrorContext(it);
    (0, errors_1.reportError)(cxt, typeError);
}
exports.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
    const { gen, data, schema } = it;
    const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
    return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it,
    };
}
//# sourceMappingURL=dataType.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignDefaults = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function assignDefaults(it, ty) {
    const { properties, items } = it.schema;
    if (ty === "object" && properties) {
        for (const key in properties) {
            assignDefault(it, key, properties[key].default);
        }
    }
    else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i) => assignDefault(it, i, sch.default));
    }
}
exports.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
    const { gen, compositeRule, data, opts } = it;
    if (defaultValue === undefined)
        return;
    const childData = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(prop)}`;
    if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
    }
    let condition = (0, codegen_1._) `${childData} === undefined`;
    if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._) `${condition} || ${childData} === null || ${childData} === ""`;
    }
    // `${childData} === undefined` +
    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
}
//# sourceMappingURL=defaults.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
const boolSchema_1 = require("./boolSchema");
const dataType_1 = require("./dataType");
const applicability_1 = require("./applicability");
const dataType_2 = require("./dataType");
const defaults_1 = require("./defaults");
const keyword_1 = require("./keyword");
const subschema_1 = require("./subschema");
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const resolve_1 = require("../resolve");
const util_1 = require("../util");
const errors_1 = require("../errors");
// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
function validateFunctionCode(it) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            topSchemaObjCode(it);
            return;
        }
    }
    validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
exports.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
    if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
            gen.code((0, codegen_1._) `"use strict"; ${funcSourceUrl(schema, opts)}`);
            destructureValCxtES5(gen, opts);
            gen.code(body);
        });
    }
    else {
        gen.func(validateName, (0, codegen_1._) `${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
    }
}
function destructureValCxt(opts) {
    return (0, codegen_1._) `{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._) `, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
    gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
    }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._) `""`);
        gen.var(names_1.default.parentData, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._) `undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
            gen.var(names_1.default.dynamicAnchors, (0, codegen_1._) `{}`);
    });
}
function topSchemaObjCode(it) {
    const { schema, opts, gen } = it;
    validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
            commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
            resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
    });
    return;
}
function resetEvaluated(it) {
    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
    const { gen, validateName } = it;
    it.evaluated = gen.const("evaluated", (0, codegen_1._) `${validateName}.evaluated`);
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._) `${it.evaluated}.props`, (0, codegen_1._) `undefined`));
    gen.if((0, codegen_1._) `${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._) `${it.evaluated}.items`, (0, codegen_1._) `undefined`));
}
function funcSourceUrl(schema, opts) {
    const schId = typeof schema == "object" && schema[opts.schemaId];
    return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._) `/*# sourceURL=${schId} */` : codegen_1.nil;
}
// schema compilation - this function is used recursively to generate code for sub-schemas
function subschemaCode(it, valid) {
    if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
            subSchemaObjCode(it, valid);
            return;
        }
    }
    (0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self }) {
    if (typeof schema == "boolean")
        return !schema;
    for (const key in schema)
        if (self.RULES.all[key])
            return true;
    return false;
}
function isSchemaObj(it) {
    return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
    const { schema, gen, opts } = it;
    if (opts.$comment && schema.$comment)
        commentKeyword(it);
    updateContext(it);
    checkAsyncSchema(it);
    const errsCount = gen.const("_errs", names_1.default.errors);
    typeAndKeywords(it, errsCount);
    // TODO var
    gen.var(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
}
function checkKeywords(it) {
    (0, util_1.checkUnknownRules)(it);
    checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
    if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
    const types = (0, dataType_1.getSchemaTypes)(it.schema);
    const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
    schemaKeywords(it, types, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
    const { schema, errSchemaPath, opts, self } = it;
    if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
        self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
    }
}
function checkNoDefault(it) {
    const { schema, opts } = it;
    if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
    }
}
function updateContext(it) {
    const schId = it.schema[it.opts.schemaId];
    if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
    if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
    const msg = schema.$comment;
    if (opts.$comment === true) {
        gen.code((0, codegen_1._) `${names_1.default.self}.logger.log(${msg})`);
    }
    else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str) `${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._) `${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
    }
}
function returnResults(it) {
    const { gen, schemaEnv, validateName, ValidationError, opts } = it;
    if (schemaEnv.$async) {
        // TODO assign unevaluated
        gen.if((0, codegen_1._) `${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._) `new ${ValidationError}(${names_1.default.vErrors})`));
    }
    else {
        gen.assign((0, codegen_1._) `${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
            assignEvaluated(it);
        gen.return((0, codegen_1._) `${names_1.default.errors} === 0`);
    }
}
function assignEvaluated({ gen, evaluated, props, items }) {
    if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.props`, props);
    if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._) `${evaluated}.items`, items);
}
function schemaKeywords(it, types, typeErrors, errsCount) {
    const { gen, schema, data, allErrors, opts, self } = it;
    const { RULES } = self;
    if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); // TODO typecast
        return;
    }
    if (!opts.jtd)
        checkStrictTypes(it, types);
    gen.block(() => {
        for (const group of RULES.rules)
            groupKeywords(group);
        groupKeywords(RULES.post);
    });
    function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
            return;
        if (group.type) {
            gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
            iterateKeywords(it, group);
            if (types.length === 1 && types[0] === group.type && typeErrors) {
                gen.else();
                (0, dataType_2.reportTypeError)(it);
            }
            gen.endIf();
        }
        else {
            iterateKeywords(it, group);
        }
        // TODO make it "ok" call?
        if (!allErrors)
            gen.if((0, codegen_1._) `${names_1.default.errors} === ${errsCount || 0}`);
    }
}
function iterateKeywords(it, group) {
    const { gen, schema, opts: { useDefaults }, } = it;
    if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
    gen.block(() => {
        for (const rule of group.rules) {
            if ((0, applicability_1.shouldUseRule)(schema, rule)) {
                keywordCode(it, rule.keyword, rule.definition, group.type);
            }
        }
    });
}
function checkStrictTypes(it, types) {
    if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
    checkContextTypes(it, types);
    if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types);
    checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types) {
    if (!types.length)
        return;
    if (!it.dataTypes.length) {
        it.dataTypes = types;
        return;
    }
    types.forEach((t) => {
        if (!includesType(it.dataTypes, t)) {
            strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
    });
    narrowSchemaTypes(it, types);
}
function checkMultipleTypes(it, ts) {
    if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
    }
}
function checkKeywordTypes(it, ts) {
    const rules = it.self.RULES.all;
    for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
            const { type } = rule.definition;
            if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
                strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
            }
        }
    }
}
function hasApplicableType(schTs, kwdT) {
    return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"));
}
function includesType(ts, t) {
    return ts.includes(t) || (t === "integer" && ts.includes("number"));
}
function narrowSchemaTypes(it, withTypes) {
    const ts = [];
    for (const t of it.dataTypes) {
        if (includesType(withTypes, t))
            ts.push(t);
        else if (withTypes.includes("integer") && t === "number")
            ts.push("integer");
    }
    it.dataTypes = ts;
}
function strictTypesError(it, msg) {
    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
    msg += ` at "${schemaPath}" (strictTypes)`;
    (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
    constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
            this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        }
        else {
            this.schemaCode = this.schemaValue;
            if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
                throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
            }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
            this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
    }
    result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
    }
    failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
            failAction();
        else
            this.error();
        if (successAction) {
            this.gen.else();
            successAction();
            if (this.allErrors)
                this.gen.endIf();
        }
        else {
            if (this.allErrors)
                this.gen.endIf();
            else
                this.gen.else();
        }
    }
    pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), undefined, failAction);
    }
    fail(condition) {
        if (condition === undefined) {
            this.error();
            if (!this.allErrors)
                this.gen.if(false); // this branch will be removed by gen.optimize
            return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
            this.gen.endIf();
        else
            this.gen.else();
    }
    fail$data(condition) {
        if (!this.$data)
            return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._) `${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
    }
    error(append, errorParams, errorPaths) {
        if (errorParams) {
            this.setParams(errorParams);
            this._error(append, errorPaths);
            this.setParams({});
            return;
        }
        this._error(append, errorPaths);
    }
    _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
    }
    $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
    }
    reset() {
        if (this.errsCount === undefined)
            throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok(cond) {
        if (!this.allErrors)
            this.gen.if(cond);
    }
    setParams(obj, assign) {
        if (assign)
            Object.assign(this.params, obj);
        else
            this.params = obj;
    }
    block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
            this.check$data(valid, $dataValid);
            codeBlock();
        });
    }
    check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
            return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._) `${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
            gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
            gen.elseIf(this.invalid$data());
            this.$dataError();
            if (valid !== codegen_1.nil)
                gen.assign(valid, false);
        }
        gen.else();
    }
    invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
            if (schemaType.length) {
                /* istanbul ignore if */
                if (!(schemaCode instanceof codegen_1.Name))
                    throw new Error("ajv implementation error");
                const st = Array.isArray(schemaType) ? schemaType : [schemaType];
                return (0, codegen_1._) `${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
            }
            return codegen_1.nil;
        }
        function invalid$DataSchema() {
            if (def.validateSchema) {
                const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); // TODO value.code for standalone
                return (0, codegen_1._) `!${validateSchemaRef}(${schemaCode})`;
            }
            return codegen_1.nil;
        }
    }
    subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: undefined, props: undefined };
        subschemaCode(nextContext, valid);
        return nextContext;
    }
    mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
            return;
        if (it.props !== true && schemaCxt.props !== undefined) {
            it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== undefined) {
            it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
    }
    mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
            gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
            return true;
        }
    }
}
exports.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword, def, ruleType) {
    const cxt = new KeywordCxt(it, def, keyword);
    if ("code" in def) {
        def.code(cxt, ruleType);
    }
    else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
    else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
    }
    else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
    }
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
    let jsonPointer;
    let data;
    if ($data === "")
        return names_1.default.rootData;
    if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
    }
    else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
            throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
            if (up >= dataLevel)
                throw new Error(errorMsg("property/index", up));
            return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
            throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
            return data;
    }
    let expr = data;
    const segments = jsonPointer.split("/");
    for (const segment of segments) {
        if (segment) {
            data = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
            expr = (0, codegen_1._) `${expr} && ${data}`;
        }
    }
    return expr;
    function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
    }
}
exports.getData = getData;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
const codegen_1 = require("../codegen");
const names_1 = require("../names");
const code_1 = require("../../vocabularies/code");
const errors_1 = require("../errors");
function macroKeywordCode(cxt, def) {
    const { gen, keyword, schema, parentSchema, it } = cxt;
    const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
    const schemaRef = useKeyword(gen, keyword, macroSchema);
    if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
    const valid = gen.name("valid");
    cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true,
    }, valid);
    cxt.pass(valid, () => cxt.error(true));
}
exports.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def) {
    var _a;
    const { gen, keyword, schema, parentSchema, $data, it } = cxt;
    checkAsyncKeyword(it, def);
    const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
    const validateRef = useKeyword(gen, keyword, validate);
    const valid = gen.let("valid");
    cxt.block$data(valid, validateKeyword);
    cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid);
    function validateKeyword() {
        if (def.errors === false) {
            assignValid();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => cxt.error());
        }
        else {
            const ruleErrs = def.async ? validateAsync() : validateSync();
            if (def.modifying)
                modifyData(cxt);
            reportErrs(() => addErrs(cxt, ruleErrs));
        }
    }
    function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._) `await `), (e) => gen.assign(valid, false).if((0, codegen_1._) `${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._) `${e}.errors`), () => gen.throw(e)));
        return ruleErrs;
    }
    function validateSync() {
        const validateErrs = (0, codegen_1._) `${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
    }
    function assignValid(_await = def.async ? (0, codegen_1._) `await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !(("compile" in def && !$data) || def.schema === false);
        gen.assign(valid, (0, codegen_1._) `${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
    }
    function reportErrs(errors) {
        var _a;
        gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== void 0 ? _a : valid), errors);
    }
}
exports.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
    const { gen, data, it } = cxt;
    gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._) `${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
    const { gen } = cxt;
    gen.if((0, codegen_1._) `Array.isArray(${errs})`, () => {
        gen
            .assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`)
            .assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
    }, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def) {
    if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword, result) {
    if (result === undefined)
        throw new Error(`keyword "${keyword}" failed to compile`);
    return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
    // TODO add tests
    return (!schemaType.length ||
        schemaType.some((st) => st === "array"
            ? Array.isArray(schema)
            : st === "object"
                ? schema && typeof schema == "object" && !Array.isArray(schema)
                : typeof schema == st || (allowUndefined && typeof schema == "undefined")));
}
exports.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
    /* istanbul ignore if */
    if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
    }
    const deps = def.dependencies;
    if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
    }
    if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
            const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` +
                self.errorsText(def.validateSchema.errors);
            if (opts.validateSchema === "log")
                self.logger.error(msg);
            else
                throw new Error(msg);
        }
    }
}
exports.validateKeywordUsage = validateKeywordUsage;
//# sourceMappingURL=keyword.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
const codegen_1 = require("../codegen");
const util_1 = require("../util");
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
    if (keyword !== undefined && schema !== undefined) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
    }
    if (keyword !== undefined) {
        const sch = it.schema[keyword];
        return schemaProp === undefined
            ? {
                schema: sch,
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}`,
            }
            : {
                schema: sch[schemaProp],
                schemaPath: (0, codegen_1._) `${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
                errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`,
            };
    }
    if (schema !== undefined) {
        if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
            throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
            schema,
            schemaPath,
            topSchemaRef,
            errSchemaPath,
        };
    }
    throw new Error('either "keyword" or "schema" must be passed');
}
exports.getSubschema = getSubschema;
function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
    if (data !== undefined && dataProp !== undefined) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
    }
    const { gen } = it;
    if (dataProp !== undefined) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._) `${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str) `${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._) `${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
    }
    if (data !== undefined) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); // replaceable if used once?
        dataContextProps(nextData);
        if (propertyName !== undefined)
            subschema.propertyName = propertyName;
        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
    }
    if (dataTypes)
        subschema.dataTypes = dataTypes;
    function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
    }
}
exports.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
    if (compositeRule !== undefined)
        subschema.compositeRule = compositeRule;
    if (createErrors !== undefined)
        subschema.createErrors = createErrors;
    if (allErrors !== undefined)
        subschema.allErrors = allErrors;
    subschema.jtdDiscriminator = jtdDiscriminator; // not inherited
    subschema.jtdMetadata = jtdMetadata; // not inherited
}
exports.extendSubschemaMode = extendSubschemaMode;
//# sourceMappingURL=subschema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
const validation_error_1 = require("./runtime/validation_error");
const ref_error_1 = require("./compile/ref_error");
const rules_1 = require("./compile/rules");
const compile_1 = require("./compile");
const codegen_2 = require("./compile/codegen");
const resolve_1 = require("./compile/resolve");
const dataType_1 = require("./compile/validate/dataType");
const util_1 = require("./compile/util");
const $dataRefSchema = require("./refs/data.json");
const uri_1 = require("./runtime/uri");
const defaultRegExp = (str, flags) => new RegExp(str, flags);
defaultRegExp.code = "new RegExp";
const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
const EXT_SCOPE_NAMES = new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error",
]);
const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now.",
};
const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.',
};
const MAX_EXPRESSION = 200;
// eslint-disable-next-line complexity
function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver: uriResolver,
    };
}
class Ajv {
    constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = new Set();
        this._loading = {};
        this._cache = new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
            addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
        this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
        const { $data, meta, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
            _dataRefSchema = { ...$dataRefSchema };
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
        }
        if (meta && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
        const { meta, schemaId } = this.opts;
        return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined);
    }
    validate(schemaKeyRef, // key, ref or schema object
    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
    data // to be validated
    ) {
        let v;
        if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
                throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        }
        else {
            v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
            this.errors = v.errors;
        return valid;
    }
    compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    compileAsync(schema, meta) {
        if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta);
        async function runCompileAsync(_schema, _meta) {
            await loadMetaSchema.call(this, _schema.$schema);
            const sch = this._addSchema(_schema, _meta);
            return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
            if ($ref && !this.getSchema($ref)) {
                await runCompileAsync.call(this, { $ref }, true);
            }
        }
        async function _compileAsync(sch) {
            try {
                return this._compileSchemaEnv(sch);
            }
            catch (e) {
                if (!(e instanceof ref_error_1.default))
                    throw e;
                checkLoaded.call(this, e);
                await loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
            }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
            if (this.refs[ref]) {
                throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
            }
        }
        async function loadMissingSchema(ref) {
            const _schema = await _loadSchema.call(this, ref);
            if (!this.refs[ref])
                await loadMetaSchema.call(this, _schema.$schema);
            if (!this.refs[ref])
                this.addSchema(_schema, ref, meta);
        }
        async function _loadSchema(ref) {
            const p = this._loading[ref];
            if (p)
                return p;
            try {
                return await (this._loading[ref] = loadSchema(ref));
            }
            finally {
                delete this._loading[ref];
            }
        }
    }
    // Adds schema to the instance
    addSchema(schema, // If array is passed, `key` will be ignored
    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
    ) {
        if (Array.isArray(schema)) {
            for (const sch of schema)
                this.addSchema(sch, undefined, _meta, _validateSchema);
            return this;
        }
        let id;
        if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id = schema[schemaId];
            if (id !== undefined && typeof id != "string") {
                throw new Error(`schema ${schemaId} must be string`);
            }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, // schema key
    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
    ) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
            return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== undefined && typeof $schema != "string") {
            throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
                this.logger.error(message);
            else
                throw new Error(message);
        }
        return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
        if (sch === undefined) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
                return;
            this.refs[keyRef] = sch;
        }
        return (sch.validate || this._compileSchemaEnv(sch));
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
        }
        switch (typeof schemaKeyRef) {
            case "undefined":
                this._removeAllSchemas(this.schemas);
                this._removeAllSchemas(this.refs);
                this._cache.clear();
                return this;
            case "string": {
                const sch = getSchEnv.call(this, schemaKeyRef);
                if (typeof sch == "object")
                    this._cache.delete(sch.schema);
                delete this.schemas[schemaKeyRef];
                delete this.refs[schemaKeyRef];
                return this;
            }
            case "object": {
                const cacheKey = schemaKeyRef;
                this._cache.delete(cacheKey);
                let id = schemaKeyRef[this.opts.schemaId];
                if (id) {
                    id = (0, resolve_1.normalizeId)(id);
                    delete this.schemas[id];
                    delete this.refs[id];
                }
                return this;
            }
            default:
                throw new Error("ajv.removeSchema: invalid parameter");
        }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions) {
        for (const def of definitions)
            this.addKeyword(def);
        return this;
    }
    addKeyword(kwdOrDef, def // deprecated
    ) {
        let keyword;
        if (typeof kwdOrDef == "string") {
            keyword = kwdOrDef;
            if (typeof def == "object") {
                this.logger.warn("these parameters are deprecated, see docs for addKeyword");
                def.keyword = keyword;
            }
        }
        else if (typeof kwdOrDef == "object" && def === undefined) {
            def = kwdOrDef;
            keyword = def.keyword;
            if (Array.isArray(keyword) && !keyword.length) {
                throw new Error("addKeywords: keyword must be string or non-empty array");
            }
        }
        else {
            throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
            (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
            return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
            ...def,
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType),
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0
            ? (k) => addRule.call(this, k, definition)
            : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        return this;
    }
    getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword) {
        // TODO return type should be Ajv
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
            const i = group.rules.findIndex((rule) => rule.keyword === keyword);
            if (i >= 0)
                group.rules.splice(i, 1);
        }
        return this;
    }
    // Add format
    addFormat(name, format) {
        if (typeof format == "string")
            format = new RegExp(format);
        this.formats[name] = format;
        return this;
    }
    errorsText(errors = this.errors, // optional array of validation errors
    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
    ) {
        if (!errors || errors.length === 0)
            return "No errors";
        return errors
            .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
            .reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1); // first segment is an empty string
            let keywords = metaSchema;
            for (const seg of segments)
                keywords = keywords[seg];
            for (const key in rules) {
                const rule = rules[key];
                if (typeof rule != "object")
                    continue;
                const { $data } = rule.definition;
                const schema = keywords[key];
                if ($data && schema)
                    keywords[key] = schemaOrData(schema);
            }
        }
        return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
                if (typeof sch == "string") {
                    delete schemas[keyRef];
                }
                else if (sch && !sch.meta) {
                    this._cache.delete(sch.schema);
                    delete schemas[keyRef];
                }
            }
        }
    }
    _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
            id = schema[schemaId];
        }
        else {
            if (this.opts.jtd)
                throw new Error("schema must be object");
            else if (typeof schema != "boolean")
                throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== undefined)
            return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
            if (baseId)
                this._checkUnique(baseId);
            this.refs[baseId] = sch;
        }
        if (validateSchema)
            this.validateSchema(schema, true);
        return sch;
    }
    _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
            throw new Error(`schema with key or id "${id}" already exists`);
        }
    }
    _compileSchemaEnv(sch) {
        if (sch.meta)
            this._compileMetaSchema(sch);
        else
            compile_1.compileSchema.call(this, sch);
        /* istanbul ignore if */
        if (!sch.validate)
            throw new Error("ajv implementation error");
        return sch.validate;
    }
    _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
            compile_1.compileSchema.call(this, sch);
        }
        finally {
            this.opts = currentOpts;
        }
    }
}
Ajv.ValidationError = validation_error_1.default;
Ajv.MissingRefError = ref_error_1.default;
exports.default = Ajv;
function checkOptions(checkOpts, options, msg, log = "error") {
    for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
}
function getSchEnv(keyRef) {
    keyRef = (0, resolve_1.normalizeId)(keyRef); // TODO tests fail without this line
    return this.schemas[keyRef] || this.refs[keyRef];
}
function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
        return;
    if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
    else
        for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
    for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
            this.addFormat(name, format);
    }
}
function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
            def.keyword = keyword;
        this.addKeyword(def);
    }
}
function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
    return metaOpts;
}
const noLogs = { log() { }, warn() { }, error() { } };
function getLogger(logger) {
    if (logger === false)
        return noLogs;
    if (logger === undefined)
        return console;
    if (logger.log && logger.warn && logger.error)
        return logger;
    throw new Error("logger must implement log, warn and error methods");
}
const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
function checkKeyword(keyword, def) {
    const { RULES } = this;
    (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def)
        return;
    if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
    }
}
function addRule(keyword, definition, dataType) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
    if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword] = true;
    if (!definition)
        return;
    const rule = {
        keyword,
        definition: {
            ...definition,
            type: (0, dataType_1.getJSONTypes)(definition.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType),
        },
    };
    if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
        ruleGroup.rules.push(rule);
    RULES.all[keyword] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
}
function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
        ruleGroup.rules.splice(i, 0, rule);
    }
    else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
    }
}
function keywordMetaschema(def) {
    let { metaSchema } = def;
    if (metaSchema === undefined)
        return;
    if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
    def.validateSchema = this.compile(metaSchema, true);
}
const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
};
function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
}
//# sourceMappingURL=core.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
const core_1 = require("./core");
const jtd_1 = require("./vocabularies/jtd");
const jtd_schema_1 = require("./refs/jtd-schema");
const serialize_1 = require("./compile/jtd/serialize");
const parse_1 = require("./compile/jtd/parse");
const META_SCHEMA_ID = "JTD-meta-schema";
class Ajv extends core_1.default {
    constructor(opts = {}) {
        super({
            ...opts,
            jtd: true,
        });
    }
    _addVocabularies() {
        super._addVocabularies();
        this.addVocabulary(jtd_1.default);
    }
    _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
            return;
        this.addMetaSchema(jtd_schema_1.default, META_SCHEMA_ID, false);
    }
    defaultMeta() {
        return (this.opts.defaultMeta =
            super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined));
    }
    compileSerializer(schema) {
        const sch = this._addSchema(schema);
        return sch.serialize || this._compileSerializer(sch);
    }
    compileParser(schema) {
        const sch = this._addSchema(schema);
        return (sch.parse || this._compileParser(sch));
    }
    _compileSerializer(sch) {
        serialize_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.serialize)
            throw new Error("ajv implementation error");
        return sch.serialize;
    }
    _compileParser(sch) {
        parse_1.default.call(this, sch, sch.schema.definitions || {});
        /* istanbul ignore if */
        if (!sch.parse)
            throw new Error("ajv implementation error");
        return sch.parse;
    }
}
exports.Ajv = Ajv;
module.exports = exports = Ajv;
module.exports.Ajv = Ajv;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Ajv;
var validate_1 = require("./compile/validate");
Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
var codegen_1 = require("./compile/codegen");
Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
var validation_error_1 = require("./runtime/validation_error");
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
var ref_error_1 = require("./compile/ref_error");
Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
//# sourceMappingURL=jtd.js.map{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2019($data) {
    ;
    [
        metaSchema,
        applicator,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2019;
//# sourceMappingURL=index.js.map{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const metaSchema = require("./schema.json");
const applicator = require("./meta/applicator.json");
const unevaluated = require("./meta/unevaluated.json");
const content = require("./meta/content.json");
const core = require("./meta/core.json");
const format = require("./meta/format-annotation.json");
const metadata = require("./meta/meta-data.json");
const validation = require("./meta/validation.json");
const META_SUPPORT_DATA = ["/properties"];
function addMetaSchema2020($data) {
    ;
    [
        metaSchema,
        applicator,
        unevaluated,
        content,
        core,
        with$data(this, format),
        metadata,
        with$data(this, validation),
    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
    return this;
    function with$data(ajv, sch) {
        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
    }
}
exports.default = addMetaSchema2020;
//# sourceMappingURL=index.js.map{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const shared = (root) => {
    const sch = {
        nullable: { type: "boolean" },
        metadata: {
            optionalProperties: {
                union: { elements: { ref: "schema" } },
            },
            additionalProperties: true,
        },
    };
    if (root)
        sch.definitions = { values: { ref: "schema" } };
    return sch;
};
const emptyForm = (root) => ({
    optionalProperties: shared(root),
});
const refForm = (root) => ({
    properties: {
        ref: { type: "string" },
    },
    optionalProperties: shared(root),
});
const typeForm = (root) => ({
    properties: {
        type: {
            enum: [
                "boolean",
                "timestamp",
                "string",
                "float32",
                "float64",
                "int8",
                "uint8",
                "int16",
                "uint16",
                "int32",
                "uint32",
            ],
        },
    },
    optionalProperties: shared(root),
});
const enumForm = (root) => ({
    properties: {
        enum: { elements: { type: "string" } },
    },
    optionalProperties: shared(root),
});
const elementsForm = (root) => ({
    properties: {
        elements: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const propertiesForm = (root) => ({
    properties: {
        properties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        optionalProperties: { values: { ref: "schema" } },
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const optionalPropertiesForm = (root) => ({
    properties: {
        optionalProperties: { values: { ref: "schema" } },
    },
    optionalProperties: {
        additionalProperties: { type: "boolean" },
        ...shared(root),
    },
});
const discriminatorForm = (root) => ({
    properties: {
        discriminator: { type: "string" },
        mapping: {
            values: {
                metadata: {
                    union: [propertiesForm(false), optionalPropertiesForm(false)],
                },
            },
        },
    },
    optionalProperties: shared(root),
});
const valuesForm = (root) => ({
    properties: {
        values: { ref: "schema" },
    },
    optionalProperties: shared(root),
});
const schema = (root) => ({
    metadata: {
        union: [
            emptyForm,
            refForm,
            typeForm,
            enumForm,
            elementsForm,
            propertiesForm,
            optionalPropertiesForm,
            discriminatorForm,
            valuesForm,
        ].map((s) => s(root)),
    },
});
const jtdMetaSchema = {
    definitions: {
        schema: schema(false),
    },
    ...schema(true),
};
exports.default = jtdMetaSchema;
//# sourceMappingURL=jtd-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://github.com/ajv-validator/ajv/issues/889
const equal = require("fast-deep-equal");
equal.code = 'require("ajv/dist/runtime/equal").default';
exports.default = equal;
//# sourceMappingURL=equal.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseJsonString = exports.parseJsonNumber = exports.parseJson = void 0;
const rxParseJson = /position\s(\d+)(?: \(line \d+ column \d+\))?$/;
function parseJson(s, pos) {
    let endPos;
    parseJson.message = undefined;
    let matches;
    if (pos)
        s = s.slice(pos);
    try {
        parseJson.position = pos + s.length;
        return JSON.parse(s);
    }
    catch (e) {
        matches = rxParseJson.exec(e.message);
        if (!matches) {
            parseJson.message = "unexpected end";
            return undefined;
        }
        endPos = +matches[1];
        const c = s[endPos];
        s = s.slice(0, endPos);
        parseJson.position = pos + endPos;
        try {
            return JSON.parse(s);
        }
        catch (e1) {
            parseJson.message = `unexpected token ${c}`;
            return undefined;
        }
    }
}
exports.parseJson = parseJson;
parseJson.message = undefined;
parseJson.position = 0;
parseJson.code = 'require("ajv/dist/runtime/parseJson").parseJson';
function parseJsonNumber(s, pos, maxDigits) {
    let numStr = "";
    let c;
    parseJsonNumber.message = undefined;
    if (s[pos] === "-") {
        numStr += "-";
        pos++;
    }
    if (s[pos] === "0") {
        numStr += "0";
        pos++;
    }
    else {
        if (!parseDigits(maxDigits)) {
            errorMessage();
            return undefined;
        }
    }
    if (maxDigits) {
        parseJsonNumber.position = pos;
        return +numStr;
    }
    if (s[pos] === ".") {
        numStr += ".";
        pos++;
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    if (((c = s[pos]), c === "e" || c === "E")) {
        numStr += "e";
        pos++;
        if (((c = s[pos]), c === "+" || c === "-")) {
            numStr += c;
            pos++;
        }
        if (!parseDigits()) {
            errorMessage();
            return undefined;
        }
    }
    parseJsonNumber.position = pos;
    return +numStr;
    function parseDigits(maxLen) {
        let digit = false;
        while (((c = s[pos]), c >= "0" && c <= "9" && (maxLen === undefined || maxLen-- > 0))) {
            digit = true;
            numStr += c;
            pos++;
        }
        return digit;
    }
    function errorMessage() {
        parseJsonNumber.position = pos;
        parseJsonNumber.message = pos < s.length ? `unexpected token ${s[pos]}` : "unexpected end";
    }
}
exports.parseJsonNumber = parseJsonNumber;
parseJsonNumber.message = undefined;
parseJsonNumber.position = 0;
parseJsonNumber.code = 'require("ajv/dist/runtime/parseJson").parseJsonNumber';
const escapedChars = {
    b: "\b",
    f: "\f",
    n: "\n",
    r: "\r",
    t: "\t",
    '"': '"',
    "/": "/",
    "\\": "\\",
};
const CODE_A = "a".charCodeAt(0);
const CODE_0 = "0".charCodeAt(0);
function parseJsonString(s, pos) {
    let str = "";
    let c;
    parseJsonString.message = undefined;
    // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
    while (true) {
        c = s[pos++];
        if (c === '"')
            break;
        if (c === "\\") {
            c = s[pos];
            if (c in escapedChars) {
                str += escapedChars[c];
                pos++;
            }
            else if (c === "u") {
                pos++;
                let count = 4;
                let code = 0;
                while (count--) {
                    code <<= 4;
                    c = s[pos];
                    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
                    if (c === undefined) {
                        errorMessage("unexpected end");
                        return undefined;
                    }
                    c = c.toLowerCase();
                    if (c >= "a" && c <= "f") {
                        code += c.charCodeAt(0) - CODE_A + 10;
                    }
                    else if (c >= "0" && c <= "9") {
                        code += c.charCodeAt(0) - CODE_0;
                    }
                    else {
                        errorMessage(`unexpected token ${c}`);
                        return undefined;
                    }
                    pos++;
                }
                str += String.fromCharCode(code);
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
            // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
        }
        else if (c === undefined) {
            errorMessage("unexpected end");
            return undefined;
        }
        else {
            if (c.charCodeAt(0) >= 0x20) {
                str += c;
            }
            else {
                errorMessage(`unexpected token ${c}`);
                return undefined;
            }
        }
    }
    parseJsonString.position = pos;
    return str;
    function errorMessage(msg) {
        parseJsonString.position = pos;
        parseJsonString.message = msg;
    }
}
exports.parseJsonString = parseJsonString;
parseJsonString.message = undefined;
parseJsonString.position = 0;
parseJsonString.code = 'require("ajv/dist/runtime/parseJson").parseJsonString';
//# sourceMappingURL=parseJson.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const rxEscapable = 
// eslint-disable-next-line no-control-regex, no-misleading-character-class
/[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
const escaped = {
    "\b": "\\b",
    "\t": "\\t",
    "\n": "\\n",
    "\f": "\\f",
    "\r": "\\r",
    '"': '\\"',
    "\\": "\\\\",
};
function quote(s) {
    rxEscapable.lastIndex = 0;
    return ('"' +
        (rxEscapable.test(s)
            ? s.replace(rxEscapable, (a) => {
                const c = escaped[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            })
            : s) +
        '"');
}
exports.default = quote;
quote.code = 'require("ajv/dist/runtime/quote").default';
//# sourceMappingURL=quote.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const re2 = require("re2");
re2.code = 'require("ajv/dist/runtime/re2").default';
exports.default = re2;
//# sourceMappingURL=re2.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DT_SEPARATOR = /t|\s/i;
const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
const TIME = /^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:z|([+-]\d\d)(?::?(\d\d))?)$/i;
const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function validTimestamp(str, allowDate) {
    // http://tools.ietf.org/html/rfc3339#section-5.6
    const dt = str.split(DT_SEPARATOR);
    return ((dt.length === 2 && validDate(dt[0]) && validTime(dt[1])) ||
        (allowDate && dt.length === 1 && validDate(dt[0])));
}
exports.default = validTimestamp;
function validDate(str) {
    const matches = DATE.exec(str);
    if (!matches)
        return false;
    const y = +matches[1];
    const m = +matches[2];
    const d = +matches[3];
    return (m >= 1 &&
        m <= 12 &&
        d >= 1 &&
        (d <= DAYS[m] ||
            // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
            (m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0))));
}
function validTime(str) {
    const matches = TIME.exec(str);
    if (!matches)
        return false;
    const hr = +matches[1];
    const min = +matches[2];
    const sec = +matches[3];
    const tzH = +(matches[4] || 0);
    const tzM = +(matches[5] || 0);
    return ((hr <= 23 && min <= 59 && sec <= 59) ||
        // leap second
        (hr - tzH === 23 && min - tzM === 59 && sec === 60));
}
validTimestamp.code = 'require("ajv/dist/runtime/timestamp").default';
//# sourceMappingURL=timestamp.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
function ucs2length(str) {
    const len = str.length;
    let length = 0;
    let pos = 0;
    let value;
    while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 0xd800 && value <= 0xdbff && pos < len) {
            // high surrogate, and there is a next character
            value = str.charCodeAt(pos);
            if ((value & 0xfc00) === 0xdc00)
                pos++; // low surrogate
        }
    }
    return length;
}
exports.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
//# sourceMappingURL=ucs2length.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uri = require("fast-uri");
uri.code = 'require("ajv/dist/runtime/uri").default';
exports.default = uri;
//# sourceMappingURL=uri.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class ValidationError extends Error {
    constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
    }
}
exports.default = ValidationError;
//# sourceMappingURL=validation_error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const scope_1 = require("../compile/codegen/scope");
const code_1 = require("../compile/codegen/code");
function standaloneCode(ajv, refsOrFunc) {
    if (!ajv.opts.code.source) {
        throw new Error("moduleCode: ajv instance must have code.source option");
    }
    const { _n } = ajv.scope.opts;
    return typeof refsOrFunc == "function"
        ? funcExportCode(refsOrFunc.source)
        : refsOrFunc !== undefined
            ? multiExportsCode(refsOrFunc, getValidate)
            : multiExportsCode(ajv.schemas, (sch) => sch.meta ? undefined : ajv.compile(sch.schema));
    function getValidate(id) {
        const v = ajv.getSchema(id);
        if (!v)
            throw new Error(`moduleCode: no schema with id ${id}`);
        return v;
    }
    function funcExportCode(source) {
        const usedValues = {};
        const n = source === null || source === void 0 ? void 0 : source.validateName;
        const vCode = validateCode(usedValues, source);
        if (ajv.opts.code.esm) {
            // Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
            return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`;
        }
        return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`;
    }
    function multiExportsCode(schemas, getValidateFunc) {
        var _a;
        const usedValues = {};
        let code = (0, code_1._) `"use strict";`;
        for (const name in schemas) {
            const v = getValidateFunc(schemas[name]);
            if (v) {
                const vCode = validateCode(usedValues, v.source);
                const exportSyntax = ajv.opts.code.esm
                    ? (0, code_1._) `export const ${(0, code_1.getEsmExportName)(name)}`
                    : (0, code_1._) `exports${(0, code_1.getProperty)(name)}`;
                code = (0, code_1._) `${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
            }
        }
        return `${code}`;
    }
    function validateCode(usedValues, s) {
        if (!s)
            throw new Error('moduleCode: function does not have "source" property');
        if (usedState(s.validateName) === scope_1.UsedValueState.Completed)
            return code_1.nil;
        setUsedState(s.validateName, scope_1.UsedValueState.Started);
        const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode);
        const code = new code_1._Code(`${scopeCode}${_n}${s.validateCode}`);
        return s.evaluated ? (0, code_1._) `${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code;
        function refValidateCode(n) {
            var _a;
            const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
            if (n.prefix === "validate" && typeof vRef == "function") {
                const v = vRef;
                return validateCode(usedValues, v.source);
            }
            else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
                const { validate, validateName } = vRef;
                if (!validateName)
                    throw new Error("ajv internal error");
                const def = ajv.opts.code.es5 ? scope_1.varKinds.var : scope_1.varKinds.const;
                const wrapper = (0, code_1._) `${def} ${n} = {validate: ${validateName}};`;
                if (usedState(validateName) === scope_1.UsedValueState.Started)
                    return wrapper;
                const vCode = validateCode(usedValues, validate === null || validate === void 0 ? void 0 : validate.source);
                return (0, code_1._) `${wrapper}${_n}${vCode}`;
            }
            return undefined;
        }
        function usedState(name) {
            var _a;
            return (_a = usedValues[name.prefix]) === null || _a === void 0 ? void 0 : _a.get(name);
        }
        function setUsedState(name, state) {
            const { prefix } = name;
            const names = (usedValues[prefix] = usedValues[prefix] || new Map());
            names.set(name, state);
        }
    }
}
module.exports = exports = standaloneCode;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = standaloneCode;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("../core");
const _1 = require(".");
const requireFromString = require("require-from-string");
class AjvPack {
    constructor(ajv) {
        this.ajv = ajv;
    }
    validate(schemaKeyRef, data) {
        return core_1.default.prototype.validate.call(this, schemaKeyRef, data);
    }
    compile(schema, meta) {
        return this.getStandalone(this.ajv.compile(schema, meta));
    }
    getSchema(keyRef) {
        const v = this.ajv.getSchema(keyRef);
        if (!v)
            return undefined;
        return this.getStandalone(v);
    }
    getStandalone(v) {
        return requireFromString((0, _1.default)(this.ajv, v));
    }
    addSchema(...args) {
        this.ajv.addSchema.call(this.ajv, ...args);
        return this;
    }
    addKeyword(...args) {
        this.ajv.addKeyword.call(this.ajv, ...args);
        return this;
    }
}
exports.default = AjvPack;
//# sourceMappingURL=instance.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=json-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=jtd-schema.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAdditionalItems = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "additionalItems",
    type: "array",
    schemaType: ["boolean", "object"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
            (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
            return;
        }
        validateAdditionalItems(cxt, items);
    },
};
function validateAdditionalItems(cxt, items) {
    const { gen, schema, data, keyword, it } = cxt;
    it.items = true;
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._) `${len} <= ${items.length}`);
    }
    else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items.length}`); // TODO var
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
    }
    function validateItems(valid) {
        gen.forRange("i", items.length, len, (i) => {
            cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
            if (!it.allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
    }
}
exports.validateAdditionalItems = validateAdditionalItems;
exports.default = def;
//# sourceMappingURL=additionalItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const util_1 = require("../../compile/util");
const error = {
    message: "must NOT have additional properties",
    params: ({ params }) => (0, codegen_1._) `{additionalProperty: ${params.additionalProperty}}`,
};
const def = {
    keyword: "additionalProperties",
    type: ["object"],
    schemaType: ["boolean", "object"],
    allowUndefined: true,
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
            return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
            gen.forIn("key", data, (key) => {
                if (!props.length && !patProps.length)
                    additionalPropertyCode(key);
                else
                    gen.if(isAdditional(key), () => additionalPropertyCode(key));
            });
        }
        function isAdditional(key) {
            let definedProp;
            if (props.length > 8) {
                // TODO maybe an option instead of hard-coded 8?
                const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
                definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
            }
            else if (props.length) {
                definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._) `${key} === ${p}`));
            }
            else {
                definedProp = codegen_1.nil;
            }
            if (patProps.length) {
                definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._) `${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
            }
            return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
            gen.code((0, codegen_1._) `delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
            if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) {
                deleteAdditional(key);
                return;
            }
            if (schema === false) {
                cxt.setParams({ additionalProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                if (opts.removeAdditional === "failing") {
                    applyAdditionalSchema(key, valid, false);
                    gen.if((0, codegen_1.not)(valid), () => {
                        cxt.reset();
                        deleteAdditional(key);
                    });
                }
                else {
                    applyAdditionalSchema(key, valid);
                    if (!allErrors)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                }
            }
        }
        function applyAdditionalSchema(key, valid, errors) {
            const subschema = {
                keyword: "additionalProperties",
                dataProp: key,
                dataPropType: util_1.Type.Str,
            };
            if (errors === false) {
                Object.assign(subschema, {
                    compositeRule: true,
                    createErrors: false,
                    allErrors: false,
                });
            }
            cxt.subschema(subschema, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=additionalProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "allOf",
    schemaType: "array",
    code(cxt) {
        const { gen, schema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i) => {
            if ((0, util_1.alwaysValidSchema)(it, sch))
                return;
            const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
            cxt.ok(valid);
            cxt.mergeEvaluated(schCxt);
        });
    },
};
exports.default = def;
//# sourceMappingURL=allOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "anyOf",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in anyOf" },
};
exports.default = def;
//# sourceMappingURL=anyOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { min, max } }) => max === undefined
        ? (0, codegen_1.str) `must contain at least ${min} valid item(s)`
        : (0, codegen_1.str) `must contain at least ${min} and no more than ${max} valid item(s)`,
    params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._) `{minContains: ${min}}` : (0, codegen_1._) `{minContains: ${min}, maxContains: ${max}}`,
};
const def = {
    keyword: "contains",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
            min = minContains === undefined ? 1 : minContains;
            max = maxContains;
        }
        else {
            min = 1;
        }
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        cxt.setParams({ min, max });
        if (max === undefined && min === 0) {
            (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
            return;
        }
        if (max !== undefined && min > max) {
            (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
            cxt.fail();
            return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            let cond = (0, codegen_1._) `${len} >= ${min}`;
            if (max !== undefined)
                cond = (0, codegen_1._) `${cond} && ${len} <= ${max}`;
            cxt.pass(cond);
            return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === undefined && min === 1) {
            validateItems(valid, () => gen.if(valid, () => gen.break()));
        }
        else if (min === 0) {
            gen.let(valid, true);
            if (max !== undefined)
                gen.if((0, codegen_1._) `${data}.length > 0`, validateItemsWithCount);
        }
        else {
            gen.let(valid, false);
            validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
            const schValid = gen.name("_valid");
            const count = gen.let("count", 0);
            validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
            gen.forRange("i", 0, len, (i) => {
                cxt.subschema({
                    keyword: "contains",
                    dataProp: i,
                    dataPropType: util_1.Type.Num,
                    compositeRule: true,
                }, _valid);
                block();
            });
        }
        function checkLimits(count) {
            gen.code((0, codegen_1._) `${count}++`);
            if (max === undefined) {
                gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true).break());
            }
            else {
                gen.if((0, codegen_1._) `${count} > ${max}`, () => gen.assign(valid, false).break());
                if (min === 1)
                    gen.assign(valid, true);
                else
                    gen.if((0, codegen_1._) `${count} >= ${min}`, () => gen.assign(valid, true));
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=contains.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
exports.error = {
    message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str) `must have ${property_ies} ${deps} when property ${property} is present`;
    },
    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._) `{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`, // TODO change to reference
};
const def = {
    keyword: "dependencies",
    type: "object",
    schemaType: "object",
    error: exports.error,
    code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
    },
};
function splitDependencies({ schema }) {
    const propertyDeps = {};
    const schemaDeps = {};
    for (const key in schema) {
        if (key === "__proto__")
            continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
    }
    return [propertyDeps, schemaDeps];
}
function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
    const { gen, data, it } = cxt;
    if (Object.keys(propertyDeps).length === 0)
        return;
    const missing = gen.let("missing");
    for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
            continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
            property: prop,
            depsCount: deps.length,
            deps: deps.join(", "),
        });
        if (it.allErrors) {
            gen.if(hasProperty, () => {
                for (const depProp of deps) {
                    (0, code_1.checkReportMissingProp)(cxt, depProp);
                }
            });
        }
        else {
            gen.if((0, codegen_1._) `${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
        }
    }
}
exports.validatePropertyDeps = validatePropertyDeps;
function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
            continue;
        gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
        }, () => gen.var(valid, true) // TODO var
        );
        cxt.ok(valid);
    }
}
exports.validateSchemaDeps = validateSchemaDeps;
exports.default = def;
//# sourceMappingURL=dependencies.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("./dependencies");
const def = {
    keyword: "dependentSchemas",
    type: "object",
    schemaType: "object",
    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentSchemas.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params }) => (0, codegen_1.str) `must match "${params.ifClause}" schema`,
    params: ({ params }) => (0, codegen_1._) `{failingKeyword: ${params.ifClause}}`,
};
const def = {
    keyword: "if",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === undefined && parentSchema.else === undefined) {
            (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
            return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
            const ifClause = gen.let("ifClause");
            cxt.setParams({ ifClause });
            gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        }
        else if (hasThen) {
            gen.if(schValid, validateClause("then"));
        }
        else {
            gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
            const schCxt = cxt.subschema({
                keyword: "if",
                compositeRule: true,
                createErrors: false,
                allErrors: false,
            }, schValid);
            cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
            return () => {
                const schCxt = cxt.subschema({ keyword }, schValid);
                gen.assign(valid, schValid);
                cxt.mergeValidEvaluated(schCxt, valid);
                if (ifClause)
                    gen.assign(ifClause, (0, codegen_1._) `${keyword}`);
                else
                    cxt.setParams({ ifClause: keyword });
            };
        }
    },
};
function hasSchema(it, keyword) {
    const schema = it.schema[keyword];
    return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
}
exports.default = def;
//# sourceMappingURL=if.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const additionalItems_1 = require("./additionalItems");
const prefixItems_1 = require("./prefixItems");
const items_1 = require("./items");
const items2020_1 = require("./items2020");
const contains_1 = require("./contains");
const dependencies_1 = require("./dependencies");
const propertyNames_1 = require("./propertyNames");
const additionalProperties_1 = require("./additionalProperties");
const properties_1 = require("./properties");
const patternProperties_1 = require("./patternProperties");
const not_1 = require("./not");
const anyOf_1 = require("./anyOf");
const oneOf_1 = require("./oneOf");
const allOf_1 = require("./allOf");
const if_1 = require("./if");
const thenElse_1 = require("./thenElse");
function getApplicator(draft2020 = false) {
    const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default,
    ];
    // array
    if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
    else
        applicator.push(additionalItems_1.default, items_1.default);
    applicator.push(contains_1.default);
    return applicator;
}
exports.default = getApplicator;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateTuple = void 0;
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "array", "boolean"],
    before: "uniqueItems",
    code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
            return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        cxt.ok((0, code_1.validateArray)(cxt));
    },
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
    const { gen, parentSchema, data, keyword, it } = cxt;
    checkStrictTuple(parentSchema);
    if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
    }
    const valid = gen.name("valid");
    const len = gen.const("len", (0, codegen_1._) `${data}.length`);
    schArr.forEach((sch, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
        gen.if((0, codegen_1._) `${len} > ${i}`, () => cxt.subschema({
            keyword,
            schemaProp: i,
            dataProp: i,
        }, valid));
        cxt.ok(valid);
    });
    function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
            const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
            (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
    }
}
exports.validateTuple = validateTuple;
exports.default = def;
//# sourceMappingURL=items.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const additionalItems_1 = require("./additionalItems");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "items",
    type: "array",
    schemaType: ["object", "boolean"],
    before: "uniqueItems",
    error,
    code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        if (prefixItems)
            (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
            cxt.ok((0, code_1.validateArray)(cxt));
    },
};
exports.default = def;
//# sourceMappingURL=items2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: "not",
    schemaType: ["object", "boolean"],
    trackErrors: true,
    code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            cxt.fail();
            return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
            keyword: "not",
            compositeRule: true,
            createErrors: false,
            allErrors: false,
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
    },
    error: { message: "must NOT be valid" },
};
exports.default = def;
//# sourceMappingURL=not.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "must match exactly one schema in oneOf",
    params: ({ params }) => (0, codegen_1._) `{passingSchemas: ${params.passing}}`,
};
const def = {
    keyword: "oneOf",
    schemaType: "array",
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        /* istanbul ignore if */
        if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
            return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
            schArr.forEach((sch, i) => {
                let schCxt;
                if ((0, util_1.alwaysValidSchema)(it, sch)) {
                    gen.var(schValid, true);
                }
                else {
                    schCxt = cxt.subschema({
                        keyword: "oneOf",
                        schemaProp: i,
                        compositeRule: true,
                    }, schValid);
                }
                if (i > 0) {
                    gen
                        .if((0, codegen_1._) `${schValid} && ${valid}`)
                        .assign(valid, false)
                        .assign(passing, (0, codegen_1._) `[${passing}, ${i}]`)
                        .else();
                }
                gen.if(schValid, () => {
                    gen.assign(valid, true);
                    gen.assign(passing, i);
                    if (schCxt)
                        cxt.mergeEvaluated(schCxt, codegen_1.Name);
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=oneOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const util_2 = require("../../compile/util");
const def = {
    keyword: "patternProperties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 ||
            (alwaysValidPatterns.length === patterns.length &&
                (!it.opts.unevaluated || it.props === true))) {
            return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
            it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
            for (const pat of patterns) {
                if (checkProperties)
                    checkMatchingProperties(pat);
                if (it.allErrors) {
                    validateProperties(pat);
                }
                else {
                    gen.var(valid, true); // TODO var
                    validateProperties(pat);
                    gen.if(valid);
                }
            }
        }
        function checkMatchingProperties(pat) {
            for (const prop in checkProperties) {
                if (new RegExp(pat).test(prop)) {
                    (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
                }
            }
        }
        function validateProperties(pat) {
            gen.forIn("key", data, (key) => {
                gen.if((0, codegen_1._) `${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
                    const alwaysValid = alwaysValidPatterns.includes(pat);
                    if (!alwaysValid) {
                        cxt.subschema({
                            keyword: "patternProperties",
                            schemaProp: pat,
                            dataProp: key,
                            dataPropType: util_2.Type.Str,
                        }, valid);
                    }
                    if (it.opts.unevaluated && props !== true) {
                        gen.assign((0, codegen_1._) `${props}[${key}]`, true);
                    }
                    else if (!alwaysValid && !it.allErrors) {
                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
                        // or if all properties were evaluated (props === true)
                        gen.if((0, codegen_1.not)(valid), () => gen.break());
                    }
                });
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=patternProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const items_1 = require("./items");
const def = {
    keyword: "prefixItems",
    type: "array",
    schemaType: ["array"],
    before: "uniqueItems",
    code: (cxt) => (0, items_1.validateTuple)(cxt, "items"),
};
exports.default = def;
//# sourceMappingURL=prefixItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("../../compile/validate");
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const additionalProperties_1 = require("./additionalProperties");
const def = {
    keyword: "properties",
    type: "object",
    schemaType: "object",
    code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
            additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
            it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
            it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
            return;
        const valid = gen.name("valid");
        for (const prop of properties) {
            if (hasDefault(prop)) {
                applyPropertySchema(prop);
            }
            else {
                gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
                applyPropertySchema(prop);
                if (!it.allErrors)
                    gen.else().var(valid, true);
                gen.endIf();
            }
            cxt.it.definedProperties.add(prop);
            cxt.ok(valid);
        }
        function hasDefault(prop) {
            return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
        }
        function applyPropertySchema(prop) {
            cxt.subschema({
                keyword: "properties",
                schemaProp: prop,
                dataProp: prop,
            }, valid);
        }
    },
};
exports.default = def;
//# sourceMappingURL=properties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: "property name must be valid",
    params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
    keyword: "propertyNames",
    type: "object",
    schemaType: ["object", "boolean"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
            cxt.setParams({ propertyName: key });
            cxt.subschema({
                keyword: "propertyNames",
                data: key,
                dataTypes: ["string"],
                propertyName: key,
                compositeRule: true,
            }, valid);
            gen.if((0, codegen_1.not)(valid), () => {
                cxt.error(true);
                if (!it.allErrors)
                    gen.break();
            });
        });
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=propertyNames.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["then", "else"],
    schemaType: ["object", "boolean"],
    code({ keyword, parentSchema, it }) {
        if (parentSchema.if === undefined)
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
    },
};
exports.default = def;
//# sourceMappingURL=thenElse.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
const codegen_1 = require("../compile/codegen");
const util_1 = require("../compile/util");
const names_1 = require("../compile/names");
const util_2 = require("../compile/util");
function checkReportMissingProp(cxt, prop) {
    const { gen, data, it } = cxt;
    gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._) `${prop}` }, true);
        cxt.error();
    });
}
exports.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
    return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._) `${missing} = ${prop}`)));
}
exports.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
    cxt.setParams({ missingProperty: missing }, true);
    cxt.error();
}
exports.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
    return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
    });
}
exports.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
}
exports.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
    return ownProperties ? (0, codegen_1._) `${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
exports.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
    const cond = (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(property)} === undefined`;
    return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
}
exports.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
exports.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
}
exports.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
    const dataAndSchema = passSchema ? (0, codegen_1._) `${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
    const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData],
    ];
    if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
    const args = (0, codegen_1._) `${dataAndSchema}, ${gen.object(...valCxt)}`;
    return context !== codegen_1.nil ? (0, codegen_1._) `${func}.call(${context}, ${args})` : (0, codegen_1._) `${func}(${args})`;
}
exports.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1._) `new RegExp`;
function usePattern({ gen, it: { opts } }, pattern) {
    const u = opts.unicodeRegExp ? "u" : "";
    const { regExp } = opts.code;
    const rx = regExp(pattern, u);
    return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._) `${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`,
    });
}
exports.usePattern = usePattern;
function validateArray(cxt) {
    const { gen, data, keyword, it } = cxt;
    const valid = gen.name("valid");
    if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
    }
    gen.var(valid, true);
    validateItems(() => gen.break());
    return valid;
    function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        gen.forRange("i", 0, len, (i) => {
            cxt.subschema({
                keyword,
                dataProp: i,
                dataPropType: util_1.Type.Num,
            }, valid);
            gen.if((0, codegen_1.not)(valid), notValid);
        });
    }
}
exports.validateArray = validateArray;
function validateUnion(cxt) {
    const { gen, schema, keyword, it } = cxt;
    /* istanbul ignore if */
    if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
    const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
    if (alwaysValid && !it.opts.unevaluated)
        return;
    const valid = gen.let("valid", false);
    const schValid = gen.name("_valid");
    gen.block(() => schema.forEach((_sch, i) => {
        const schCxt = cxt.subschema({
            keyword,
            schemaProp: i,
            compositeRule: true,
        }, schValid);
        gen.assign(valid, (0, codegen_1._) `${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
        // or if all properties and items were evaluated (it.props === true && it.items === true)
        if (!merged)
            gen.if((0, codegen_1.not)(valid));
    }));
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
exports.validateUnion = validateUnion;
//# sourceMappingURL=code.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const def = {
    keyword: "id",
    code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
    },
};
exports.default = def;
//# sourceMappingURL=id.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const id_1 = require("./id");
const ref_1 = require("./ref");
const core = [
    "$schema",
    "$id",
    "$defs",
    "$vocabulary",
    { keyword: "$comment" },
    "definitions",
    id_1.default,
    ref_1.default,
];
exports.default = core;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callRef = exports.getValidate = void 0;
const ref_error_1 = require("../../compile/ref_error");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$ref",
    schemaType: "string",
    code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
            return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
        if (schOrEnv === undefined)
            throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
            return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
            if (env === root)
                return callRef(cxt, validateName, env, env.$async);
            const rootName = gen.scopeValue("root", { ref: root });
            return callRef(cxt, (0, codegen_1._) `${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
            const v = getValidate(cxt, sch);
            callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
            const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
            const valid = gen.name("valid");
            const schCxt = cxt.subschema({
                schema: sch,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: $ref,
            }, valid);
            cxt.mergeEvaluated(schCxt);
            cxt.ok(valid);
        }
    },
};
function getValidate(cxt, sch) {
    const { gen } = cxt;
    return sch.validate
        ? gen.scopeValue("validate", { ref: sch.validate })
        : (0, codegen_1._) `${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
exports.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
    const { gen, it } = cxt;
    const { allErrors, schemaEnv: env, opts } = it;
    const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
    if ($async)
        callAsyncRef();
    else
        callSyncRef();
    function callAsyncRef() {
        if (!env.$async)
            throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
            gen.code((0, codegen_1._) `await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
            addEvaluatedFrom(v); // TODO will not work with async, it has to be returned with the result
            if (!allErrors)
                gen.assign(valid, true);
        }, (e) => {
            gen.if((0, codegen_1._) `!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
            addErrorsFrom(e);
            if (!allErrors)
                gen.assign(valid, false);
        });
        cxt.ok(valid);
    }
    function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
    }
    function addErrorsFrom(source) {
        const errs = (0, codegen_1._) `${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._) `${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); // TODO tagged
        gen.assign(names_1.default.errors, (0, codegen_1._) `${names_1.default.vErrors}.length`);
    }
    function addEvaluatedFrom(source) {
        var _a;
        if (!it.opts.unevaluated)
            return;
        const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
        // TODO refactor
        if (it.props !== true) {
            if (schEvaluated && !schEvaluated.dynamicProps) {
                if (schEvaluated.props !== undefined) {
                    it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
                }
            }
            else {
                const props = gen.var("props", (0, codegen_1._) `${source}.evaluated.props`);
                it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
            }
        }
        if (it.items !== true) {
            if (schEvaluated && !schEvaluated.dynamicItems) {
                if (schEvaluated.items !== undefined) {
                    it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
                }
            }
            else {
                const items = gen.var("items", (0, codegen_1._) `${source}.evaluated.items`);
                it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
            }
        }
    }
}
exports.callRef = callRef;
exports.default = def;
//# sourceMappingURL=ref.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const types_1 = require("../discriminator/types");
const compile_1 = require("../../compile");
const ref_error_1 = require("../../compile/ref_error");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag
        ? `tag "${tagName}" must be string`
        : `value of tag "${tagName}" must be in oneOf`,
    params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._) `{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`,
};
const def = {
    keyword: "discriminator",
    type: "object",
    schemaType: "object",
    error,
    code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
            throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
            throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
            throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
            throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._) `typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
            const mapping = getMapping();
            gen.if(false);
            for (const tagValue in mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(mapping[tagValue]));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
            cxt.mergeEvaluated(schCxt, codegen_1.Name);
            return _valid;
        }
        function getMapping() {
            var _a;
            const oneOfMapping = {};
            const topRequired = hasRequired(parentSchema);
            let tagRequired = true;
            for (let i = 0; i < oneOf.length; i++) {
                let sch = oneOf[i];
                if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
                    const ref = sch.$ref;
                    sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
                    if (sch instanceof compile_1.SchemaEnv)
                        sch = sch.schema;
                    if (sch === undefined)
                        throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
                }
                const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
                if (typeof propSch != "object") {
                    throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
                }
                tagRequired = tagRequired && (topRequired || hasRequired(sch));
                addMappings(propSch, i);
            }
            if (!tagRequired)
                throw new Error(`discriminator: "${tagName}" must be required`);
            return oneOfMapping;
            function hasRequired({ required }) {
                return Array.isArray(required) && required.includes(tagName);
            }
            function addMappings(sch, i) {
                if (sch.const) {
                    addMapping(sch.const, i);
                }
                else if (sch.enum) {
                    for (const tagValue of sch.enum) {
                        addMapping(tagValue, i);
                    }
                }
                else {
                    throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
                }
            }
            function addMapping(tagValue, i) {
                if (typeof tagValue != "string" || tagValue in oneOfMapping) {
                    throw new Error(`discriminator: "${tagName}" values must be unique strings`);
                }
                oneOfMapping[tagValue] = i;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DiscrError = void 0;
var DiscrError;
(function (DiscrError) {
    DiscrError["Tag"] = "tag";
    DiscrError["Mapping"] = "mapping";
})(DiscrError || (exports.DiscrError = DiscrError = {}));
//# sourceMappingURL=types.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const dynamic_1 = require("./dynamic");
const next_1 = require("./next");
const unevaluated_1 = require("./unevaluated");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft2020Vocabularies = [
    dynamic_1.default,
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(true),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
    next_1.default,
    unevaluated_1.default,
];
exports.default = draft2020Vocabularies;
//# sourceMappingURL=draft2020.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("./core");
const validation_1 = require("./validation");
const applicator_1 = require("./applicator");
const format_1 = require("./format");
const metadata_1 = require("./metadata");
const draft7Vocabularies = [
    core_1.default,
    validation_1.default,
    (0, applicator_1.default)(),
    format_1.default,
    metadata_1.metadataVocabulary,
    metadata_1.contentVocabulary,
];
exports.default = draft7Vocabularies;
//# sourceMappingURL=draft7.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicAnchor = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const compile_1 = require("../../compile");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicAnchor",
    schemaType: "string",
    code: (cxt) => dynamicAnchor(cxt, cxt.schema),
};
function dynamicAnchor(cxt, anchor) {
    const { gen, it } = cxt;
    it.schemaEnv.root.dynamicAnchors[anchor] = true;
    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
    const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));
}
exports.dynamicAnchor = dynamicAnchor;
function _getValidate(cxt) {
    const { schemaEnv, schema, self } = cxt.it;
    const { root, baseId, localRefs, meta } = schemaEnv.root;
    const { schemaId } = self.opts;
    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
    compile_1.compileSchema.call(self, sch);
    return (0, ref_1.getValidate)(cxt, sch);
}
exports.default = def;
//# sourceMappingURL=dynamicAnchor.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.dynamicRef = void 0;
const codegen_1 = require("../../compile/codegen");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const def = {
    keyword: "$dynamicRef",
    schemaType: "string",
    code: (cxt) => dynamicRef(cxt, cxt.schema),
};
function dynamicRef(cxt, ref) {
    const { gen, keyword, it } = cxt;
    if (ref[0] !== "#")
        throw new Error(`"${keyword}" only supports hash fragment reference`);
    const anchor = ref.slice(1);
    if (it.allErrors) {
        _dynamicRef();
    }
    else {
        const valid = gen.let("valid", false);
        _dynamicRef(valid);
        cxt.ok(valid);
    }
    function _dynamicRef(valid) {
        // TODO the assumption here is that `recursiveRef: #` always points to the root
        // of the schema object, which is not correct, because there may be $id that
        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
        // Because of that 2 tests in recursiveRef.json fail.
        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
        // (This problem is not tested in JSON-Schema-Test-Suite)
        if (it.schemaEnv.root.dynamicAnchors[anchor]) {
            const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
        }
        else {
            _callRef(it.validateName, valid)();
        }
    }
    function _callRef(validate, valid) {
        return valid
            ? () => gen.block(() => {
                (0, ref_1.callRef)(cxt, validate);
                gen.let(valid, true);
            })
            : () => (0, ref_1.callRef)(cxt, validate);
    }
}
exports.dynamicRef = dynamicRef;
exports.default = def;
//# sourceMappingURL=dynamicRef.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const dynamicRef_1 = require("./dynamicRef");
const recursiveAnchor_1 = require("./recursiveAnchor");
const recursiveRef_1 = require("./recursiveRef");
const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const util_1 = require("../../compile/util");
const def = {
    keyword: "$recursiveAnchor",
    schemaType: "boolean",
    code(cxt) {
        if (cxt.schema)
            (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
        else
            (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
    },
};
exports.default = def;
//# sourceMappingURL=recursiveAnchor.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicRef_1 = require("./dynamicRef");
const def = {
    keyword: "$recursiveRef",
    schemaType: "string",
    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),
};
exports.default = def;
//# sourceMappingURL=recursiveRef.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=errors.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match format "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{format: ${schemaCode}}`,
};
const def = {
    keyword: "format",
    type: ["number", "string"],
    schemaType: "string",
    $data: true,
    error,
    code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self } = it;
        if (!opts.validateFormats)
            return;
        if ($data)
            validate$DataFormat();
        else
            validateFormat();
        function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
                ref: self.formats,
                code: opts.code.formats,
            });
            const fDef = gen.const("fDef", (0, codegen_1._) `${fmts}[${schemaCode}]`);
            const fType = gen.let("fType");
            const format = gen.let("format");
            // TODO simplify
            gen.if((0, codegen_1._) `typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._) `${fDef}.type || "string"`).assign(format, (0, codegen_1._) `${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._) `"string"`).assign(format, fDef));
            cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
            function unknownFmt() {
                if (opts.strictSchema === false)
                    return codegen_1.nil;
                return (0, codegen_1._) `${schemaCode} && !${format}`;
            }
            function invalidFmt() {
                const callFormat = schemaEnv.$async
                    ? (0, codegen_1._) `(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
                    : (0, codegen_1._) `${format}(${data})`;
                const validData = (0, codegen_1._) `(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
                return (0, codegen_1._) `${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
            }
        }
        function validateFormat() {
            const formatDef = self.formats[schema];
            if (!formatDef) {
                unknownFormat();
                return;
            }
            if (formatDef === true)
                return;
            const [fmtType, format, fmtRef] = getFormat(formatDef);
            if (fmtType === ruleType)
                cxt.pass(validCondition());
            function unknownFormat() {
                if (opts.strictSchema === false) {
                    self.logger.warn(unknownMsg());
                    return;
                }
                throw new Error(unknownMsg());
                function unknownMsg() {
                    return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
                }
            }
            function getFormat(fmtDef) {
                const code = fmtDef instanceof RegExp
                    ? (0, codegen_1.regexpCode)(fmtDef)
                    : opts.code.formats
                        ? (0, codegen_1._) `${opts.code.formats}${(0, codegen_1.getProperty)(schema)}`
                        : undefined;
                const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
                if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
                    return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._) `${fmt}.validate`];
                }
                return ["string", fmtDef, fmt];
            }
            function validCondition() {
                if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
                    if (!schemaEnv.$async)
                        throw new Error("async format in sync schema");
                    return (0, codegen_1._) `await ${fmtRef}(${data})`;
                }
                return typeof format == "function" ? (0, codegen_1._) `${fmtRef}(${data})` : (0, codegen_1._) `${fmtRef}.test(${data})`;
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=format.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const format_1 = require("./format");
const format = [format_1.default];
exports.default = format;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const types_1 = require("../discriminator/types");
const error = {
    message: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? params.discrError === types_1.DiscrError.Tag
                ? `tag "${schema}" must be string`
                : `value of tag "${schema}" must be in mapping`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { schema, params } = cxt;
        return params.discrError
            ? (0, codegen_1._) `{error: ${params.discrError}, tag: ${schema}, tagValue: ${params.tag}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "discriminator",
    schemaType: "string",
    implements: ["mapping"],
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, parentSchema } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        gen.if(cond);
        validateDiscriminator();
        gen.elseIf((0, codegen_1.not)(valid));
        cxt.error();
        gen.endIf();
        cxt.ok(valid);
        function validateDiscriminator() {
            const tag = gen.const("tag", (0, codegen_1._) `${data}${(0, codegen_1.getProperty)(schema)}`);
            gen.if((0, codegen_1._) `${tag} === undefined`);
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag });
            gen.elseIf((0, codegen_1._) `typeof ${tag} == "string"`);
            validateMapping(tag);
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Tag, tag }, { instancePath: schema });
            gen.endIf();
        }
        function validateMapping(tag) {
            gen.if(false);
            for (const tagValue in parentSchema.mapping) {
                gen.elseIf((0, codegen_1._) `${tag} === ${tagValue}`);
                gen.assign(valid, applyTagSchema(tagValue));
            }
            gen.else();
            cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag }, { instancePath: schema, schemaPath: "mapping", parentSchema: true });
            gen.endIf();
        }
        function applyTagSchema(schemaProp) {
            const _valid = gen.name("valid");
            cxt.subschema({
                keyword: "mapping",
                schemaProp,
                jtdDiscriminator: schema,
            }, _valid);
            return _valid;
        }
    },
};
exports.default = def;
//# sourceMappingURL=discriminator.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "elements",
    schemaType: "object",
    error: (0, error_1.typeError)("array"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const [valid] = (0, nullable_1.checkNullable)(cxt);
        gen.if((0, codegen_1.not)(valid), () => gen.if((0, codegen_1._) `Array.isArray(${data})`, () => gen.assign(valid, (0, code_1.validateArray)(cxt)), () => cxt.error()));
        cxt.ok(valid);
    },
};
exports.default = def;
//# sourceMappingURL=elements.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, schemaValue, parentSchema, it } = cxt;
        if (schema.length === 0)
            throw new Error("enum must have non-empty array");
        if (schema.length !== new Set(schema).size)
            throw new Error("enum items must be unique");
        let valid;
        const isString = (0, codegen_1._) `typeof ${data} == "string"`;
        if (schema.length >= it.opts.loopEnum) {
            let cond;
            [valid, cond] = (0, nullable_1.checkNullable)(cxt, isString);
            gen.if(cond, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            valid = (0, codegen_1.and)(isString, (0, codegen_1.or)(...schema.map((value) => (0, codegen_1._) `${data} === ${value}`)));
            if (parentSchema.nullable)
                valid = (0, codegen_1.or)((0, codegen_1._) `${data} === null`, valid);
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._) `${valid} = ${data} === ${v}`, () => gen.break()));
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.typeErrorParams = exports.typeErrorMessage = exports.typeError = void 0;
const codegen_1 = require("../../compile/codegen");
function typeError(t) {
    return {
        message: (cxt) => typeErrorMessage(cxt, t),
        params: (cxt) => typeErrorParams(cxt, t),
    };
}
exports.typeError = typeError;
function typeErrorMessage({ parentSchema }, t) {
    return (parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable) ? `must be ${t} or null` : `must be ${t}`;
}
exports.typeErrorMessage = typeErrorMessage;
function typeErrorParams({ parentSchema }, t) {
    return (0, codegen_1._) `{type: ${t}, nullable: ${!!(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.nullable)}}`;
}
exports.typeErrorParams = typeErrorParams;
//# sourceMappingURL=error.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ref_1 = require("./ref");
const type_1 = require("./type");
const enum_1 = require("./enum");
const elements_1 = require("./elements");
const properties_1 = require("./properties");
const optionalProperties_1 = require("./optionalProperties");
const discriminator_1 = require("./discriminator");
const values_1 = require("./values");
const union_1 = require("./union");
const metadata_1 = require("./metadata");
const jtdVocabulary = [
    "definitions",
    ref_1.default,
    type_1.default,
    enum_1.default,
    elements_1.default,
    properties_1.default,
    optionalProperties_1.default,
    discriminator_1.default,
    values_1.default,
    union_1.default,
    metadata_1.default,
    { keyword: "additionalProperties", schemaType: "boolean" },
    { keyword: "nullable", schemaType: "boolean" },
];
exports.default = jtdVocabulary;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkMetadata = void 0;
const util_1 = require("../../compile/util");
const def = {
    keyword: "metadata",
    schemaType: "object",
    code(cxt) {
        checkMetadata(cxt);
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
            return;
        const valid = gen.name("valid");
        cxt.subschema({ keyword: "metadata", jtdMetadata: true }, valid);
        cxt.ok(valid);
    },
};
function checkMetadata({ it, keyword }, metadata) {
    if (it.jtdMetadata !== metadata) {
        throw new Error(`JTD: "${keyword}" cannot be used in this schema location`);
    }
}
exports.checkMetadata = checkMetadata;
exports.default = def;
//# sourceMappingURL=metadata.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkNullableObject = exports.checkNullable = void 0;
const codegen_1 = require("../../compile/codegen");
function checkNullable({ gen, data, parentSchema }, cond = codegen_1.nil) {
    const valid = gen.name("valid");
    if (parentSchema.nullable) {
        gen.let(valid, (0, codegen_1._) `${data} === null`);
        cond = (0, codegen_1.not)(valid);
    }
    else {
        gen.let(valid, false);
    }
    return [valid, cond];
}
exports.checkNullable = checkNullable;
function checkNullableObject(cxt, cond) {
    const [valid, cond_] = checkNullable(cxt, cond);
    return [valid, (0, codegen_1._) `${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`];
}
exports.checkNullableObject = checkNullableObject;
//# sourceMappingURL=nullable.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const properties_1 = require("./properties");
const def = {
    keyword: "optionalProperties",
    schemaType: "object",
    error: properties_1.error,
    code(cxt) {
        if (cxt.parentSchema.properties)
            return;
        (0, properties_1.validateProperties)(cxt);
    },
};
exports.default = def;
//# sourceMappingURL=optionalProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateProperties = exports.error = void 0;
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
var PropError;
(function (PropError) {
    PropError["Additional"] = "additional";
    PropError["Missing"] = "missing";
})(PropError || (PropError = {}));
exports.error = {
    message: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? "must NOT have additional properties"
                : `must have property '${params.missingProperty}'`
            : (0, error_1.typeErrorMessage)(cxt, "object");
    },
    params: (cxt) => {
        const { params } = cxt;
        return params.propError
            ? params.propError === PropError.Additional
                ? (0, codegen_1._) `{error: ${params.propError}, additionalProperty: ${params.additionalProperty}}`
                : (0, codegen_1._) `{error: ${params.propError}, missingProperty: ${params.missingProperty}}`
            : (0, error_1.typeErrorParams)(cxt, "object");
    },
};
const def = {
    keyword: "properties",
    schemaType: "object",
    error: exports.error,
    code: validateProperties,
};
// const error: KeywordErrorDefinition = {
//   message: "should NOT have additional properties",
//   params: ({params}) => _`{additionalProperty: ${params.additionalProperty}}`,
// }
function validateProperties(cxt) {
    (0, metadata_1.checkMetadata)(cxt);
    const { gen, data, parentSchema, it } = cxt;
    const { additionalProperties, nullable } = parentSchema;
    if (it.jtdDiscriminator && nullable)
        throw new Error("JTD: nullable inside discriminator mapping");
    if (commonProperties()) {
        throw new Error("JTD: properties and optionalProperties have common members");
    }
    const [allProps, properties] = schemaProperties("properties");
    const [allOptProps, optProperties] = schemaProperties("optionalProperties");
    if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
        return;
    }
    const [valid, cond] = it.jtdDiscriminator === undefined
        ? (0, nullable_1.checkNullableObject)(cxt, data)
        : [gen.let("valid", false), true];
    gen.if(cond, () => gen.assign(valid, true).block(() => {
        validateProps(properties, "properties", true);
        validateProps(optProperties, "optionalProperties");
        if (!additionalProperties)
            validateAdditional();
    }));
    cxt.pass(valid);
    function commonProperties() {
        const props = parentSchema.properties;
        const optProps = parentSchema.optionalProperties;
        if (!(props && optProps))
            return false;
        for (const p in props) {
            if (Object.prototype.hasOwnProperty.call(optProps, p))
                return true;
        }
        return false;
    }
    function schemaProperties(keyword) {
        const schema = parentSchema[keyword];
        const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
        if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
            throw new Error(`JTD: discriminator tag used in ${keyword}`);
        }
        const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        return [allPs, ps];
    }
    function validateProps(props, keyword, required) {
        const _valid = gen.var("valid");
        for (const prop of props) {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => applyPropertySchema(prop, keyword, _valid), () => missingProperty(prop));
            cxt.ok(_valid);
        }
        function missingProperty(prop) {
            if (required) {
                gen.assign(_valid, false);
                cxt.error(false, { propError: PropError.Missing, missingProperty: prop }, { schemaPath: prop });
            }
            else {
                gen.assign(_valid, true);
            }
        }
    }
    function applyPropertySchema(prop, keyword, _valid) {
        cxt.subschema({
            keyword,
            schemaProp: prop,
            dataProp: prop,
        }, _valid);
    }
    function validateAdditional() {
        gen.forIn("key", data, (key) => {
            const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator);
            const addOptProp = isAdditional(key, allOptProps, "optionalProperties");
            const extra = addProp === true ? addOptProp : addOptProp === true ? addProp : (0, codegen_1.and)(addProp, addOptProp);
            gen.if(extra, () => {
                if (it.opts.removeAdditional) {
                    gen.code((0, codegen_1._) `delete ${data}[${key}]`);
                }
                else {
                    cxt.error(false, { propError: PropError.Additional, additionalProperty: key }, { instancePath: key, parentSchema: true });
                    if (!it.opts.allErrors)
                        gen.break();
                }
            });
        });
    }
    function isAdditional(key, props, keyword, jtdDiscriminator) {
        let additional;
        if (props.length > 8) {
            // TODO maybe an option instead of hard-coded 8?
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema[keyword], keyword);
            additional = (0, codegen_1.not)((0, code_1.isOwnProperty)(gen, propsSchema, key));
            if (jtdDiscriminator !== undefined) {
                additional = (0, codegen_1.and)(additional, (0, codegen_1._) `${key} !== ${jtdDiscriminator}`);
            }
        }
        else if (props.length || jtdDiscriminator !== undefined) {
            const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props);
            additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._) `${key} !== ${p}`));
        }
        else {
            additional = true;
        }
        return additional;
    }
}
exports.validateProperties = validateProperties;
exports.default = def;
//# sourceMappingURL=properties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasRef = void 0;
const compile_1 = require("../../compile");
const codegen_1 = require("../../compile/codegen");
const ref_error_1 = require("../../compile/ref_error");
const names_1 = require("../../compile/names");
const ref_1 = require("../core/ref");
const metadata_1 = require("./metadata");
const def = {
    keyword: "ref",
    schemaType: "string",
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema: ref, parentSchema, it } = cxt;
        const { schemaEnv: { root }, } = it;
        const valid = gen.name("valid");
        if (parentSchema.nullable) {
            gen.var(valid, (0, codegen_1._) `${data} === null`);
            gen.if((0, codegen_1.not)(valid), validateJtdRef);
        }
        else {
            gen.var(valid, false);
            validateJtdRef();
        }
        cxt.ok(valid);
        function validateJtdRef() {
            var _a;
            const refSchema = (_a = root.schema.definitions) === null || _a === void 0 ? void 0 : _a[ref];
            if (!refSchema) {
                throw new ref_error_1.default(it.opts.uriResolver, "", ref, `No definition ${ref}`);
            }
            if (hasRef(refSchema) || !it.opts.inlineRefs)
                callValidate(refSchema);
            else
                inlineRefSchema(refSchema);
        }
        function callValidate(schema) {
            const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
            const v = (0, ref_1.getValidate)(cxt, sch);
            const errsCount = gen.const("_errs", names_1.default.errors);
            (0, ref_1.callRef)(cxt, v, sch, sch.$async);
            gen.assign(valid, (0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        }
        function inlineRefSchema(schema) {
            const schName = gen.scopeValue("schema", it.opts.code.source === true ? { ref: schema, code: (0, codegen_1.stringify)(schema) } : { ref: schema });
            cxt.subschema({
                schema,
                dataTypes: [],
                schemaPath: codegen_1.nil,
                topSchemaRef: schName,
                errSchemaPath: `/definitions/${ref}`,
            }, valid);
        }
    },
};
function hasRef(schema) {
    for (const key in schema) {
        let sch;
        if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch)))
            return true;
    }
    return false;
}
exports.hasRef = hasRef;
exports.default = def;
//# sourceMappingURL=ref.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intRange = void 0;
const codegen_1 = require("../../compile/codegen");
const timestamp_1 = require("../../runtime/timestamp");
const util_1 = require("../../compile/util");
const metadata_1 = require("./metadata");
const error_1 = require("./error");
exports.intRange = {
    int8: [-128, 127, 3],
    uint8: [0, 255, 3],
    int16: [-32768, 32767, 5],
    uint16: [0, 65535, 5],
    int32: [-2147483648, 2147483647, 10],
    uint32: [0, 4294967295, 10],
};
const error = {
    message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
    params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
};
function timestampCode(cxt) {
    const { gen, data, it } = cxt;
    const { timestamp, allowDate } = it.opts;
    if (timestamp === "date")
        return (0, codegen_1._) `${data} instanceof Date `;
    const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
    const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
    const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
    return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
}
const def = {
    keyword: "type",
    schemaType: "string",
    error,
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { data, schema, parentSchema, it } = cxt;
        let cond;
        switch (schema) {
            case "boolean":
            case "string":
                cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
                break;
            case "timestamp": {
                cond = timestampCode(cxt);
                break;
            }
            case "float32":
            case "float64":
                cond = (0, codegen_1._) `typeof ${data} == "number"`;
                break;
            default: {
                const sch = schema;
                cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
                if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
                    if (sch === "uint32")
                        cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
                }
                else {
                    const [min, max] = exports.intRange[sch];
                    cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
                }
            }
        }
        cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
    },
};
exports.default = def;
//# sourceMappingURL=type.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const def = {
    keyword: "union",
    schemaType: "array",
    trackErrors: true,
    code: code_1.validateUnion,
    error: { message: "must match a schema in union" },
};
exports.default = def;
//# sourceMappingURL=union.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const metadata_1 = require("./metadata");
const nullable_1 = require("./nullable");
const error_1 = require("./error");
const def = {
    keyword: "values",
    schemaType: "object",
    error: (0, error_1.typeError)("object"),
    code(cxt) {
        (0, metadata_1.checkMetadata)(cxt);
        const { gen, data, schema, it } = cxt;
        const [valid, cond] = (0, nullable_1.checkNullableObject)(cxt, data);
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
            gen.if((0, codegen_1.not)((0, codegen_1.or)(cond, valid)), () => cxt.error());
        }
        else {
            gen.if(cond);
            gen.assign(valid, validateMap());
            gen.elseIf((0, codegen_1.not)(valid));
            cxt.error();
            gen.endIf();
        }
        cxt.ok(valid);
        function validateMap() {
            const _valid = gen.name("valid");
            if (it.allErrors) {
                const validMap = gen.let("valid", true);
                validateValues(() => gen.assign(validMap, false));
                return validMap;
            }
            gen.var(_valid, true);
            validateValues(() => gen.break());
            return _valid;
            function validateValues(notValid) {
                gen.forIn("key", data, (key) => {
                    cxt.subschema({
                        keyword: "values",
                        dataProp: key,
                        dataPropType: util_1.Type.Str,
                    }, _valid);
                    gen.if((0, codegen_1.not)(_valid), notValid);
                });
            }
        }
    },
};
exports.default = def;
//# sourceMappingURL=values.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.contentVocabulary = exports.metadataVocabulary = void 0;
exports.metadataVocabulary = [
    "title",
    "description",
    "default",
    "deprecated",
    "readOnly",
    "writeOnly",
    "examples",
];
exports.contentVocabulary = [
    "contentMediaType",
    "contentEncoding",
    "contentSchema",
];
//# sourceMappingURL=metadata.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependentRequired_1 = require("./validation/dependentRequired");
const dependentSchemas_1 = require("./applicator/dependentSchemas");
const limitContains_1 = require("./validation/limitContains");
const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
exports.default = next;
//# sourceMappingURL=next.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const unevaluatedProperties_1 = require("./unevaluatedProperties");
const unevaluatedItems_1 = require("./unevaluatedItems");
const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
exports.default = unevaluated;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { len } }) => (0, codegen_1.str) `must NOT have more than ${len} items`,
    params: ({ params: { len } }) => (0, codegen_1._) `{limit: ${len}}`,
};
const def = {
    keyword: "unevaluatedItems",
    type: "array",
    schemaType: ["boolean", "object"],
    error,
    code(cxt) {
        const { gen, schema, data, it } = cxt;
        const items = it.items || 0;
        if (items === true)
            return;
        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
        if (schema === false) {
            cxt.setParams({ len: items });
            cxt.fail((0, codegen_1._) `${len} > ${items}`);
        }
        else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`);
            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
            cxt.ok(valid);
        }
        it.items = true;
        function validateItems(valid, from) {
            gen.forRange("i", from, len, (i) => {
                cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
                if (!it.allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            });
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const names_1 = require("../../compile/names");
const error = {
    message: "must NOT have unevaluated properties",
    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,
};
const def = {
    keyword: "unevaluatedProperties",
    type: "object",
    schemaType: ["boolean", "object"],
    trackErrors: true,
    error,
    code(cxt) {
        const { gen, schema, data, errsCount, it } = cxt;
        /* istanbul ignore if */
        if (!errsCount)
            throw new Error("ajv implementation error");
        const { allErrors, props } = it;
        if (props instanceof codegen_1.Name) {
            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
        }
        else if (props !== true) {
            gen.forIn("key", data, (key) => props === undefined
                ? unevaluatedPropCode(key)
                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
        }
        it.props = true;
        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
        function unevaluatedPropCode(key) {
            if (schema === false) {
                cxt.setParams({ unevaluatedProperty: key });
                cxt.error();
                if (!allErrors)
                    gen.break();
                return;
            }
            if (!(0, util_1.alwaysValidSchema)(it, schema)) {
                const valid = gen.name("valid");
                cxt.subschema({
                    keyword: "unevaluatedProperties",
                    dataProp: key,
                    dataPropType: util_1.Type.Str,
                }, valid);
                if (!allErrors)
                    gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
        }
        function unevaluatedDynamic(evaluatedProps, key) {
            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;
        }
        function unevaluatedStatic(evaluatedProps, key) {
            const ps = [];
            for (const p in evaluatedProps) {
                if (evaluatedProps[p] === true)
                    ps.push((0, codegen_1._) `${key} !== ${p}`);
            }
            return (0, codegen_1.and)(...ps);
        }
    },
};
exports.default = def;
//# sourceMappingURL=unevaluatedProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to constant",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValue: ${schemaCode}}`,
};
const def = {
    keyword: "const",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || (schema && typeof schema == "object")) {
            cxt.fail$data((0, codegen_1._) `!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        }
        else {
            cxt.fail((0, codegen_1._) `${schema} !== ${data}`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=const.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dependencies_1 = require("../applicator/dependencies");
const def = {
    keyword: "dependentRequired",
    type: "object",
    schemaType: "object",
    error: dependencies_1.error,
    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),
};
exports.default = def;
//# sourceMappingURL=dependentRequired.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: "must be equal to one of the allowed values",
    params: ({ schemaCode }) => (0, codegen_1._) `{allowedValues: ${schemaCode}}`,
};
const def = {
    keyword: "enum",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
            throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => (eql !== null && eql !== void 0 ? eql : (eql = (0, util_1.useFunc)(gen, equal_1.default)));
        let valid;
        if (useLoop || $data) {
            valid = gen.let("valid");
            cxt.block$data(valid, loopEnum);
        }
        else {
            /* istanbul ignore if */
            if (!Array.isArray(schema))
                throw new Error("ajv implementation error");
            const vSchema = gen.const("vSchema", schemaCode);
            valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
        }
        cxt.pass(valid);
        function loopEnum() {
            gen.assign(valid, false);
            gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._) `${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i) {
            const sch = schema[i];
            return typeof sch === "object" && sch !== null
                ? (0, codegen_1._) `${getEql()}(${data}, ${vSchema}[${i}])`
                : (0, codegen_1._) `${data} === ${sch}`;
        }
    },
};
exports.default = def;
//# sourceMappingURL=enum.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const limitNumber_1 = require("./limitNumber");
const multipleOf_1 = require("./multipleOf");
const limitLength_1 = require("./limitLength");
const pattern_1 = require("./pattern");
const limitProperties_1 = require("./limitProperties");
const required_1 = require("./required");
const limitItems_1 = require("./limitItems");
const uniqueItems_1 = require("./uniqueItems");
const const_1 = require("./const");
const enum_1 = require("./enum");
const validation = [
    // number
    limitNumber_1.default,
    multipleOf_1.default,
    // string
    limitLength_1.default,
    pattern_1.default,
    // object
    limitProperties_1.default,
    required_1.default,
    // array
    limitItems_1.default,
    uniqueItems_1.default,
    // any
    { keyword: "type", schemaType: ["string", "array"] },
    { keyword: "nullable", schemaType: "boolean" },
    const_1.default,
    enum_1.default,
];
exports.default = validation;
//# sourceMappingURL=index.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../compile/util");
const def = {
    keyword: ["maxContains", "minContains"],
    type: "array",
    schemaType: "number",
    code({ keyword, parentSchema, it }) {
        if (parentSchema.contains === undefined) {
            (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=limitContains.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} items`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxItems", "minItems"],
    type: "array",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `${data}.length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitItems.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const ucs2length_1 = require("../../runtime/ucs2length");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} characters`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxLength", "minLength"],
    type: "string",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._) `${data}.length` : (0, codegen_1._) `${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._) `${len} ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitLength.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const ops = codegen_1.operators;
const KWDs = {
    maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
    minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
    exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
    exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE },
};
const error = {
    message: ({ keyword, schemaCode }) => (0, codegen_1.str) `must be ${KWDs[keyword].okStr} ${schemaCode}`,
    params: ({ keyword, schemaCode }) => (0, codegen_1._) `{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`,
};
const def = {
    keyword: Object.keys(KWDs),
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._) `${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
    },
};
exports.default = def;
//# sourceMappingURL=limitNumber.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str) `must NOT have ${comp} than ${schemaCode} properties`;
    },
    params: ({ schemaCode }) => (0, codegen_1._) `{limit: ${schemaCode}}`,
};
const def = {
    keyword: ["maxProperties", "minProperties"],
    type: "object",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._) `Object.keys(${data}).length ${op} ${schemaCode}`);
    },
};
exports.default = def;
//# sourceMappingURL=limitProperties.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must be multiple of ${schemaCode}`,
    params: ({ schemaCode }) => (0, codegen_1._) `{multipleOf: ${schemaCode}}`,
};
const def = {
    keyword: "multipleOf",
    type: "number",
    schemaType: "number",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec
            ? (0, codegen_1._) `Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}`
            : (0, codegen_1._) `${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._) `(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
    },
};
exports.default = def;
//# sourceMappingURL=multipleOf.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const util_1 = require("../../compile/util");
const codegen_1 = require("../../compile/codegen");
const error = {
    message: ({ schemaCode }) => (0, codegen_1.str) `must match pattern "${schemaCode}"`,
    params: ({ schemaCode }) => (0, codegen_1._) `{pattern: ${schemaCode}}`,
};
const def = {
    keyword: "pattern",
    type: "string",
    schemaType: "string",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
            const { regExp } = it.opts.code;
            const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._) `new RegExp` : (0, util_1.useFunc)(gen, regExp);
            const valid = gen.let("valid");
            gen.try(() => gen.assign(valid, (0, codegen_1._) `${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
            cxt.fail$data((0, codegen_1._) `!${valid}`);
        }
        else {
            const regExp = (0, code_1.usePattern)(cxt, schema);
            cxt.fail$data((0, codegen_1._) `!${regExp}.test(${data})`);
        }
    },
};
exports.default = def;
//# sourceMappingURL=pattern.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const code_1 = require("../code");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
    message: ({ params: { missingProperty } }) => (0, codegen_1.str) `must have required property '${missingProperty}'`,
    params: ({ params: { missingProperty } }) => (0, codegen_1._) `{missingProperty: ${missingProperty}}`,
};
const def = {
    keyword: "required",
    type: "object",
    schemaType: "array",
    $data: true,
    error,
    code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
            return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
            allErrorsMode();
        else
            exitOnErrorMode();
        if (opts.strictRequired) {
            const props = cxt.parentSchema.properties;
            const { definedProperties } = cxt.it;
            for (const requiredKey of schema) {
                if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === undefined && !definedProperties.has(requiredKey)) {
                    const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
                    const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
                    (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
                }
            }
        }
        function allErrorsMode() {
            if (useLoop || $data) {
                cxt.block$data(codegen_1.nil, loopAllRequired);
            }
            else {
                for (const prop of schema) {
                    (0, code_1.checkReportMissingProp)(cxt, prop);
                }
            }
        }
        function exitOnErrorMode() {
            const missing = gen.let("missing");
            if (useLoop || $data) {
                const valid = gen.let("valid", true);
                cxt.block$data(valid, () => loopUntilMissing(missing, valid));
                cxt.ok(valid);
            }
            else {
                gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
                (0, code_1.reportMissingProp)(cxt, missing);
                gen.else();
            }
        }
        function loopAllRequired() {
            gen.forOf("prop", schemaCode, (prop) => {
                cxt.setParams({ missingProperty: prop });
                gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
            });
        }
        function loopUntilMissing(missing, valid) {
            cxt.setParams({ missingProperty: missing });
            gen.forOf(missing, schemaCode, () => {
                gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
                gen.if((0, codegen_1.not)(valid), () => {
                    cxt.error();
                    gen.break();
                });
            }, codegen_1.nil);
        }
    },
};
exports.default = def;
//# sourceMappingURL=required.js.map"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dataType_1 = require("../../compile/validate/dataType");
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const equal_1 = require("../../runtime/equal");
const error = {
    message: ({ params: { i, j } }) => (0, codegen_1.str) `must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
    params: ({ params: { i, j } }) => (0, codegen_1._) `{i: ${i}, j: ${j}}`,
};
const def = {
    keyword: "uniqueItems",
    type: "array",
    schemaType: "boolean",
    $data: true,
    error,
    code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
            return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._) `${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
            const i = gen.let("i", (0, codegen_1._) `${data}.length`);
            const j = gen.let("j");
            cxt.setParams({ i, j });
            gen.assign(valid, true);
            gen.if((0, codegen_1._) `${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        function canOptimize() {
            return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i, j) {
            const item = gen.name("item");
            const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
            const indices = gen.const("indices", (0, codegen_1._) `{}`);
            gen.for((0, codegen_1._) `;${i}--;`, () => {
                gen.let(item, (0, codegen_1._) `${data}[${i}]`);
                gen.if(wrongType, (0, codegen_1._) `continue`);
                if (itemTypes.length > 1)
                    gen.if((0, codegen_1._) `typeof ${item} == "string"`, (0, codegen_1._) `${item} += "_"`);
                gen
                    .if((0, codegen_1._) `typeof ${indices}[${item}] == "number"`, () => {
                    gen.assign(j, (0, codegen_1._) `${indices}[${item}]`);
                    cxt.error();
                    gen.assign(valid, false).break();
                })
                    .code((0, codegen_1._) `${indices}[${item}] = ${i}`);
            });
        }
        function loopN2(i, j) {
            const eql = (0, util_1.useFunc)(gen, equal_1.default);
            const outer = gen.name("outer");
            gen.label(outer).for((0, codegen_1._) `;${i}--;`, () => gen.for((0, codegen_1._) `${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._) `${eql}(${data}[${i}], ${data}[${j}])`, () => {
                cxt.error();
                gen.assign(valid, false).break(outer);
            })));
        }
    },
};
exports.default = def;
//# sourceMappingURL=uniqueItems.js.map{
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)",
  "type": "object",
  "required": ["$data"],
  "properties": {
    "$data": {
      "type": "string",
      "anyOf": [{"format": "relative-json-pointer"}, {"format": "json-pointer"}]
    }
  },
  "additionalProperties": false
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/applicator": true
  },
  "$recursiveAnchor": true,

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "additionalItems": {"$recursiveRef": "#"},
    "unevaluatedItems": {"$recursiveRef": "#"},
    "items": {
      "anyOf": [{"$recursiveRef": "#"}, {"$ref": "#/$defs/schemaArray"}]
    },
    "contains": {"$recursiveRef": "#"},
    "additionalProperties": {"$recursiveRef": "#"},
    "unevaluatedProperties": {"$recursiveRef": "#"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {
        "$recursiveRef": "#"
      }
    },
    "propertyNames": {"$recursiveRef": "#"},
    "if": {"$recursiveRef": "#"},
    "then": {"$recursiveRef": "#"},
    "else": {"$recursiveRef": "#"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$recursiveRef": "#"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$recursiveRef": "#"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "contentSchema": {"$recursiveRef": "#"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true
  },
  "$recursiveAnchor": true,

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$anchor": {
      "type": "string",
      "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveRef": {
      "type": "string",
      "format": "uri-reference"
    },
    "$recursiveAnchor": {
      "type": "boolean",
      "default": false
    },
    "$vocabulary": {
      "type": "object",
      "propertyNames": {
        "type": "string",
        "format": "uri"
      },
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/format",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/format": true
  },
  "$recursiveAnchor": true,

  "title": "Format vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true
  },
  "$recursiveAnchor": true,

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/validation": true
  },
  "$recursiveAnchor": true,

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "https://json-schema.org/draft/2019-09/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2019-09/vocab/core": true,
    "https://json-schema.org/draft/2019-09/vocab/applicator": true,
    "https://json-schema.org/draft/2019-09/vocab/validation": true,
    "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
    "https://json-schema.org/draft/2019-09/vocab/format": false,
    "https://json-schema.org/draft/2019-09/vocab/content": true
  },
  "$recursiveAnchor": true,

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "properties": {
    "definitions": {
      "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.",
      "type": "object",
      "additionalProperties": {"$recursiveRef": "#"},
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$recursiveRef": "#"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      }
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/applicator",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/applicator": true
  },
  "$dynamicAnchor": "meta",

  "title": "Applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "prefixItems": {"$ref": "#/$defs/schemaArray"},
    "items": {"$dynamicRef": "#meta"},
    "contains": {"$dynamicRef": "#meta"},
    "additionalProperties": {"$dynamicRef": "#meta"},
    "properties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependentSchemas": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "default": {}
    },
    "propertyNames": {"$dynamicRef": "#meta"},
    "if": {"$dynamicRef": "#meta"},
    "then": {"$dynamicRef": "#meta"},
    "else": {"$dynamicRef": "#meta"},
    "allOf": {"$ref": "#/$defs/schemaArray"},
    "anyOf": {"$ref": "#/$defs/schemaArray"},
    "oneOf": {"$ref": "#/$defs/schemaArray"},
    "not": {"$dynamicRef": "#meta"}
  },
  "$defs": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$dynamicRef": "#meta"}
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/content",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Content vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "contentEncoding": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentSchema": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/core",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "$ref": "#/$defs/uriReferenceString",
      "$comment": "Non-empty fragments not allowed.",
      "pattern": "^[^#]*#?$"
    },
    "$schema": {"$ref": "#/$defs/uriString"},
    "$ref": {"$ref": "#/$defs/uriReferenceString"},
    "$anchor": {"$ref": "#/$defs/anchorString"},
    "$dynamicRef": {"$ref": "#/$defs/uriReferenceString"},
    "$dynamicAnchor": {"$ref": "#/$defs/anchorString"},
    "$vocabulary": {
      "type": "object",
      "propertyNames": {"$ref": "#/$defs/uriString"},
      "additionalProperties": {
        "type": "boolean"
      }
    },
    "$comment": {
      "type": "string"
    },
    "$defs": {
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"}
    }
  },
  "$defs": {
    "anchorString": {
      "type": "string",
      "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$"
    },
    "uriString": {
      "type": "string",
      "format": "uri"
    },
    "uriReferenceString": {
      "type": "string",
      "format": "uri-reference"
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Format vocabulary meta-schema for annotation results",
  "type": ["object", "boolean"],
  "properties": {
    "format": {"type": "string"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/meta-data",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true
  },
  "$dynamicAnchor": "meta",

  "title": "Meta-data vocabulary meta-schema",

  "type": ["object", "boolean"],
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "deprecated": {
      "type": "boolean",
      "default": false
    },
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "writeOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true
  },
  "$dynamicAnchor": "meta",

  "title": "Unevaluated applicator vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "unevaluatedItems": {"$dynamicRef": "#meta"},
    "unevaluatedProperties": {"$dynamicRef": "#meta"}
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/meta/validation",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/validation": true
  },
  "$dynamicAnchor": "meta",

  "title": "Validation vocabulary meta-schema",
  "type": ["object", "boolean"],
  "properties": {
    "type": {
      "anyOf": [
        {"$ref": "#/$defs/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/$defs/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "const": true,
    "enum": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/$defs/nonNegativeInteger"},
    "minLength": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "maxItems": {"$ref": "#/$defs/nonNegativeInteger"},
    "minItems": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "maxContains": {"$ref": "#/$defs/nonNegativeInteger"},
    "minContains": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 1
    },
    "maxProperties": {"$ref": "#/$defs/nonNegativeInteger"},
    "minProperties": {"$ref": "#/$defs/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/$defs/stringArray"},
    "dependentRequired": {
      "type": "object",
      "additionalProperties": {
        "$ref": "#/$defs/stringArray"
      }
    }
  },
  "$defs": {
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "$ref": "#/$defs/nonNegativeInteger",
      "default": 0
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  }
}
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://json-schema.org/draft/2020-12/schema",
  "$vocabulary": {
    "https://json-schema.org/draft/2020-12/vocab/core": true,
    "https://json-schema.org/draft/2020-12/vocab/applicator": true,
    "https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
    "https://json-schema.org/draft/2020-12/vocab/validation": true,
    "https://json-schema.org/draft/2020-12/vocab/meta-data": true,
    "https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
    "https://json-schema.org/draft/2020-12/vocab/content": true
  },
  "$dynamicAnchor": "meta",

  "title": "Core and Validation specifications meta-schema",
  "allOf": [
    {"$ref": "meta/core"},
    {"$ref": "meta/applicator"},
    {"$ref": "meta/unevaluated"},
    {"$ref": "meta/validation"},
    {"$ref": "meta/meta-data"},
    {"$ref": "meta/format-annotation"},
    {"$ref": "meta/content"}
  ],
  "type": ["object", "boolean"],
  "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
  "properties": {
    "definitions": {
      "$comment": "\"definitions\" has been replaced by \"$defs\".",
      "type": "object",
      "additionalProperties": {"$dynamicRef": "#meta"},
      "deprecated": true,
      "default": {}
    },
    "dependencies": {
      "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$dynamicRef": "#meta"}, {"$ref": "meta/validation#/$defs/stringArray"}]
      },
      "deprecated": true,
      "default": {}
    },
    "$recursiveAnchor": {
      "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
      "$ref": "meta/core#/$defs/anchorString",
      "deprecated": true
    },
    "$recursiveRef": {
      "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
      "$ref": "meta/core#/$defs/uriReferenceString",
      "deprecated": true
    }
  }
}
{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "http://json-schema.org/draft-06/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": {},
    "examples": {
      "type": "array",
      "items": {}
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": {}
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": {},
    "enum": {
      "type": "array",
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": {}
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://json-schema.org/draft-07/schema#",
  "title": "Core schema meta-schema",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    },
    "nonNegativeInteger": {
      "type": "integer",
      "minimum": 0
    },
    "nonNegativeIntegerDefault0": {
      "allOf": [{"$ref": "#/definitions/nonNegativeInteger"}, {"default": 0}]
    },
    "simpleTypes": {
      "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
    },
    "stringArray": {
      "type": "array",
      "items": {"type": "string"},
      "uniqueItems": true,
      "default": []
    }
  },
  "type": ["object", "boolean"],
  "properties": {
    "$id": {
      "type": "string",
      "format": "uri-reference"
    },
    "$schema": {
      "type": "string",
      "format": "uri"
    },
    "$ref": {
      "type": "string",
      "format": "uri-reference"
    },
    "$comment": {
      "type": "string"
    },
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "default": true,
    "readOnly": {
      "type": "boolean",
      "default": false
    },
    "examples": {
      "type": "array",
      "items": true
    },
    "multipleOf": {
      "type": "number",
      "exclusiveMinimum": 0
    },
    "maximum": {
      "type": "number"
    },
    "exclusiveMaximum": {
      "type": "number"
    },
    "minimum": {
      "type": "number"
    },
    "exclusiveMinimum": {
      "type": "number"
    },
    "maxLength": {"$ref": "#/definitions/nonNegativeInteger"},
    "minLength": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "pattern": {
      "type": "string",
      "format": "regex"
    },
    "additionalItems": {"$ref": "#"},
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}],
      "default": true
    },
    "maxItems": {"$ref": "#/definitions/nonNegativeInteger"},
    "minItems": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "uniqueItems": {
      "type": "boolean",
      "default": false
    },
    "contains": {"$ref": "#"},
    "maxProperties": {"$ref": "#/definitions/nonNegativeInteger"},
    "minProperties": {"$ref": "#/definitions/nonNegativeIntegerDefault0"},
    "required": {"$ref": "#/definitions/stringArray"},
    "additionalProperties": {"$ref": "#"},
    "definitions": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "properties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "default": {}
    },
    "patternProperties": {
      "type": "object",
      "additionalProperties": {"$ref": "#"},
      "propertyNames": {"format": "regex"},
      "default": {}
    },
    "dependencies": {
      "type": "object",
      "additionalProperties": {
        "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/stringArray"}]
      }
    },
    "propertyNames": {"$ref": "#"},
    "const": true,
    "enum": {
      "type": "array",
      "items": true,
      "minItems": 1,
      "uniqueItems": true
    },
    "type": {
      "anyOf": [
        {"$ref": "#/definitions/simpleTypes"},
        {
          "type": "array",
          "items": {"$ref": "#/definitions/simpleTypes"},
          "minItems": 1,
          "uniqueItems": true
        }
      ]
    },
    "format": {"type": "string"},
    "contentMediaType": {"type": "string"},
    "contentEncoding": {"type": "string"},
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"}
  },
  "default": true
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/json-schema-secure.json#",
  "title": "Meta-schema for the security assessment of JSON Schemas",
  "description": "If a JSON AnySchema fails validation against this meta-schema, it may be unsafe to validate untrusted data",
  "definitions": {
    "schemaArray": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#"}
    }
  },
  "dependencies": {
    "patternProperties": {
      "description": "prevent slow validation of large property names",
      "required": ["propertyNames"],
      "properties": {
        "propertyNames": {
          "required": ["maxLength"]
        }
      }
    },
    "uniqueItems": {
      "description": "prevent slow validation of large non-scalar arrays",
      "if": {
        "properties": {
          "uniqueItems": {"const": true},
          "items": {
            "properties": {
              "type": {
                "anyOf": [
                  {
                    "enum": ["object", "array"]
                  },
                  {
                    "type": "array",
                    "contains": {"enum": ["object", "array"]}
                  }
                ]
              }
            }
          }
        }
      },
      "then": {
        "required": ["maxItems"]
      }
    },
    "pattern": {
      "description": "prevent slow pattern matching of large strings",
      "required": ["maxLength"]
    },
    "format": {
      "description": "prevent slow format validation of large strings",
      "required": ["maxLength"]
    }
  },
  "properties": {
    "additionalItems": {"$ref": "#"},
    "additionalProperties": {"$ref": "#"},
    "dependencies": {
      "additionalProperties": {
        "anyOf": [{"type": "array"}, {"$ref": "#"}]
      }
    },
    "items": {
      "anyOf": [{"$ref": "#"}, {"$ref": "#/definitions/schemaArray"}]
    },
    "definitions": {
      "additionalProperties": {"$ref": "#"}
    },
    "patternProperties": {
      "additionalProperties": {"$ref": "#"}
    },
    "properties": {
      "additionalProperties": {"$ref": "#"}
    },
    "if": {"$ref": "#"},
    "then": {"$ref": "#"},
    "else": {"$ref": "#"},
    "allOf": {"$ref": "#/definitions/schemaArray"},
    "anyOf": {"$ref": "#/definitions/schemaArray"},
    "oneOf": {"$ref": "#/definitions/schemaArray"},
    "not": {"$ref": "#"},
    "contains": {"$ref": "#"},
    "propertyNames": {"$ref": "#"}
  }
}
{
  "name": "ajv",
  "version": "8.18.0",
  "description": "Another JSON Schema Validator",
  "main": "dist/ajv.js",
  "types": "dist/ajv.d.ts",
  "files": [
    "lib/",
    "dist/",
    ".runkit_example.js"
  ],
  "sideEffects": false,
  "scripts": {
    "eslint": "eslint \"lib/**/*.ts\" \"spec/**/*.*s\" --ignore-pattern spec/JSON-Schema-Test-Suite",
    "prettier:write": "prettier --write \"./**/*.{json,yaml,js,ts}\"",
    "prettier:check": "prettier --list-different \"./**/*.{json,yaml,js,ts}\"",
    "test-spec": "cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register \"spec/**/*.spec.{ts,js}\" -R dot",
    "test-codegen": "nyc cross-env TS_NODE_PROJECT=spec/tsconfig.json mocha -r ts-node/register 'spec/codegen.spec.ts' -R spec",
    "test-debug": "npm run test-spec -- --inspect-brk",
    "test-cov": "nyc npm run test-spec",
    "rollup": "rm -rf bundle && rollup -c",
    "bundle": "rm -rf bundle && node ./scripts/bundle.js ajv ajv7 ajv7 && node ./scripts/bundle.js 2019 ajv2019 ajv2019 && node ./scripts/bundle.js 2020 ajv2020 ajv2020 && node ./scripts/bundle.js jtd ajvJTD ajvJTD",
    "build": "rm -rf dist && tsc && cp -r lib/refs dist && rm dist/refs/json-schema-2019-09/index.ts && rm dist/refs/json-schema-2020-12/index.ts && rm dist/refs/jtd-schema.ts",
    "json-tests": "rm -rf spec/_json/*.js && node scripts/jsontests",
    "test-karma": "karma start",
    "test-browser": "rm -rf .browser && npm run bundle && scripts/prepare-tests && karma start",
    "test-all": "npm run test-cov && if-node-version 12 npm run test-browser",
    "test": "npm run json-tests && npm run prettier:check && npm run eslint && npm link && npm link --legacy-peer-deps ajv && npm run test-cov",
    "test-ci": "AJV_FULL_TEST=true npm test",
    "prepublish": "npm run build",
    "benchmark": "npm i && npm run build && npm link && cd ./benchmark && npm link --legacy-peer-deps ajv && npm i && node ./jtd",
    "docs:dev": "./scripts/prepare-site && vuepress dev docs",
    "docs:build": "./scripts/prepare-site && vuepress build docs"
  },
  "nyc": {
    "exclude": [
      "**/spec/**",
      "node_modules"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ]
  },
  "repository": "ajv-validator/ajv",
  "keywords": [
    "JSON",
    "schema",
    "validator",
    "validation",
    "jsonschema",
    "json-schema",
    "json-schema-validator",
    "json-schema-validation"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": "https://github.com/ajv-validator/ajv/issues",
  "homepage": "https://ajv.js.org",
  "runkitExampleFilename": ".runkit_example.js",
  "dependencies": {
    "fast-deep-equal": "^3.1.3",
    "fast-uri": "^3.0.1",
    "json-schema-traverse": "^1.0.0",
    "require-from-string": "^2.0.2"
  },
  "devDependencies": {
    "@ajv-validator/config": "^0.5.0",
    "@rollup/plugin-commonjs": "^25.0.7",
    "@rollup/plugin-json": "^6.1.0",
    "@rollup/plugin-node-resolve": "^15.2.3",
    "@rollup/plugin-typescript": "^11.1.6",
    "@types/chai": "^4.3.11",
    "@types/mocha": "^10.0.6",
    "@types/node": "^20.11.30",
    "@types/require-from-string": "^1.2.3",
    "@typescript-eslint/eslint-plugin": "^7.3.1",
    "@typescript-eslint/parser": "^7.3.1",
    "ajv-formats": "^3.0.1",
    "browserify": "^17.0.0",
    "chai": "^4.4.1",
    "cross-env": "^7.0.3",
    "dayjs": "^1.11.10",
    "dayjs-plugin-utc": "^0.1.2",
    "eslint": "^8.57.0",
    "eslint-config-prettier": "^9.1.0",
    "glob": "^10.3.10",
    "husky": "^9.0.11",
    "if-node-version": "^1.1.1",
    "jimp": "^0.22.10",
    "js-beautify": "^1.15.1",
    "json-schema-test": "^2.0.0",
    "karma": "^6.4.2",
    "karma-chrome-launcher": "^3.2.0",
    "karma-mocha": "^2.0.1",
    "lint-staged": "^15.2.2",
    "mocha": "^10.3.0",
    "module-from-string": "^3.3.0",
    "node-fetch": "^3.3.2",
    "nyc": "^15.1.0",
    "prettier": "3.0.3",
    "re2": "^1.20.9",
    "rollup": "^2.79.1",
    "rollup-plugin-terser": "^7.0.2",
    "ts-node": "^10.9.2",
    "tsify": "^5.0.4",
    "typescript": "5.3.3",
    "uri-js": "^4.4.1"
  },
  "collective": {
    "type": "opencollective",
    "url": "https://opencollective.com/ajv"
  },
  "funding": {
    "type": "github",
    "url": "https://github.com/sponsors/epoberezkin"
  },
  "prettier": "@ajv-validator/config/prettierrc.json",
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged && npm test"
    }
  },
  "lint-staged": {
    "*.{json,yaml,js,ts}": "prettier --write"
  }
}
extends: eslint:recommended
env:
  node: true
  browser: true
rules:
  block-scoped-var: 2
  complexity: [2, 15]
  curly: [2, multi-or-nest, consistent]
  dot-location: [2, property]
  dot-notation: 2
  indent: [2, 2, SwitchCase: 1]
  linebreak-style: [2, unix]
  new-cap: 2
  no-console: [2, allow: [warn, error]]
  no-else-return: 2
  no-eq-null: 2
  no-fallthrough: 2
  no-invalid-this: 2
  no-return-assign: 2
  no-shadow: 1
  no-trailing-spaces: 2
  no-use-before-define: [2, nofunc]
  quotes: [2, single, avoid-escape]
  semi: [2, always]
  strict: [2, global]
  valid-jsdoc: [2, requireReturn: false]
  no-control-regex: 0
github: epoberezkin
tidelift: "npm/json-schema-traverse"
name: build

on:
  push:
    branches: [master]
  pull_request:
    branches: ["*"]

jobs:
  build:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [10.x, 12.x, 14.x]

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v1
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm install
      - run: npm test
      - name: Coveralls
        uses: coverallsapp/github-action@master
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
name: publish

on:
  release:
    types: [published]

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: 14
          registry-url: https://registry.npmjs.org/
      - run: npm install
      - run: npm test
      - name: Publish beta version to npm
        if: "github.event.release.prerelease"
        run: npm publish --tag beta
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      - name: Publish to npm
        if: "!github.event.release.prerelease"
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
MIT License

Copyright (c) 2017 Evgeny Poberezkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# json-schema-traverse
Traverse JSON Schema passing each schema object to callback

[![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild)
[![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse)
[![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master)


## Install

```
npm install json-schema-traverse
```


## Usage

```javascript
const traverse = require('json-schema-traverse');
const schema = {
  properties: {
    foo: {type: 'string'},
    bar: {type: 'integer'}
  }
};

traverse(schema, {cb});
// cb is called 3 times with:
// 1. root schema
// 2. {type: 'string'}
// 3. {type: 'integer'}

// Or:

traverse(schema, {cb: {pre, post}});
// pre is called 3 times with:
// 1. root schema
// 2. {type: 'string'}
// 3. {type: 'integer'}
//
// post is called 3 times with:
// 1. {type: 'string'}
// 2. {type: 'integer'}
// 3. root schema

```

Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is.  Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed.

Callback is passed these parameters:

- _schema_: the current schema object
- _JSON pointer_: from the root schema to the current schema object
- _root schema_: the schema passed to `traverse` object
- _parent JSON pointer_: from the root schema to the parent schema object (see below)
- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.)
- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema
- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'`


## Traverse objects in all unknown keywords

```javascript
const traverse = require('json-schema-traverse');
const schema = {
  mySchema: {
    minimum: 1,
    maximum: 2
  }
};

traverse(schema, {allKeys: true, cb});
// cb is called 2 times with:
// 1. root schema
// 2. mySchema
```

Without option `allKeys: true` callback will be called only with root schema.


## Enterprise support

json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers.


## Security contact

To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues.


## License

[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE)
'use strict';

var traverse = module.exports = function (schema, opts, cb) {
  // Legacy support for v0.3.1 and earlier.
  if (typeof opts == 'function') {
    cb = opts;
    opts = {};
  }

  cb = opts.cb || cb;
  var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
  var post = cb.post || function() {};

  _traverse(opts, pre, post, schema, '', schema);
};


traverse.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};

traverse.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};

traverse.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};

traverse.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};


function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse.arrayKeywords) {
          for (var i=0; i<sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse.propsKeywords) {
        if (sch && typeof sch == 'object') {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
        _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}


function escapeJsonPtr(str) {
  return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
{
  "name": "json-schema-traverse",
  "version": "1.0.0",
  "description": "Traverse JSON Schema passing each schema object to callback",
  "main": "index.js",
  "types": "index.d.ts",
  "scripts": {
    "eslint": "eslint index.js spec",
    "test-spec": "mocha spec -R spec",
    "test": "npm run eslint && nyc npm run test-spec"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/epoberezkin/json-schema-traverse.git"
  },
  "keywords": [
    "JSON-Schema",
    "traverse",
    "iterate"
  ],
  "author": "Evgeny Poberezkin",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/epoberezkin/json-schema-traverse/issues"
  },
  "homepage": "https://github.com/epoberezkin/json-schema-traverse#readme",
  "devDependencies": {
    "eslint": "^7.3.1",
    "mocha": "^8.0.1",
    "nyc": "^15.0.0",
    "pre-commit": "^1.2.2"
  },
  "nyc": {
    "exclude": [
      "**/spec/**",
      "node_modules"
    ],
    "reporter": [
      "lcov",
      "text-summary"
    ]
  }
}
parserOptions:
  ecmaVersion: 6
globals:
  beforeEach: false
  describe: false
  it: false
'use strict';

var schema = {
  additionalItems: subschema('additionalItems'),
  items: subschema('items'),
  contains: subschema('contains'),
  additionalProperties: subschema('additionalProperties'),
  propertyNames: subschema('propertyNames'),
  not: subschema('not'),
  allOf: [
    subschema('allOf_0'),
    subschema('allOf_1'),
    {
      items: [
        subschema('items_0'),
        subschema('items_1'),
      ]
    }
  ],
  anyOf: [
    subschema('anyOf_0'),
    subschema('anyOf_1'),
  ],
  oneOf: [
    subschema('oneOf_0'),
    subschema('oneOf_1'),
  ],
  definitions: {
    foo: subschema('definitions_foo'),
    bar: subschema('definitions_bar'),
  },
  properties: {
    foo: subschema('properties_foo'),
    bar: subschema('properties_bar'),
  },
  patternProperties: {
    foo: subschema('patternProperties_foo'),
    bar: subschema('patternProperties_bar'),
  },
  dependencies: {
    foo: subschema('dependencies_foo'),
    bar: subschema('dependencies_bar'),
  },
  required: ['foo', 'bar']
};


function subschema(keyword) {
  var sch = {
    properties: {},
    additionalProperties: false,
    additionalItems: false,
    anyOf: [
      {format: 'email'},
      {format: 'hostname'}
    ]
  };
  sch.properties['foo_' + keyword] = {title: 'foo'};
  sch.properties['bar_' + keyword] = {title: 'bar'};
  return sch;
}


module.exports = {
  schema: schema,

  // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
  expectedCalls: [[schema, '', schema, undefined, undefined, undefined, undefined]]
    .concat(expectedCalls('additionalItems'))
    .concat(expectedCalls('items'))
    .concat(expectedCalls('contains'))
    .concat(expectedCalls('additionalProperties'))
    .concat(expectedCalls('propertyNames'))
    .concat(expectedCalls('not'))
    .concat(expectedCallsChild('allOf', 0))
    .concat(expectedCallsChild('allOf', 1))
    .concat([
      [schema.allOf[2], '/allOf/2', schema, '', 'allOf', schema, 2],
      [schema.allOf[2].items[0], '/allOf/2/items/0', schema, '/allOf/2', 'items', schema.allOf[2], 0],
      [schema.allOf[2].items[0].properties.foo_items_0, '/allOf/2/items/0/properties/foo_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'foo_items_0'],
      [schema.allOf[2].items[0].properties.bar_items_0, '/allOf/2/items/0/properties/bar_items_0', schema, '/allOf/2/items/0', 'properties', schema.allOf[2].items[0], 'bar_items_0'],
      [schema.allOf[2].items[0].anyOf[0], '/allOf/2/items/0/anyOf/0', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 0],
      [schema.allOf[2].items[0].anyOf[1], '/allOf/2/items/0/anyOf/1', schema, '/allOf/2/items/0', 'anyOf', schema.allOf[2].items[0], 1],

      [schema.allOf[2].items[1], '/allOf/2/items/1', schema, '/allOf/2', 'items', schema.allOf[2], 1],
      [schema.allOf[2].items[1].properties.foo_items_1, '/allOf/2/items/1/properties/foo_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'foo_items_1'],
      [schema.allOf[2].items[1].properties.bar_items_1, '/allOf/2/items/1/properties/bar_items_1', schema, '/allOf/2/items/1', 'properties', schema.allOf[2].items[1], 'bar_items_1'],
      [schema.allOf[2].items[1].anyOf[0], '/allOf/2/items/1/anyOf/0', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 0],
      [schema.allOf[2].items[1].anyOf[1], '/allOf/2/items/1/anyOf/1', schema, '/allOf/2/items/1', 'anyOf', schema.allOf[2].items[1], 1]
    ])
    .concat(expectedCallsChild('anyOf', 0))
    .concat(expectedCallsChild('anyOf', 1))
    .concat(expectedCallsChild('oneOf', 0))
    .concat(expectedCallsChild('oneOf', 1))
    .concat(expectedCallsChild('definitions', 'foo'))
    .concat(expectedCallsChild('definitions', 'bar'))
    .concat(expectedCallsChild('properties', 'foo'))
    .concat(expectedCallsChild('properties', 'bar'))
    .concat(expectedCallsChild('patternProperties', 'foo'))
    .concat(expectedCallsChild('patternProperties', 'bar'))
    .concat(expectedCallsChild('dependencies', 'foo'))
    .concat(expectedCallsChild('dependencies', 'bar'))
};


function expectedCalls(keyword) {
  return [
    [schema[keyword], `/${keyword}`, schema, '', keyword, schema, undefined],
    [schema[keyword].properties[`foo_${keyword}`], `/${keyword}/properties/foo_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `foo_${keyword}`],
    [schema[keyword].properties[`bar_${keyword}`], `/${keyword}/properties/bar_${keyword}`, schema, `/${keyword}`, 'properties', schema[keyword], `bar_${keyword}`],
    [schema[keyword].anyOf[0], `/${keyword}/anyOf/0`, schema, `/${keyword}`, 'anyOf', schema[keyword], 0],
    [schema[keyword].anyOf[1], `/${keyword}/anyOf/1`, schema, `/${keyword}`, 'anyOf', schema[keyword], 1]
  ];
}


function expectedCallsChild(keyword, i) {
  return [
    [schema[keyword][i], `/${keyword}/${i}`, schema, '', keyword, schema, i],
    [schema[keyword][i].properties[`foo_${keyword}_${i}`], `/${keyword}/${i}/properties/foo_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `foo_${keyword}_${i}`],
    [schema[keyword][i].properties[`bar_${keyword}_${i}`], `/${keyword}/${i}/properties/bar_${keyword}_${i}`, schema, `/${keyword}/${i}`, 'properties', schema[keyword][i], `bar_${keyword}_${i}`],
    [schema[keyword][i].anyOf[0], `/${keyword}/${i}/anyOf/0`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 0],
    [schema[keyword][i].anyOf[1], `/${keyword}/${i}/anyOf/1`, schema, `/${keyword}/${i}`, 'anyOf', schema[keyword][i], 1]
  ];
}
'use strict';

var traverse = require('../index');
var assert = require('assert');

describe('json-schema-traverse', function() {
  var calls;

  beforeEach(function() {
    calls = [];
  });

  it('should traverse all keywords containing schemas recursively', function() {
    var schema = require('./fixtures/schema').schema;
    var expectedCalls = require('./fixtures/schema').expectedCalls;

    traverse(schema, {cb: callback});
    assert.deepStrictEqual(calls, expectedCalls);
  });

  describe('Legacy v0.3.1 API', function() {
    it('should traverse all keywords containing schemas recursively', function() {
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should work when an options object is provided', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var schema = require('./fixtures/schema').schema;
      var expectedCalls = require('./fixtures/schema').expectedCalls;

      traverse(schema, {}, callback);
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });


  describe('allKeys option', function() {
    var schema = {
      someObject: {
        minimum: 1,
        maximum: 2
      }
    };

    it('should traverse objects with allKeys: true option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined],
        [schema.someObject, '/someObject', schema, '', 'someObject', schema, undefined]
      ];

      traverse(schema, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects with allKeys: false option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {allKeys: false, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT traverse objects without allKeys option', function() {
      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema, '', schema, undefined, undefined, undefined, undefined]
      ];

      traverse(schema, {cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });


    it('should NOT travers objects in standard keywords which value is not a schema', function() {
      var schema2 = {
        const: {foo: 'bar'},
        enum: ['a', 'b'],
        required: ['foo'],
        another: {

        },
        patternProperties: {}, // will not traverse - no properties
        dependencies: true, // will not traverse - invalid
        properties: {
          smaller: {
            type: 'number'
          },
          larger: {
            type: 'number',
            minimum: {$data: '1/smaller'}
          }
        }
      };

      // schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex
      var expectedCalls = [
        [schema2, '', schema2, undefined, undefined, undefined, undefined],
        [schema2.another, '/another', schema2, '', 'another', schema2, undefined],
        [schema2.properties.smaller, '/properties/smaller', schema2, '', 'properties', schema2, 'smaller'],
        [schema2.properties.larger, '/properties/larger', schema2, '', 'properties', schema2, 'larger'],
      ];

      traverse(schema2, {allKeys: true, cb: callback});
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  describe('pre and post', function() {
    var schema = {
      type: 'object',
      properties: {
        name: {type: 'string'},
        age: {type: 'number'}
      }
    };

    it('should traverse schema in pre-order', function() {
      traverse(schema, {cb: {pre}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in post-order', function() {
      traverse(schema, {cb: {post}});
      var expectedCalls = [
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });

    it('should traverse schema in pre- and post-order at the same time', function() {
      traverse(schema, {cb: {pre, post}});
      var expectedCalls = [
        ['pre', schema, '', schema, undefined, undefined, undefined, undefined],
        ['pre', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['post', schema.properties.name, '/properties/name', schema, '', 'properties', schema, 'name'],
        ['pre', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema.properties.age, '/properties/age', schema, '', 'properties', schema, 'age'],
        ['post', schema, '', schema, undefined, undefined, undefined, undefined],
      ];
      assert.deepStrictEqual(calls, expectedCalls);
    });
  });

  function callback() {
    calls.push(Array.prototype.slice.call(arguments));
  }

  function pre() {
    calls.push(['pre'].concat(Array.prototype.slice.call(arguments)));
  }

  function post() {
    calls.push(['post'].concat(Array.prototype.slice.call(arguments)));
  }
});
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
semver(1) -- The semantic versioner for npm
===========================================

## Install

```bash
npm install semver
````

## Usage

As a node module:

```js
const semver = require('semver')

semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean('  =v1.2.3   ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```

You can also just load the module for the function that you care about if
you'd like to minimize your footprint.

```js
// load the whole API at once in a single object
const semver = require('semver')

// or just load the bits you need
// all of them listed here, just pick and choose what you want

// classes
const SemVer = require('semver/classes/semver')
const Comparator = require('semver/classes/comparator')
const Range = require('semver/classes/range')

// functions for working with versions
const semverParse = require('semver/functions/parse')
const semverValid = require('semver/functions/valid')
const semverClean = require('semver/functions/clean')
const semverInc = require('semver/functions/inc')
const semverDiff = require('semver/functions/diff')
const semverMajor = require('semver/functions/major')
const semverMinor = require('semver/functions/minor')
const semverPatch = require('semver/functions/patch')
const semverPrerelease = require('semver/functions/prerelease')
const semverCompare = require('semver/functions/compare')
const semverRcompare = require('semver/functions/rcompare')
const semverCompareLoose = require('semver/functions/compare-loose')
const semverCompareBuild = require('semver/functions/compare-build')
const semverSort = require('semver/functions/sort')
const semverRsort = require('semver/functions/rsort')

// low-level comparators between versions
const semverGt = require('semver/functions/gt')
const semverLt = require('semver/functions/lt')
const semverEq = require('semver/functions/eq')
const semverNeq = require('semver/functions/neq')
const semverGte = require('semver/functions/gte')
const semverLte = require('semver/functions/lte')
const semverCmp = require('semver/functions/cmp')
const semverCoerce = require('semver/functions/coerce')

// working with ranges
const semverSatisfies = require('semver/functions/satisfies')
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
const semverMinSatisfying = require('semver/ranges/min-satisfying')
const semverToComparators = require('semver/ranges/to-comparators')
const semverMinVersion = require('semver/ranges/min-version')
const semverValidRange = require('semver/ranges/valid')
const semverOutside = require('semver/ranges/outside')
const semverGtr = require('semver/ranges/gtr')
const semverLtr = require('semver/ranges/ltr')
const semverIntersects = require('semver/ranges/intersects')
const semverSimplifyRange = require('semver/ranges/simplify')
const semverRangeSubset = require('semver/ranges/subset')
```

As a command-line utility:

```
$ semver -h

A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter

Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence

Options:
-r --range <range>
        Print versions that match the specified range.

-i --increment [<level>]
        Increment a version by the specified level.  Level can
        be one of: major, minor, patch, premajor, preminor,
        prepatch, prerelease, or release.  Default level is 'patch'.
        Only one version may be specified.

--preid <identifier>
        Identifier to be used to prefix premajor, preminor,
        prepatch or prerelease version increments.

-l --loose
        Interpret versions and ranges loosely

-n <0|1|false>
        Base number for prerelease identifier (default: 0).
        Use false to omit the number altogether.

-p --include-prerelease
        Always include prerelease versions in range matching

-c --coerce
        Coerce a string into SemVer if possible
        (does not imply --loose)

--rtl
        Coerce version strings right to left

--ltr
        Coerce version strings left to right (default)

Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.

If no satisfying versions are found, then exits failure.

Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```

## Versions

A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.

A leading `"="` or `"v"` character is stripped off and ignored.
Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer
specification but should not be used anymore.

## Ranges

A `version range` is a set of `comparators` that specify versions
that satisfy the range.

A `comparator` is composed of an `operator` and a `version`.  The set
of primitive `operators` is:

* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal.  If no operator is specified, then equality is assumed,
  so this operator is optional but MAY be included.

For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and
would match the versions `2.0.0` and `3.1.0`, but not the versions
`1.0.1` or `1.1.0`.

Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.

A range is composed of one or more comparator sets, joined by `||`.  A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.

For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.

The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.

### Prerelease Tags

If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.

For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules.  The version
range only accepts prerelease tags on the `1.2.3` version.
Version `3.4.5` *would* satisfy the range because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.

The purpose of this behavior is twofold.  First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range-matching
semantics.

Second, a user who has opted into using a prerelease version has
indicated the intent to use *that specific* set of
alpha/beta/rc versions.  By including a prerelease tag in the range,
the user is indicating that they are aware of the risk.  However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.

Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for range-matching)
by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.

#### Prerelease Identifiers

The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:

```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```

command-line example:

```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```

Which then can be used to increment further:

```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```

To get out of the prerelease phase, use the `release` option:

```bash
$ semver 1.2.4-beta.1 -i release
1.2.4
```

#### Prerelease Identifier Base

The method `.inc` takes an optional parameter 'identifierBase' string
that will let you let your prerelease number as zero-based or one-based.
Set to `false` to omit the prerelease number altogether.
If you do not specify this parameter, it will default to zero-based.

```javascript
semver.inc('1.2.3', 'prerelease', 'beta', '1')
// '1.2.4-beta.1'
```

```javascript
semver.inc('1.2.3', 'prerelease', 'beta', false)
// '1.2.4-beta'
```

command-line example:

```bash
$ semver 1.2.3 -i prerelease --preid beta -n 1
1.2.4-beta.1
```

```bash
$ semver 1.2.3 -i prerelease --preid beta -n false
1.2.4-beta
```

### Advanced Range Syntax

Advanced range syntax desugars to primitive comparators in
deterministic ways.

Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.

#### Hyphen Ranges `X.Y.Z - A.B.C`

Specifies an inclusive set.

* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`

If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.

* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`

If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.

* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`

#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`

Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.

* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
  `includePrerelease` is specified, in which case any version at all
  satisfies)
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)

A partial version range is treated as an X-Range, so the special
character is in fact optional.

* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`

#### Tilde Ranges `~1.2.3` `~1.2` `~1`

Allows patch-level changes if a minor version is specified on the
comparator.  Allows minor-level changes if not.

* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.

#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`

Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple.  In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.

Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.

Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`.  It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.

* `^1.2.3` := `>=1.2.3 <2.0.0-0`
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0`  Note that prereleases in the
  `0.0.3` version *only* will be allowed, if they are greater than or
  equal to `beta`.  So, `0.0.3-pr.2` would be allowed.

When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.

* `^1.2.x` := `>=1.2.0 <2.0.0-0`
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
* `^0.0` := `>=0.0.0 <0.1.0-0`

A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.

* `^1.x` := `>=1.0.0 <2.0.0-0`
* `^0.x` := `>=0.0.0 <1.0.0-0`

### Range Grammar

Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:

```bnf
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= parts
build      ::= parts
parts      ::= part ( '.' part ) *
part       ::= nr | [-0-9A-Za-z]+
```

## Functions

All methods and classes take a final `options` object argument.  All
options in this object are `false` by default.  The options supported
are:

- `loose`: Be more forgiving about not-quite-valid semver strings.
  (Any resulting output will always be 100% strict compliant, of
  course.)  For backwards compatibility reasons, if the `options`
  argument is a boolean value instead of an object, it is interpreted
  to be the `loose` param.
- `includePrerelease`: Set to suppress the [default
  behavior](https://github.com/npm/node-semver#prerelease-tags) of
  excluding prerelease tagged versions from ranges unless they are
  explicitly opted into.

Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.

* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, releaseType, options, identifier, identifierBase)`: 
  Return the version incremented by the release
  type (`major`, `premajor`, `minor`, `preminor`, `patch`,
  `prepatch`, `prerelease`, or `release`), or null if it's not valid
  * `premajor` in one call will bump the version up to the next major
    version and down to a prerelease of that major version.
    `preminor`, and `prepatch` work the same way.
  * If called from a non-prerelease version, `prerelease` will work the
    same as `prepatch`. It increments the patch version and then makes a
    prerelease. If the input version is already a prerelease it simply
    increments it.
  * `release` will remove any prerelease part of the version.
  * `identifier` can be used to prefix `premajor`, `preminor`,
    `prepatch`, or `prerelease` version increments. `identifierBase`
    is the base to be used for the `prerelease` identifier.
* `prerelease(v)`: Returns an array of prerelease components, or null
  if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
  or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
  a `SemVer` object or `null`.

### Comparison

* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
  even if they're not the same string.  You already know how to
  compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
  the corresponding function above.  `"==="` and `"!=="` do simple
  string comparison, but are included for completeness.  Throws if an
  invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
  `v2` is greater.  Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of `compare`.  Sorts an array of versions
  in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
  are equal.  Sorts in ascending order if passed to `Array.sort()`.
* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`.
* `diff(v1, v2)`: Returns the difference between two versions by the release type
  (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
  or null if the versions are the same.

### Sorting

* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild` 
  function.
* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on
  the `compareBuild` function in descending order.

### Comparators

* `intersects(comparator)`: Return true if the comparators intersect

### Ranges

* `validRange(range)`: Return the valid range or null if it's not valid.
* `satisfies(version, range)`: Return true if the version satisfies the
  range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
  that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
  that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can match
  the given range.
* `gtr(version, range)`: Return `true` if the version is greater than all the
  versions possible in the range.
* `ltr(version, range)`: Return `true` if the version is less than all the
  versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
  the bounds of the range in either the high or low direction.  The
  `hilo` argument must be either the string `'>'` or `'<'`.  (This is
  the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the range comparators intersect.
* `simplifyRange(versions, range)`: Return a "simplified" range that
  matches the same items in the `versions` list as the range specified.  Note
  that it does *not* guarantee that it would match the same versions in all
  cases, only for the set of versions provided.  This is useful when
  generating ranges by joining together multiple versions with `||`
  programmatically, to provide the user with something a bit more
  ergonomic.  If the provided range is shorter in string-length than the
  generated range, then that is returned.
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
  entirely contained by the `superRange` range.

Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range!  For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.

If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.

### Coercion

* `coerce(version, options)`: Coerces a string to semver if possible

This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters).  Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`).  All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`).  Only text which lacks digits will fail coercion (`version one`
is not valid).  The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`).  The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).

If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple.  For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`.  `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.

If the `options.includePrerelease` flag is set, then the `coerce` result will contain
prerelease and build parts of a version.  For example, `1.2.3.4-rc.1+rev.2`
will preserve prerelease `rc.1` and build `rev.2` in the result.

### Clean

* `clean(version)`: Clean a string to be a valid semver if possible

This will return a cleaned and trimmed semver version. If the provided
version is not valid a null will be returned. This does not work for
ranges.

ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean('  =v2.1.5')`: `'2.1.5'`
* `s.clean('      2.1.5   ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`

## Constants

As a convenience, helper constants are exported to provide information about what `node-semver` supports:

### `RELEASE_TYPES`

- major
- premajor
- minor
- preminor
- patch
- prepatch
- prerelease

```
const semver = require('semver');

if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) {
  console.log('This is a valid release type!');
} else {
  console.warn('This is NOT a valid release type!');
}
```

### `SEMVER_SPEC_VERSION`

2.0.0

```
const semver = require('semver');

console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION);
```

## Exported Modules

<!--
TODO: Make sure that all of these items are documented (classes aren't,
eg), and then pull the module name into the documentation for that specific
thing.
-->

You may pull in just the part of this semver utility that you need if you
are sensitive to packing and tree-shaking concerns.  The main
`require('semver')` export uses getter functions to lazily load the parts
of the API that are used.

The following modules are available:

* `require('semver')`
* `require('semver/classes')`
* `require('semver/classes/comparator')`
* `require('semver/classes/range')`
* `require('semver/classes/semver')`
* `require('semver/functions/clean')`
* `require('semver/functions/cmp')`
* `require('semver/functions/coerce')`
* `require('semver/functions/compare')`
* `require('semver/functions/compare-build')`
* `require('semver/functions/compare-loose')`
* `require('semver/functions/diff')`
* `require('semver/functions/eq')`
* `require('semver/functions/gt')`
* `require('semver/functions/gte')`
* `require('semver/functions/inc')`
* `require('semver/functions/lt')`
* `require('semver/functions/lte')`
* `require('semver/functions/major')`
* `require('semver/functions/minor')`
* `require('semver/functions/neq')`
* `require('semver/functions/parse')`
* `require('semver/functions/patch')`
* `require('semver/functions/prerelease')`
* `require('semver/functions/rcompare')`
* `require('semver/functions/rsort')`
* `require('semver/functions/satisfies')`
* `require('semver/functions/sort')`
* `require('semver/functions/valid')`
* `require('semver/ranges/gtr')`
* `require('semver/ranges/intersects')`
* `require('semver/ranges/ltr')`
* `require('semver/ranges/max-satisfying')`
* `require('semver/ranges/min-satisfying')`
* `require('semver/ranges/min-version')`
* `require('semver/ranges/outside')`
* `require('semver/ranges/simplify')`
* `require('semver/ranges/subset')`
* `require('semver/ranges/to-comparators')`
* `require('semver/ranges/valid')`

#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.

'use strict'

const argv = process.argv.slice(2)

let versions = []

const range = []

let inc = null

const version = require('../package.json').version

let loose = false

let includePrerelease = false

let coerce = false

let rtl = false

let identifier

let identifierBase

const semver = require('../')
const parseOptions = require('../internal/parse-options')

let reverse = false

let options = {}

const main = () => {
  if (!argv.length) {
    return help()
  }
  while (argv.length) {
    let a = argv.shift()
    const indexOfEqualSign = a.indexOf('=')
    if (indexOfEqualSign !== -1) {
      const value = a.slice(indexOfEqualSign + 1)
      a = a.slice(0, indexOfEqualSign)
      argv.unshift(value)
    }
    switch (a) {
      case '-rv': case '-rev': case '--rev': case '--reverse':
        reverse = true
        break
      case '-l': case '--loose':
        loose = true
        break
      case '-p': case '--include-prerelease':
        includePrerelease = true
        break
      case '-v': case '--version':
        versions.push(argv.shift())
        break
      case '-i': case '--inc': case '--increment':
        switch (argv[0]) {
          case 'major': case 'minor': case 'patch': case 'prerelease':
          case 'premajor': case 'preminor': case 'prepatch':
          case 'release':
            inc = argv.shift()
            break
          default:
            inc = 'patch'
            break
        }
        break
      case '--preid':
        identifier = argv.shift()
        break
      case '-r': case '--range':
        range.push(argv.shift())
        break
      case '-n':
        identifierBase = argv.shift()
        if (identifierBase === 'false') {
          identifierBase = false
        }
        break
      case '-c': case '--coerce':
        coerce = true
        break
      case '--rtl':
        rtl = true
        break
      case '--ltr':
        rtl = false
        break
      case '-h': case '--help': case '-?':
        return help()
      default:
        versions.push(a)
        break
    }
  }

  options = parseOptions({ loose, includePrerelease, rtl })

  versions = versions.map((v) => {
    return coerce ? (semver.coerce(v, options) || { version: v }).version : v
  }).filter((v) => {
    return semver.valid(v, options)
  })
  if (!versions.length) {
    return fail()
  }
  if (inc && (versions.length !== 1 || range.length)) {
    return failInc()
  }

  for (let i = 0, l = range.length; i < l; i++) {
    versions = versions.filter((v) => {
      return semver.satisfies(v, range[i], options)
    })
    if (!versions.length) {
      return fail()
    }
  }
  versions
    .sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options))
    .map(v => semver.clean(v, options))
    .map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v)
    .forEach(v => console.log(v))
}

const failInc = () => {
  console.error('--inc can only be used on a single version with no range')
  fail()
}

const fail = () => process.exit(1)

const help = () => console.log(
`SemVer ${version}

A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter

Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence

Options:
-r --range <range>
        Print versions that match the specified range.

-i --increment [<level>]
        Increment a version by the specified level.  Level can
        be one of: major, minor, patch, premajor, preminor,
        prepatch, prerelease, or release.  Default level is 'patch'.
        Only one version may be specified.

--preid <identifier>
        Identifier to be used to prefix premajor, preminor,
        prepatch or prerelease version increments.

-l --loose
        Interpret versions and ranges loosely

-p --include-prerelease
        Always include prerelease versions in range matching

-c --coerce
        Coerce a string into SemVer if possible
        (does not imply --loose)

--rtl
        Coerce version strings right to left

--ltr
        Coerce version strings left to right (default)

-n <base>
        Base number to be used for the prerelease identifier.
        Can be either 0 or 1, or false to omit the number altogether.
        Defaults to 0.

Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.

If no satisfying versions are found, then exits failure.

Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)

main()
'use strict'

const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
  static get ANY () {
    return ANY
  }

  constructor (comp, options) {
    options = parseOptions(options)

    if (comp instanceof Comparator) {
      if (comp.loose === !!options.loose) {
        return comp
      } else {
        comp = comp.value
      }
    }

    comp = comp.trim().split(/\s+/).join(' ')
    debug('comparator', comp, options)
    this.options = options
    this.loose = !!options.loose
    this.parse(comp)

    if (this.semver === ANY) {
      this.value = ''
    } else {
      this.value = this.operator + this.semver.version
    }

    debug('comp', this)
  }

  parse (comp) {
    const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
    const m = comp.match(r)

    if (!m) {
      throw new TypeError(`Invalid comparator: ${comp}`)
    }

    this.operator = m[1] !== undefined ? m[1] : ''
    if (this.operator === '=') {
      this.operator = ''
    }

    // if it literally is just '>' or '' then allow anything.
    if (!m[2]) {
      this.semver = ANY
    } else {
      this.semver = new SemVer(m[2], this.options.loose)
    }
  }

  toString () {
    return this.value
  }

  test (version) {
    debug('Comparator.test', version, this.options.loose)

    if (this.semver === ANY || version === ANY) {
      return true
    }

    if (typeof version === 'string') {
      try {
        version = new SemVer(version, this.options)
      } catch (er) {
        return false
      }
    }

    return cmp(version, this.operator, this.semver, this.options)
  }

  intersects (comp, options) {
    if (!(comp instanceof Comparator)) {
      throw new TypeError('a Comparator is required')
    }

    if (this.operator === '') {
      if (this.value === '') {
        return true
      }
      return new Range(comp.value, options).test(this.value)
    } else if (comp.operator === '') {
      if (comp.value === '') {
        return true
      }
      return new Range(this.value, options).test(comp.semver)
    }

    options = parseOptions(options)

    // Special cases where nothing can possibly be lower
    if (options.includePrerelease &&
      (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
      return false
    }
    if (!options.includePrerelease &&
      (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
      return false
    }

    // Same direction increasing (> or >=)
    if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
      return true
    }
    // Same direction decreasing (< or <=)
    if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
      return true
    }
    // same SemVer and both sides are inclusive (<= or >=)
    if (
      (this.semver.version === comp.semver.version) &&
      this.operator.includes('=') && comp.operator.includes('=')) {
      return true
    }
    // opposite directions less than
    if (cmp(this.semver, '<', comp.semver, options) &&
      this.operator.startsWith('>') && comp.operator.startsWith('<')) {
      return true
    }
    // opposite directions greater than
    if (cmp(this.semver, '>', comp.semver, options) &&
      this.operator.startsWith('<') && comp.operator.startsWith('>')) {
      return true
    }
    return false
  }
}

module.exports = Comparator

const parseOptions = require('../internal/parse-options')
const { safeRe: re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')
'use strict'

module.exports = {
  SemVer: require('./semver.js'),
  Range: require('./range.js'),
  Comparator: require('./comparator.js'),
}
'use strict'

const SPACE_CHARACTERS = /\s+/g

// hoisted class for cyclic dependency
class Range {
  constructor (range, options) {
    options = parseOptions(options)

    if (range instanceof Range) {
      if (
        range.loose === !!options.loose &&
        range.includePrerelease === !!options.includePrerelease
      ) {
        return range
      } else {
        return new Range(range.raw, options)
      }
    }

    if (range instanceof Comparator) {
      // just put it in the set and return
      this.raw = range.value
      this.set = [[range]]
      this.formatted = undefined
      return this
    }

    this.options = options
    this.loose = !!options.loose
    this.includePrerelease = !!options.includePrerelease

    // First reduce all whitespace as much as possible so we do not have to rely
    // on potentially slow regexes like \s*. This is then stored and used for
    // future error messages as well.
    this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')

    // First, split on ||
    this.set = this.raw
      .split('||')
      // map the range to a 2d array of comparators
      .map(r => this.parseRange(r.trim()))
      // throw out any comparator lists that are empty
      // this generally means that it was not a valid range, which is allowed
      // in loose mode, but will still throw if the WHOLE range is invalid.
      .filter(c => c.length)

    if (!this.set.length) {
      throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
    }

    // if we have any that are not the null set, throw out null sets.
    if (this.set.length > 1) {
      // keep the first one, in case they're all null sets
      const first = this.set[0]
      this.set = this.set.filter(c => !isNullSet(c[0]))
      if (this.set.length === 0) {
        this.set = [first]
      } else if (this.set.length > 1) {
        // if we have any that are *, then the range is just *
        for (const c of this.set) {
          if (c.length === 1 && isAny(c[0])) {
            this.set = [c]
            break
          }
        }
      }
    }

    this.formatted = undefined
  }

  get range () {
    if (this.formatted === undefined) {
      this.formatted = ''
      for (let i = 0; i < this.set.length; i++) {
        if (i > 0) {
          this.formatted += '||'
        }
        const comps = this.set[i]
        for (let k = 0; k < comps.length; k++) {
          if (k > 0) {
            this.formatted += ' '
          }
          this.formatted += comps[k].toString().trim()
        }
      }
    }
    return this.formatted
  }

  format () {
    return this.range
  }

  toString () {
    return this.range
  }

  parseRange (range) {
    // memoize range parsing for performance.
    // this is a very hot path, and fully deterministic.
    const memoOpts =
      (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
      (this.options.loose && FLAG_LOOSE)
    const memoKey = memoOpts + ':' + range
    const cached = cache.get(memoKey)
    if (cached) {
      return cached
    }

    const loose = this.options.loose
    // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
    const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
    range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
    debug('hyphen replace', range)

    // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
    range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
    debug('comparator trim', range)

    // `~ 1.2.3` => `~1.2.3`
    range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
    debug('tilde trim', range)

    // `^ 1.2.3` => `^1.2.3`
    range = range.replace(re[t.CARETTRIM], caretTrimReplace)
    debug('caret trim', range)

    // At this point, the range is completely trimmed and
    // ready to be split into comparators.

    let rangeList = range
      .split(' ')
      .map(comp => parseComparator(comp, this.options))
      .join(' ')
      .split(/\s+/)
      // >=0.0.0 is equivalent to *
      .map(comp => replaceGTE0(comp, this.options))

    if (loose) {
      // in loose mode, throw out any that are not valid comparators
      rangeList = rangeList.filter(comp => {
        debug('loose invalid filter', comp, this.options)
        return !!comp.match(re[t.COMPARATORLOOSE])
      })
    }
    debug('range list', rangeList)

    // if any comparators are the null set, then replace with JUST null set
    // if more than one comparator, remove any * comparators
    // also, don't include the same comparator more than once
    const rangeMap = new Map()
    const comparators = rangeList.map(comp => new Comparator(comp, this.options))
    for (const comp of comparators) {
      if (isNullSet(comp)) {
        return [comp]
      }
      rangeMap.set(comp.value, comp)
    }
    if (rangeMap.size > 1 && rangeMap.has('')) {
      rangeMap.delete('')
    }

    const result = [...rangeMap.values()]
    cache.set(memoKey, result)
    return result
  }

  intersects (range, options) {
    if (!(range instanceof Range)) {
      throw new TypeError('a Range is required')
    }

    return this.set.some((thisComparators) => {
      return (
        isSatisfiable(thisComparators, options) &&
        range.set.some((rangeComparators) => {
          return (
            isSatisfiable(rangeComparators, options) &&
            thisComparators.every((thisComparator) => {
              return rangeComparators.every((rangeComparator) => {
                return thisComparator.intersects(rangeComparator, options)
              })
            })
          )
        })
      )
    })
  }

  // if ANY of the sets match ALL of its comparators, then pass
  test (version) {
    if (!version) {
      return false
    }

    if (typeof version === 'string') {
      try {
        version = new SemVer(version, this.options)
      } catch (er) {
        return false
      }
    }

    for (let i = 0; i < this.set.length; i++) {
      if (testSet(this.set[i], version, this.options)) {
        return true
      }
    }
    return false
  }
}

module.exports = Range

const LRU = require('../internal/lrucache')
const cache = new LRU()

const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
  safeRe: re,
  t,
  comparatorTrimReplace,
  tildeTrimReplace,
  caretTrimReplace,
} = require('../internal/re')
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')

const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''

// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
  let result = true
  const remainingComparators = comparators.slice()
  let testComparator = remainingComparators.pop()

  while (result && remainingComparators.length) {
    result = remainingComparators.every((otherComparator) => {
      return testComparator.intersects(otherComparator, options)
    })

    testComparator = remainingComparators.pop()
  }

  return result
}

// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
  comp = comp.replace(re[t.BUILD], '')
  debug('comp', comp, options)
  comp = replaceCarets(comp, options)
  debug('caret', comp)
  comp = replaceTildes(comp, options)
  debug('tildes', comp)
  comp = replaceXRanges(comp, options)
  debug('xrange', comp)
  comp = replaceStars(comp, options)
  debug('stars', comp)
  return comp
}

const isX = id => !id || id.toLowerCase() === 'x' || id === '*'

// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
  return comp
    .trim()
    .split(/\s+/)
    .map((c) => replaceTilde(c, options))
    .join(' ')
}

const replaceTilde = (comp, options) => {
  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
  return comp.replace(r, (_, M, m, p, pr) => {
    debug('tilde', comp, _, M, m, p, pr)
    let ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
    } else if (isX(p)) {
      // ~1.2 == >=1.2.0 <1.3.0-0
      ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
    } else if (pr) {
      debug('replaceTilde pr', pr)
      ret = `>=${M}.${m}.${p}-${pr
      } <${M}.${+m + 1}.0-0`
    } else {
      // ~1.2.3 == >=1.2.3 <1.3.0-0
      ret = `>=${M}.${m}.${p
      } <${M}.${+m + 1}.0-0`
    }

    debug('tilde return', ret)
    return ret
  })
}

// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
  return comp
    .trim()
    .split(/\s+/)
    .map((c) => replaceCaret(c, options))
    .join(' ')
}

const replaceCaret = (comp, options) => {
  debug('caret', comp, options)
  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
  const z = options.includePrerelease ? '-0' : ''
  return comp.replace(r, (_, M, m, p, pr) => {
    debug('caret', comp, _, M, m, p, pr)
    let ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
    } else if (isX(p)) {
      if (M === '0') {
        ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
      } else {
        ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
      }
    } else if (pr) {
      debug('replaceCaret pr', pr)
      if (M === '0') {
        if (m === '0') {
          ret = `>=${M}.${m}.${p}-${pr
          } <${M}.${m}.${+p + 1}-0`
        } else {
          ret = `>=${M}.${m}.${p}-${pr
          } <${M}.${+m + 1}.0-0`
        }
      } else {
        ret = `>=${M}.${m}.${p}-${pr
        } <${+M + 1}.0.0-0`
      }
    } else {
      debug('no pr')
      if (M === '0') {
        if (m === '0') {
          ret = `>=${M}.${m}.${p
          }${z} <${M}.${m}.${+p + 1}-0`
        } else {
          ret = `>=${M}.${m}.${p
          }${z} <${M}.${+m + 1}.0-0`
        }
      } else {
        ret = `>=${M}.${m}.${p
        } <${+M + 1}.0.0-0`
      }
    }

    debug('caret return', ret)
    return ret
  })
}

const replaceXRanges = (comp, options) => {
  debug('replaceXRanges', comp, options)
  return comp
    .split(/\s+/)
    .map((c) => replaceXRange(c, options))
    .join(' ')
}

const replaceXRange = (comp, options) => {
  comp = comp.trim()
  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
  return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
    debug('xRange', comp, ret, gtlt, M, m, p, pr)
    const xM = isX(M)
    const xm = xM || isX(m)
    const xp = xm || isX(p)
    const anyX = xp

    if (gtlt === '=' && anyX) {
      gtlt = ''
    }

    // if we're including prereleases in the match, then we need
    // to fix this to -0, the lowest possible prerelease value
    pr = options.includePrerelease ? '-0' : ''

    if (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0-0'
      } else {
        // nothing is forbidden
        ret = '*'
      }
    } else if (gtlt && anyX) {
      // we know patch is an x, because we have any x at all.
      // replace X with 0
      if (xm) {
        m = 0
      }
      p = 0

      if (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        gtlt = '>='
        if (xm) {
          M = +M + 1
          m = 0
          p = 0
        } else {
          m = +m + 1
          p = 0
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<'
        if (xm) {
          M = +M + 1
        } else {
          m = +m + 1
        }
      }

      if (gtlt === '<') {
        pr = '-0'
      }

      ret = `${gtlt + M}.${m}.${p}${pr}`
    } else if (xm) {
      ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
    } else if (xp) {
      ret = `>=${M}.${m}.0${pr
      } <${M}.${+m + 1}.0-0`
    }

    debug('xRange return', ret)

    return ret
  })
}

// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
  debug('replaceStars', comp, options)
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp
    .trim()
    .replace(re[t.STAR], '')
}

const replaceGTE0 = (comp, options) => {
  debug('replaceGTE0', comp, options)
  return comp
    .trim()
    .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}

// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
// TODO build?
const hyphenReplace = incPr => ($0,
  from, fM, fm, fp, fpr, fb,
  to, tM, tm, tp, tpr) => {
  if (isX(fM)) {
    from = ''
  } else if (isX(fm)) {
    from = `>=${fM}.0.0${incPr ? '-0' : ''}`
  } else if (isX(fp)) {
    from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
  } else if (fpr) {
    from = `>=${from}`
  } else {
    from = `>=${from}${incPr ? '-0' : ''}`
  }

  if (isX(tM)) {
    to = ''
  } else if (isX(tm)) {
    to = `<${+tM + 1}.0.0-0`
  } else if (isX(tp)) {
    to = `<${tM}.${+tm + 1}.0-0`
  } else if (tpr) {
    to = `<=${tM}.${tm}.${tp}-${tpr}`
  } else if (incPr) {
    to = `<${tM}.${tm}.${+tp + 1}-0`
  } else {
    to = `<=${to}`
  }

  return `${from} ${to}`.trim()
}

const testSet = (set, version, options) => {
  for (let i = 0; i < set.length; i++) {
    if (!set[i].test(version)) {
      return false
    }
  }

  if (version.prerelease.length && !options.includePrerelease) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (let i = 0; i < set.length; i++) {
      debug(set[i].semver)
      if (set[i].semver === Comparator.ANY) {
        continue
      }

      if (set[i].semver.prerelease.length > 0) {
        const allowed = set[i].semver
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch) {
          return true
        }
      }
    }

    // Version has a -pre, but it's not one of the ones we like.
    return false
  }

  return true
}
'use strict'

const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { safeRe: re, t } = require('../internal/re')

const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
  constructor (version, options) {
    options = parseOptions(options)

    if (version instanceof SemVer) {
      if (version.loose === !!options.loose &&
        version.includePrerelease === !!options.includePrerelease) {
        return version
      } else {
        version = version.version
      }
    } else if (typeof version !== 'string') {
      throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
    }

    if (version.length > MAX_LENGTH) {
      throw new TypeError(
        `version is longer than ${MAX_LENGTH} characters`
      )
    }

    debug('SemVer', version, options)
    this.options = options
    this.loose = !!options.loose
    // this isn't actually relevant for versions, but keep it so that we
    // don't run into trouble passing this.options around.
    this.includePrerelease = !!options.includePrerelease

    const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])

    if (!m) {
      throw new TypeError(`Invalid Version: ${version}`)
    }

    this.raw = version

    // these are actually numbers
    this.major = +m[1]
    this.minor = +m[2]
    this.patch = +m[3]

    if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
      throw new TypeError('Invalid major version')
    }

    if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
      throw new TypeError('Invalid minor version')
    }

    if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
      throw new TypeError('Invalid patch version')
    }

    // numberify any prerelease numeric ids
    if (!m[4]) {
      this.prerelease = []
    } else {
      this.prerelease = m[4].split('.').map((id) => {
        if (/^[0-9]+$/.test(id)) {
          const num = +id
          if (num >= 0 && num < MAX_SAFE_INTEGER) {
            return num
          }
        }
        return id
      })
    }

    this.build = m[5] ? m[5].split('.') : []
    this.format()
  }

  format () {
    this.version = `${this.major}.${this.minor}.${this.patch}`
    if (this.prerelease.length) {
      this.version += `-${this.prerelease.join('.')}`
    }
    return this.version
  }

  toString () {
    return this.version
  }

  compare (other) {
    debug('SemVer.compare', this.version, this.options, other)
    if (!(other instanceof SemVer)) {
      if (typeof other === 'string' && other === this.version) {
        return 0
      }
      other = new SemVer(other, this.options)
    }

    if (other.version === this.version) {
      return 0
    }

    return this.compareMain(other) || this.comparePre(other)
  }

  compareMain (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    if (this.major < other.major) {
      return -1
    }
    if (this.major > other.major) {
      return 1
    }
    if (this.minor < other.minor) {
      return -1
    }
    if (this.minor > other.minor) {
      return 1
    }
    if (this.patch < other.patch) {
      return -1
    }
    if (this.patch > other.patch) {
      return 1
    }
    return 0
  }

  comparePre (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    // NOT having a prerelease is > having one
    if (this.prerelease.length && !other.prerelease.length) {
      return -1
    } else if (!this.prerelease.length && other.prerelease.length) {
      return 1
    } else if (!this.prerelease.length && !other.prerelease.length) {
      return 0
    }

    let i = 0
    do {
      const a = this.prerelease[i]
      const b = other.prerelease[i]
      debug('prerelease compare', i, a, b)
      if (a === undefined && b === undefined) {
        return 0
      } else if (b === undefined) {
        return 1
      } else if (a === undefined) {
        return -1
      } else if (a === b) {
        continue
      } else {
        return compareIdentifiers(a, b)
      }
    } while (++i)
  }

  compareBuild (other) {
    if (!(other instanceof SemVer)) {
      other = new SemVer(other, this.options)
    }

    let i = 0
    do {
      const a = this.build[i]
      const b = other.build[i]
      debug('build compare', i, a, b)
      if (a === undefined && b === undefined) {
        return 0
      } else if (b === undefined) {
        return 1
      } else if (a === undefined) {
        return -1
      } else if (a === b) {
        continue
      } else {
        return compareIdentifiers(a, b)
      }
    } while (++i)
  }

  // preminor will bump the version up to the next minor release, and immediately
  // down to pre-release. premajor and prepatch work the same way.
  inc (release, identifier, identifierBase) {
    if (release.startsWith('pre')) {
      if (!identifier && identifierBase === false) {
        throw new Error('invalid increment argument: identifier is empty')
      }
      // Avoid an invalid semver results
      if (identifier) {
        const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
        if (!match || match[1] !== identifier) {
          throw new Error(`invalid identifier: ${identifier}`)
        }
      }
    }

    switch (release) {
      case 'premajor':
        this.prerelease.length = 0
        this.patch = 0
        this.minor = 0
        this.major++
        this.inc('pre', identifier, identifierBase)
        break
      case 'preminor':
        this.prerelease.length = 0
        this.patch = 0
        this.minor++
        this.inc('pre', identifier, identifierBase)
        break
      case 'prepatch':
        // If this is already a prerelease, it will bump to the next version
        // drop any prereleases that might already exist, since they are not
        // relevant at this point.
        this.prerelease.length = 0
        this.inc('patch', identifier, identifierBase)
        this.inc('pre', identifier, identifierBase)
        break
      // If the input is a non-prerelease version, this acts the same as
      // prepatch.
      case 'prerelease':
        if (this.prerelease.length === 0) {
          this.inc('patch', identifier, identifierBase)
        }
        this.inc('pre', identifier, identifierBase)
        break
      case 'release':
        if (this.prerelease.length === 0) {
          throw new Error(`version ${this.raw} is not a prerelease`)
        }
        this.prerelease.length = 0
        break

      case 'major':
        // If this is a pre-major version, bump up to the same major version.
        // Otherwise increment major.
        // 1.0.0-5 bumps to 1.0.0
        // 1.1.0 bumps to 2.0.0
        if (
          this.minor !== 0 ||
          this.patch !== 0 ||
          this.prerelease.length === 0
        ) {
          this.major++
        }
        this.minor = 0
        this.patch = 0
        this.prerelease = []
        break
      case 'minor':
        // If this is a pre-minor version, bump up to the same minor version.
        // Otherwise increment minor.
        // 1.2.0-5 bumps to 1.2.0
        // 1.2.1 bumps to 1.3.0
        if (this.patch !== 0 || this.prerelease.length === 0) {
          this.minor++
        }
        this.patch = 0
        this.prerelease = []
        break
      case 'patch':
        // If this is not a pre-release version, it will increment the patch.
        // If it is a pre-release it will bump up to the same patch version.
        // 1.2.0-5 patches to 1.2.0
        // 1.2.0 patches to 1.2.1
        if (this.prerelease.length === 0) {
          this.patch++
        }
        this.prerelease = []
        break
      // This probably shouldn't be used publicly.
      // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
      case 'pre': {
        const base = Number(identifierBase) ? 1 : 0

        if (this.prerelease.length === 0) {
          this.prerelease = [base]
        } else {
          let i = this.prerelease.length
          while (--i >= 0) {
            if (typeof this.prerelease[i] === 'number') {
              this.prerelease[i]++
              i = -2
            }
          }
          if (i === -1) {
            // didn't increment anything
            if (identifier === this.prerelease.join('.') && identifierBase === false) {
              throw new Error('invalid increment argument: identifier already exists')
            }
            this.prerelease.push(base)
          }
        }
        if (identifier) {
          // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
          // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
          let prerelease = [identifier, base]
          if (identifierBase === false) {
            prerelease = [identifier]
          }
          if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
            if (isNaN(this.prerelease[1])) {
              this.prerelease = prerelease
            }
          } else {
            this.prerelease = prerelease
          }
        }
        break
      }
      default:
        throw new Error(`invalid increment argument: ${release}`)
    }
    this.raw = this.format()
    if (this.build.length) {
      this.raw += `+${this.build.join('.')}`
    }
    return this
  }
}

module.exports = SemVer
'use strict'

const parse = require('./parse')
const clean = (version, options) => {
  const s = parse(version.trim().replace(/^[=v]+/, ''), options)
  return s ? s.version : null
}
module.exports = clean
'use strict'

const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')

const cmp = (a, op, b, loose) => {
  switch (op) {
    case '===':
      if (typeof a === 'object') {
        a = a.version
      }
      if (typeof b === 'object') {
        b = b.version
      }
      return a === b

    case '!==':
      if (typeof a === 'object') {
        a = a.version
      }
      if (typeof b === 'object') {
        b = b.version
      }
      return a !== b

    case '':
    case '=':
    case '==':
      return eq(a, b, loose)

    case '!=':
      return neq(a, b, loose)

    case '>':
      return gt(a, b, loose)

    case '>=':
      return gte(a, b, loose)

    case '<':
      return lt(a, b, loose)

    case '<=':
      return lte(a, b, loose)

    default:
      throw new TypeError(`Invalid operator: ${op}`)
  }
}
module.exports = cmp
'use strict'

const SemVer = require('../classes/semver')
const parse = require('./parse')
const { safeRe: re, t } = require('../internal/re')

const coerce = (version, options) => {
  if (version instanceof SemVer) {
    return version
  }

  if (typeof version === 'number') {
    version = String(version)
  }

  if (typeof version !== 'string') {
    return null
  }

  options = options || {}

  let match = null
  if (!options.rtl) {
    match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
  } else {
    // Find the right-most coercible string that does not share
    // a terminus with a more left-ward coercible string.
    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
    // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
    //
    // Walk through the string checking with a /g regexp
    // Manually set the index so as to pick up overlapping matches.
    // Stop when we get a match that ends at the string end, since no
    // coercible string can be more right-ward without the same terminus.
    const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
    let next
    while ((next = coerceRtlRegex.exec(version)) &&
        (!match || match.index + match[0].length !== version.length)
    ) {
      if (!match ||
            next.index + next[0].length !== match.index + match[0].length) {
        match = next
      }
      coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
    }
    // leave it in a clean state
    coerceRtlRegex.lastIndex = -1
  }

  if (match === null) {
    return null
  }

  const major = match[2]
  const minor = match[3] || '0'
  const patch = match[4] || '0'
  const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
  const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''

  return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
module.exports = coerce
'use strict'

const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
  const versionA = new SemVer(a, loose)
  const versionB = new SemVer(b, loose)
  return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild
'use strict'

const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose
'use strict'

const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
  new SemVer(a, loose).compare(new SemVer(b, loose))

module.exports = compare
'use strict'

const parse = require('./parse.js')

const diff = (version1, version2) => {
  const v1 = parse(version1, null, true)
  const v2 = parse(version2, null, true)
  const comparison = v1.compare(v2)

  if (comparison === 0) {
    return null
  }

  const v1Higher = comparison > 0
  const highVersion = v1Higher ? v1 : v2
  const lowVersion = v1Higher ? v2 : v1
  const highHasPre = !!highVersion.prerelease.length
  const lowHasPre = !!lowVersion.prerelease.length

  if (lowHasPre && !highHasPre) {
    // Going from prerelease -> no prerelease requires some special casing

    // If the low version has only a major, then it will always be a major
    // Some examples:
    // 1.0.0-1 -> 1.0.0
    // 1.0.0-1 -> 1.1.1
    // 1.0.0-1 -> 2.0.0
    if (!lowVersion.patch && !lowVersion.minor) {
      return 'major'
    }

    // If the main part has no difference
    if (lowVersion.compareMain(highVersion) === 0) {
      if (lowVersion.minor && !lowVersion.patch) {
        return 'minor'
      }
      return 'patch'
    }
  }

  // add the `pre` prefix if we are going to a prerelease version
  const prefix = highHasPre ? 'pre' : ''

  if (v1.major !== v2.major) {
    return prefix + 'major'
  }

  if (v1.minor !== v2.minor) {
    return prefix + 'minor'
  }

  if (v1.patch !== v2.patch) {
    return prefix + 'patch'
  }

  // high and low are prereleases
  return 'prerelease'
}

module.exports = diff
'use strict'

const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq
'use strict'

const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt
'use strict'

const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte
'use strict'

const SemVer = require('../classes/semver')

const inc = (version, release, options, identifier, identifierBase) => {
  if (typeof (options) === 'string') {
    identifierBase = identifier
    identifier = options
    options = undefined
  }

  try {
    return new SemVer(
      version instanceof SemVer ? version.version : version,
      options
    ).inc(release, identifier, identifierBase).version
  } catch (er) {
    return null
  }
}
module.exports = inc
'use strict'

const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt
'use strict'

const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte
'use strict'

const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major
'use strict'

const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor
'use strict'

const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq
'use strict'

const SemVer = require('../classes/semver')
const parse = (version, options, throwErrors = false) => {
  if (version instanceof SemVer) {
    return version
  }
  try {
    return new SemVer(version, options)
  } catch (er) {
    if (!throwErrors) {
      return null
    }
    throw er
  }
}

module.exports = parse
'use strict'

const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch
'use strict'

const parse = require('./parse')
const prerelease = (version, options) => {
  const parsed = parse(version, options)
  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease
'use strict'

const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare
'use strict'

const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort
'use strict'

const Range = require('../classes/range')
const satisfies = (version, range, options) => {
  try {
    range = new Range(range, options)
  } catch (er) {
    return false
  }
  return range.test(version)
}
module.exports = satisfies
'use strict'

const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort
'use strict'

const parse = require('./parse')
const valid = (version, options) => {
  const v = parse(version, options)
  return v ? v.version : null
}
module.exports = valid
'use strict'

// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
const constants = require('./internal/constants')
const SemVer = require('./classes/semver')
const identifiers = require('./internal/identifiers')
const parse = require('./functions/parse')
const valid = require('./functions/valid')
const clean = require('./functions/clean')
const inc = require('./functions/inc')
const diff = require('./functions/diff')
const major = require('./functions/major')
const minor = require('./functions/minor')
const patch = require('./functions/patch')
const prerelease = require('./functions/prerelease')
const compare = require('./functions/compare')
const rcompare = require('./functions/rcompare')
const compareLoose = require('./functions/compare-loose')
const compareBuild = require('./functions/compare-build')
const sort = require('./functions/sort')
const rsort = require('./functions/rsort')
const gt = require('./functions/gt')
const lt = require('./functions/lt')
const eq = require('./functions/eq')
const neq = require('./functions/neq')
const gte = require('./functions/gte')
const lte = require('./functions/lte')
const cmp = require('./functions/cmp')
const coerce = require('./functions/coerce')
const Comparator = require('./classes/comparator')
const Range = require('./classes/range')
const satisfies = require('./functions/satisfies')
const toComparators = require('./ranges/to-comparators')
const maxSatisfying = require('./ranges/max-satisfying')
const minSatisfying = require('./ranges/min-satisfying')
const minVersion = require('./ranges/min-version')
const validRange = require('./ranges/valid')
const outside = require('./ranges/outside')
const gtr = require('./ranges/gtr')
const ltr = require('./ranges/ltr')
const intersects = require('./ranges/intersects')
const simplifyRange = require('./ranges/simplify')
const subset = require('./ranges/subset')
module.exports = {
  parse,
  valid,
  clean,
  inc,
  diff,
  major,
  minor,
  patch,
  prerelease,
  compare,
  rcompare,
  compareLoose,
  compareBuild,
  sort,
  rsort,
  gt,
  lt,
  eq,
  neq,
  gte,
  lte,
  cmp,
  coerce,
  Comparator,
  Range,
  satisfies,
  toComparators,
  maxSatisfying,
  minSatisfying,
  minVersion,
  validRange,
  outside,
  gtr,
  ltr,
  intersects,
  simplifyRange,
  subset,
  SemVer,
  re: internalRe.re,
  src: internalRe.src,
  tokens: internalRe.t,
  SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
  RELEASE_TYPES: constants.RELEASE_TYPES,
  compareIdentifiers: identifiers.compareIdentifiers,
  rcompareIdentifiers: identifiers.rcompareIdentifiers,
}
'use strict'

// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'

const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991

// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16

// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6

const RELEASE_TYPES = [
  'major',
  'premajor',
  'minor',
  'preminor',
  'patch',
  'prepatch',
  'prerelease',
]

module.exports = {
  MAX_LENGTH,
  MAX_SAFE_COMPONENT_LENGTH,
  MAX_SAFE_BUILD_LENGTH,
  MAX_SAFE_INTEGER,
  RELEASE_TYPES,
  SEMVER_SPEC_VERSION,
  FLAG_INCLUDE_PRERELEASE: 0b001,
  FLAG_LOOSE: 0b010,
}
'use strict'

const debug = (
  typeof process === 'object' &&
  process.env &&
  process.env.NODE_DEBUG &&
  /\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
  : () => {}

module.exports = debug
'use strict'

const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
  if (typeof a === 'number' && typeof b === 'number') {
    return a === b ? 0 : a < b ? -1 : 1
  }

  const anum = numeric.test(a)
  const bnum = numeric.test(b)

  if (anum && bnum) {
    a = +a
    b = +b
  }

  return a === b ? 0
    : (anum && !bnum) ? -1
    : (bnum && !anum) ? 1
    : a < b ? -1
    : 1
}

const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)

module.exports = {
  compareIdentifiers,
  rcompareIdentifiers,
}
'use strict'

class LRUCache {
  constructor () {
    this.max = 1000
    this.map = new Map()
  }

  get (key) {
    const value = this.map.get(key)
    if (value === undefined) {
      return undefined
    } else {
      // Remove the key from the map and add it to the end
      this.map.delete(key)
      this.map.set(key, value)
      return value
    }
  }

  delete (key) {
    return this.map.delete(key)
  }

  set (key, value) {
    const deleted = this.delete(key)

    if (!deleted && value !== undefined) {
      // If cache is full, delete the least recently used item
      if (this.map.size >= this.max) {
        const firstKey = this.map.keys().next().value
        this.delete(firstKey)
      }

      this.map.set(key, value)
    }

    return this
  }
}

module.exports = LRUCache
'use strict'

// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
  if (!options) {
    return emptyOpts
  }

  if (typeof options !== 'object') {
    return looseOption
  }

  return options
}
module.exports = parseOptions
'use strict'

const {
  MAX_SAFE_COMPONENT_LENGTH,
  MAX_SAFE_BUILD_LENGTH,
  MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}

// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const safeSrc = exports.safeSrc = []
const t = exports.t = {}
let R = 0

const LETTERDASHNUMBER = '[a-zA-Z0-9-]'

// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
  ['\\s', 1],
  ['\\d', MAX_LENGTH],
  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]

const makeSafeRegex = (value) => {
  for (const [token, max] of safeRegexReplacements) {
    value = value
      .split(`${token}*`).join(`${token}{0,${max}}`)
      .split(`${token}+`).join(`${token}{1,${max}}`)
  }
  return value
}

const createToken = (name, value, isGlobal) => {
  const safe = makeSafeRegex(value)
  const index = R++
  debug(name, index, value)
  t[name] = index
  src[index] = value
  safeSrc[index] = safe
  re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
  safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}

// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.

// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.

createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')

// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.

createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)

// ## Main Version
// Three dot-separated numeric identifiers.

createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})\\.` +
                   `(${src[t.NUMERICIDENTIFIER]})`)

createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
                        `(${src[t.NUMERICIDENTIFIERLOOSE]})`)

// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numeric identifiers include numeric identifiers but can be longer.
// Therefore non-numeric identifiers must go first.

createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIER]})`)

createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIERLOOSE]})`)

// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.

createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)

createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)

// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.

createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)

// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.

createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)

// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.

// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.

createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
  src[t.BUILD]}?`)

createToken('FULL', `^${src[t.FULLPLAIN]}$`)

// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
  src[t.BUILD]}?`)

createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)

createToken('GTLT', '((?:<|>)?=?)')

// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)

createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
                   `(?:${src[t.PRERELEASE]})?${
                     src[t.BUILD]}?` +
                   `)?)?`)

createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
                        `(?:${src[t.PRERELEASELOOSE]})?${
                          src[t.BUILD]}?` +
                        `)?)?`)

createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)

// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
              '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
              `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
              `(?:${src[t.PRERELEASE]})?` +
              `(?:${src[t.BUILD]})?` +
              `(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)

// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')

createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'

createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)

// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')

createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'

createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)

// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)

// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'

// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
                   `\\s+-\\s+` +
                   `(${src[t.XRANGEPLAIN]})` +
                   `\\s*$`)

createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s+-\\s+` +
                        `(${src[t.XRANGEPLAINLOOSE]})` +
                        `\\s*$`)

// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')
{
  "name": "semver",
  "version": "7.7.4",
  "description": "The semantic version parser used by npm.",
  "main": "index.js",
  "scripts": {
    "test": "tap",
    "snap": "tap",
    "lint": "npm run eslint",
    "postlint": "template-oss-check",
    "lintfix": "npm run eslint -- --fix",
    "posttest": "npm run lint",
    "template-oss-apply": "template-oss-apply --force",
    "eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
  },
  "devDependencies": {
    "@npmcli/eslint-config": "^6.0.0",
    "@npmcli/template-oss": "4.29.0",
    "benchmark": "^2.1.4",
    "tap": "^16.0.0"
  },
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/npm/node-semver.git"
  },
  "bin": {
    "semver": "bin/semver.js"
  },
  "files": [
    "bin/",
    "lib/",
    "classes/",
    "functions/",
    "internal/",
    "ranges/",
    "index.js",
    "preload.js",
    "range.bnf"
  ],
  "tap": {
    "timeout": 30,
    "coverage-map": "map.js",
    "nyc-arg": [
      "--exclude",
      "tap-snapshots/**"
    ]
  },
  "engines": {
    "node": ">=10"
  },
  "author": "GitHub Inc.",
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "version": "4.29.0",
    "engines": ">=10",
    "distPaths": [
      "classes/",
      "functions/",
      "internal/",
      "ranges/",
      "index.js",
      "preload.js",
      "range.bnf"
    ],
    "allowPaths": [
      "/classes/",
      "/functions/",
      "/internal/",
      "/ranges/",
      "/index.js",
      "/preload.js",
      "/range.bnf",
      "/benchmarks"
    ],
    "publish": "true"
  }
}
'use strict'

// XXX remove in v8 or beyond
module.exports = require('./index.js')
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | [1-9] ( [0-9] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= parts
build      ::= parts
parts      ::= part ( '.' part ) *
part       ::= nr | [-0-9A-Za-z]+
'use strict'

// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr
'use strict'

const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
  r1 = new Range(r1, options)
  r2 = new Range(r2, options)
  return r1.intersects(r2, options)
}
module.exports = intersects
'use strict'

const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')

const maxSatisfying = (versions, range, options) => {
  let max = null
  let maxSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!max || maxSV.compare(v) === -1) {
        // compare(max, v, true)
        max = v
        maxSV = new SemVer(max, options)
      }
    }
  })
  return max
}
module.exports = maxSatisfying
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
  let min = null
  let minSV = null
  let rangeObj = null
  try {
    rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach((v) => {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!min || minSV.compare(v) === 1) {
        // compare(min, v, true)
        min = v
        minSV = new SemVer(min, options)
      }
    }
  })
  return min
}
module.exports = minSatisfying
'use strict'

const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')

const minVersion = (range, loose) => {
  range = new Range(range, loose)

  let minver = new SemVer('0.0.0')
  if (range.test(minver)) {
    return minver
  }

  minver = new SemVer('0.0.0-0')
  if (range.test(minver)) {
    return minver
  }

  minver = null
  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let setMin = null
    comparators.forEach((comparator) => {
      // Clone to avoid manipulating the comparator's semver object.
      const compver = new SemVer(comparator.semver.version)
      switch (comparator.operator) {
        case '>':
          if (compver.prerelease.length === 0) {
            compver.patch++
          } else {
            compver.prerelease.push(0)
          }
          compver.raw = compver.format()
          /* fallthrough */
        case '':
        case '>=':
          if (!setMin || gt(compver, setMin)) {
            setMin = compver
          }
          break
        case '<':
        case '<=':
          /* Ignore maximum versions */
          break
        /* istanbul ignore next */
        default:
          throw new Error(`Unexpected operation: ${comparator.operator}`)
      }
    })
    if (setMin && (!minver || gt(minver, setMin))) {
      minver = setMin
    }
  }

  if (minver && range.test(minver)) {
    return minver
  }

  return null
}
module.exports = minVersion
'use strict'

const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')

const outside = (version, range, hilo, options) => {
  version = new SemVer(version, options)
  range = new Range(range, options)

  let gtfn, ltefn, ltfn, comp, ecomp
  switch (hilo) {
    case '>':
      gtfn = gt
      ltefn = lte
      ltfn = lt
      comp = '>'
      ecomp = '>='
      break
    case '<':
      gtfn = lt
      ltefn = gte
      ltfn = gt
      comp = '<'
      ecomp = '<='
      break
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"')
  }

  // If it satisfies the range it is not outside
  if (satisfies(version, range, options)) {
    return false
  }

  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.

  for (let i = 0; i < range.set.length; ++i) {
    const comparators = range.set[i]

    let high = null
    let low = null

    comparators.forEach((comparator) => {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator
      low = low || comparator
      if (gtfn(comparator.semver, high.semver, options)) {
        high = comparator
      } else if (ltfn(comparator.semver, low.semver, options)) {
        low = comparator
      }
    })

    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false
    }

    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false
    }
  }
  return true
}

module.exports = outside
'use strict'

// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
  const set = []
  let first = null
  let prev = null
  const v = versions.sort((a, b) => compare(a, b, options))
  for (const version of v) {
    const included = satisfies(version, range, options)
    if (included) {
      prev = version
      if (!first) {
        first = version
      }
    } else {
      if (prev) {
        set.push([first, prev])
      }
      prev = null
      first = null
    }
  }
  if (first) {
    set.push([first, null])
  }

  const ranges = []
  for (const [min, max] of set) {
    if (min === max) {
      ranges.push(min)
    } else if (!max && min === v[0]) {
      ranges.push('*')
    } else if (!max) {
      ranges.push(`>=${min}`)
    } else if (min === v[0]) {
      ranges.push(`<=${max}`)
    } else {
      ranges.push(`${min} - ${max}`)
    }
  }
  const simplified = ranges.join(' || ')
  const original = typeof range.raw === 'string' ? range.raw : String(range)
  return simplified.length < original.length ? simplified : range
}
'use strict'

const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')

// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
//   some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
//   - If C is only the ANY comparator, return true
//   - Else if in prerelease mode, return false
//   - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
//   - if in prerelease mode, return true
//   - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
//   - If GT, and EQ does not satisfy GT, return true (null set)
//   - If LT, and EQ does not satisfy LT, return true (null set)
//   - If EQ satisfies every C, return true
//   - Else return false
// - If GT
//   - If GT.semver is lower than any > or >= comp in C, return false
//   - If GT is >=, and GT.semver does not satisfy every C, return false
//   - If GT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
//   - If LT.semver is greater than any < or <= comp in C, return false
//   - If LT is <=, and LT.semver does not satisfy every C, return false
//   - If LT.semver has a prerelease, and not in prerelease mode
//     - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true

const subset = (sub, dom, options = {}) => {
  if (sub === dom) {
    return true
  }

  sub = new Range(sub, options)
  dom = new Range(dom, options)
  let sawNonNull = false

  OUTER: for (const simpleSub of sub.set) {
    for (const simpleDom of dom.set) {
      const isSub = simpleSubset(simpleSub, simpleDom, options)
      sawNonNull = sawNonNull || isSub !== null
      if (isSub) {
        continue OUTER
      }
    }
    // the null set is a subset of everything, but null simple ranges in
    // a complex range should be ignored.  so if we saw a non-null range,
    // then we know this isn't a subset, but if EVERY simple range was null,
    // then it is a subset.
    if (sawNonNull) {
      return false
    }
  }
  return true
}

const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]

const simpleSubset = (sub, dom, options) => {
  if (sub === dom) {
    return true
  }

  if (sub.length === 1 && sub[0].semver === ANY) {
    if (dom.length === 1 && dom[0].semver === ANY) {
      return true
    } else if (options.includePrerelease) {
      sub = minimumVersionWithPreRelease
    } else {
      sub = minimumVersion
    }
  }

  if (dom.length === 1 && dom[0].semver === ANY) {
    if (options.includePrerelease) {
      return true
    } else {
      dom = minimumVersion
    }
  }

  const eqSet = new Set()
  let gt, lt
  for (const c of sub) {
    if (c.operator === '>' || c.operator === '>=') {
      gt = higherGT(gt, c, options)
    } else if (c.operator === '<' || c.operator === '<=') {
      lt = lowerLT(lt, c, options)
    } else {
      eqSet.add(c.semver)
    }
  }

  if (eqSet.size > 1) {
    return null
  }

  let gtltComp
  if (gt && lt) {
    gtltComp = compare(gt.semver, lt.semver, options)
    if (gtltComp > 0) {
      return null
    } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
      return null
    }
  }

  // will iterate one or zero times
  for (const eq of eqSet) {
    if (gt && !satisfies(eq, String(gt), options)) {
      return null
    }

    if (lt && !satisfies(eq, String(lt), options)) {
      return null
    }

    for (const c of dom) {
      if (!satisfies(eq, String(c), options)) {
        return false
      }
    }

    return true
  }

  let higher, lower
  let hasDomLT, hasDomGT
  // if the subset has a prerelease, we need a comparator in the superset
  // with the same tuple and a prerelease, or it's not a subset
  let needDomLTPre = lt &&
    !options.includePrerelease &&
    lt.semver.prerelease.length ? lt.semver : false
  let needDomGTPre = gt &&
    !options.includePrerelease &&
    gt.semver.prerelease.length ? gt.semver : false
  // exception: <1.2.3-0 is the same as <1.2.3
  if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
      lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
    needDomLTPre = false
  }

  for (const c of dom) {
    hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
    hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
    if (gt) {
      if (needDomGTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomGTPre.major &&
            c.semver.minor === needDomGTPre.minor &&
            c.semver.patch === needDomGTPre.patch) {
          needDomGTPre = false
        }
      }
      if (c.operator === '>' || c.operator === '>=') {
        higher = higherGT(gt, c, options)
        if (higher === c && higher !== gt) {
          return false
        }
      } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
        return false
      }
    }
    if (lt) {
      if (needDomLTPre) {
        if (c.semver.prerelease && c.semver.prerelease.length &&
            c.semver.major === needDomLTPre.major &&
            c.semver.minor === needDomLTPre.minor &&
            c.semver.patch === needDomLTPre.patch) {
          needDomLTPre = false
        }
      }
      if (c.operator === '<' || c.operator === '<=') {
        lower = lowerLT(lt, c, options)
        if (lower === c && lower !== lt) {
          return false
        }
      } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
        return false
      }
    }
    if (!c.operator && (lt || gt) && gtltComp !== 0) {
      return false
    }
  }

  // if there was a < or >, and nothing in the dom, then must be false
  // UNLESS it was limited by another range in the other direction.
  // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
  if (gt && hasDomLT && !lt && gtltComp !== 0) {
    return false
  }

  if (lt && hasDomGT && !gt && gtltComp !== 0) {
    return false
  }

  // we needed a prerelease range in a specific tuple, but didn't get one
  // then this isn't a subset.  eg >=1.2.3-pre is not a subset of >=1.0.0,
  // because it includes prereleases in the 1.2.3 tuple
  if (needDomGTPre || needDomLTPre) {
    return false
  }

  return true
}

// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp > 0 ? a
    : comp < 0 ? b
    : b.operator === '>' && a.operator === '>=' ? b
    : a
}

// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
  if (!a) {
    return b
  }
  const comp = compare(a.semver, b.semver, options)
  return comp < 0 ? a
    : comp > 0 ? b
    : b.operator === '<' && a.operator === '<=' ? b
    : a
}

module.exports = subset
'use strict'

const Range = require('../classes/range')

// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
  new Range(range, options).set
    .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))

module.exports = toComparators
'use strict'

const Range = require('../classes/range')
const validRange = (range, options) => {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, options).range || '*'
  } catch (er) {
    return null
  }
}
module.exports = validRange
{
	"name": "conf",
	"version": "10.2.0",
	"description": "Simple config handling for your app or module",
	"license": "MIT",
	"repository": "sindresorhus/conf",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"main": "dist/source",
	"engines": {
		"node": ">=12"
	},
	"scripts": {
		"test": "xo && npm run build && nyc ava",
		"build": "del-cli dist && tsc",
		"prepack": "npm run build"
	},
	"files": [
		"dist/source"
	],
	"keywords": [
		"config",
		"store",
		"app",
		"storage",
		"conf",
		"configuration",
		"settings",
		"preferences",
		"json",
		"data",
		"persist",
		"persistent",
		"save",
		"load",
		"read",
		"write",
		"cache"
	],
	"dependencies": {
		"ajv": "^8.6.3",
		"ajv-formats": "^2.1.1",
		"atomically": "^1.7.0",
		"debounce-fn": "^4.0.0",
		"dot-prop": "^6.0.1",
		"env-paths": "^2.2.1",
		"json-schema-typed": "^7.0.3",
		"onetime": "^5.1.2",
		"pkg-up": "^3.1.0",
		"semver": "^7.3.5"
	},
	"devDependencies": {
		"@ava/typescript": "^1.1.1",
		"@sindresorhus/tsconfig": "^0.7.0",
		"@types/node": "^14.14.41",
		"@types/semver": "^7.3.4",
		"@types/write-file-atomic": "^3.0.1",
		"ava": "^3.15.0",
		"clear-module": "^4.1.1",
		"del": "^6.0.0",
		"del-cli": "^3.0.1",
		"delay": "^5.0.0",
		"nyc": "^15.1.0",
		"p-event": "^4.2.0",
		"tempy": "^1.0.1",
		"tsd": "^0.14.0",
		"typescript": "^4.4.3",
		"xo": "^0.38.2"
	},
	"types": "dist/source",
	"ava": {
		"files": [
			"test/*",
			"!test/index.test-d.ts"
		],
		"timeout": "1m",
		"typescript": {
			"rewritePaths": {
				"test/": "dist/test/"
			}
		}
	},
	"xo": {
		"rules": {
			"@typescript-eslint/no-implicit-any-catch": "off"
		}
	},
	"nyc": {
		"extension": [
			".ts"
		],
		"exclude": [
			"**/test/**"
		]
	}
}
# conf

> Simple config handling for your app or module

All you have to care about is what to persist. This module will handle all the dull details like where and how.

**It does not support multiple processes writing to the same store.**\
I initially made this tool to let command-line tools persist some data.

*If you need this for Electron, check out [`electron-store`](https://github.com/sindresorhus/electron-store) instead.*

## Install

```
$ npm install conf
```

## Usage

```js
const Conf = require('conf');

const config = new Conf();

config.set('unicorn', '🦄');
console.log(config.get('unicorn'));
//=> '🦄'

// Use dot-notation to access nested properties
config.set('foo.bar', true);
console.log(config.get('foo'));
//=> {bar: true}

config.delete('unicorn');
console.log(config.get('unicorn'));
//=> undefined
```

Or [create a subclass](https://github.com/sindresorhus/electron-store/blob/main/index.js).

## API

Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config.

### Conf(options?)

Returns a new instance.

### options

Type: `object`

#### defaults

Type: `object`

Default values for the config items.

**Note:** The values in `defaults` will overwrite the `default` key in the `schema` option.

#### schema

Type: `object`

[JSON Schema](https://json-schema.org) to validate your config data.

Under the hood, the JSON Schema validator [ajv](https://github.com/epoberezkin/ajv) is used to validate your config. We use [JSON Schema draft-07](https://json-schema.org/latest/json-schema-validation.html) and support all [validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) and [formats](https://github.com/epoberezkin/ajv#formats).

You should define your schema as an object where each key is the name of your data's property and each value is a JSON schema used to validate that property. See more [here](https://json-schema.org/understanding-json-schema/reference/object.html#properties).

Example:

```js
const Conf = require('conf');

const schema = {
	foo: {
		type: 'number',
		maximum: 100,
		minimum: 1,
		default: 50
	},
	bar: {
		type: 'string',
		format: 'url'
	}
};

const config = new Conf({schema});

console.log(config.get('foo'));
//=> 50

config.set('foo', '1');
// [Error: Config schema violation: `foo` should be number]
```

**Note:** The `default` value will be overwritten by the `defaults` option if set.

### migrations

Type: `object`

You can use migrations to perform operations to the store whenever a **project version** is upgraded.

The `migrations` object should consist of a key-value pair of `'version': handler`. The `version` can also be a [semver range](https://github.com/npm/node-semver#ranges).

Example:

```js
const Conf = require('conf');

const store = new Conf({
	migrations: {
		'0.0.1': store => {
			store.set('debugPhase', true);
		},
		'1.0.0': store => {
			store.delete('debugPhase');
			store.set('phase', '1.0.0');
		},
		'1.0.2': store => {
			store.set('phase', '1.0.2');
		},
		'>=2.0.0': store => {
			store.set('phase', '>=2.0.0');
		}
	}
});
```

> Note: The version the migrations use refers to the **project version** by default. If you want to change this behavior, specify the [`projectVersion`](#projectVersion) option.

### beforeEachMigration

Type: `Function`\
Default: `undefined`

The given callback function will be called before each migration step.

The function receives the store as the first argument and a context object as the second argument with the following properties:

- `fromVersion` - The version the migration step is being migrated from.
- `toVersion` - The version the migration step is being migrated to.
- `finalVersion` - The final version after all the migrations are applied.
- `versions` - All the versions with a migration step.

This can be useful for logging purposes, preparing migration data, etc.

Example:

```js
const Conf = require('conf');

console.log = someLogger.log;

const mainConfig = new Conf({
	beforeEachMigration: (store, context) => {
		console.log(`[main-config] migrate from ${context.fromVersion} → ${context.toVersion}`);
	},
	migrations: {
		'0.4.0': store => {
			store.set('debugPhase', true);
		},
	}
});

const secondConfig = new Conf({
	beforeEachMigration: (store, context) => {
		console.log(`[second-config] migrate from ${context.fromVersion} → ${context.toVersion}`);
	},
	migrations: {
		'1.0.1': store => {
			store.set('debugPhase', true);
		},
	}
});
```

#### configName

Type: `string`\
Default: `'config'`

Name of the config file (without extension).

Useful if you need multiple config files for your app or module. For example, different config files between two major versions.

#### projectName

Type: `string`\
Default: The `name` field in the package.json closest to where `conf` is imported.

You only need to specify this if you don't have a package.json file in your project or if it doesn't have a name defined within it.

#### projectVersion

Type: `string`\
Default: The `version` field in the package.json closest to where `conf` is imported.

You only need to specify this if you don't have a package.json file in your project or if it doesn't have a version defined within it.

#### cwd

Type: `string`\
Default: System default [user config directory](https://github.com/sindresorhus/env-paths#pathsconfig)

**You most likely don't need this. Please don't use it unless you really have to. By default, it will pick the optimal location by adhering to system conventions. You are very likely to get this wrong and annoy users.**

Overrides `projectName`.

The only use-case I can think of is having the config located in the app directory or on some external storage.

#### encryptionKey

Type: `string | Buffer | TypedArray | DataView`\
Default: `undefined`

Note that this is **not intended for security purposes**, since the encryption key would be easily found inside a plain-text Node.js app.

Its main use is for obscurity. If a user looks through the config directory and finds the config file, since it's just a JSON file, they may be tempted to modify it. By providing an encryption key, the file will be obfuscated, which should hopefully deter any users from doing so.

When specified, the store will be encrypted using the [`aes-256-cbc`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) encryption algorithm.

#### fileExtension

Type: `string`\
Default: `'json'`

Extension of the config file.

You would usually not need this, but could be useful if you want to interact with a file with a custom file extension that can be associated with your app. These might be simple save/export/preference files that are intended to be shareable or saved outside of the app.

#### clearInvalidConfig

Type: `boolean`\
Default: `false`

The config is cleared if reading the config file causes a `SyntaxError`. This is a good behavior for unimportant data, as the config file is not intended to be hand-edited, so it usually means the config is corrupt and there's nothing the user can do about it anyway. However, if you let the user edit the config file directly, mistakes might happen and it could be more useful to throw an error when the config is invalid instead of clearing.

#### serialize

Type: `Function`\
Default: `value => JSON.stringify(value, null, '\t')`

Function to serialize the config object to a UTF-8 string when writing the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

#### deserialize

Type: `Function`\
Default: `JSON.parse`

Function to deserialize the config object from a UTF-8 string when reading the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

#### projectSuffix

Type: `string`\
Default: `'nodejs'`

**You most likely don't need this. Please don't use it unless you really have to.**

Suffix appended to `projectName` during config file creation to avoid name conflicts with native apps.

You can pass an empty string to remove the suffix.

For example, on macOS, the config file will be stored in the `~/Library/Preferences/foo-nodejs` directory, where `foo` is the `projectName`.

#### accessPropertiesByDotNotation

Type: `boolean`\
Default: `true`

Accessing nested properties by dot notation. For example:

```js
const Conf = require('conf');

const config = new Conf();

config.set({
	foo: {
		bar: {
			foobar: '🦄'
		}
	}
});

console.log(config.get('foo.bar.foobar'));
//=> '🦄'
```

Alternatively, you can set this option to `false` so the whole string would be treated as one key.

```js
const Conf = require('conf');

const config = new Conf({accessPropertiesByDotNotation: false});

config.set({
	`foo.bar.foobar`: '🦄'
});

console.log(config.get('foo.bar.foobar'));
//=> '🦄'
```

#### watch

type: `boolean`\
Default: `false`

Watch for any changes in the config file and call the callback for `onDidChange` or `onDidAnyChange` if set. This is useful if there are multiple processes changing the same config file.

#### configFileMode

Type: `number`\
Default: `0o666`

The [mode](https://en.wikipedia.org/wiki/File-system_permissions#Numeric_notation) that will be used for the config file.

You would usually not need this, but it could be useful if you want to restrict the permissions of the config file. Setting a permission such as `0o600` would result in a config file that can only be accessed by the user running the program.

Note that setting restrictive permissions can cause problems if different users need to read the file. A common problem is a user running your tool with and without `sudo` and then not being able to access the config the second time.

### Instance

You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a `key` to access nested properties.

The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.

#### .set(key, value)

Set an item.

The `value` must be JSON serializable. Trying to set the type `undefined`, `function`, or `symbol` will result in a TypeError.

#### .set(object)

Set multiple items at once.

#### .get(key, defaultValue?)

Get an item or `defaultValue` if the item does not exist.

#### .reset(...keys)

Reset items to their default values, as defined by the `defaults` or `schema` option.

Use `.clear()` to reset all items.

#### .has(key)

Check if an item exists.

#### .delete(key)

Delete an item.

#### .clear()

Delete all items.

This resets known items to their default values, if defined by the `defaults` or `schema` option.

#### .onDidChange(key, callback)

`callback`: `(newValue, oldValue) => {}`

Watches the given `key`, calling `callback` on any changes.

When a key is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.

Returns a function which you can use to unsubscribe:

```js
const unsubscribe = conf.onDidChange(key, callback);

unsubscribe();
```

#### .onDidAnyChange(callback)

`callback`: `(newValue, oldValue) => {}`

Watches the whole config object, calling `callback` on any changes.

`oldValue` and `newValue` will be the config object before and after the change, respectively. You must compare `oldValue` to `newValue` to find out what changed.

Returns a function which you can use to unsubscribe:

```js
const unsubscribe = conf.onDidAnyChange(callback);

unsubscribe();
```

#### .size

Get the item count.

#### .store

Get all the config as an object or replace the current config with an object:

```js
conf.store = {
	hello: 'world'
};
```

#### .path

Get the path to the config file.

## FAQ

### How is this different from [`configstore`](https://github.com/yeoman/configstore)?

I'm also the author of `configstore`. While it's pretty good, I did make some mistakes early on that are hard to change at this point. This module is the result of everything I learned from making `configstore`. Mainly where the config is stored. In `configstore`, the config is stored in `~/.config` (which is mainly a Linux convention) on all systems, while `conf` stores config in the system default [user config directory](https://github.com/sindresorhus/env-paths#pathsconfig). The `~/.config` directory, it turns out, often have an incorrect permission on macOS and Windows, which has caused a lot of grief for users.

### Can I use YAML or another serialization format?

The `serialize` and `deserialize` options can be used to customize the format of the config file, as long as the representation is compatible with `utf8` encoding.

Example using YAML:

```js
const Conf = require('conf');
const yaml = require('js-yaml');

const config = new Conf({
	fileExtension: 'yaml',
	serialize: yaml.safeDump,
	deserialize: yaml.safeLoad
});
```

## Related

- [electron-store](https://github.com/sindresorhus/electron-store) - Simple data persistence for your Electron app or module
- [cache-conf](https://github.com/SamVerschueren/cache-conf) - Simple cache config handling for your app or module
'use strict';
const mimicFn = require('mimic-fn');

module.exports = (inputFunction, options = {}) => {
	if (typeof inputFunction !== 'function') {
		throw new TypeError(`Expected the first argument to be a function, got \`${typeof inputFunction}\``);
	}

	const {
		wait = 0,
		before = false,
		after = true
	} = options;

	if (!before && !after) {
		throw new Error('Both `before` and `after` are false, function wouldn\'t be called.');
	}

	let timeout;
	let result;

	const debouncedFunction = function (...arguments_) {
		const context = this;

		const later = () => {
			timeout = undefined;

			if (after) {
				result = inputFunction.apply(context, arguments_);
			}
		};

		const shouldCallNow = before && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);

		if (shouldCallNow) {
			result = inputFunction.apply(context, arguments_);
		}

		return result;
	};

	mimicFn(debouncedFunction, inputFunction);

	debouncedFunction.cancel = () => {
		if (timeout) {
			clearTimeout(timeout);
			timeout = undefined;
		}
	};

	return debouncedFunction;
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "debounce-fn",
	"version": "4.0.0",
	"description": "Debounce a function",
	"license": "MIT",
	"repository": "sindresorhus/debounce-fn",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=10"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"debounce",
		"function",
		"debouncer",
		"fn",
		"func",
		"throttle",
		"delay",
		"invoked"
	],
	"dependencies": {
		"mimic-fn": "^3.0.0"
	},
	"devDependencies": {
		"ava": "^1.4.1",
		"delay": "^4.2.0",
		"tsd": "^0.11.0",
		"xo": "^0.26.1"
	}
}
# debounce-fn [![Build Status](https://travis-ci.org/sindresorhus/debounce-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/debounce-fn)

> [Debounce](https://davidwalsh.name/javascript-debounce-function) a function

## Install

```
$ npm install debounce-fn
```

## Usage

```js
const debounceFn = require('debounce-fn');

window.onresize = debounceFn(() => {
	// Do something on window resize
}, {wait: 100});
```

## API

### debounceFn(input, options?)

Returns a debounced function that delays calling the `input` function until after `wait` milliseconds have elapsed since the last time the debounced function was called.

It comes with a `.cancel()` method to cancel any scheduled `input` function calls.

#### input

Type: `Function`

Function to debounce.

#### options

Type: `object`

##### wait

Type: `number`\
Default: `0`

Time to wait until the `input` function is called.

##### before

Type: `boolean`\
Default: `false`

Trigger the function on the leading edge of the `wait` interval.

For example, can be useful for preventing accidental double-clicks on a "submit" button from firing a second time.

##### after

Type: `boolean`\
Default: `true`

Trigger the function on the trailing edge of the `wait` interval.

## Related

- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
'use strict';
const isObj = require('is-obj');

const disallowedKeys = new Set([
	'__proto__',
	'prototype',
	'constructor'
]);

const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.has(segment));

function getPathSegments(path) {
	const pathArray = path.split('.');
	const parts = [];

	for (let i = 0; i < pathArray.length; i++) {
		let p = pathArray[i];

		while (p[p.length - 1] === '\\' && pathArray[i + 1] !== undefined) {
			p = p.slice(0, -1) + '.';
			p += pathArray[++i];
		}

		parts.push(p);
	}

	if (!isValidPath(parts)) {
		return [];
	}

	return parts;
}

module.exports = {
	get(object, path, value) {
		if (!isObj(object) || typeof path !== 'string') {
			return value === undefined ? object : value;
		}

		const pathArray = getPathSegments(path);
		if (pathArray.length === 0) {
			return;
		}

		for (let i = 0; i < pathArray.length; i++) {
			object = object[pathArray[i]];

			if (object === undefined || object === null) {
				// `object` is either `undefined` or `null` so we want to stop the loop, and
				// if this is not the last bit of the path, and
				// if it did't return `undefined`
				// it would return `null` if `object` is `null`
				// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
				if (i !== pathArray.length - 1) {
					return value;
				}

				break;
			}
		}

		return object === undefined ? value : object;
	},

	set(object, path, value) {
		if (!isObj(object) || typeof path !== 'string') {
			return object;
		}

		const root = object;
		const pathArray = getPathSegments(path);

		for (let i = 0; i < pathArray.length; i++) {
			const p = pathArray[i];

			if (!isObj(object[p])) {
				object[p] = {};
			}

			if (i === pathArray.length - 1) {
				object[p] = value;
			}

			object = object[p];
		}

		return root;
	},

	delete(object, path) {
		if (!isObj(object) || typeof path !== 'string') {
			return false;
		}

		const pathArray = getPathSegments(path);

		for (let i = 0; i < pathArray.length; i++) {
			const p = pathArray[i];

			if (i === pathArray.length - 1) {
				delete object[p];
				return true;
			}

			object = object[p];

			if (!isObj(object)) {
				return false;
			}
		}
	},

	has(object, path) {
		if (!isObj(object) || typeof path !== 'string') {
			return false;
		}

		const pathArray = getPathSegments(path);
		if (pathArray.length === 0) {
			return false;
		}

		// eslint-disable-next-line unicorn/no-for-loop
		for (let i = 0; i < pathArray.length; i++) {
			if (isObj(object)) {
				if (!(pathArray[i] in object)) {
					return false;
				}

				object = object[pathArray[i]];
			} else {
				return false;
			}
		}

		return true;
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "dot-prop",
	"version": "6.0.1",
	"description": "Get, set, or delete a property from a nested object using a dot path",
	"license": "MIT",
	"repository": "sindresorhus/dot-prop",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=10"
	},
	"scripts": {
		"test": "xo && ava && tsd",
		"bench": "node bench.js"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"object",
		"prop",
		"property",
		"dot",
		"path",
		"get",
		"set",
		"delete",
		"access",
		"notation",
		"dotty"
	],
	"dependencies": {
		"is-obj": "^2.0.0"
	},
	"devDependencies": {
		"ava": "^2.1.0",
		"benchmark": "^2.1.4",
		"tsd": "^0.13.1",
		"xo": "^0.33.1"
	},
	"xo": {
		"rules": {
			"@typescript-eslint/method-signature-style": "off"
		}
	}
}
# dot-prop [![Build Status](https://travis-ci.com/sindresorhus/dot-prop.svg?branch=master)](https://travis-ci.com/github/sindresorhus/dot-prop)

> Get, set, or delete a property from a nested object using a dot path

## Install

```
$ npm install dot-prop
```

## Usage

```js
const dotProp = require('dot-prop');

// Getter
dotProp.get({foo: {bar: 'unicorn'}}, 'foo.bar');
//=> 'unicorn'

dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep');
//=> undefined

dotProp.get({foo: {bar: 'a'}}, 'foo.notDefined.deep', 'default value');
//=> 'default value'

dotProp.get({foo: {'dot.dot': 'unicorn'}}, 'foo.dot\\.dot');
//=> 'unicorn'

// Setter
const object = {foo: {bar: 'a'}};
dotProp.set(object, 'foo.bar', 'b');
console.log(object);
//=> {foo: {bar: 'b'}}

const foo = dotProp.set({}, 'foo.bar', 'c');
console.log(foo);
//=> {foo: {bar: 'c'}}

dotProp.set(object, 'foo.baz', 'x');
console.log(object);
//=> {foo: {bar: 'b', baz: 'x'}}

// Has
dotProp.has({foo: {bar: 'unicorn'}}, 'foo.bar');
//=> true

// Deleter
const object = {foo: {bar: 'a'}};
dotProp.delete(object, 'foo.bar');
console.log(object);
//=> {foo: {}}

object.foo.bar = {x: 'y', y: 'x'};
dotProp.delete(object, 'foo.bar.x');
console.log(object);
//=> {foo: {bar: {y: 'x'}}}
```

## API

### get(object, path, defaultValue?)

Get the value of the property at the given path.

Returns the value if any.

### set(object, path, value)

Set the property at the given path to the given value.

Returns the object.

### has(object, path)

Check whether the property at the given path exists.

Returns a boolean.

### delete(object, path)

Delete the property at the given path.

Returns a boolean of whether the property existed before being deleted.

#### object

Type: `object`

Object to get, set, or delete the `path` value.

You are allowed to pass in `undefined` as the object to the `get` and `has` functions.

#### path

Type: `string`

Path of the property in the object, using `.` to separate each nested key.

Use `\\.` if you have a `.` in the key.

The following path components are invalid and results in `undefined` being returned: `__proto__`, `prototype`, `constructor`.

#### value

Type: `unknown`

Value to set at `path`.

#### defaultValue

Type: `unknown`

Default value.

---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-dot-prop?utm_source=npm-dot-prop&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
'use strict';
const path = require('path');
const {app, ipcMain, ipcRenderer, shell} = require('electron');
const Conf = require('conf');

let isInitialized = false;

// Set up the `ipcMain` handler for communication between renderer and main process.
const initDataListener = () => {
	if (!ipcMain || !app) {
		throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
	}

	const appData = {
		defaultCwd: app.getPath('userData'),
		appVersion: app.getVersion()
	};

	if (isInitialized) {
		return appData;
	}

	ipcMain.on('electron-store-get-data', event => {
		event.returnValue = appData;
	});

	isInitialized = true;

	return appData;
};

class ElectronStore extends Conf {
	constructor(options) {
		let defaultCwd;
		let appVersion;

		// If we are in the renderer process, we communicate with the main process
		// to get the required data for the module otherwise, we pull from the main process.
		if (ipcRenderer) {
			const appData = ipcRenderer.sendSync('electron-store-get-data');

			if (!appData) {
				throw new Error('Electron Store: You need to call `.initRenderer()` from the main process.');
			}

			({defaultCwd, appVersion} = appData);
		} else if (ipcMain && app) {
			({defaultCwd, appVersion} = initDataListener());
		}

		options = {
			name: 'config',
			...options
		};

		if (!options.projectVersion) {
			options.projectVersion = appVersion;
		}

		if (options.cwd) {
			options.cwd = path.isAbsolute(options.cwd) ? options.cwd : path.join(defaultCwd, options.cwd);
		} else {
			options.cwd = defaultCwd;
		}

		options.configName = options.name;
		delete options.name;

		super(options);
	}

	static initRenderer() {
		initDataListener();
	}

	async openInEditor() {
		const error = await shell.openPath(this.path);

		if (error) {
			throw new Error(error);
		}
	}
}

module.exports = ElectronStore;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "electron-store",
	"version": "8.2.0",
	"description": "Simple data persistence for your Electron app or module - Save and load user settings, app state, cache, etc",
	"license": "MIT",
	"repository": "sindresorhus/electron-store",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"sideEffects": false,
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"electron",
		"store",
		"app",
		"config",
		"storage",
		"conf",
		"configuration",
		"settings",
		"preferences",
		"json",
		"data",
		"persist",
		"persistent",
		"save"
	],
	"dependencies": {
		"conf": "^10.2.0",
		"type-fest": "^2.17.0"
	},
	"devDependencies": {
		"ava": "^2.4.0",
		"electron": "^12.0.4",
		"execa": "^5.0.0",
		"tsd": "^0.14.0",
		"xo": "^0.38.2"
	},
	"xo": {
		"envs": [
			"node",
			"browser"
		]
	}
}
# electron-store

> Simple data persistence for your [Electron](https://electronjs.org) app or module - Save and load user settings, app state, cache, etc

Electron doesn't have a built-in way to persist user settings and other data. This module handles that for you, so you can focus on building your app. The data is saved in a JSON file named config.json in [`app.getPath('userData')`](https://electronjs.org/docs/api/app#appgetpathname).

You can use this module directly in both the main and renderer process. For use in the renderer process only, you need to call `Store.initRenderer()` in the main process, or create a new Store instance (`new Store()`) in the main process.

## Install

```sh
npm install electron-store
```

*Requires Electron 11 or later.*

## Usage

```js
const Store = require('electron-store');

const store = new Store();

store.set('unicorn', '🦄');
console.log(store.get('unicorn'));
//=> '🦄'

// Use dot-notation to access nested properties
store.set('foo.bar', true);
console.log(store.get('foo'));
//=> {bar: true}

store.delete('unicorn');
console.log(store.get('unicorn'));
//=> undefined
```

## API

Changes are written to disk atomically, so if the process crashes during a write, it will not corrupt the existing config.

### Store(options?)

Returns a new instance.

### options

Type: `object`

#### defaults

Type: `object`

Default values for the store items.

**Note:** The values in `defaults` will overwrite the `default` key in the `schema` option.

#### schema

type: `object`

[JSON Schema](https://json-schema.org) to validate your config data.

Under the hood, the JSON Schema validator [ajv](https://github.com/epoberezkin/ajv) is used to validate your config. We use [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) and support all [validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) and [formats](https://github.com/epoberezkin/ajv#formats).

You should define your schema as an object where each key is the name of your data's property and each value is a JSON schema used to validate that property. See more [here](https://json-schema.org/understanding-json-schema/reference/object.html#properties).

Example:

```js
const Store = require('electron-store');

const schema = {
	foo: {
		type: 'number',
		maximum: 100,
		minimum: 1,
		default: 50
	},
	bar: {
		type: 'string',
		format: 'url'
	}
};

const store = new Store({schema});

console.log(store.get('foo'));
//=> 50

store.set('foo', '1');
// [Error: Config schema violation: `foo` should be number]
```

**Note:** The `default` value will be overwritten by the `defaults` option if set.

#### migrations

Type: `object`

**Important: I cannot provide support for this feature. It has some known bugs. I have no plans to work on it, but pull requests are welcome.**

You can use migrations to perform operations to the store whenever a version is upgraded.

The `migrations` object should consist of a key-value pair of `'version': handler`. The `version` can also be a [semver range](https://github.com/npm/node-semver#ranges).

Example:

```js
const Store = require('electron-store');

const store = new Store({
	migrations: {
		'0.0.1': store => {
			store.set('debugPhase', true);
		},
		'1.0.0': store => {
			store.delete('debugPhase');
			store.set('phase', '1.0.0');
		},
		'1.0.2': store => {
			store.set('phase', '1.0.2');
		},
		'>=2.0.0': store => {
			store.set('phase', '>=2.0.0');
		}
	}
});
```

### beforeEachMigration

Type: `Function`\
Default: `undefined`

The given callback function will be called before each migration step.

The function receives the store as the first argument and a context object as the second argument with the following properties:

- `fromVersion` - The version the migration step is being migrated from.
- `toVersion` - The version the migration step is being migrated to.
- `finalVersion` - The final version after all the migrations are applied.
- `versions` - All the versions with a migration step.

This can be useful for logging purposes, preparing migration data, etc.

Example:

```js
const Store = require('electron-store');

console.log = someLogger.log;

const mainConfig = new Store({
	beforeEachMigration: (store, context) => {
		console.log(`[main-config] migrate from ${context.fromVersion} → ${context.toVersion}`);
	},
	migrations: {
		'0.4.0': store => {
			store.set('debugPhase', true);
		}
	}
});

const secondConfig = new Store({
	beforeEachMigration: (store, context) => {
		console.log(`[second-config] migrate from ${context.fromVersion} → ${context.toVersion}`);
	},
	migrations: {
		'1.0.1': store => {
			store.set('debugPhase', true);
		}
	}
});
```

#### name

Type: `string`\
Default: `'config'`

Name of the storage file (without extension).

This is useful if you want multiple storage files for your app. Or if you're making a reusable Electron module that persists some data, in which case you should **not** use the name `config`.

#### cwd

Type: `string`\
Default: [`app.getPath('userData')`](https://electronjs.org/docs/api/app#appgetpathname)

Storage file location. *Don't specify this unless absolutely necessary! By default, it will pick the optimal location by adhering to system conventions. You are very likely to get this wrong and annoy users.*

If a relative path, it's relative to the default cwd. For example, `{cwd: 'unicorn'}` would result in a storage file in `~/Library/Application Support/App Name/unicorn`.

#### encryptionKey

Type: `string | Buffer | TypedArray | DataView`\
Default: `undefined`

Note that this is **not intended for security purposes**, since the encryption key would be easily found inside a plain-text Node.js app.

Its main use is for obscurity. If a user looks through the config directory and finds the config file, since it's just a JSON file, they may be tempted to modify it. By providing an encryption key, the file will be obfuscated, which should hopefully deter any users from doing so.

When specified, the store will be encrypted using the [`aes-256-cbc`](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation) encryption algorithm.

#### fileExtension

Type: `string`\
Default: `'json'`

Extension of the config file.

You would usually not need this, but could be useful if you want to interact with a file with a custom file extension that can be associated with your app. These might be simple save/export/preference files that are intended to be shareable or saved outside of the app.

#### clearInvalidConfig

Type: `boolean`\
Default: `false`

The config is cleared if reading the config file causes a `SyntaxError`. This is a good behavior for unimportant data, as the config file is not intended to be hand-edited, so it usually means the config is corrupt and there's nothing the user can do about it anyway. However, if you let the user edit the config file directly, mistakes might happen and it could be more useful to throw an error when the config is invalid instead of clearing.

#### serialize

Type: `Function`\
Default: `value => JSON.stringify(value, null, '\t')`

Function to serialize the config object to a UTF-8 string when writing the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

#### deserialize

Type: `Function`\
Default: `JSON.parse`

Function to deserialize the config object from a UTF-8 string when reading the config file.

You would usually not need this, but it could be useful if you want to use a format other than JSON.

#### accessPropertiesByDotNotation

Type: `boolean`\
Default: `true`

Accessing nested properties by dot notation. For example:

```js
const Store = require('electron-store');

const store = new Store();

store.set({
	foo: {
		bar: {
			foobar: '🦄'
		}
	}
});

console.log(store.get('foo.bar.foobar'));
//=> '🦄'
```

Alternatively, you can set this option to `false` so the whole string would be treated as one key.

```js
const store = new Store({accessPropertiesByDotNotation: false});

store.set({
	`foo.bar.foobar`: '🦄'
});

console.log(store.get('foo.bar.foobar'));
//=> '🦄'
```

#### watch

Type: `boolean`\
Default: `false`

Watch for any changes in the config file and call the callback for `onDidChange` or `onDidAnyChange` if set. This is useful if there are multiple processes changing the same config file, for example, if you want changes done in the main process to be reflected in a renderer process.

### Instance

You can use [dot-notation](https://github.com/sindresorhus/dot-prop) in a `key` to access nested properties.

The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.

#### .set(key, value)

Set an item.

The `value` must be JSON serializable. Trying to set the type `undefined`, `function`, or `symbol` will result in a TypeError.

#### .set(object)

Set multiple items at once.

#### .get(key, defaultValue?)

Get an item or `defaultValue` if the item does not exist.

#### .reset(...keys)

Reset items to their default values, as defined by the `defaults` or `schema` option.

Use `.clear()` to reset all items.

#### .has(key)

Check if an item exists.

#### .delete(key)

Delete an item.

#### .clear()

Delete all items.

This resets known items to their default values, if defined by the `defaults` or `schema` option.

#### .onDidChange(key, callback)

`callback`: `(newValue, oldValue) => {}`

Watches the given `key`, calling `callback` on any changes.

When a key is first set `oldValue` will be `undefined`, and when a key is deleted `newValue` will be `undefined`.

Returns a function which you can use to unsubscribe:

```js
const unsubscribe = store.onDidChange(key, callback);

unsubscribe();
```

#### .onDidAnyChange(callback)

`callback`: `(newValue, oldValue) => {}`

Watches the whole config object, calling `callback` on any changes.

`oldValue` and `newValue` will be the config object before and after the change, respectively. You must compare `oldValue` to `newValue` to find out what changed.

Returns a function which you can use to unsubscribe:

```js
const unsubscribe = store.onDidAnyChange(callback);

unsubscribe();
```

#### .size

Get the item count.

#### .store

Get all the data as an object or replace the current data with an object:

```js
const Store = require('electron-store');

const store = new Store();

store.store = {
	hello: 'world'
};
```

#### .path

Get the path to the storage file.

#### .openInEditor()

Open the storage file in the user's editor.

Returns a promise that resolves when the editor has been opened, or rejects if it failed to open.

### initRenderer()

Initializer to set up the required `ipc` communication channels for the module when a `Store` instance is not created in the main process and you are creating a `Store` instance in the Electron renderer process only.

In the main process:

```js
const Store = require('electron-store');

Store.initRenderer();
```

And in the renderer process:

```js
const Store = require('electron-store');

const store = new Store();

store.set('unicorn', '🦄');
console.log(store.get('unicorn'));
//=> '🦄'
```

## FAQ

#### [Advantages over `window.localStorage`](https://github.com/sindresorhus/electron-store/issues/17)

#### Can I use YAML or another serialization format?

The `serialize` and `deserialize` options can be used to customize the format of the config file, as long as the representation is compatible with `utf8` encoding.

Example using YAML:

```js
const Store = require('electron-store');
const yaml = require('js-yaml');

const store = new Store({
	fileExtension: 'yaml',
	serialize: yaml.safeDump,
	deserialize: yaml.safeLoad
});
```

#### How do I get store values in the renderer process when my store was initialized in the main process?

The store is not a singleton, so you will need to either [initialize the store in a file that is imported in both the main and renderer process](https://github.com/sindresorhus/electron-store/issues/15), or you have to pass the values back and forth as messages. Electron provides a handy [`invoke/handle` API](https://www.electronjs.org/docs/api/ipc-main#ipcmainhandlechannel-listener) that works well for accessing these values.

```js
ipcMain.handle('getStoreValue', (event, key) => {
	return store.get(key);
});
```

```js
const foo = await ipcRenderer.invoke('getStoreValue', 'foo');
```

#### Can I use it for large amounts of data?

This package is not a database. It simply uses a JSON file that is read/written on every change. Prefer using it for smaller amounts of data like user settings, value caching, state, etc.

If you need to store large blobs of data, I recommend saving it to disk and to use this package to store the path to the file instead.

## Related

- [electron-util](https://github.com/sindresorhus/electron-util) - Useful utilities for developing Electron apps and modules
- [electron-debug](https://github.com/sindresorhus/electron-debug) - Adds useful debug features to your Electron app
- [electron-context-menu](https://github.com/sindresorhus/electron-context-menu) - Context menu for your Electron app
- [electron-dl](https://github.com/sindresorhus/electron-dl) - Simplified file downloads for your Electron app
- [electron-unhandled](https://github.com/sindresorhus/electron-unhandled) - Catch unhandled errors and promise rejections in your Electron app
- [electron-reloader](https://github.com/sindresorhus/electron-reloader) - Simple auto-reloading for Electron apps during development
- [electron-serve](https://github.com/sindresorhus/electron-serve) - Static file serving for Electron apps
- [conf](https://github.com/sindresorhus/conf) - Simple config handling for your app or module
- [More…](https://github.com/search?q=user%3Asindresorhus+electron)
'use strict';
const path = require('path');
const os = require('os');

const homedir = os.homedir();
const tmpdir = os.tmpdir();
const {env} = process;

const macos = name => {
	const library = path.join(homedir, 'Library');

	return {
		data: path.join(library, 'Application Support', name),
		config: path.join(library, 'Preferences', name),
		cache: path.join(library, 'Caches', name),
		log: path.join(library, 'Logs', name),
		temp: path.join(tmpdir, name)
	};
};

const windows = name => {
	const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
	const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');

	return {
		// Data/config/cache/log are invented by me as Windows isn't opinionated about this
		data: path.join(localAppData, name, 'Data'),
		config: path.join(appData, name, 'Config'),
		cache: path.join(localAppData, name, 'Cache'),
		log: path.join(localAppData, name, 'Log'),
		temp: path.join(tmpdir, name)
	};
};

// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
const linux = name => {
	const username = path.basename(homedir);

	return {
		data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
		config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
		cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
		// https://wiki.debian.org/XDGBaseDirectorySpecification#state
		log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
		temp: path.join(tmpdir, username, name)
	};
};

const envPaths = (name, options) => {
	if (typeof name !== 'string') {
		throw new TypeError(`Expected string, got ${typeof name}`);
	}

	options = Object.assign({suffix: 'nodejs'}, options);

	if (options.suffix) {
		// Add suffix to prevent possible conflict with native apps
		name += `-${options.suffix}`;
	}

	if (process.platform === 'darwin') {
		return macos(name);
	}

	if (process.platform === 'win32') {
		return windows(name);
	}

	return linux(name);
};

module.exports = envPaths;
// TODO: Remove this for the next major release
module.exports.default = envPaths;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "env-paths",
	"version": "2.2.1",
	"description": "Get paths for storing things like data, config, cache, etc",
	"license": "MIT",
	"repository": "sindresorhus/env-paths",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"common",
		"user",
		"paths",
		"env",
		"environment",
		"directory",
		"dir",
		"appdir",
		"path",
		"data",
		"config",
		"cache",
		"logs",
		"temp",
		"linux",
		"unix"
	],
	"devDependencies": {
		"ava": "^1.4.1",
		"tsd": "^0.7.1",
		"xo": "^0.24.0"
	}
}
# env-paths

> Get paths for storing things like data, config, cache, etc

Uses the correct OS-specific paths. Most developers get this wrong.


## Install

```
$ npm install env-paths
```


## Usage

```js
const envPaths = require('env-paths');

const paths = envPaths('MyApp');

paths.data;
//=> '/home/sindresorhus/.local/share/MyApp-nodejs'

paths.config
//=> '/home/sindresorhus/.config/MyApp-nodejs'
```


## API

### paths = envPaths(name, options?)

Note: It only generates the path strings. It doesn't create the directories for you. You could use [`make-dir`](https://github.com/sindresorhus/make-dir) to create the directories.

#### name

Type: `string`

Name of your project. Used to generate the paths.

#### options

Type: `object`

##### suffix

Type: `string`<br>
Default: `'nodejs'`

**Don't use this option unless you really have to!**<br>
Suffix appended to the project name to avoid name conflicts with native
apps. Pass an empty string to disable it.

### paths.data

Directory for data files.

Example locations (with the default `nodejs` [suffix](#suffix)):

- macOS: `~/Library/Application Support/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Data` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Data`)
- Linux: `~/.local/share/MyApp-nodejs` (or `$XDG_DATA_HOME/MyApp-nodejs`)

### paths.config

Directory for config files.

Example locations (with the default `nodejs` [suffix](#suffix)):

- macOS: `~/Library/Preferences/MyApp-nodejs`
- Windows: `%APPDATA%\MyApp-nodejs\Config` (for example, `C:\Users\USERNAME\AppData\Roaming\MyApp-nodejs\Config`)
- Linux: `~/.config/MyApp-nodejs` (or `$XDG_CONFIG_HOME/MyApp-nodejs`)

### paths.cache

Directory for non-essential data files.

Example locations (with the default `nodejs` [suffix](#suffix)):

- macOS: `~/Library/Caches/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Cache` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Cache`)
- Linux: `~/.cache/MyApp-nodejs` (or `$XDG_CACHE_HOME/MyApp-nodejs`)

### paths.log

Directory for log files.

Example locations (with the default `nodejs` [suffix](#suffix)):

- macOS: `~/Library/Logs/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Log` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Log`)
- Linux: `~/.local/state/MyApp-nodejs` (or `$XDG_STATE_HOME/MyApp-nodejs`)

### paths.temp

Directory for temporary files.

Example locations (with the default `nodejs` [suffix](#suffix)):

- macOS: `/var/folders/jf/f2twvvvs5jl_m49tf034ffpw0000gn/T/MyApp-nodejs`
- Windows: `%LOCALAPPDATA%\Temp\MyApp-nodejs` (for example, `C:\Users\USERNAME\AppData\Local\Temp\MyApp-nodejs`)
- Linux: `/tmp/USERNAME/MyApp-nodejs`

---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-env-paths?utm_source=npm-env-paths&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
'use strict';
const path = require('path');
const locatePath = require('locate-path');

module.exports = (filename, opts = {}) => {
	const startDir = path.resolve(opts.cwd || '');
	const {root} = path.parse(startDir);

	const filenames = [].concat(filename);

	return new Promise(resolve => {
		(function find(dir) {
			locatePath(filenames, {cwd: dir}).then(file => {
				if (file) {
					resolve(path.join(dir, file));
				} else if (dir === root) {
					resolve(null);
				} else {
					find(path.dirname(dir));
				}
			});
		})(startDir);
	});
};

module.exports.sync = (filename, opts = {}) => {
	let dir = path.resolve(opts.cwd || '');
	const {root} = path.parse(dir);

	const filenames = [].concat(filename);

	// eslint-disable-next-line no-constant-condition
	while (true) {
		const file = locatePath.sync(filenames, {cwd: dir});

		if (file) {
			return path.join(dir, file);
		}

		if (dir === root) {
			return null;
		}

		dir = path.dirname(dir);
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "find-up",
	"version": "3.0.0",
	"description": "Find a file or directory by walking up parent directories",
	"license": "MIT",
	"repository": "sindresorhus/find-up",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava"
	},
	"files": [
		"index.js"
	],
	"keywords": [
		"find",
		"up",
		"find-up",
		"findup",
		"look-up",
		"look",
		"file",
		"search",
		"match",
		"package",
		"resolve",
		"parent",
		"parents",
		"folder",
		"directory",
		"dir",
		"walk",
		"walking",
		"path"
	],
	"dependencies": {
		"locate-path": "^3.0.0"
	},
	"devDependencies": {
		"ava": "*",
		"tempy": "^0.2.1",
		"xo": "*"
	}
}
# find-up [![Build Status: Linux and macOS](https://travis-ci.org/sindresorhus/find-up.svg?branch=master)](https://travis-ci.org/sindresorhus/find-up) [![Build Status: Windows](https://ci.appveyor.com/api/projects/status/l0cyjmvh5lq72vq2/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/find-up/branch/master)

> Find a file or directory by walking up parent directories


## Install

```
$ npm install find-up
```


## Usage

```
/
└── Users
		└── sindresorhus
				├── unicorn.png
				└── foo
						└── bar
								├── baz
								└── example.js
```

`example.js`

```js
const findUp = require('find-up');

(async () => {
	console.log(await findUp('unicorn.png'));
	//=> '/Users/sindresorhus/unicorn.png'

	console.log(await findUp(['rainbow.png', 'unicorn.png']));
	//=> '/Users/sindresorhus/unicorn.png'
})();
```


## API

### findUp(filename, [options])

Returns a `Promise` for either the filepath or `null` if it couldn't be found.

### findUp([filenameA, filenameB], [options])

Returns a `Promise` for either the first filepath found (by respecting the order) or `null` if none could be found.

### findUp.sync(filename, [options])

Returns a filepath or `null`.

### findUp.sync([filenameA, filenameB], [options])

Returns the first filepath found (by respecting the order) or `null`.

#### filename

Type: `string`

Filename of the file to find.

#### options

Type: `Object`

##### cwd

Type: `string`<br>
Default: `process.cwd()`

Directory to start from.


## Related

- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
BSD-2-Clause License

Copyright (c) 2018 IETF Trust, Austin Wright, Henry Andrews, Geraint Luff,
and Cloudflare, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

# json-schema-typed

JSON Schema draft-07 TypeScript definitions with complete inline documentation
for each property.

[![code style: Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
[![npm](https://img.shields.io/npm/v/json-schema-typed.svg?style=flat-square)](https://npmjs.org/package/json-schema-typed)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)
[![License](https://img.shields.io/badge/license-BSD--2--Clause-blue.svg?style=flat-square)](https://github.com/typeschema/json-schema-typed/blob/master/LICENSE)

## Install

```sh
npm install json-schema-typed # NPM
yarn add json-schema-typed # or Yarn
```

## Usage

TypeScript:

```typescript
import { JSONSchema } from 'json-schema-typed'

const schema: JSONSchema = {
  // ...
}
```

## API

Additional exports:

| Name                        | Type       | Purpose                                                    |
| --------------------------- | ---------- | ---------------------------------------------------------- |
| `JSONSchemaFormat`          | Enum       | JSON Schema string formats.                                |
| `JSONSchemaType`            | Enum       | Standard values for the "type" field.                      |
| `JSONSchemaContentEncoding` | Enum       | JSON Schema content encoding strategies.                   |
| `JSONSchemaKeys`            | `string[]` | All the standard property keys available in a JSON schema. |

## Versioning

```
+----- Major version is synchronized with the major version of JSON Schema.
| +--- Minor version has BREAKING CHANGE and/or new features.
| | +- Patch version.
| | |
x.x.x
```

---

## Sponsors

- [Loomble](https://loomble.com/)

## Maintainers

- [Jay Rylan](https://jayrylan.com/)

## License

[BSD-2-Clause](https://github.com/typeschema/json-schema-typed/blob/master/LICENSE)
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(exports.JSONSchemaFormat || (exports.JSONSchemaFormat = {}));

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(exports.JSONSchemaType || (exports.JSONSchemaType = {}));

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(exports.JSONSchemaContentEncoding || (exports.JSONSchemaContentEncoding = {}));

const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];

exports.JSONSchemaKeys = JSONSchemaKeys;
//# sourceMappingURL=index.js.map
"use strict";

export let JSONSchemaFormat;

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(JSONSchemaFormat || (JSONSchemaFormat = {}));

export let JSONSchemaType;

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(JSONSchemaType || (JSONSchemaType = {}));

export let JSONSchemaContentEncoding;

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));

export const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];let JSONSchemaFormat;

(function (JSONSchemaFormat) {
  JSONSchemaFormat["Date"] = "date";
  JSONSchemaFormat["DateTime"] = "date-time";
  JSONSchemaFormat["Email"] = "email";
  JSONSchemaFormat["Hostname"] = "hostname";
  JSONSchemaFormat["IDNEmail"] = "idn-email";
  JSONSchemaFormat["IDNHostname"] = "idn-hostname";
  JSONSchemaFormat["IPv4"] = "ipv4";
  JSONSchemaFormat["IPv6"] = "ipv6";
  JSONSchemaFormat["IRI"] = "iri";
  JSONSchemaFormat["IRIReference"] = "iri-reference";
  JSONSchemaFormat["JSONPointer"] = "json-pointer";
  JSONSchemaFormat["JSONPointerURIFragment"] = "json-pointer-uri-fragment";
  JSONSchemaFormat["RegEx"] = "regex";
  JSONSchemaFormat["RelativeJSONPointer"] = "relative-json-pointer";
  JSONSchemaFormat["Time"] = "time";
  JSONSchemaFormat["URI"] = "uri";
  JSONSchemaFormat["URIReference"] = "uri-reference";
  JSONSchemaFormat["URITemplate"] = "uri-template";
  JSONSchemaFormat["UUID"] = "uuid";
})(JSONSchemaFormat || (JSONSchemaFormat = {}));

let JSONSchemaType;

(function (JSONSchemaType) {
  JSONSchemaType["Array"] = "array";
  JSONSchemaType["Boolean"] = "boolean";
  JSONSchemaType["Integer"] = "integer";
  JSONSchemaType["Null"] = "null";
  JSONSchemaType["Number"] = "number";
  JSONSchemaType["Object"] = "object";
  JSONSchemaType["String"] = "string";
})(JSONSchemaType || (JSONSchemaType = {}));

let JSONSchemaContentEncoding;

(function (JSONSchemaContentEncoding) {
  JSONSchemaContentEncoding["7bit"] = "7bit";
  JSONSchemaContentEncoding["8bit"] = "8bit";
  JSONSchemaContentEncoding["Binary"] = "binary";
  JSONSchemaContentEncoding["QuotedPrintable"] = "quoted-printable";
  JSONSchemaContentEncoding["Base64"] = "base64";
  JSONSchemaContentEncoding["IETFToken"] = "ietf-token";
  JSONSchemaContentEncoding["XToken"] = "x-token";
})(JSONSchemaContentEncoding || (JSONSchemaContentEncoding = {}));

const JSONSchemaKeys = ['$comment', '$id', '$ref', '$schema', 'additionalItems', 'additionalProperties', 'allOf', 'anyOf', 'const', 'contains', 'contentEncoding', 'contentMediaType', 'default', 'definitions', 'dependencies', 'description', 'else', 'enum', 'examples', 'exclusiveMaximum', 'exclusiveMinimum', 'format', 'if', 'items', 'maximum', 'maxItems', 'maxLength', 'maxProperties', 'minimum', 'minItems', 'minLength', 'minProperties', 'multipleOf', 'not', 'oneOf', 'pattern', 'patternProperties', 'properties', 'propertyNames', 'readOnly', 'required', 'then', 'title', 'type', 'uniqueItems', 'writeOnly'];

export { JSONSchemaContentEncoding, JSONSchemaFormat, JSONSchemaKeys, JSONSchemaType };
//# sourceMappingURL=index.js.map
{
  "name": "json-schema-typed",
  "description": "JSONSchema TypeScript definitions.",
  "version": "7.0.3",
  "license": "BSD-2-Clause",
  "files": [
    "dist-*/",
    "bin/"
  ],
  "pika": true,
  "sideEffects": false,
  "keywords": [
    "jsonschema",
    "typescript"
  ],
  "homepage": "https://github.com/typeslick/json-schema-typed",
  "contributors": [
    {
      "name": "Austin Wright",
      "email": "aaa@bzfx.net"
    },
    {
      "name": "Henry Andrews",
      "email": "henry@cloudflare.com"
    },
    {
      "name": "Geraint Luff",
      "email": "luffgd@gmail.com"
    },
    {
      "name": "Jay Rylan",
      "email": "jay@jayrylan.com"
    }
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/typeslick/json-schema-typed.git"
  },
  "dependencies": {},
  "devDependencies": {
    "@babel/cli": "7.6.4",
    "@babel/core": "7.6.4",
    "@babel/runtime-corejs2": "7.6.3",
    "@loomble/cspell-dictionary": "1.0.0",
    "@microsoft/api-extractor": "7.3.4",
    "@pika/pack": "0.5.0",
    "@pika/plugin-build-node": "0.7.1",
    "@pika/plugin-build-types": "0.7.1",
    "@pika/plugin-build-web": "0.7.1",
    "@pika/plugin-standard-pkg": "0.7.1",
    "@types/babel__core": "7.1.3",
    "@types/jest": "24.0.20",
    "@types/jest-diff": "20.0.1",
    "@types/node": "12.11.7",
    "babel-core": "6.26.3",
    "babel-jest": "24.9.0",
    "babel-preset-slick": "7.0.4",
    "core-js": "3.3.4",
    "cspell": "4.0.31",
    "deep-sort-object": "1.0.2",
    "jest": "24.9.0",
    "jest-serializer-path": "0.1.15",
    "prettier": "1.18.2",
    "tsconfig-slick": "3.0.2",
    "tslint": "5.20.0",
    "tslint-slick": "5.0.0",
    "typedoc": "0.15.0",
    "typedoc-plugin-markdown": "2.2.11",
    "typescript": "3.6.4",
    "typescript-tslint-plugin": "0.5.4"
  },
  "esnext": "dist-src/index.js",
  "main": "dist-node/index.js",
  "module": "dist-web/index.js",
  "types": "dist-types/index.d.ts"
}
'use strict';
const path = require('path');
const pathExists = require('path-exists');
const pLocate = require('p-locate');

module.exports = (iterable, options) => {
	options = Object.assign({
		cwd: process.cwd()
	}, options);

	return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options);
};

module.exports.sync = (iterable, options) => {
	options = Object.assign({
		cwd: process.cwd()
	}, options);

	for (const el of iterable) {
		if (pathExists.sync(path.resolve(options.cwd, el))) {
			return el;
		}
	}
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "locate-path",
	"version": "3.0.0",
	"description": "Get the first path that exists on disk of multiple paths",
	"license": "MIT",
	"repository": "sindresorhus/locate-path",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava"
	},
	"files": [
		"index.js"
	],
	"keywords": [
		"locate",
		"path",
		"paths",
		"file",
		"files",
		"exists",
		"find",
		"finder",
		"search",
		"searcher",
		"array",
		"iterable",
		"iterator"
	],
	"dependencies": {
		"p-locate": "^3.0.0",
		"path-exists": "^3.0.0"
	},
	"devDependencies": {
		"ava": "*",
		"xo": "*"
	}
}
# locate-path [![Build Status](https://travis-ci.org/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.org/sindresorhus/locate-path)

> Get the first path that exists on disk of multiple paths


## Install

```
$ npm install locate-path
```


## Usage

Here we find the first file that exists on disk, in array order.

```js
const locatePath = require('locate-path');

const files = [
	'unicorn.png',
	'rainbow.png', // Only this one actually exists on disk
	'pony.png'
];

(async () => {
	console(await locatePath(files));
	//=> 'rainbow'
})();
```


## API

### locatePath(input, [options])

Returns a `Promise` for the first path that exists or `undefined` if none exists.

#### input

Type: `Iterable<string>`

Paths to check.

#### options

Type: `Object`

##### concurrency

Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`

Number of concurrently pending promises.

##### preserveOrder

Type: `boolean`<br>
Default: `true`

Preserve `input` order when searching.

Disable this to improve performance if you don't care about the order.

##### cwd

Type: `string`<br>
Default: `process.cwd()`

Current working directory.

### locatePath.sync(input, [options])

Returns the first path that exists or `undefined` if none exists.

#### input

Type: `Iterable<string>`

Paths to check.

#### options

Type: `Object`

##### cwd

Same as above.


## Related

- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
'use strict';

const copyProperty = (to, from, property, ignoreNonConfigurable) => {
	// `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
	// `Function#prototype` is non-writable and non-configurable so can never be modified.
	if (property === 'length' || property === 'prototype') {
		return;
	}

	// `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
	if (property === 'arguments' || property === 'caller') {
		return;
	}

	const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
	const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);

	if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
		return;
	}

	Object.defineProperty(to, property, fromDescriptor);
};

// `Object.defineProperty()` throws if the property exists, is not configurable and either:
//  - one its descriptors is changed
//  - it is non-writable and its value is changed
const canCopyProperty = function (toDescriptor, fromDescriptor) {
	return toDescriptor === undefined || toDescriptor.configurable || (
		toDescriptor.writable === fromDescriptor.writable &&
		toDescriptor.enumerable === fromDescriptor.enumerable &&
		toDescriptor.configurable === fromDescriptor.configurable &&
		(toDescriptor.writable || toDescriptor.value === fromDescriptor.value)
	);
};

const changePrototype = (to, from) => {
	const fromPrototype = Object.getPrototypeOf(from);
	if (fromPrototype === Object.getPrototypeOf(to)) {
		return;
	}

	Object.setPrototypeOf(to, fromPrototype);
};

const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;

const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');

// We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
// We use `bind()` instead of a closure for the same reason.
// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
const changeToString = (to, from, name) => {
	const withName = name === '' ? '' : `with ${name.trim()}() `;
	const newToString = wrappedToString.bind(null, withName, from.toString());
	// Ensure `to.toString.toString` is non-enumerable and has the same `same`
	Object.defineProperty(newToString, 'name', toStringName);
	Object.defineProperty(to, 'toString', {...toStringDescriptor, value: newToString});
};

const mimicFn = (to, from, {ignoreNonConfigurable = false} = {}) => {
	const {name} = to;

	for (const property of Reflect.ownKeys(from)) {
		copyProperty(to, from, property, ignoreNonConfigurable);
	}

	changePrototype(to, from);
	changeToString(to, from, name);

	return to;
};

module.exports = mimicFn;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "mimic-fn",
	"version": "3.1.0",
	"description": "Make a function mimic another one",
	"license": "MIT",
	"repository": "sindresorhus/mimic-fn",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=8"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"function",
		"mimic",
		"imitate",
		"rename",
		"copy",
		"inherit",
		"properties",
		"name",
		"func",
		"fn",
		"set",
		"infer",
		"change"
	],
	"devDependencies": {
		"ava": "^2.1.0",
		"tsd": "^0.7.1",
		"xo": "^0.24.0"
	}
}
<img src="media/logo.svg" alt="mimic-fn" width="400">
<br>

[![Build Status](https://travis-ci.org/sindresorhus/mimic-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-fn)

> Make a function mimic another one

Useful when you wrap a function in another function and like to preserve the original name and other properties.


## Install

```
$ npm install mimic-fn
```


## Usage

```js
const mimicFn = require('mimic-fn');

function foo() {}
foo.unicorn = '🦄';

function wrapper() {
	return foo();
}

console.log(wrapper.name);
//=> 'wrapper'

mimicFn(wrapper, foo);

console.log(wrapper.name);
//=> 'foo'

console.log(wrapper.unicorn);
//=> '🦄'

console.log(String(wrapper));
//=> '/* Wrapped with wrapper() */\nfunction foo() {}'
```


## API

### mimicFn(to, from, options?)

Modifies the `to` function to mimic the `from` function. Returns the `to` function.

`name`, `displayName`, and any other properties of `from` are copied. The `length` property is not copied. Prototype, class, and inherited properties are copied.

`to.toString()` will return the same as `from.toString()` but prepended with a `Wrapped with to()` comment.

#### to

Type: `Function`

Mimicking function.

#### from

Type: `Function`

Function to mimic.

#### options

Type: `object`

##### ignoreNonConfigurable

Type: `boolean`<br>
Default: `false`

Skip modifying [non-configurable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description) instead of throwing an error.

## Related

- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name and other properties


---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-mimic-fn?utm_source=npm-mimic-fn&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
'use strict';
const mimicFn = require('mimic-fn');

const calledFunctions = new WeakMap();

const onetime = (function_, options = {}) => {
	if (typeof function_ !== 'function') {
		throw new TypeError('Expected a function');
	}

	let returnValue;
	let callCount = 0;
	const functionName = function_.displayName || function_.name || '<anonymous>';

	const onetime = function (...arguments_) {
		calledFunctions.set(onetime, ++callCount);

		if (callCount === 1) {
			returnValue = function_.apply(this, arguments_);
			function_ = null;
		} else if (options.throw === true) {
			throw new Error(`Function \`${functionName}\` can only be called once`);
		}

		return returnValue;
	};

	mimicFn(onetime, function_);
	calledFunctions.set(onetime, callCount);

	return onetime;
};

module.exports = onetime;
// TODO: Remove this for the next major release
module.exports.default = onetime;

module.exports.callCount = function_ => {
	if (!calledFunctions.has(function_)) {
		throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
	}

	return calledFunctions.get(function_);
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';

const mimicFn = (to, from) => {
	for (const prop of Reflect.ownKeys(from)) {
		Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
	}

	return to;
};

module.exports = mimicFn;
// TODO: Remove this for the next major release
module.exports.default = mimicFn;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "mimic-fn",
	"version": "2.1.0",
	"description": "Make a function mimic another one",
	"license": "MIT",
	"repository": "sindresorhus/mimic-fn",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"function",
		"mimic",
		"imitate",
		"rename",
		"copy",
		"inherit",
		"properties",
		"name",
		"func",
		"fn",
		"set",
		"infer",
		"change"
	],
	"devDependencies": {
		"ava": "^1.4.1",
		"tsd": "^0.7.1",
		"xo": "^0.24.0"
	}
}
# mimic-fn [![Build Status](https://travis-ci.org/sindresorhus/mimic-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-fn)

> Make a function mimic another one

Useful when you wrap a function in another function and like to preserve the original name and other properties.


## Install

```
$ npm install mimic-fn
```


## Usage

```js
const mimicFn = require('mimic-fn');

function foo() {}
foo.unicorn = '🦄';

function wrapper() {
	return foo();
}

console.log(wrapper.name);
//=> 'wrapper'

mimicFn(wrapper, foo);

console.log(wrapper.name);
//=> 'foo'

console.log(wrapper.unicorn);
//=> '🦄'
```


## API

It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set.

### mimicFn(to, from)

Modifies the `to` function and returns it.

#### to

Type: `Function`

Mimicking function.

#### from

Type: `Function`

Function to mimic.


## Related

- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function
- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name, length and other properties


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
{
	"name": "onetime",
	"version": "5.1.2",
	"description": "Ensure a function is only called once",
	"license": "MIT",
	"repository": "sindresorhus/onetime",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"once",
		"function",
		"one",
		"onetime",
		"func",
		"fn",
		"single",
		"call",
		"called",
		"prevent"
	],
	"dependencies": {
		"mimic-fn": "^2.1.0"
	},
	"devDependencies": {
		"ava": "^1.4.1",
		"tsd": "^0.7.1",
		"xo": "^0.24.0"
	}
}
# onetime [![Build Status](https://travis-ci.com/sindresorhus/onetime.svg?branch=master)](https://travis-ci.com/github/sindresorhus/onetime)

> Ensure a function is only called once

When called multiple times it will return the return value from the first call.

*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.*

## Install

```
$ npm install onetime
```

## Usage

```js
const onetime = require('onetime');

let i = 0;

const foo = onetime(() => ++i);

foo(); //=> 1
foo(); //=> 1
foo(); //=> 1

onetime.callCount(foo); //=> 3
```

```js
const onetime = require('onetime');

const foo = onetime(() => {}, {throw: true});

foo();

foo();
//=> Error: Function `foo` can only be called once
```

## API

### onetime(fn, options?)

Returns a function that only calls `fn` once.

#### fn

Type: `Function`

Function that should only be called once.

#### options

Type: `object`

##### throw

Type: `boolean`\
Default: `false`

Throw an error when called more than once.

### onetime.callCount(fn)

Returns a number representing how many times `fn` has been called.

Note: It throws an error if you pass in a function that is not wrapped by `onetime`.

```js
const onetime = require('onetime');

const foo = onetime(() => {});

foo();
foo();
foo();

console.log(onetime.callCount(foo));
//=> 3
```

#### fn

Type: `Function`

Function to get call count from.

## onetime for enterprise

Available as part of the Tidelift Subscription.

The maintainers of onetime and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
'use strict';
const Queue = require('yocto-queue');

const pLimit = concurrency => {
	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
		throw new TypeError('Expected `concurrency` to be a number from 1 and up');
	}

	const queue = new Queue();
	let activeCount = 0;

	const next = () => {
		activeCount--;

		if (queue.size > 0) {
			queue.dequeue()();
		}
	};

	const run = async (fn, resolve, ...args) => {
		activeCount++;

		const result = (async () => fn(...args))();

		resolve(result);

		try {
			await result;
		} catch {}

		next();
	};

	const enqueue = (fn, resolve, ...args) => {
		queue.enqueue(run.bind(null, fn, resolve, ...args));

		(async () => {
			// This function needs to wait until the next microtask before comparing
			// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
			// when the run function is dequeued and called. The comparison in the if-statement
			// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
			await Promise.resolve();

			if (activeCount < concurrency && queue.size > 0) {
				queue.dequeue()();
			}
		})();
	};

	const generator = (fn, ...args) => new Promise(resolve => {
		enqueue(fn, resolve, ...args);
	});

	Object.defineProperties(generator, {
		activeCount: {
			get: () => activeCount
		},
		pendingCount: {
			get: () => queue.size
		},
		clearQueue: {
			value: () => {
				queue.clear();
			}
		}
	});

	return generator;
};

module.exports = pLimit;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "p-limit",
	"version": "3.1.0",
	"description": "Run multiple promise-returning & async functions with limited concurrency",
	"license": "MIT",
	"repository": "sindresorhus/p-limit",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=10"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"promise",
		"limit",
		"limited",
		"concurrency",
		"throttle",
		"throat",
		"rate",
		"batch",
		"ratelimit",
		"task",
		"queue",
		"async",
		"await",
		"promises",
		"bluebird"
	],
	"dependencies": {
		"yocto-queue": "^0.1.0"
	},
	"devDependencies": {
		"ava": "^2.4.0",
		"delay": "^4.4.0",
		"in-range": "^2.0.0",
		"random-int": "^2.0.1",
		"time-span": "^4.0.0",
		"tsd": "^0.13.1",
		"xo": "^0.35.0"
	}
}
# p-limit

> Run multiple promise-returning & async functions with limited concurrency

## Install

```
$ npm install p-limit
```

## Usage

```js
const pLimit = require('p-limit');

const limit = pLimit(1);

const input = [
	limit(() => fetchSomething('foo')),
	limit(() => fetchSomething('bar')),
	limit(() => doSomething())
];

(async () => {
	// Only one promise is run at once
	const result = await Promise.all(input);
	console.log(result);
})();
```

## API

### pLimit(concurrency)

Returns a `limit` function.

#### concurrency

Type: `number`\
Minimum: `1`\
Default: `Infinity`

Concurrency limit.

### limit(fn, ...args)

Returns the promise returned by calling `fn(...args)`.

#### fn

Type: `Function`

Promise-returning/async function.

#### args

Any arguments to pass through to `fn`.

Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.

### limit.activeCount

The number of promises that are currently running.

### limit.pendingCount

The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).

### limit.clearQueue()

Discard pending promises that are waiting to run.

This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.

Note: This does not cancel promises that are already running.

## FAQ

### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package?

This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.

## Related

- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
- [More…](https://github.com/sindresorhus/promise-fun)

---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-p-limit?utm_source=npm-p-limit&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
'use strict';
const pLimit = require('p-limit');

class EndError extends Error {
	constructor(value) {
		super();
		this.value = value;
	}
}

// The input can also be a promise, so we `Promise.resolve()` it
const testElement = (el, tester) => Promise.resolve(el).then(tester);

// The input can also be a promise, so we `Promise.all()` them both
const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));

module.exports = (iterable, tester, opts) => {
	opts = Object.assign({
		concurrency: Infinity,
		preserveOrder: true
	}, opts);

	const limit = pLimit(opts.concurrency);

	// Start all the promises concurrently with optional limit
	const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);

	// Check the promises either serially or concurrently
	const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);

	return Promise.all(items.map(el => checkLimit(finder, el)))
		.then(() => {})
		.catch(err => err instanceof EndError ? err.value : Promise.reject(err));
};
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const pTry = require('p-try');

const pLimit = concurrency => {
	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
		return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
	}

	const queue = [];
	let activeCount = 0;

	const next = () => {
		activeCount--;

		if (queue.length > 0) {
			queue.shift()();
		}
	};

	const run = (fn, resolve, ...args) => {
		activeCount++;

		const result = pTry(fn, ...args);

		resolve(result);

		result.then(next, next);
	};

	const enqueue = (fn, resolve, ...args) => {
		if (activeCount < concurrency) {
			run(fn, resolve, ...args);
		} else {
			queue.push(run.bind(null, fn, resolve, ...args));
		}
	};

	const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
	Object.defineProperties(generator, {
		activeCount: {
			get: () => activeCount
		},
		pendingCount: {
			get: () => queue.length
		},
		clearQueue: {
			value: () => {
				queue.length = 0;
			}
		}
	});

	return generator;
};

module.exports = pLimit;
module.exports.default = pLimit;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "p-limit",
	"version": "2.3.0",
	"description": "Run multiple promise-returning & async functions with limited concurrency",
	"license": "MIT",
	"repository": "sindresorhus/p-limit",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava && tsd-check"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"promise",
		"limit",
		"limited",
		"concurrency",
		"throttle",
		"throat",
		"rate",
		"batch",
		"ratelimit",
		"task",
		"queue",
		"async",
		"await",
		"promises",
		"bluebird"
	],
	"dependencies": {
		"p-try": "^2.0.0"
	},
	"devDependencies": {
		"ava": "^1.2.1",
		"delay": "^4.1.0",
		"in-range": "^1.0.0",
		"random-int": "^1.0.0",
		"time-span": "^2.0.0",
		"tsd-check": "^0.3.0",
		"xo": "^0.24.0"
	}
}
# p-limit [![Build Status](https://travis-ci.org/sindresorhus/p-limit.svg?branch=master)](https://travis-ci.org/sindresorhus/p-limit)

> Run multiple promise-returning & async functions with limited concurrency

## Install

```
$ npm install p-limit
```

## Usage

```js
const pLimit = require('p-limit');

const limit = pLimit(1);

const input = [
	limit(() => fetchSomething('foo')),
	limit(() => fetchSomething('bar')),
	limit(() => doSomething())
];

(async () => {
	// Only one promise is run at once
	const result = await Promise.all(input);
	console.log(result);
})();
```

## API

### pLimit(concurrency)

Returns a `limit` function.

#### concurrency

Type: `number`\
Minimum: `1`\
Default: `Infinity`

Concurrency limit.

### limit(fn, ...args)

Returns the promise returned by calling `fn(...args)`.

#### fn

Type: `Function`

Promise-returning/async function.

#### args

Any arguments to pass through to `fn`.

Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions.

### limit.activeCount

The number of promises that are currently running.

### limit.pendingCount

The number of promises that are waiting to run (i.e. their internal `fn` was not called yet).

### limit.clearQueue()

Discard pending promises that are waiting to run.

This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app.

Note: This does not cancel promises that are already running.

## FAQ

### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package?

This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue.

## Related

- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control
- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions
- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions
- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency
- [More…](https://github.com/sindresorhus/promise-fun)

---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-p-limit?utm_source=npm-p-limit&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
{
	"name": "p-locate",
	"version": "3.0.0",
	"description": "Get the first fulfilled promise that satisfies the provided testing function",
	"license": "MIT",
	"repository": "sindresorhus/p-locate",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=6"
	},
	"scripts": {
		"test": "xo && ava"
	},
	"files": [
		"index.js"
	],
	"keywords": [
		"promise",
		"locate",
		"find",
		"finder",
		"search",
		"searcher",
		"test",
		"array",
		"collection",
		"iterable",
		"iterator",
		"race",
		"fulfilled",
		"fastest",
		"async",
		"await",
		"promises",
		"bluebird"
	],
	"dependencies": {
		"p-limit": "^2.0.0"
	},
	"devDependencies": {
		"ava": "*",
		"delay": "^3.0.0",
		"in-range": "^1.0.0",
		"time-span": "^2.0.0",
		"xo": "*"
	}
}
# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate)

> Get the first fulfilled promise that satisfies the provided testing function

Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find).


## Install

```
$ npm install p-locate
```


## Usage

Here we find the first file that exists on disk, in array order.

```js
const pathExists = require('path-exists');
const pLocate = require('p-locate');

const files = [
	'unicorn.png',
	'rainbow.png', // Only this one actually exists on disk
	'pony.png'
];

(async () => {
	const foundPath = await pLocate(files, file => pathExists(file));

	console.log(foundPath);
	//=> 'rainbow'
})();
```

*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.*


## API

### pLocate(input, tester, [options])

Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`.

#### input

Type: `Iterable<Promise|any>`

#### tester(element)

Type: `Function`

Expected to return a `Promise<boolean>` or boolean.

#### options

Type: `Object`

##### concurrency

Type: `number`<br>
Default: `Infinity`<br>
Minimum: `1`

Number of concurrently pending promises returned by `tester`.

##### preserveOrder

Type: `boolean`<br>
Default: `true`

Preserve `input` order when searching.

Disable this to improve performance if you don't care about the order.


## Related

- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently
- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled
- [More…](https://github.com/sindresorhus/promise-fun)


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
'use strict';
const fs = require('fs');

module.exports = fp => new Promise(resolve => {
	fs.access(fp, err => {
		resolve(!err);
	});
});

module.exports.sync = fp => {
	try {
		fs.accessSync(fp);
		return true;
	} catch (err) {
		return false;
	}
};
The MIT License (MIT)

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
{
  "name": "path-exists",
  "version": "3.0.0",
  "description": "Check if a path exists",
  "license": "MIT",
  "repository": "sindresorhus/path-exists",
  "author": {
    "name": "Sindre Sorhus",
    "email": "sindresorhus@gmail.com",
    "url": "sindresorhus.com"
  },
  "engines": {
    "node": ">=4"
  },
  "scripts": {
    "test": "xo && ava"
  },
  "files": [
    "index.js"
  ],
  "keywords": [
    "path",
    "exists",
    "exist",
    "file",
    "filepath",
    "fs",
    "filesystem",
    "file-system",
    "access",
    "stat"
  ],
  "devDependencies": {
    "ava": "*",
    "xo": "*"
  },
  "xo": {
    "esnext": true
  }
}
# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists)

> Check if a path exists

Because [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), but there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it.

Never use this before handling a file though:

> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there.


## Install

```
$ npm install --save path-exists
```


## Usage

```js
// foo.js
const pathExists = require('path-exists');

pathExists('foo.js').then(exists => {
	console.log(exists);
	//=> true
});
```


## API

### pathExists(path)

Returns a promise for a boolean of whether the path exists.

### pathExists.sync(path)

Returns a boolean of whether the path exists.


## Related

- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
'use strict';
const findUp = require('find-up');

module.exports = async ({cwd} = {}) => findUp('package.json', {cwd});
module.exports.sync = ({cwd} = {}) => findUp.sync('package.json', {cwd});
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "pkg-up",
	"version": "3.1.0",
	"description": "Find the closest package.json file",
	"license": "MIT",
	"repository": "sindresorhus/pkg-up",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "sindresorhus.com"
	},
	"engines": {
		"node": ">=8"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"pkg",
		"package",
		"file",
		"find",
		"up",
		"find-up",
		"findup",
		"look-up",
		"look",
		"search",
		"match",
		"resolve",
		"parent",
		"parents",
		"folder",
		"directory",
		"dir",
		"walk",
		"walking",
		"path"
	],
	"dependencies": {
		"find-up": "^3.0.0"
	},
	"devDependencies": {
		"ava": "^1.4.1",
		"tsd": "^0.7.2",
		"xo": "^0.24.0"
	}
}
# pkg-up [![Build Status](https://travis-ci.org/sindresorhus/pkg-up.svg?branch=master)](https://travis-ci.org/sindresorhus/pkg-up)

> Find the closest package.json file


## Install

```
$ npm install pkg-up
```


## Usage

```
/
└── Users
    └── sindresorhus
        └── foo
            ├── package.json
            └── bar
                ├── baz
                └── example.js
```

```js
// example.js
const pkgUp = require('pkg-up');

(async () => {
	console.log(await pkgUp());
	//=> '/Users/sindresorhus/foo/package.json'
})();
```


## API

### pkgUp([options])

Returns a `Promise<string>` for the filepath, or `Promise<null>` if it couldn't be found.

### pkgUp.sync([options])

Returns the filepath, or `null` if it couldn't be found.

#### options

Type: `Object`

#### cwd

Type: `string`<br>
Default: `process.cwd()`

Directory to start from.


## Related

- [read-pkg-up](https://github.com/sindresorhus/read-pkg-up) - Read the closest package.json file
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
- [find-up](https://github.com/sindresorhus/find-up) - Find a file by walking up parent directories


## License

MIT © [Sindre Sorhus](https://sindresorhus.com)
The ISC License

Copyright (c) Isaac Z. Schlueter and Contributors

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
semver(1) -- The semantic versioner for npm
===========================================

## Install

```bash
npm install semver
````

## Usage

As a node module:

```js
const semver = require('semver')

semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean('  =v1.2.3   ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```

As a command-line utility:

```
$ semver -h

A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter

Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence

Options:
-r --range <range>
        Print versions that match the specified range.

-i --increment [<level>]
        Increment a version by the specified level.  Level can
        be one of: major, minor, patch, premajor, preminor,
        prepatch, or prerelease.  Default level is 'patch'.
        Only one version may be specified.

--preid <identifier>
        Identifier to be used to prefix premajor, preminor,
        prepatch or prerelease version increments.

-l --loose
        Interpret versions and ranges loosely

-p --include-prerelease
        Always include prerelease versions in range matching

-c --coerce
        Coerce a string into SemVer if possible
        (does not imply --loose)

--rtl
        Coerce version strings right to left

--ltr
        Coerce version strings left to right (default)

Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.

If no satisfying versions are found, then exits failure.

Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```

## Versions

A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.

A leading `"="` or `"v"` character is stripped off and ignored.

## Ranges

A `version range` is a set of `comparators` which specify versions
that satisfy the range.

A `comparator` is composed of an `operator` and a `version`.  The set
of primitive `operators` is:

* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal.  If no operator is specified, then equality is assumed,
  so this operator is optional, but MAY be included.

For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`.

Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.

A range is composed of one or more comparator sets, joined by `||`.  A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.

For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.

The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.

### Prerelease Tags

If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.

For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules.  The version
range only accepts prerelease tags on the `1.2.3` version.  The
version `3.4.5` *would* satisfy the range, because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.

The purpose for this behavior is twofold.  First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range matching
semantics.

Second, a user who has opted into using a prerelease version has
clearly indicated the intent to use *that specific* set of
alpha/beta/rc versions.  By including a prerelease tag in the range,
the user is indicating that they are aware of the risk.  However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.

Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for the purpose of range
matching) by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.

#### Prerelease Identifiers

The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:

```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```

command-line example:

```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```

Which then can be used to increment further:

```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```

### Advanced Range Syntax

Advanced range syntax desugars to primitive comparators in
deterministic ways.

Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.

#### Hyphen Ranges `X.Y.Z - A.B.C`

Specifies an inclusive set.

* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`

If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.

* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`

If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.

* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`

#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`

Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.

* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)

A partial version range is treated as an X-Range, so the special
character is in fact optional.

* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`

#### Tilde Ranges `~1.2.3` `~1.2` `~1`

Allows patch-level changes if a minor version is specified on the
comparator.  Allows minor-level changes if not.

* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.

#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`

Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple.  In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.

Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.

Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`.  It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.

* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
  the `1.2.3` version will be allowed, if they are greater than or
  equal to `beta.2`.  So, `1.2.3-beta.4` would be allowed, but
  `1.2.4-beta.2` would not, because it is a prerelease of a
  different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4`  Note that prereleases in the
  `0.0.3` version *only* will be allowed, if they are greater than or
  equal to `beta`.  So, `0.0.3-pr.2` would be allowed.

When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.

* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`

A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.

* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`

### Range Grammar

Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:

```bnf
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= parts
build      ::= parts
parts      ::= part ( '.' part ) *
part       ::= nr | [-0-9A-Za-z]+
```

## Functions

All methods and classes take a final `options` object argument.  All
options in this object are `false` by default.  The options supported
are:

- `loose`  Be more forgiving about not-quite-valid semver strings.
  (Any resulting output will always be 100% strict compliant, of
  course.)  For backwards compatibility reasons, if the `options`
  argument is a boolean value instead of an object, it is interpreted
  to be the `loose` param.
- `includePrerelease`  Set to suppress the [default
  behavior](https://github.com/npm/node-semver#prerelease-tags) of
  excluding prerelease tagged versions from ranges unless they are
  explicitly opted into.

Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.

* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, release)`: Return the version incremented by the release
  type (`major`,   `premajor`, `minor`, `preminor`, `patch`,
  `prepatch`, or `prerelease`), or null if it's not valid
  * `premajor` in one call will bump the version up to the next major
    version and down to a prerelease of that major version.
    `preminor`, and `prepatch` work the same way.
  * If called from a non-prerelease version, the `prerelease` will work the
    same as `prepatch`. It increments the patch version, then makes a
    prerelease. If the input version is already a prerelease it simply
    increments it.
* `prerelease(v)`: Returns an array of prerelease components, or null
  if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
  or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
  a `SemVer` object or `null`.

### Comparison

* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
  even if they're not the exact same string.  You already know how to
  compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
  the corresponding function above.  `"==="` and `"!=="` do simple
  string comparison, but are included for completeness.  Throws if an
  invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
  `v2` is greater.  Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of compare.  Sorts an array of versions
  in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
  are equal.  Sorts in ascending order if passed to `Array.sort()`.
  `v2` is greater.  Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
  (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
  or null if the versions are the same.

### Comparators

* `intersects(comparator)`: Return true if the comparators intersect

### Ranges

* `validRange(range)`: Return the valid range or null if it's not valid
* `satisfies(version, range)`: Return true if the version satisfies the
  range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
  that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
  that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can possibly match
  the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
  versions possible in the range.
* `ltr(version, range)`: Return `true` if version is less than all the
  versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
  the bounds of the range in either the high or low direction.  The
  `hilo` argument must be either the string `'>'` or `'<'`.  (This is
  the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect

Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range!  For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so the version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.

If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.

### Coercion

* `coerce(version, options)`: Coerces a string to semver if possible

This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string, and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters).  Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`).  All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`).  Only text which lacks digits will fail coercion (`version one`
is not valid).  The maximum  length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`).  The maximum value for any
semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).

If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple.  For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`.  `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.

### Clean

* `clean(version)`: Clean a string to be a valid semver if possible

This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. 

ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean('  =v2.1.5')`: `2.1.5`
* `s.clean('      2.1.5   ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.

var argv = process.argv.slice(2)

var versions = []

var range = []

var inc = null

var version = require('../package.json').version

var loose = false

var includePrerelease = false

var coerce = false

var rtl = false

var identifier

var semver = require('../semver')

var reverse = false

var options = {}

main()

function main () {
  if (!argv.length) return help()
  while (argv.length) {
    var a = argv.shift()
    var indexOfEqualSign = a.indexOf('=')
    if (indexOfEqualSign !== -1) {
      a = a.slice(0, indexOfEqualSign)
      argv.unshift(a.slice(indexOfEqualSign + 1))
    }
    switch (a) {
      case '-rv': case '-rev': case '--rev': case '--reverse':
        reverse = true
        break
      case '-l': case '--loose':
        loose = true
        break
      case '-p': case '--include-prerelease':
        includePrerelease = true
        break
      case '-v': case '--version':
        versions.push(argv.shift())
        break
      case '-i': case '--inc': case '--increment':
        switch (argv[0]) {
          case 'major': case 'minor': case 'patch': case 'prerelease':
          case 'premajor': case 'preminor': case 'prepatch':
            inc = argv.shift()
            break
          default:
            inc = 'patch'
            break
        }
        break
      case '--preid':
        identifier = argv.shift()
        break
      case '-r': case '--range':
        range.push(argv.shift())
        break
      case '-c': case '--coerce':
        coerce = true
        break
      case '--rtl':
        rtl = true
        break
      case '--ltr':
        rtl = false
        break
      case '-h': case '--help': case '-?':
        return help()
      default:
        versions.push(a)
        break
    }
  }

  var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }

  versions = versions.map(function (v) {
    return coerce ? (semver.coerce(v, options) || { version: v }).version : v
  }).filter(function (v) {
    return semver.valid(v)
  })
  if (!versions.length) return fail()
  if (inc && (versions.length !== 1 || range.length)) { return failInc() }

  for (var i = 0, l = range.length; i < l; i++) {
    versions = versions.filter(function (v) {
      return semver.satisfies(v, range[i], options)
    })
    if (!versions.length) return fail()
  }
  return success(versions)
}

function failInc () {
  console.error('--inc can only be used on a single version with no range')
  fail()
}

function fail () { process.exit(1) }

function success () {
  var compare = reverse ? 'rcompare' : 'compare'
  versions.sort(function (a, b) {
    return semver[compare](a, b, options)
  }).map(function (v) {
    return semver.clean(v, options)
  }).map(function (v) {
    return inc ? semver.inc(v, inc, options, identifier) : v
  }).forEach(function (v, i, _) { console.log(v) })
}

function help () {
  console.log(['SemVer ' + version,
    '',
    'A JavaScript implementation of the https://semver.org/ specification',
    'Copyright Isaac Z. Schlueter',
    '',
    'Usage: semver [options] <version> [<version> [...]]',
    'Prints valid versions sorted by SemVer precedence',
    '',
    'Options:',
    '-r --range <range>',
    '        Print versions that match the specified range.',
    '',
    '-i --increment [<level>]',
    '        Increment a version by the specified level.  Level can',
    '        be one of: major, minor, patch, premajor, preminor,',
    "        prepatch, or prerelease.  Default level is 'patch'.",
    '        Only one version may be specified.',
    '',
    '--preid <identifier>',
    '        Identifier to be used to prefix premajor, preminor,',
    '        prepatch or prerelease version increments.',
    '',
    '-l --loose',
    '        Interpret versions and ranges loosely',
    '',
    '-p --include-prerelease',
    '        Always include prerelease versions in range matching',
    '',
    '-c --coerce',
    '        Coerce a string into SemVer if possible',
    '        (does not imply --loose)',
    '',
    '--rtl',
    '        Coerce version strings right to left',
    '',
    '--ltr',
    '        Coerce version strings left to right (default)',
    '',
    'Program exits successfully if any valid version satisfies',
    'all supplied ranges, and prints all satisfying versions.',
    '',
    'If no satisfying versions are found, then exits failure.',
    '',
    'Versions are printed in ascending order, so supplying',
    'multiple versions to the utility will just sort them.'
  ].join('\n'))
}
{
  "name": "semver",
  "version": "6.3.1",
  "description": "The semantic version parser used by npm.",
  "main": "semver.js",
  "scripts": {
    "test": "tap test/ --100 --timeout=30",
    "lint": "echo linting disabled",
    "postlint": "template-oss-check",
    "template-oss-apply": "template-oss-apply --force",
    "lintfix": "npm run lint -- --fix",
    "snap": "tap test/ --100 --timeout=30",
    "posttest": "npm run lint"
  },
  "devDependencies": {
    "@npmcli/template-oss": "4.17.0",
    "tap": "^12.7.0"
  },
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": "https://github.com/npm/node-semver.git"
  },
  "bin": {
    "semver": "./bin/semver.js"
  },
  "files": [
    "bin",
    "range.bnf",
    "semver.js"
  ],
  "author": "GitHub Inc.",
  "templateOSS": {
    "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
    "content": "./scripts/template-oss",
    "version": "4.17.0"
  }
}
range-set  ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range      ::= hyphen | simple ( ' ' simple ) * | ''
hyphen     ::= partial ' - ' partial
simple     ::= primitive | partial | tilde | caret
primitive  ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial    ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr         ::= 'x' | 'X' | '*' | nr
nr         ::= '0' | [1-9] ( [0-9] ) *
tilde      ::= '~' partial
caret      ::= '^' partial
qualifier  ::= ( '-' pre )? ( '+' build )?
pre        ::= parts
build      ::= parts
parts      ::= part ( '.' part ) *
part       ::= nr | [-0-9A-Za-z]+
exports = module.exports = SemVer

var debug
/* istanbul ignore next */
if (typeof process === 'object' &&
    process.env &&
    process.env.NODE_DEBUG &&
    /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
  debug = function () {
    var args = Array.prototype.slice.call(arguments, 0)
    args.unshift('SEMVER')
    console.log.apply(console, args)
  }
} else {
  debug = function () {}
}

// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
exports.SEMVER_SPEC_VERSION = '2.0.0'

var MAX_LENGTH = 256
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
  /* istanbul ignore next */ 9007199254740991

// Max safe segment length for coercion.
var MAX_SAFE_COMPONENT_LENGTH = 16

var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6

// The actual regexps go on exports.re
var re = exports.re = []
var safeRe = exports.safeRe = []
var src = exports.src = []
var t = exports.tokens = {}
var R = 0

function tok (n) {
  t[n] = R++
}

var LETTERDASHNUMBER = '[a-zA-Z0-9-]'

// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
var safeRegexReplacements = [
  ['\\s', 1],
  ['\\d', MAX_LENGTH],
  [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]

function makeSafeRe (value) {
  for (var i = 0; i < safeRegexReplacements.length; i++) {
    var token = safeRegexReplacements[i][0]
    var max = safeRegexReplacements[i][1]
    value = value
      .split(token + '*').join(token + '{0,' + max + '}')
      .split(token + '+').join(token + '{1,' + max + '}')
  }
  return value
}

// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.

// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.

tok('NUMERICIDENTIFIER')
src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*'
tok('NUMERICIDENTIFIERLOOSE')
src[t.NUMERICIDENTIFIERLOOSE] = '\\d+'

// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.

tok('NONNUMERICIDENTIFIER')
src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-]' + LETTERDASHNUMBER + '*'

// ## Main Version
// Three dot-separated numeric identifiers.

tok('MAINVERSION')
src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[t.NUMERICIDENTIFIER] + ')\\.' +
                   '(' + src[t.NUMERICIDENTIFIER] + ')'

tok('MAINVERSIONLOOSE')
src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' +
                        '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'

// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.

tok('PRERELEASEIDENTIFIER')
src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] +
                            '|' + src[t.NONNUMERICIDENTIFIER] + ')'

tok('PRERELEASEIDENTIFIERLOOSE')
src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] +
                                 '|' + src[t.NONNUMERICIDENTIFIER] + ')'

// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.

tok('PRERELEASE')
src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] +
                  '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))'

tok('PRERELEASELOOSE')
src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] +
                       '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'

// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.

tok('BUILDIDENTIFIER')
src[t.BUILDIDENTIFIER] = LETTERDASHNUMBER + '+'

// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.

tok('BUILD')
src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] +
             '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'

// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.

// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups.  The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.

tok('FULL')
tok('FULLPLAIN')
src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] +
                  src[t.PRERELEASE] + '?' +
                  src[t.BUILD] + '?'

src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'

// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
tok('LOOSEPLAIN')
src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] +
                  src[t.PRERELEASELOOSE] + '?' +
                  src[t.BUILD] + '?'

tok('LOOSE')
src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$'

tok('GTLT')
src[t.GTLT] = '((?:<|>)?=?)'

// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
tok('XRANGEIDENTIFIERLOOSE')
src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'
tok('XRANGEIDENTIFIER')
src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*'

tok('XRANGEPLAIN')
src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
                   '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' +
                   '(?:' + src[t.PRERELEASE] + ')?' +
                   src[t.BUILD] + '?' +
                   ')?)?'

tok('XRANGEPLAINLOOSE')
src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' +
                        '(?:' + src[t.PRERELEASELOOSE] + ')?' +
                        src[t.BUILD] + '?' +
                        ')?)?'

tok('XRANGE')
src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$'
tok('XRANGELOOSE')
src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'

// Coercion.
// Extract anything that could conceivably be a part of a valid semver
tok('COERCE')
src[t.COERCE] = '(^|[^\\d])' +
              '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' +
              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
              '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' +
              '(?:$|[^\\d])'
tok('COERCERTL')
re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g')
safeRe[t.COERCERTL] = new RegExp(makeSafeRe(src[t.COERCE]), 'g')

// Tilde ranges.
// Meaning is "reasonably at or greater than"
tok('LONETILDE')
src[t.LONETILDE] = '(?:~>?)'

tok('TILDETRIM')
src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+'
re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g')
safeRe[t.TILDETRIM] = new RegExp(makeSafeRe(src[t.TILDETRIM]), 'g')
var tildeTrimReplace = '$1~'

tok('TILDE')
src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$'
tok('TILDELOOSE')
src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'

// Caret ranges.
// Meaning is "at least and backwards compatible with"
tok('LONECARET')
src[t.LONECARET] = '(?:\\^)'

tok('CARETTRIM')
src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+'
re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g')
safeRe[t.CARETTRIM] = new RegExp(makeSafeRe(src[t.CARETTRIM]), 'g')
var caretTrimReplace = '$1^'

tok('CARET')
src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$'
tok('CARETLOOSE')
src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'

// A simple gt/lt/eq thing, or just "" to indicate "any version"
tok('COMPARATORLOOSE')
src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$'
tok('COMPARATOR')
src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'

// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
tok('COMPARATORTRIM')
src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] +
                      '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'

// this one has to use the /g flag
re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g')
safeRe[t.COMPARATORTRIM] = new RegExp(makeSafeRe(src[t.COMPARATORTRIM]), 'g')
var comparatorTrimReplace = '$1$2$3'

// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
tok('HYPHENRANGE')
src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' +
                   '\\s+-\\s+' +
                   '(' + src[t.XRANGEPLAIN] + ')' +
                   '\\s*$'

tok('HYPHENRANGELOOSE')
src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' +
                        '\\s+-\\s+' +
                        '(' + src[t.XRANGEPLAINLOOSE] + ')' +
                        '\\s*$'

// Star ranges basically just allow anything at all.
tok('STAR')
src[t.STAR] = '(<|>)?=?\\s*\\*'

// Compile to actual regexp objects.
// All are flag-free, unless they were created above with a flag.
for (var i = 0; i < R; i++) {
  debug(i, src[i])
  if (!re[i]) {
    re[i] = new RegExp(src[i])

    // Replace all greedy whitespace to prevent regex dos issues. These regex are
    // used internally via the safeRe object since all inputs in this library get
    // normalized first to trim and collapse all extra whitespace. The original
    // regexes are exported for userland consumption and lower level usage. A
    // future breaking change could export the safer regex only with a note that
    // all input should have extra whitespace removed.
    safeRe[i] = new RegExp(makeSafeRe(src[i]))
  }
}

exports.parse = parse
function parse (version, options) {
  if (!options || typeof options !== 'object') {
    options = {
      loose: !!options,
      includePrerelease: false
    }
  }

  if (version instanceof SemVer) {
    return version
  }

  if (typeof version !== 'string') {
    return null
  }

  if (version.length > MAX_LENGTH) {
    return null
  }

  var r = options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL]
  if (!r.test(version)) {
    return null
  }

  try {
    return new SemVer(version, options)
  } catch (er) {
    return null
  }
}

exports.valid = valid
function valid (version, options) {
  var v = parse(version, options)
  return v ? v.version : null
}

exports.clean = clean
function clean (version, options) {
  var s = parse(version.trim().replace(/^[=v]+/, ''), options)
  return s ? s.version : null
}

exports.SemVer = SemVer

function SemVer (version, options) {
  if (!options || typeof options !== 'object') {
    options = {
      loose: !!options,
      includePrerelease: false
    }
  }
  if (version instanceof SemVer) {
    if (version.loose === options.loose) {
      return version
    } else {
      version = version.version
    }
  } else if (typeof version !== 'string') {
    throw new TypeError('Invalid Version: ' + version)
  }

  if (version.length > MAX_LENGTH) {
    throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters')
  }

  if (!(this instanceof SemVer)) {
    return new SemVer(version, options)
  }

  debug('SemVer', version, options)
  this.options = options
  this.loose = !!options.loose

  var m = version.trim().match(options.loose ? safeRe[t.LOOSE] : safeRe[t.FULL])

  if (!m) {
    throw new TypeError('Invalid Version: ' + version)
  }

  this.raw = version

  // these are actually numbers
  this.major = +m[1]
  this.minor = +m[2]
  this.patch = +m[3]

  if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
    throw new TypeError('Invalid major version')
  }

  if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
    throw new TypeError('Invalid minor version')
  }

  if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
    throw new TypeError('Invalid patch version')
  }

  // numberify any prerelease numeric ids
  if (!m[4]) {
    this.prerelease = []
  } else {
    this.prerelease = m[4].split('.').map(function (id) {
      if (/^[0-9]+$/.test(id)) {
        var num = +id
        if (num >= 0 && num < MAX_SAFE_INTEGER) {
          return num
        }
      }
      return id
    })
  }

  this.build = m[5] ? m[5].split('.') : []
  this.format()
}

SemVer.prototype.format = function () {
  this.version = this.major + '.' + this.minor + '.' + this.patch
  if (this.prerelease.length) {
    this.version += '-' + this.prerelease.join('.')
  }
  return this.version
}

SemVer.prototype.toString = function () {
  return this.version
}

SemVer.prototype.compare = function (other) {
  debug('SemVer.compare', this.version, this.options, other)
  if (!(other instanceof SemVer)) {
    other = new SemVer(other, this.options)
  }

  return this.compareMain(other) || this.comparePre(other)
}

SemVer.prototype.compareMain = function (other) {
  if (!(other instanceof SemVer)) {
    other = new SemVer(other, this.options)
  }

  return compareIdentifiers(this.major, other.major) ||
         compareIdentifiers(this.minor, other.minor) ||
         compareIdentifiers(this.patch, other.patch)
}

SemVer.prototype.comparePre = function (other) {
  if (!(other instanceof SemVer)) {
    other = new SemVer(other, this.options)
  }

  // NOT having a prerelease is > having one
  if (this.prerelease.length && !other.prerelease.length) {
    return -1
  } else if (!this.prerelease.length && other.prerelease.length) {
    return 1
  } else if (!this.prerelease.length && !other.prerelease.length) {
    return 0
  }

  var i = 0
  do {
    var a = this.prerelease[i]
    var b = other.prerelease[i]
    debug('prerelease compare', i, a, b)
    if (a === undefined && b === undefined) {
      return 0
    } else if (b === undefined) {
      return 1
    } else if (a === undefined) {
      return -1
    } else if (a === b) {
      continue
    } else {
      return compareIdentifiers(a, b)
    }
  } while (++i)
}

SemVer.prototype.compareBuild = function (other) {
  if (!(other instanceof SemVer)) {
    other = new SemVer(other, this.options)
  }

  var i = 0
  do {
    var a = this.build[i]
    var b = other.build[i]
    debug('prerelease compare', i, a, b)
    if (a === undefined && b === undefined) {
      return 0
    } else if (b === undefined) {
      return 1
    } else if (a === undefined) {
      return -1
    } else if (a === b) {
      continue
    } else {
      return compareIdentifiers(a, b)
    }
  } while (++i)
}

// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
SemVer.prototype.inc = function (release, identifier) {
  switch (release) {
    case 'premajor':
      this.prerelease.length = 0
      this.patch = 0
      this.minor = 0
      this.major++
      this.inc('pre', identifier)
      break
    case 'preminor':
      this.prerelease.length = 0
      this.patch = 0
      this.minor++
      this.inc('pre', identifier)
      break
    case 'prepatch':
      // If this is already a prerelease, it will bump to the next version
      // drop any prereleases that might already exist, since they are not
      // relevant at this point.
      this.prerelease.length = 0
      this.inc('patch', identifier)
      this.inc('pre', identifier)
      break
    // If the input is a non-prerelease version, this acts the same as
    // prepatch.
    case 'prerelease':
      if (this.prerelease.length === 0) {
        this.inc('patch', identifier)
      }
      this.inc('pre', identifier)
      break

    case 'major':
      // If this is a pre-major version, bump up to the same major version.
      // Otherwise increment major.
      // 1.0.0-5 bumps to 1.0.0
      // 1.1.0 bumps to 2.0.0
      if (this.minor !== 0 ||
          this.patch !== 0 ||
          this.prerelease.length === 0) {
        this.major++
      }
      this.minor = 0
      this.patch = 0
      this.prerelease = []
      break
    case 'minor':
      // If this is a pre-minor version, bump up to the same minor version.
      // Otherwise increment minor.
      // 1.2.0-5 bumps to 1.2.0
      // 1.2.1 bumps to 1.3.0
      if (this.patch !== 0 || this.prerelease.length === 0) {
        this.minor++
      }
      this.patch = 0
      this.prerelease = []
      break
    case 'patch':
      // If this is not a pre-release version, it will increment the patch.
      // If it is a pre-release it will bump up to the same patch version.
      // 1.2.0-5 patches to 1.2.0
      // 1.2.0 patches to 1.2.1
      if (this.prerelease.length === 0) {
        this.patch++
      }
      this.prerelease = []
      break
    // This probably shouldn't be used publicly.
    // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
    case 'pre':
      if (this.prerelease.length === 0) {
        this.prerelease = [0]
      } else {
        var i = this.prerelease.length
        while (--i >= 0) {
          if (typeof this.prerelease[i] === 'number') {
            this.prerelease[i]++
            i = -2
          }
        }
        if (i === -1) {
          // didn't increment anything
          this.prerelease.push(0)
        }
      }
      if (identifier) {
        // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
        // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
        if (this.prerelease[0] === identifier) {
          if (isNaN(this.prerelease[1])) {
            this.prerelease = [identifier, 0]
          }
        } else {
          this.prerelease = [identifier, 0]
        }
      }
      break

    default:
      throw new Error('invalid increment argument: ' + release)
  }
  this.format()
  this.raw = this.version
  return this
}

exports.inc = inc
function inc (version, release, loose, identifier) {
  if (typeof (loose) === 'string') {
    identifier = loose
    loose = undefined
  }

  try {
    return new SemVer(version, loose).inc(release, identifier).version
  } catch (er) {
    return null
  }
}

exports.diff = diff
function diff (version1, version2) {
  if (eq(version1, version2)) {
    return null
  } else {
    var v1 = parse(version1)
    var v2 = parse(version2)
    var prefix = ''
    if (v1.prerelease.length || v2.prerelease.length) {
      prefix = 'pre'
      var defaultResult = 'prerelease'
    }
    for (var key in v1) {
      if (key === 'major' || key === 'minor' || key === 'patch') {
        if (v1[key] !== v2[key]) {
          return prefix + key
        }
      }
    }
    return defaultResult // may be undefined
  }
}

exports.compareIdentifiers = compareIdentifiers

var numeric = /^[0-9]+$/
function compareIdentifiers (a, b) {
  var anum = numeric.test(a)
  var bnum = numeric.test(b)

  if (anum && bnum) {
    a = +a
    b = +b
  }

  return a === b ? 0
    : (anum && !bnum) ? -1
    : (bnum && !anum) ? 1
    : a < b ? -1
    : 1
}

exports.rcompareIdentifiers = rcompareIdentifiers
function rcompareIdentifiers (a, b) {
  return compareIdentifiers(b, a)
}

exports.major = major
function major (a, loose) {
  return new SemVer(a, loose).major
}

exports.minor = minor
function minor (a, loose) {
  return new SemVer(a, loose).minor
}

exports.patch = patch
function patch (a, loose) {
  return new SemVer(a, loose).patch
}

exports.compare = compare
function compare (a, b, loose) {
  return new SemVer(a, loose).compare(new SemVer(b, loose))
}

exports.compareLoose = compareLoose
function compareLoose (a, b) {
  return compare(a, b, true)
}

exports.compareBuild = compareBuild
function compareBuild (a, b, loose) {
  var versionA = new SemVer(a, loose)
  var versionB = new SemVer(b, loose)
  return versionA.compare(versionB) || versionA.compareBuild(versionB)
}

exports.rcompare = rcompare
function rcompare (a, b, loose) {
  return compare(b, a, loose)
}

exports.sort = sort
function sort (list, loose) {
  return list.sort(function (a, b) {
    return exports.compareBuild(a, b, loose)
  })
}

exports.rsort = rsort
function rsort (list, loose) {
  return list.sort(function (a, b) {
    return exports.compareBuild(b, a, loose)
  })
}

exports.gt = gt
function gt (a, b, loose) {
  return compare(a, b, loose) > 0
}

exports.lt = lt
function lt (a, b, loose) {
  return compare(a, b, loose) < 0
}

exports.eq = eq
function eq (a, b, loose) {
  return compare(a, b, loose) === 0
}

exports.neq = neq
function neq (a, b, loose) {
  return compare(a, b, loose) !== 0
}

exports.gte = gte
function gte (a, b, loose) {
  return compare(a, b, loose) >= 0
}

exports.lte = lte
function lte (a, b, loose) {
  return compare(a, b, loose) <= 0
}

exports.cmp = cmp
function cmp (a, op, b, loose) {
  switch (op) {
    case '===':
      if (typeof a === 'object')
        a = a.version
      if (typeof b === 'object')
        b = b.version
      return a === b

    case '!==':
      if (typeof a === 'object')
        a = a.version
      if (typeof b === 'object')
        b = b.version
      return a !== b

    case '':
    case '=':
    case '==':
      return eq(a, b, loose)

    case '!=':
      return neq(a, b, loose)

    case '>':
      return gt(a, b, loose)

    case '>=':
      return gte(a, b, loose)

    case '<':
      return lt(a, b, loose)

    case '<=':
      return lte(a, b, loose)

    default:
      throw new TypeError('Invalid operator: ' + op)
  }
}

exports.Comparator = Comparator
function Comparator (comp, options) {
  if (!options || typeof options !== 'object') {
    options = {
      loose: !!options,
      includePrerelease: false
    }
  }

  if (comp instanceof Comparator) {
    if (comp.loose === !!options.loose) {
      return comp
    } else {
      comp = comp.value
    }
  }

  if (!(this instanceof Comparator)) {
    return new Comparator(comp, options)
  }

  comp = comp.trim().split(/\s+/).join(' ')
  debug('comparator', comp, options)
  this.options = options
  this.loose = !!options.loose
  this.parse(comp)

  if (this.semver === ANY) {
    this.value = ''
  } else {
    this.value = this.operator + this.semver.version
  }

  debug('comp', this)
}

var ANY = {}
Comparator.prototype.parse = function (comp) {
  var r = this.options.loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]
  var m = comp.match(r)

  if (!m) {
    throw new TypeError('Invalid comparator: ' + comp)
  }

  this.operator = m[1] !== undefined ? m[1] : ''
  if (this.operator === '=') {
    this.operator = ''
  }

  // if it literally is just '>' or '' then allow anything.
  if (!m[2]) {
    this.semver = ANY
  } else {
    this.semver = new SemVer(m[2], this.options.loose)
  }
}

Comparator.prototype.toString = function () {
  return this.value
}

Comparator.prototype.test = function (version) {
  debug('Comparator.test', version, this.options.loose)

  if (this.semver === ANY || version === ANY) {
    return true
  }

  if (typeof version === 'string') {
    try {
      version = new SemVer(version, this.options)
    } catch (er) {
      return false
    }
  }

  return cmp(version, this.operator, this.semver, this.options)
}

Comparator.prototype.intersects = function (comp, options) {
  if (!(comp instanceof Comparator)) {
    throw new TypeError('a Comparator is required')
  }

  if (!options || typeof options !== 'object') {
    options = {
      loose: !!options,
      includePrerelease: false
    }
  }

  var rangeTmp

  if (this.operator === '') {
    if (this.value === '') {
      return true
    }
    rangeTmp = new Range(comp.value, options)
    return satisfies(this.value, rangeTmp, options)
  } else if (comp.operator === '') {
    if (comp.value === '') {
      return true
    }
    rangeTmp = new Range(this.value, options)
    return satisfies(comp.semver, rangeTmp, options)
  }

  var sameDirectionIncreasing =
    (this.operator === '>=' || this.operator === '>') &&
    (comp.operator === '>=' || comp.operator === '>')
  var sameDirectionDecreasing =
    (this.operator === '<=' || this.operator === '<') &&
    (comp.operator === '<=' || comp.operator === '<')
  var sameSemVer = this.semver.version === comp.semver.version
  var differentDirectionsInclusive =
    (this.operator === '>=' || this.operator === '<=') &&
    (comp.operator === '>=' || comp.operator === '<=')
  var oppositeDirectionsLessThan =
    cmp(this.semver, '<', comp.semver, options) &&
    ((this.operator === '>=' || this.operator === '>') &&
    (comp.operator === '<=' || comp.operator === '<'))
  var oppositeDirectionsGreaterThan =
    cmp(this.semver, '>', comp.semver, options) &&
    ((this.operator === '<=' || this.operator === '<') &&
    (comp.operator === '>=' || comp.operator === '>'))

  return sameDirectionIncreasing || sameDirectionDecreasing ||
    (sameSemVer && differentDirectionsInclusive) ||
    oppositeDirectionsLessThan || oppositeDirectionsGreaterThan
}

exports.Range = Range
function Range (range, options) {
  if (!options || typeof options !== 'object') {
    options = {
      loose: !!options,
      includePrerelease: false
    }
  }

  if (range instanceof Range) {
    if (range.loose === !!options.loose &&
        range.includePrerelease === !!options.includePrerelease) {
      return range
    } else {
      return new Range(range.raw, options)
    }
  }

  if (range instanceof Comparator) {
    return new Range(range.value, options)
  }

  if (!(this instanceof Range)) {
    return new Range(range, options)
  }

  this.options = options
  this.loose = !!options.loose
  this.includePrerelease = !!options.includePrerelease

  // First reduce all whitespace as much as possible so we do not have to rely
  // on potentially slow regexes like \s*. This is then stored and used for
  // future error messages as well.
  this.raw = range
    .trim()
    .split(/\s+/)
    .join(' ')

  // First, split based on boolean or ||
  this.set = this.raw.split('||').map(function (range) {
    return this.parseRange(range.trim())
  }, this).filter(function (c) {
    // throw out any that are not relevant for whatever reason
    return c.length
  })

  if (!this.set.length) {
    throw new TypeError('Invalid SemVer Range: ' + this.raw)
  }

  this.format()
}

Range.prototype.format = function () {
  this.range = this.set.map(function (comps) {
    return comps.join(' ').trim()
  }).join('||').trim()
  return this.range
}

Range.prototype.toString = function () {
  return this.range
}

Range.prototype.parseRange = function (range) {
  var loose = this.options.loose
  // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
  var hr = loose ? safeRe[t.HYPHENRANGELOOSE] : safeRe[t.HYPHENRANGE]
  range = range.replace(hr, hyphenReplace)
  debug('hyphen replace', range)
  // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
  range = range.replace(safeRe[t.COMPARATORTRIM], comparatorTrimReplace)
  debug('comparator trim', range, safeRe[t.COMPARATORTRIM])

  // `~ 1.2.3` => `~1.2.3`
  range = range.replace(safeRe[t.TILDETRIM], tildeTrimReplace)

  // `^ 1.2.3` => `^1.2.3`
  range = range.replace(safeRe[t.CARETTRIM], caretTrimReplace)

  // normalize spaces
  range = range.split(/\s+/).join(' ')

  // At this point, the range is completely trimmed and
  // ready to be split into comparators.

  var compRe = loose ? safeRe[t.COMPARATORLOOSE] : safeRe[t.COMPARATOR]
  var set = range.split(' ').map(function (comp) {
    return parseComparator(comp, this.options)
  }, this).join(' ').split(/\s+/)
  if (this.options.loose) {
    // in loose mode, throw out any that are not valid comparators
    set = set.filter(function (comp) {
      return !!comp.match(compRe)
    })
  }
  set = set.map(function (comp) {
    return new Comparator(comp, this.options)
  }, this)

  return set
}

Range.prototype.intersects = function (range, options) {
  if (!(range instanceof Range)) {
    throw new TypeError('a Range is required')
  }

  return this.set.some(function (thisComparators) {
    return (
      isSatisfiable(thisComparators, options) &&
      range.set.some(function (rangeComparators) {
        return (
          isSatisfiable(rangeComparators, options) &&
          thisComparators.every(function (thisComparator) {
            return rangeComparators.every(function (rangeComparator) {
              return thisComparator.intersects(rangeComparator, options)
            })
          })
        )
      })
    )
  })
}

// take a set of comparators and determine whether there
// exists a version which can satisfy it
function isSatisfiable (comparators, options) {
  var result = true
  var remainingComparators = comparators.slice()
  var testComparator = remainingComparators.pop()

  while (result && remainingComparators.length) {
    result = remainingComparators.every(function (otherComparator) {
      return testComparator.intersects(otherComparator, options)
    })

    testComparator = remainingComparators.pop()
  }

  return result
}

// Mostly just for testing and legacy API reasons
exports.toComparators = toComparators
function toComparators (range, options) {
  return new Range(range, options).set.map(function (comp) {
    return comp.map(function (c) {
      return c.value
    }).join(' ').trim().split(' ')
  })
}

// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
function parseComparator (comp, options) {
  debug('comp', comp, options)
  comp = replaceCarets(comp, options)
  debug('caret', comp)
  comp = replaceTildes(comp, options)
  debug('tildes', comp)
  comp = replaceXRanges(comp, options)
  debug('xrange', comp)
  comp = replaceStars(comp, options)
  debug('stars', comp)
  return comp
}

function isX (id) {
  return !id || id.toLowerCase() === 'x' || id === '*'
}

// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
function replaceTildes (comp, options) {
  return comp.trim().split(/\s+/).map(function (comp) {
    return replaceTilde(comp, options)
  }).join(' ')
}

function replaceTilde (comp, options) {
  var r = options.loose ? safeRe[t.TILDELOOSE] : safeRe[t.TILDE]
  return comp.replace(r, function (_, M, m, p, pr) {
    debug('tilde', comp, _, M, m, p, pr)
    var ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
    } else if (isX(p)) {
      // ~1.2 == >=1.2.0 <1.3.0
      ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
    } else if (pr) {
      debug('replaceTilde pr', pr)
      ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
            ' <' + M + '.' + (+m + 1) + '.0'
    } else {
      // ~1.2.3 == >=1.2.3 <1.3.0
      ret = '>=' + M + '.' + m + '.' + p +
            ' <' + M + '.' + (+m + 1) + '.0'
    }

    debug('tilde return', ret)
    return ret
  })
}

// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
// ^1.2.3 --> >=1.2.3 <2.0.0
// ^1.2.0 --> >=1.2.0 <2.0.0
function replaceCarets (comp, options) {
  return comp.trim().split(/\s+/).map(function (comp) {
    return replaceCaret(comp, options)
  }).join(' ')
}

function replaceCaret (comp, options) {
  debug('caret', comp, options)
  var r = options.loose ? safeRe[t.CARETLOOSE] : safeRe[t.CARET]
  return comp.replace(r, function (_, M, m, p, pr) {
    debug('caret', comp, _, M, m, p, pr)
    var ret

    if (isX(M)) {
      ret = ''
    } else if (isX(m)) {
      ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'
    } else if (isX(p)) {
      if (M === '0') {
        ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'
      } else {
        ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'
      }
    } else if (pr) {
      debug('replaceCaret pr', pr)
      if (M === '0') {
        if (m === '0') {
          ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
                ' <' + M + '.' + m + '.' + (+p + 1)
        } else {
          ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
                ' <' + M + '.' + (+m + 1) + '.0'
        }
      } else {
        ret = '>=' + M + '.' + m + '.' + p + '-' + pr +
              ' <' + (+M + 1) + '.0.0'
      }
    } else {
      debug('no pr')
      if (M === '0') {
        if (m === '0') {
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + m + '.' + (+p + 1)
        } else {
          ret = '>=' + M + '.' + m + '.' + p +
                ' <' + M + '.' + (+m + 1) + '.0'
        }
      } else {
        ret = '>=' + M + '.' + m + '.' + p +
              ' <' + (+M + 1) + '.0.0'
      }
    }

    debug('caret return', ret)
    return ret
  })
}

function replaceXRanges (comp, options) {
  debug('replaceXRanges', comp, options)
  return comp.split(/\s+/).map(function (comp) {
    return replaceXRange(comp, options)
  }).join(' ')
}

function replaceXRange (comp, options) {
  comp = comp.trim()
  var r = options.loose ? safeRe[t.XRANGELOOSE] : safeRe[t.XRANGE]
  return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
    debug('xRange', comp, ret, gtlt, M, m, p, pr)
    var xM = isX(M)
    var xm = xM || isX(m)
    var xp = xm || isX(p)
    var anyX = xp

    if (gtlt === '=' && anyX) {
      gtlt = ''
    }

    // if we're including prereleases in the match, then we need
    // to fix this to -0, the lowest possible prerelease value
    pr = options.includePrerelease ? '-0' : ''

    if (xM) {
      if (gtlt === '>' || gtlt === '<') {
        // nothing is allowed
        ret = '<0.0.0-0'
      } else {
        // nothing is forbidden
        ret = '*'
      }
    } else if (gtlt && anyX) {
      // we know patch is an x, because we have any x at all.
      // replace X with 0
      if (xm) {
        m = 0
      }
      p = 0

      if (gtlt === '>') {
        // >1 => >=2.0.0
        // >1.2 => >=1.3.0
        // >1.2.3 => >= 1.2.4
        gtlt = '>='
        if (xm) {
          M = +M + 1
          m = 0
          p = 0
        } else {
          m = +m + 1
          p = 0
        }
      } else if (gtlt === '<=') {
        // <=0.7.x is actually <0.8.0, since any 0.7.x should
        // pass.  Similarly, <=7.x is actually <8.0.0, etc.
        gtlt = '<'
        if (xm) {
          M = +M + 1
        } else {
          m = +m + 1
        }
      }

      ret = gtlt + M + '.' + m + '.' + p + pr
    } else if (xm) {
      ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr
    } else if (xp) {
      ret = '>=' + M + '.' + m + '.0' + pr +
        ' <' + M + '.' + (+m + 1) + '.0' + pr
    }

    debug('xRange return', ret)

    return ret
  })
}

// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
function replaceStars (comp, options) {
  debug('replaceStars', comp, options)
  // Looseness is ignored here.  star is always as loose as it gets!
  return comp.trim().replace(safeRe[t.STAR], '')
}

// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0
function hyphenReplace ($0,
  from, fM, fm, fp, fpr, fb,
  to, tM, tm, tp, tpr, tb) {
  if (isX(fM)) {
    from = ''
  } else if (isX(fm)) {
    from = '>=' + fM + '.0.0'
  } else if (isX(fp)) {
    from = '>=' + fM + '.' + fm + '.0'
  } else {
    from = '>=' + from
  }

  if (isX(tM)) {
    to = ''
  } else if (isX(tm)) {
    to = '<' + (+tM + 1) + '.0.0'
  } else if (isX(tp)) {
    to = '<' + tM + '.' + (+tm + 1) + '.0'
  } else if (tpr) {
    to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr
  } else {
    to = '<=' + to
  }

  return (from + ' ' + to).trim()
}

// if ANY of the sets match ALL of its comparators, then pass
Range.prototype.test = function (version) {
  if (!version) {
    return false
  }

  if (typeof version === 'string') {
    try {
      version = new SemVer(version, this.options)
    } catch (er) {
      return false
    }
  }

  for (var i = 0; i < this.set.length; i++) {
    if (testSet(this.set[i], version, this.options)) {
      return true
    }
  }
  return false
}

function testSet (set, version, options) {
  for (var i = 0; i < set.length; i++) {
    if (!set[i].test(version)) {
      return false
    }
  }

  if (version.prerelease.length && !options.includePrerelease) {
    // Find the set of versions that are allowed to have prereleases
    // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
    // That should allow `1.2.3-pr.2` to pass.
    // However, `1.2.4-alpha.notready` should NOT be allowed,
    // even though it's within the range set by the comparators.
    for (i = 0; i < set.length; i++) {
      debug(set[i].semver)
      if (set[i].semver === ANY) {
        continue
      }

      if (set[i].semver.prerelease.length > 0) {
        var allowed = set[i].semver
        if (allowed.major === version.major &&
            allowed.minor === version.minor &&
            allowed.patch === version.patch) {
          return true
        }
      }
    }

    // Version has a -pre, but it's not one of the ones we like.
    return false
  }

  return true
}

exports.satisfies = satisfies
function satisfies (version, range, options) {
  try {
    range = new Range(range, options)
  } catch (er) {
    return false
  }
  return range.test(version)
}

exports.maxSatisfying = maxSatisfying
function maxSatisfying (versions, range, options) {
  var max = null
  var maxSV = null
  try {
    var rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach(function (v) {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!max || maxSV.compare(v) === -1) {
        // compare(max, v, true)
        max = v
        maxSV = new SemVer(max, options)
      }
    }
  })
  return max
}

exports.minSatisfying = minSatisfying
function minSatisfying (versions, range, options) {
  var min = null
  var minSV = null
  try {
    var rangeObj = new Range(range, options)
  } catch (er) {
    return null
  }
  versions.forEach(function (v) {
    if (rangeObj.test(v)) {
      // satisfies(v, range, options)
      if (!min || minSV.compare(v) === 1) {
        // compare(min, v, true)
        min = v
        minSV = new SemVer(min, options)
      }
    }
  })
  return min
}

exports.minVersion = minVersion
function minVersion (range, loose) {
  range = new Range(range, loose)

  var minver = new SemVer('0.0.0')
  if (range.test(minver)) {
    return minver
  }

  minver = new SemVer('0.0.0-0')
  if (range.test(minver)) {
    return minver
  }

  minver = null
  for (var i = 0; i < range.set.length; ++i) {
    var comparators = range.set[i]

    comparators.forEach(function (comparator) {
      // Clone to avoid manipulating the comparator's semver object.
      var compver = new SemVer(comparator.semver.version)
      switch (comparator.operator) {
        case '>':
          if (compver.prerelease.length === 0) {
            compver.patch++
          } else {
            compver.prerelease.push(0)
          }
          compver.raw = compver.format()
          /* fallthrough */
        case '':
        case '>=':
          if (!minver || gt(minver, compver)) {
            minver = compver
          }
          break
        case '<':
        case '<=':
          /* Ignore maximum versions */
          break
        /* istanbul ignore next */
        default:
          throw new Error('Unexpected operation: ' + comparator.operator)
      }
    })
  }

  if (minver && range.test(minver)) {
    return minver
  }

  return null
}

exports.validRange = validRange
function validRange (range, options) {
  try {
    // Return '*' instead of '' so that truthiness works.
    // This will throw if it's invalid anyway
    return new Range(range, options).range || '*'
  } catch (er) {
    return null
  }
}

// Determine if version is less than all the versions possible in the range
exports.ltr = ltr
function ltr (version, range, options) {
  return outside(version, range, '<', options)
}

// Determine if version is greater than all the versions possible in the range.
exports.gtr = gtr
function gtr (version, range, options) {
  return outside(version, range, '>', options)
}

exports.outside = outside
function outside (version, range, hilo, options) {
  version = new SemVer(version, options)
  range = new Range(range, options)

  var gtfn, ltefn, ltfn, comp, ecomp
  switch (hilo) {
    case '>':
      gtfn = gt
      ltefn = lte
      ltfn = lt
      comp = '>'
      ecomp = '>='
      break
    case '<':
      gtfn = lt
      ltefn = gte
      ltfn = gt
      comp = '<'
      ecomp = '<='
      break
    default:
      throw new TypeError('Must provide a hilo val of "<" or ">"')
  }

  // If it satisifes the range it is not outside
  if (satisfies(version, range, options)) {
    return false
  }

  // From now on, variable terms are as if we're in "gtr" mode.
  // but note that everything is flipped for the "ltr" function.

  for (var i = 0; i < range.set.length; ++i) {
    var comparators = range.set[i]

    var high = null
    var low = null

    comparators.forEach(function (comparator) {
      if (comparator.semver === ANY) {
        comparator = new Comparator('>=0.0.0')
      }
      high = high || comparator
      low = low || comparator
      if (gtfn(comparator.semver, high.semver, options)) {
        high = comparator
      } else if (ltfn(comparator.semver, low.semver, options)) {
        low = comparator
      }
    })

    // If the edge version comparator has a operator then our version
    // isn't outside it
    if (high.operator === comp || high.operator === ecomp) {
      return false
    }

    // If the lowest version comparator has an operator and our version
    // is less than it then it isn't higher than the range
    if ((!low.operator || low.operator === comp) &&
        ltefn(version, low.semver)) {
      return false
    } else if (low.operator === ecomp && ltfn(version, low.semver)) {
      return false
    }
  }
  return true
}

exports.prerelease = prerelease
function prerelease (version, options) {
  var parsed = parse(version, options)
  return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}

exports.intersects = intersects
function intersects (r1, r2, options) {
  r1 = new Range(r1, options)
  r2 = new Range(r2, options)
  return r1.intersects(r2)
}

exports.coerce = coerce
function coerce (version, options) {
  if (version instanceof SemVer) {
    return version
  }

  if (typeof version === 'number') {
    version = String(version)
  }

  if (typeof version !== 'string') {
    return null
  }

  options = options || {}

  var match = null
  if (!options.rtl) {
    match = version.match(safeRe[t.COERCE])
  } else {
    // Find the right-most coercible string that does not share
    // a terminus with a more left-ward coercible string.
    // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
    //
    // Walk through the string checking with a /g regexp
    // Manually set the index so as to pick up overlapping matches.
    // Stop when we get a match that ends at the string end, since no
    // coercible string can be more right-ward without the same terminus.
    var next
    while ((next = safeRe[t.COERCERTL].exec(version)) &&
      (!match || match.index + match[0].length !== version.length)
    ) {
      if (!match ||
          next.index + next[0].length !== match.index + match[0].length) {
        match = next
      }
      safeRe[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
    }
    // leave it in a clean state
    safeRe[t.COERCERTL].lastIndex = -1
  }

  if (match === null) {
    return null
  }

  return parse(match[2] +
    '.' + (match[3] || '0') +
    '.' + (match[4] || '0'), options)
}
{
	"name": "type-fest",
	"version": "2.19.0",
	"description": "A collection of essential TypeScript types",
	"license": "(MIT OR CC0-1.0)",
	"repository": "sindresorhus/type-fest",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=12.20"
	},
	"scripts": {
		"test": "xo && tsd && tsc && node script/test/source-files-extension.js"
	},
	"files": [
		"index.d.ts",
		"source"
	],
	"keywords": [
		"typescript",
		"ts",
		"types",
		"utility",
		"util",
		"utilities",
		"omit",
		"merge",
		"json"
	],
	"devDependencies": {
		"@sindresorhus/tsconfig": "~0.7.0",
		"expect-type": "^0.13.0",
		"tsd": "^0.20.0",
		"typescript": "^4.6.3",
		"xo": "^0.43.0"
	},
	"types": "./index.d.ts",
	"xo": {
		"rules": {
			"@typescript-eslint/ban-types": "off",
			"@typescript-eslint/indent": "off",
			"node/no-unsupported-features/es-builtins": "off",
			"import/extensions": "off",
			"@typescript-eslint/no-redeclare": "off",
			"@typescript-eslint/no-confusing-void-expression": "off"
		}
	}
}
<div align="center">
	<br>
	<br>
	<img src="media/logo.svg" alt="type-fest" height="300">
	<br>
	<br>
	<b>A collection of essential TypeScript types</b>
	<br>
	<br>
	<br>
	<br>
	<hr>
	<div align="center">
		<p>
			<p>
				<sup>
					<a href="https://github.com/sponsors/sindresorhus">Sindre Sorhus' open source work is supported by the community</a>
				</sup>
			</p>
			<sup>Special thanks to:</sup>
			<br>
			<br>
			<a href="https://standardresume.co/tech">
				<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="180"/>
			</a>
			<br>
			<br>
			<br>
			<a href="https://workos.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=type-fest&utm_source=github">
				<div>
					<img src="https://sindresorhus.com/assets/thanks/workos-logo-white-bg.svg" width="220" alt="WorkOS">
				</div>
				<b>Your app, enterprise-ready.</b>
				<div>
					<sub>Start selling to enterprise customers with just a few lines of code.</sub>
					<br>
					<sup>Add Single Sign-On (and more) in minutes instead of months.</sup>
				</div>
			</a>
			<br>
			<br>
			<br>
			<a href="https://www.useanvil.com/?utm_source=sindresorhus#gh-light-mode-only">
				<div>
					<img src="https://sindresorhus.com/assets/thanks/anvil-logo-light.svg" width="200" alt="Anvil">
				</div>
				<br>
				<b>Paperwork that makes the data work.</b>
				<div>
					<sub>
					Easy APIs for paperwork. PDF generation, e-signature and embeddable no-code webforms.
					<br>
					The easiest way to build paperwork automation into your product.
					</sub>
				</div>
			</a>
			<a href="https://www.useanvil.com/?utm_source=sindresorhus#gh-dark-mode-only">
				<div>
					<img src="https://sindresorhus.com/assets/thanks/anvil-logo-dark.svg" width="200" alt="Anvil">
				</div>
				<br>
				<b>Paperwork that makes the data work.</b>
				<div>
					<sub>
					Easy APIs for paperwork. PDF generation, e-signature and embeddable no-code webforms.
					<br>
					The easiest way to build paperwork automation into your product.
					</sub>
				</div>
			</a>
		</p>
	</div>
	<br>
	<hr>
</div>
<br>
<br>

[![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://giphy.com/gifs/illustration-rainbow-unicorn-26AHG5KGFxSkUWw1i)
[![npm dependents](https://badgen.net/npm/dependents/type-fest)](https://www.npmjs.com/package/type-fest?activeTab=dependents)
[![npm downloads](https://badgen.net/npm/dt/type-fest)](https://www.npmjs.com/package/type-fest)
[![Docs](https://paka.dev/badges/v0/cute.svg)](https://paka.dev/npm/type-fest)

Many of the types here should have been built-in. You can help by suggesting some of them to the [TypeScript project](https://github.com/Microsoft/TypeScript/blob/main/CONTRIBUTING.md).

Either add this package as a dependency or copy-paste the needed types. No credit required. 👌

PR welcome for additional commonly needed types and docs improvements. Read the [contributing guidelines](.github/contributing.md) first.

**Help wanted with reviewing [proposals](https://github.com/sindresorhus/type-fest/issues) and [pull requests](https://github.com/sindresorhus/type-fest/pulls).**

## Install

```sh
npm install type-fest
```

*Requires TypeScript >=4.2*

## Usage

```ts
import type {Except} from 'type-fest';

type Foo = {
	unicorn: string;
	rainbow: boolean;
};

type FooWithoutRainbow = Except<Foo, 'rainbow'>;
//=> {unicorn: string}
```

## API

Click the type names for complete docs.

### Basic

- [`Primitive`](source/primitive.d.ts) - Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
- [`Class`](source/basic.d.ts) - Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
- [`Constructor`](source/basic.d.ts) - Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
- [`TypedArray`](source/typed-array.d.ts) - Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
- [`ObservableLike`](source/observable-like.d.ts) - Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).

### Utilities

- [`Except`](source/except.d.ts) - Create a type from an object type without certain keys. This is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys).
- [`Writable`](source/writable.d.ts) - Create a type that strips `readonly` from all or some of an object's keys. The inverse of `Readonly<T>`. Formerly named `Mutable`.
- [`Merge`](source/merge.d.ts) - Merge two types into a new type. Keys of the second type overrides keys of the first type.
- [`MergeExclusive`](source/merge-exclusive.d.ts) - Create a type that has mutually exclusive keys.
- [`RequireAtLeastOne`](source/require-at-least-one.d.ts) - Create a type that requires at least one of the given keys.
- [`RequireExactlyOne`](source/require-exactly-one.d.ts) - Create a type that requires exactly a single key of the given keys and disallows more.
- [`RequireAllOrNone`](source/require-all-or-none.d.ts) - Create a type that requires all of the given keys or none of the given keys.
- [`RemoveIndexSignature`](source/remove-index-signature.d.ts) - Create a type that only has explicitly defined properties, absent of any index signatures.
- [`PartialDeep`](source/partial-deep.d.ts) - Create a deeply optional version of another type. Use [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) if you only need one level deep.
- [`PartialOnUndefinedDeep`](source/partial-on-undefined-deep.d.ts) - Create a deep version of another type where all keys accepting `undefined` type are set to optional.
- [`ReadonlyDeep`](source/readonly-deep.d.ts) - Create a deeply immutable version of an `object`/`Map`/`Set`/`Array` type. Use [`Readonly<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) if you only need one level deep.
- [`LiteralUnion`](source/literal-union.d.ts) - Create a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. Workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729).
- [`Opaque`](source/opaque.d.ts) - Create an [opaque type](https://codemix.com/opaque-types-in-javascript/).
- [`UnwrapOpaque`](source/opaque.d.ts) - Revert an [opaque type](https://codemix.com/opaque-types-in-javascript/) back to its original type.
- [`InvariantOf`](source/invariant-of.d.ts) - Create an [invariant type](https://basarat.gitbook.io/typescript/type-system/type-compatibility#footnote-invariance), which is a type that does not accept supertypes and subtypes.
- [`SetOptional`](source/set-optional.d.ts) - Create a type that makes the given keys optional.
- [`SetRequired`](source/set-required.d.ts) - Create a type that makes the given keys required.
- [`SetNonNullable`](source/set-non-nullable.d.ts) - Create a type that makes the given keys non-nullable.
- [`ValueOf`](source/value-of.d.ts) - Create a union of the given object's values, and optionally specify which keys to get the values from.
- [`ConditionalKeys`](source/conditional-keys.d.ts) - Extract keys from a shape where values extend the given `Condition` type.
- [`ConditionalPick`](source/conditional-pick.d.ts) - Like `Pick` except it selects properties from a shape where the values extend the given `Condition` type.
- [`ConditionalExcept`](source/conditional-except.d.ts) - Like `Omit` except it removes properties from a shape where the values extend the given `Condition` type.
- [`UnionToIntersection`](source/union-to-intersection.d.ts) - Convert a union type to an intersection type.
- [`LiteralToPrimitive`](source/literal-to-primitive.d.ts) - Convert a [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types) to the [primitive type](source/primitive.d.ts) it belongs to.
- [`Stringified`](source/stringified.d.ts) - Create a type with the keys of the given type changed to `string` type.
- [`IterableElement`](source/iterable-element.d.ts) - Get the element type of an `Iterable`/`AsyncIterable`. For example, an array or a generator.
- [`Entry`](source/entry.d.ts) - Create a type that represents the type of an entry of a collection.
- [`Entries`](source/entries.d.ts) - Create a type that represents the type of the entries of a collection.
- [`SetReturnType`](source/set-return-type.d.ts) - Create a function type with a return type of your choice and the same parameters as the given function type.
- [`Simplify`](source/simplify.d.ts) - Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
- [`Get`](source/get.d.ts) - Get a deeply-nested property from an object using a key path, like [Lodash's `.get()`](https://lodash.com/docs/latest#get) function.
- [`StringKeyOf`](source/string-key-of.d.ts) - Get keys of the given type as strings.
- [`Schema`](source/schema.d.ts) - Create a deep version of another object type where property values are recursively replaced into a given value type.
- [`Exact`](source/exact.d.ts) - Create a type that does not allow extra properties.
- [`OptionalKeysOf`](source/optional-keys-of.d.ts) - Extract all optional keys from the given type.
- [`HasOptionalKeys`](source/has-optional-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any optional fields.
- [`RequiredKeysOf`](source/required-keys-of.d.ts) - Extract all required keys from the given type.
- [`HasRequiredKeys`](source/has-required-keys.d.ts) - Create a `true`/`false` type depending on whether the given type has any required fields.
- [`Spread`](source/spread.d.ts) - Mimic the type inferred by TypeScript when merging two objects or two arrays/tuples using the spread syntax.

### JSON

- [`Jsonify`](source/jsonify.d.ts) - Transform a type to one that is assignable to the `JsonValue` type.
- [`JsonPrimitive`](source/basic.d.ts) - Matches a JSON primitive.
- [`JsonObject`](source/basic.d.ts) - Matches a JSON object.
- [`JsonArray`](source/basic.d.ts) - Matches a JSON array.
- [`JsonValue`](source/basic.d.ts) - Matches any valid JSON value.

### Async

- [`Promisable`](source/promisable.d.ts) - Create a type that represents either the value or the value wrapped in `PromiseLike`.
- [`AsyncReturnType`](source/async-return-type.d.ts) - Unwrap the return type of a function that returns a `Promise`.
- [`Asyncify`](source/asyncify.d.ts) - Create an async version of the given function type.

### String

- [`Trim`](source/trim.d.ts) - Remove leading and trailing spaces from a string.
- [`Split`](source/split.d.ts) - Represents an array of strings split using a given character or character set.
- [`Replace`](source/replace.d.ts) - Represents a string with some or all matches replaced by a replacement.

### Array

- [`Includes`](source/includes.d.ts) - Returns a boolean for whether the given array includes the given item.
- [`Join`](source/join.d.ts) - Join an array of strings and/or numbers using the given string as a delimiter.
- [`LastArrayElement`](source/last-array-element.d.ts) - Extracts the type of the last element of an array.
- [`FixedLengthArray`](source/fixed-length-array.d.ts) - Create a type that represents an array of the given type and length.
- [`MultidimensionalArray`](source/multidimensional-array.d.ts) - Create a type that represents a multidimensional array of the given type and dimensions.
- [`MultidimensionalReadonlyArray`](source/multidimensional-readonly-array.d.ts) - Create a type that represents a multidimensional readonly array of the given type and dimensions.
- [`ReadonlyTuple`](source/readonly-tuple.d.ts) - Create a type that represents a read-only tuple of the given type and length.

### Numeric

- [`PositiveInfinity`](source/numeric.d.ts) - Matches the hidden `Infinity` type.
- [`NegativeInfinity`](source/numeric.d.ts) - Matches the hidden `-Infinity` type.
- [`Finite`](source/numeric.d.ts) - A finite `number`.
- [`Integer`](source/numeric.d.ts) - A `number` that is an integer.
- [`Float`](source/numeric.d.ts) - A `number` that is not an integer.
- [`NegativeFloat`](source/numeric.d.ts) - A negative (`-∞ < x < 0`) `number` that is not an integer.
- [`Negative`](source/numeric.d.ts) - A negative `number`/`bigint` (`-∞ < x < 0`)
- [`NonNegative`](source/numeric.d.ts) - A non-negative `number`/`bigint` (`0 <= x < ∞`).
- [`NegativeInteger`](source/numeric.d.ts) - A negative (`-∞ < x < 0`) `number` that is an integer.
- [`NonNegativeInteger`](source/numeric.d.ts) - A non-negative (`0 <= x < ∞`) `number` that is an integer.

### Change case

- [`CamelCase`](source/camel-case.d.ts) - Convert a string literal to camel-case (`fooBar`).
- [`CamelCasedProperties`](source/camel-cased-properties.d.ts) - Convert object properties to camel-case (`fooBar`).
- [`CamelCasedPropertiesDeep`](source/camel-cased-properties-deep.d.ts) - Convert object properties to camel-case recursively (`fooBar`).
- [`KebabCase`](source/kebab-case.d.ts) - Convert a string literal to kebab-case (`foo-bar`).
- [`KebabCasedProperties`](source/kebab-cased-properties.d.ts) - Convert a object properties to kebab-case recursively (`foo-bar`).
- [`KebabCasedPropertiesDeep`](source/kebab-cased-properties-deep.d.ts) - Convert object properties to kebab-case (`foo-bar`).
- [`PascalCase`](source/pascal-case.d.ts) - Converts a string literal to pascal-case (`FooBar`)
- [`PascalCasedProperties`](source/pascal-cased-properties.d.ts) - Converts object properties to pascal-case (`FooBar`)
- [`PascalCasedPropertiesDeep`](source/pascal-cased-properties-deep.d.ts) - Converts object properties to pascal-case (`FooBar`)
- [`SnakeCase`](source/snake-case.d.ts) - Convert a string literal to snake-case (`foo_bar`).
- [`SnakeCasedProperties`](source/snake-cased-properties-deep.d.ts) - Convert object properties to snake-case (`foo_bar`).
- [`SnakeCasedPropertiesDeep`](source/snake-cased-properties-deep.d.ts) - Convert object properties to snake-case recursively (`foo_bar`).
- [`ScreamingSnakeCase`](source/screaming-snake-case.d.ts) - Convert a string literal to screaming-snake-case (`FOO_BAR`).
- [`DelimiterCase`](source/delimiter-case.d.ts) - Convert a string literal to a custom string delimiter casing.
- [`DelimiterCasedProperties`](source/delimiter-cased-properties.d.ts) - Convert object properties to a custom string delimiter casing.
- [`DelimiterCasedPropertiesDeep`](source/delimiter-cased-properties-deep.d.ts) - Convert object properties to a custom string delimiter casing recursively.

### Miscellaneous

- [`PackageJson`](source/package-json.d.ts) - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). It also includes support for [TypeScript Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) and [Yarn Workspaces](https://classic.yarnpkg.com/lang/en/docs/workspaces/).
- [`TsConfigJson`](source/tsconfig-json.d.ts) - Type for [TypeScript's `tsconfig.json` file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) (TypeScript 4.4).

## Declined types

*If we decline a type addition, we will make sure to document the better solution here.*

- [`Diff` and `Spread`](https://github.com/sindresorhus/type-fest/pull/7) - The pull request author didn't provide any real-world use-cases and the PR went stale. If you think this type is useful, provide some real-world use-cases and we might reconsider.
- [`Dictionary`](https://github.com/sindresorhus/type-fest/issues/33) - You only save a few characters (`Dictionary<number>` vs `Record<string, number>`) from [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type), which is more flexible and well-known. Also, you shouldn't use an object as a dictionary. We have `Map` in JavaScript now.
- [`ExtractProperties` and `ExtractMethods`](https://github.com/sindresorhus/type-fest/pull/4) - The types violate the single responsibility principle. Instead, refine your types into more granular type hierarchies.
- [`Url2Json`](https://github.com/sindresorhus/type-fest/pull/262) - Inferring search parameters from a URL string is a cute idea, but not very useful in practice, since search parameters are usually dynamic and defined separately.
- [`Nullish`](https://github.com/sindresorhus/type-fest/pull/318) - The type only saves a couple of characters, not everyone knows what "nullish" means, and I'm also trying to [get away from `null`](https://github.com/sindresorhus/meta/discussions/7).
- [`TitleCase`](https://github.com/sindresorhus/type-fest/pull/303) - It's not solving a common need and is a better fit for a separate package.
- [`ExtendOr` and `ExtendAnd`](https://github.com/sindresorhus/type-fest/pull/247) - The benefits don't outweigh having to learn what they mean.
- [`PackageJsonExtras`](https://github.com/sindresorhus/type-fest/issues/371) - There are too many possible configurations that can be put into `package.json`. If you would like to extend `PackageJson` to support an additional configuration in your project, please see the *Extending existing types* section below.

## Alternative type names

*If you know one of our types by a different name, add it here for discovery.*

- `PartialBy` - See [`SetOptional`](https://github.com/sindresorhus/type-fest/blob/main/source/set-optional.d.ts)
- `RecordDeep`- See [`Schema`](https://github.com/sindresorhus/type-fest/blob/main/source/schema.d.ts)

## Tips

### Extending existing types

- [`PackageJson`](source/package-json.d.ts) - There are a lot of tools that place extra configurations inside the `package.json` file. You can extend `PackageJson` to support these additional configurations.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBDAnmApnA3gBQIYGMDW2A5igFIDOEAdnNuXAEJ0o4HFmVUC+cAZlBBBwA5ElQBaXinIxhAbgCwAKFCRYCZGnQAZYFRgooPfoJHSANntmKlysWlaESFanAC8jZo-YuaAMgwLKwBhal5gIgB+AC44XX1DADpQqnCiLhsgA)

	```ts
	import type {PackageJson as BasePackageJson} from 'type-fest';
	import type {Linter} from 'eslint';

	type PackageJson = BasePackageJson & {eslintConfig?: Linter.Config};
	```
	</details>

### Related

- [typed-query-selector](https://github.com/g-plane/typed-query-selector) - Enhances `document.querySelector` and `document.querySelectorAll` with a template literal type that matches element types returned from an HTML element query selector.
- [`Linter.Config`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/eslint/index.d.ts) - Definitions for the [ESLint configuration schema](https://eslint.org/docs/user-guide/configuring/language-options).

### Built-in types

There are many advanced types most users don't know about.

- [`Partial<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype) - Make all properties in `T` optional.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgHIHsAmEDC6QzADmyA3gLABQyycADnanALYQBcyAzmFKEQNxUaddFDAcQAV2YAjaIMoBfKlQQAbOJ05osEAIIMAQpOBrsUMkOR1eANziRkCfISKSoD4Pg4ZseAsTIALyW1DS0DEysHADkvvoMMQA0VsKi4sgAzAAMuVaKClY2wPaOknSYDrguADwA0sgQAB6QIJjaANYQAJ7oMDp+LsQAfAAUXd0cdUnI9mo+uv6uANp1ALoAlKHhyGAAFsCcAHTOAW4eYF4gyxNrwbNwago0ypRWp66jH8QcAApwYmAjxq8SWIy2FDCNDA3ToKFBQyIdR69wmfQG1TOhShyBgomQX3w3GQE2Q6IA8jIAFYQBBgI4TTiEs5bTQYsFInrLTbbHZOIlgZDlSqQABqj0kKBC3yINx6a2xfOQwH6o2FVXFaklwSCIUkbQghBAEEwENSfNOlykEGefNe5uhB2O6sgS3GPRmLogmslG1tLxUOKgEDA7hAuydtteryAA)

	```ts
	interface NodeConfig {
			appName: string;
			port: number;
	}

	class NodeAppBuilder {
			private configuration: NodeConfig = {
					appName: 'NodeApp',
					port: 3000
			};

			private updateConfig<Key extends keyof NodeConfig>(key: Key, value: NodeConfig[Key]) {
					this.configuration[key] = value;
			}

			config(config: Partial<NodeConfig>) {
					type NodeConfigKey = keyof NodeConfig;

					for (const key of Object.keys(config) as NodeConfigKey[]) {
							const updateValue = config[key];

							if (updateValue === undefined) {
									continue;
							}

							this.updateConfig(key, updateValue);
					}

					return this;
			}
	}

	// `Partial<NodeConfig>`` allows us to provide only a part of the
	// NodeConfig interface.
	new NodeAppBuilder().config({appName: 'ToDoApp'});
	```
	</details>

- [`Required<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredtype) - Make all properties in `T` required.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgGED21VQGJZwC2wA3gFCjXAzFJgA2A-AFzADOUckA5gNxUaIYjA4ckvGG07c+g6gF8KQkAgCuEFFDA5O6gEbEwUbLm2ESwABQIixACJIoSdgCUYAR3Vg4MACYAPGYuFvYAfACU5Ko0APRxwADKMBD+wFAAFuh2Vv7OSBlYGdmc8ABu8LHKsRyGxqY4oQT21pTCIHQMjOwA5DAAHgACxAAOjDAAdChYxL0ANLHUouKSMH0AEmAAhJhY6ozpAJ77GTCMjMCiV0ToSAb7UJPPC9WRgrEJwAAqR6MwSRQPFGUFocDgRHYxnEfGAowh-zgUCOwF6KwkUl6tXqJhCeEsxDaS1AXSYfUGI3GUxmc0WSneQA)

	```ts
	interface ContactForm {
			email?: string;
			message?: string;
	}

	function submitContactForm(formData: Required<ContactForm>) {
			// Send the form data to the server.
	}

	submitContactForm({
			email: 'ex@mple.com',
			message: 'Hi! Could you tell me more about…',
	});

	// TypeScript error: missing property 'message'
	submitContactForm({
			email: 'ex@mple.com',
	});
	```
	</details>

- [`Readonly<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#readonlytype) - Make all properties in `T` readonly.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/AQ4UwOwVwW2AZA9gc3mAbmANsA3gKFCOAHkAzMgGkOJABEwAjKZa2kAUQCcvEu32AMQCGAF2FYBIAL4BufDRABLCKLBcywgMZgEKZOoDCiCGSXI8i4hGEwwALmABnUVxXJ57YFgzZHSVF8sT1BpBSItLGEnJz1kAy5LLy0TM2RHACUwYQATEywATwAeAITjU3MAPnkrCJMXLigtUT4AClxgGztKbyDgaX99I1TzAEokr1BRAAslJwA6FIqLAF48TtswHp9MHDla9hJGACswZvmyLjAwAC8wVpm5xZHkUZDaMKIwqyWXYCW0oN4sNlsA1h0ug5gAByACyBQAggAHJHQ7ZBIFoXbzBjMCz7OoQP5YIaJNYQMAAdziCVaALGNSIAHomcAACoFJFgADKWjcSNEwG4vC4ji0wggEEQguiTnMEGALWAV1yAFp8gVgEjeFyuKICvMrCTgVxnst5jtsGC4ljsPNhXxGaAWcAAOq6YRXYDCRg+RWIcA5JSC+kWdCepQ+v3RYCU3RInzRMCGwlpC19NYBW1Ye08R1AA)

	```ts
	enum LogLevel {
			Off,
			Debug,
			Error,
			Fatal
	};

	interface LoggerConfig {
			name: string;
			level: LogLevel;
	}

	class Logger {
			config: Readonly<LoggerConfig>;

			constructor({name, level}: LoggerConfig) {
					this.config = {name, level};
					Object.freeze(this.config);
			}
	}

	const config: LoggerConfig = {
		name: 'MyApp',
		level: LogLevel.Debug
	};

	const logger = new Logger(config);

	// TypeScript Error: cannot assign to read-only property.
	logger.config.level = LogLevel.Error;

	// We are able to edit config variable as we please.
	config.level = LogLevel.Error;
	```
	</details>

- [`Pick<T, K>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys) - From `T`, pick a set of properties whose keys are in the union `K`.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/AQ4SwOwFwUwJwGYEMDGNgEE5TCgNugN4BQoZwOUBAXMAM5RyQDmA3KeSFABYCuAtgCMISMHloMmENh04oA9tBjQJjFuzIBfYrOAB6PcADCcGElh1gEGAHcKATwAO6ebyjB5CTNlwFwSxFR0BX5HeToYABNgBDh5fm8cfBg6AHIKG3ldA2BHOOcfFNpUygJ0pAhokr4hETFUgDpswywkggAFUwA3MFtgAF5gQgowKhhVKTYKGuFRcXo1aVZgbTIoJ3RW3xhOmB6+wfbcAGsAHi3kgBpgEtGy4AAfG54BWfqAPnZm4AAlZUj4MAkMA8GAGB4vEgfMlLLw6CwPBA8PYRmMgZVgAC6CgmI4cIommQELwICh8RBgKZKvALh1ur0bHQABR5PYMui0Wk7em2ADaAF0AJS0AASABUALIAGQAogR+Mp3CROCAFBBwVC2ikBpj5CgBIqGjizLA5TAFdAmalImAuqlBRoVQh5HBgEy1eDWfs7J5cjzGYKhroVfpDEhHM4MV6GRR5NN0JrtnRg6BVirTFBeHAKYmYY6QNpdB73LmCJZBlSAXAubtvczeSmQMNSuMbmKNgBlHFgPEUNwusBIPAAQlS1xetTmxT0SDoESgdD0C4aACtHMwxytLrohawgA)

	```ts
	interface Article {
			title: string;
			thumbnail: string;
			content: string;
	}

	// Creates new type out of the `Article` interface composed
	// from the Articles' two properties: `title` and `thumbnail`.
	// `ArticlePreview = {title: string; thumbnail: string}`
	type ArticlePreview = Pick<Article, 'title' | 'thumbnail'>;

	// Render a list of articles using only title and description.
	function renderArticlePreviews(previews: ArticlePreview[]): HTMLElement {
			const articles = document.createElement('div');

			for (const preview of previews) {
					// Append preview to the articles.
			}

			return articles;
	}

	const articles = renderArticlePreviews([
			{
				title: 'TypeScript tutorial!',
				thumbnail: '/assets/ts.jpg'
			}
	]);
	```
	</details>

- [`Record<K, T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) - Construct a type with a set of properties `K` of type `T`.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/AQ4ejYAUHsGcCWAXBMB2dgwGbAKYC2ADgDYwCeeemCaWArgE7ADGMxAhmuQHQBQoYEnJE8wALKEARnkaxEKdMAC8wAOS0kstGuAAfdQBM8ANzxlRjXQbVaWACwC0JPB0NqA3HwGgIwAJJoWozYHCxixnAsjAhStADmwESMMJYo1Fi4HMCIaPEu+MRklHj8gpqyoeHAAKJFFFTAAN4+giDYCIxwSAByHAR4AFw5SDF5Xm2gJBzdfQPD3WPxE5PAlBxdAPLYNQAelgh4aOHDaPQEMowrIAC+3oJ+AMKMrlrAXFhSAFZ4LEhC9g4-0BmA4JBISXgiCkBQABpILrJ5MhUGhYcATGD6Bk4Hh-jNgABrPDkOBlXyQAAq9ngYmJpOAAHcEOCRjAXqwYODfoo6DhakUSph+Uh7GI4P0xER4Cj0OSQGwMP8tP1hgAlX7swwAHgRl2RvIANALSA08ABtAC6AD4VM1Wm0Kow0MMrYaHYJjGYLLJXZb3at1HYnC43Go-QHQDcvA6-JsmEJXARgCDgMYWAhjIYhDAU+YiMAAFIwex0ZmilMITCGF79TLAGRsAgJYAAZRwSEZGzEABFTOZUrJ5Yn+jwnWgeER6HB7AAKJrADpdXqS4ZqYultTG6azVfqHswPBbtauLY7fayQ7HIbAAAMwBuAEoYw9IBq2Ixs9h2eFMOQYPQObALQKJgggABeYhghCIpikkKRpOQRIknAsZUiIeCttECBEP8NSMCkjDDAARMGziuIYxHwYOjDCMBmDNnAuTxA6irdCOBB1Lh5Dqpqn66tISIykawBnOCtqqC0gbjqc9DgpGkxegOliyfJDrRkAA)

	```ts
	// Positions of employees in our company.
	type MemberPosition = 'intern' | 'developer' | 'tech-lead';

	// Interface describing properties of a single employee.
	interface Employee {
			firstName: string;
			lastName: string;
			yearsOfExperience: number;
	}

	// Create an object that has all possible `MemberPosition` values set as keys.
	// Those keys will store a collection of Employees of the same position.
	const team: Record<MemberPosition, Employee[]> = {
			intern: [],
			developer: [],
			'tech-lead': [],
	};

	// Our team has decided to help John with his dream of becoming Software Developer.
	team.intern.push({
		firstName: 'John',
		lastName: 'Doe',
		yearsOfExperience: 0
	});

	// `Record` forces you to initialize all of the property keys.
	// TypeScript Error: "tech-lead" property is missing
	const teamEmpty: Record<MemberPosition, null> = {
			intern: null,
			developer: null,
	};
	```
	</details>

- [`Exclude<T, U>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion) - Exclude from `T` those types that are assignable to `U`.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgMrQG7QMIHsQzADmyA3gFDLIAOuUYAXMiAK4A2byAPsgM5hRQJHqwC2AI2gBucgF9y5MAE9qKAEoQAjiwj8AEnBAATNtGQBeZAAooWphu26wAGmS3e93bRC8IASgsAPmRDJRlyAHoI5ABRAA8ENhYjFFYOZGVVZBgoXFFkAAM0zh5+QRBhZhYJaAKAOkjogEkQZAQ4X2QAdwALCFbaemRgXmQtFjhOMFwq9K6ULuB0lk6U+HYwZAxJnQaYFhAEMGB8ZCIIMAAFOjAANR2IK0HGWISklIAedCgsKDwCYgAbQA5M9gQBdVzFQJ+JhiSRQMiUYYwayZCC4VHPCzmSzAspCYEBWxgFhQAZwKC+FpgJ43VwARgADH4ZFQSWSBjcZPJyPtDsdTvxKWBvr8rD1DCZoJ5HPopaYoK4EPhCEQmGKcKriLCtrhgEYkVQVT5Nr4fmZLLZtMBbFZgT0wGBqES6ghbHBIJqoBKFdBWQpjfh+DQbhY2tqiHVsbjLMVkAB+ZAAZiZaeQTHOVxu9ySjxNaujNwDVHNvzqbBGkBAdPoAfkQA)

	```ts
	interface ServerConfig {
		port: null | string | number;
	}

	type RequestHandler = (request: Request, response: Response) => void;

	// Exclude `null` type from `null | string | number`.
	// In case the port is equal to `null`, we will use default value.
	function getPortValue(port: Exclude<ServerConfig['port'], null>): number {
		if (typeof port === 'string') {
			return parseInt(port, 10);
		}

		return port;
	}

	function startServer(handler: RequestHandler, config: ServerConfig): void {
		const server = require('http').createServer(handler);

		const port = config.port === null ? 3000 : getPortValue(config.port);
		server.listen(port);
	}
	```
	</details>

- [`Extract<T, U>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union) - Extract from `T` those types that are assignable to `U`.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXzSwEdkQBJYACgEoAueVZAWwCMQYBuAKDDwGcM8MgBF4AXngBlAJ6scESgHIRi6ty5ZUGdoihgEABXZ888AN5d48ANoiAuvUat23K6ihMQ9ATE0BzV3goPy8GZjZOLgBfLi4Aejj4AEEICBwAdz54MAALKFQQ+BxEeAAHY1NgKAwoIKy0grr4DByEUpgccpgMaXgAaxBerCzi+B9-ZulygDouFHRsU1z8kKMYE1RhaqgAHkt4AHkWACt4EAAPbVRgLLWNgBp9gGlBs8uQa6yAUUuYPQwdgNpKM7nh7mMML4CgA+R5WABqUAgpDeVxuhxO1he0jsXGh8EoOBO9COx3BQPo2PBADckaR6IjkSA6PBqTgsMBzPsicdrEC7OJWXSQNwYvFEgAVTS9JLXODpeDpKBZFg4GCoWa8VACIJykAKiQWKy2YQOAioYikCg0OEMDyhRSy4DyxS24KhAAMjyi6gS8AAwjh5OD0iBFHAkJoEOksC1mnkMJq8gUQKDNttKPlnfrwYp3J5XfBHXqoKpfYkAOI4ansTxaeDADmoRSCCBYAbxhC6TDx6rwYHIRX5bScjA4bLJwoDmDwDkfbA9JMrVMVdM1TN69LgkTgwgkchUahqIA)

	```ts
	declare function uniqueId(): number;

	const ID = Symbol('ID');

	interface Person {
		[ID]: number;
		name: string;
		age: number;
	}

	// Allows changing the person data as long as the property key is of string type.
	function changePersonData<
		Obj extends Person,
		Key extends Extract<keyof Person, string>,
		Value extends Obj[Key]
	> (obj: Obj, key: Key, value: Value): void {
		obj[key] = value;
	}

	// Tiny Andrew was born.
	const andrew = {
		[ID]: uniqueId(),
		name: 'Andrew',
		age: 0,
	};

	// Cool, we're fine with that.
	changePersonData(andrew, 'name', 'Pony');

	// Goverment didn't like the fact that you wanted to change your identity.
	changePersonData(andrew, ID, uniqueId());
	```
	</details>

- [`NonNullable<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype) - Exclude `null` and `undefined` from `T`.
	<details>
	<summary>
			Example
	</summary>
	Works with <a href="https://www.typescriptlang.org/tsconfig#strictNullChecks"><code>strictNullChecks</code></a> set to <code>true</code>.

	[Playground](https://typescript-play.js.org/?target=6#code/C4TwDgpgBACg9gJ2AOQK4FsBGEFQLxQDOwCAlgHYDmUAPlORtrnQwDasDcAUFwPQBU-WAEMkUOADMowqAGNWwwoSgATCBIqlgpOOSjAAFsOBRSy1IQgr9cKJlSlW1mZYQA3HFH68u8xcoBlHA8EACEHJ08Aby4oKDBUTFZSWXjEFEYcAEIALihkXTR2YSSIAB54JDQsHAA+blj4xOTUsHSACkMzPKD3HHDHNQQAGjSkPMqMmoQASh7g-oihqBi4uNIpdraxPAI2VhmVxrX9AzMAOm2ppnwoAA4ABifuE4BfKAhWSyOTuK7CS7pao3AhXF5rV48E4ICDAVAIPT-cGQyG+XTEIgLMJLTx7CAAdygvRCA0iCHaMwarhJOIQjUBSHaACJHk8mYdeLwxtdcVAAOSsh58+lXdr7Dlcq7A3n3J4PEUdADMcspUE53OluAIUGVTx46oAKuAIAFZGQwCYAKIIBCILjUxaDHAMnla+iodjcIA)

	```ts
	type PortNumber = string | number | null;

	/** Part of a class definition that is used to build a server */
	class ServerBuilder {
			portNumber!: NonNullable<PortNumber>;

			port(this: ServerBuilder, port: PortNumber): ServerBuilder {
					if (port == null) {
							this.portNumber = 8000;
					} else {
							this.portNumber = port;
					}

					return this;
			}
	}

	const serverBuilder = new ServerBuilder();

	serverBuilder
			.port('8000')   // portNumber = '8000'
			.port(null)     // portNumber =  8000
			.port(3000);    // portNumber =  3000

	// TypeScript error
	serverBuilder.portNumber = null;
	```
	</details>

- [`Parameters<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype) - Obtain the parameters of a function type in a tuple.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/GYVwdgxgLglg9mABAZwBYmMANgUwBQxgAOIUAXIgIZgCeA2gLoCUFAbnDACaIDeAUIkQB6IYgCypSlBxUATrMo1ECsJzgBbLEoipqAc0J7EMKMgDkiHLnU4wp46pwAPHMgB0fAL58+oSLARECEosLAA5ABUYG2QAHgAxJGdpVWREPDdMylk9ZApqemZEAF4APipacrw-CApEgBogkKwAYThwckQwEHUAIxxZJl4BYVEImiIZKF0oZRwiWVdbeygJmThgOYgcGFYcbhqApCJsyhtpWXcR1cnEePBoeDAABVPzgbTixFeFd8uEsClADcIxGiygIFkSEOT3SmTc2VydQeRx+ZxwF2QQ34gkEwDgsnSuFmMBKiAADEDjIhYk1Qm0OlSYABqZnYka4xA1DJZHJYkGc7yCbyeRA+CAIZCzNAYbA4CIAdxg2zJwVCkWirjwMswuEaACYmCCgA)

	```ts
	function shuffle(input: any[]): void {
		// Mutate array randomly changing its' elements indexes.
	}

	function callNTimes<Fn extends (...args: any[]) => any> (func: Fn, callCount: number) {
		// Type that represents the type of the received function parameters.
		type FunctionParameters = Parameters<Fn>;

		return function (...args: FunctionParameters) {
			for (let i = 0; i < callCount; i++) {
				func(...args);
			}
		}
	}

	const shuffleTwice = callNTimes(shuffle, 2);
	```
	</details>

- [`ConstructorParameters<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype) - Obtain the parameters of a constructor function type in a tuple.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECCBOAXAlqApgWQPYBM0mgG8AoaaFRENALmgkXmQDsBzAblOmCycTV4D8teo1YdO3JiICuwRFngAKClWENmLAJRFOZRAAtkEAHQq00ALzlklNBzIBfYk+KhIMAJJTEYJsDQAwmDA+mgAPAAq0GgAHnxMODCKTGgA7tCKxllg8CwQtL4AngDaALraFgB80EWa1SRkAA6MAG5gfNAB4FABPDJyCrQR9tDNyG0dwMGhtBhgjWEiGgA00F70vv4RhY3hEZXVVinpc42KmuJkkv3y8Bly8EPaDWTkhiZd7r3e8LK3llwGCMXGQWGhEOsfH5zJlsrl8p0+gw-goAAo5MAAW3BaHgEEilU0tEhmzQ212BJ0ry4SOg+kg+gBBiMximIGA0nAfAQLGk2N4EAAEgzYcYcnkLsRdDTvNEYkYUKwSdCme9WdM0MYwYhFPSIPpJdTkAAzDKxBUaZX+aAAQgsVmkCTQxuYaBw2ng4Ok8CYcotSu8pMur09iG9vuObxZnx6SN+AyUWTF8MN0CcZE4Ywm5jZHK5aB5fP4iCFIqT4oRRTKRLo6lYVNeAHpG50wOzOe1zHr9NLQ+HoABybsD4HOKXXRA1JCoKhBELmI5pNaB6Fz0KKBAodDYPAgSUTmqYsAALx4m5nC6nW9nGq14KtaEUA9gR9PvuNCjQ9BgACNvcwNBtAcLiAA)

	```ts
	class ArticleModel {
		title: string;
		content?: string;

		constructor(title: string) {
			this.title = title;
		}
	}

	class InstanceCache<T extends (new (...args: any[]) => any)> {
		private ClassConstructor: T;
		private cache: Map<string, InstanceType<T>> = new Map();

		constructor (ctr: T) {
			this.ClassConstructor = ctr;
		}

		getInstance (...args: ConstructorParameters<T>): InstanceType<T> {
			const hash = this.calculateArgumentsHash(...args);

			const existingInstance = this.cache.get(hash);
			if (existingInstance !== undefined) {
				return existingInstance;
			}

			return new this.ClassConstructor(...args);
		}

		private calculateArgumentsHash(...args: any[]): string {
			// Calculate hash.
			return 'hash';
		}
	}

	const articleCache = new InstanceCache(ArticleModel);
	const amazonArticle = articleCache.getInstance('Amazon forests burining!');
	```
	</details>

- [`ReturnType<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype) - Obtain the return type of a function type.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)

	```ts
	/** Provides every element of the iterable `iter` into the `callback` function and stores the results in an array. */
	function mapIter<
			Elem,
			Func extends (elem: Elem) => any,
			Ret extends ReturnType<Func>
	>(iter: Iterable<Elem>, callback: Func): Ret[] {
			const mapped: Ret[] = [];

			for (const elem of iter) {
					mapped.push(callback(elem));
			}

			return mapped;
	}

	const setObject: Set<string> = new Set();
	const mapObject: Map<number, string> = new Map();

	mapIter(setObject, (value: string) => value.indexOf('Foo')); // number[]

	mapIter(mapObject, ([key, value]: [number, string]) => {
			return key % 2 === 0 ? value : 'Odd';
	}); // string[]
	```
	</details>

- [`InstanceType<T>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype) - Obtain the instance type of a constructor function type.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/MYGwhgzhAECSAmICmBlJAnAbgS2E6A3gFDTTwD2AcuQC4AW2AdgOYAUAlAFzSbnbyEAvkWFFQkGJSQB3GMVI1sNZNwg10TZgG4S0YOUY0kh1es07d+xmvQBXYDXLpWi5UlMaWAGj0GjJ6BtNdkJdBQYIADpXZGgAXmgYpB1ScOwoq38aeN9DYxoU6GFRKzVoJjUwRjwAYXJbPPRuAFkwAAcAHgAxBodsAx9GWwBbACMMAD4cxhloVraOCyYjdAAzMDxoOut1e0d0UNIZ6WhWSPOwdGYIbiqATwBtAF0uaHudUQB6ACpv6ABpJBINqJdAbADW0Do5BOw3u5R2VTwMHIq2gAANtjZ0bkbHsnFCwJh8ONjHp0EgwEZ4JFoN9PkRVr1FAZoMwkDRYIjqkgOrosepoEgAB7+eAwAV2BxOLy6ACCVxgIrFEoMeOl6AACpcwMMORgIB1JRMiBNWKVdhruJKfOdIpdrtwFddXlzKjyACp3Nq842HaDIbL6BrZBIVGhIpB1EMYSLsmjmtWW-YhAA+qegAAYLKQLQj3ZsEsdccmnGcLor2Dn8xGedHGpEIBzEzspfsfMHDNAANTQACMVaIljV5GQkRA5DYmIpVKQAgAJARO9le33BDXIyi0YuLW2nJFGLqkOvxFB0YPdBSaLZ0IwNzyPkO8-xkGgsLh8Al427a3hWAhXwwHA8EHT5PmgAB1bAQBAANJ24adKWpft72RaBUTgRBUCAj89HAM8xCTaBjggABRQx0DuHJv25P9dCkWRZVIAAiBjoFImpmjlFBgA0NpsjadByDacgIDAEAIAAQmYpjoGYgAZSBsmGPw6DtZiiFA8CoJguDmAQmoZ2QvtUKQLdoAYmBTwgdEiCAA)

	```ts
	class IdleService {
			doNothing (): void {}
	}

	class News {
			title: string;
			content: string;

			constructor(title: string, content: string) {
					this.title = title;
					this.content = content;
			}
	}

	const instanceCounter: Map<Function, number> = new Map();

	interface Constructor {
			new(...args: any[]): any;
	}

	// Keep track how many instances of `Constr` constructor have been created.
	function getInstance<
			Constr extends Constructor,
			Args extends ConstructorParameters<Constr>
	>(constructor: Constr, ...args: Args): InstanceType<Constr> {
			let count = instanceCounter.get(constructor) || 0;

			const instance = new constructor(...args);

			instanceCounter.set(constructor, count + 1);

			console.log(`Created ${count + 1} instances of ${Constr.name} class`);

			return instance;
	}


	const idleService = getInstance(IdleService);
	// Will log: `Created 1 instances of IdleService class`
	const newsEntry = getInstance(News, 'New ECMAScript proposals!', 'Last month...');
	// Will log: `Created 1 instances of News class`
	```
	</details>

- [`Omit<T, K>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) - Constructs a type by picking all properties from T and then removing K.
	<details>
	<summary>
			Example
	</summary>

	[Playground](https://typescript-play.js.org/?target=6#code/JYOwLgpgTgZghgYwgAgIImAWzgG2QbwChlks4BzCAVShwC5kBnMKUcgbmKYAcIFgIjBs1YgOXMpSFMWbANoBdTiW5woFddwAW0kfKWEAvoUIB6U8gDCUCHEiNkICAHdkYAJ69kz4GC3JcPG4oAHteKDABBxCYNAxsPFBIWEQUCAAPJG4wZABySUFcgJAAEzMLXNV1ck0dIuCw6EjBADpy5AB1FAQ4EGQAV0YUP2AHDy8wEOQbUugmBLwtEIA3OcmQnEjuZBgQqE7gAGtgZAhwKHdkHFGwNvGUdDIcAGUliIBJEF3kAF5kAHlML4ADyPBIAGjyBUYRQAPnkqho4NoYQA+TiEGD9EAISIhPozErQMG4AASK2gn2+AApek9pCSXm8wFSQooAJQMUkAFQAsgAZACiOAgmDOOSIJAQ+OYyGl4DgoDmf2QJRCCH6YvALQQNjsEGFovF1NyJWAy1y7OUyHMyE+yRAuFImG4Iq1YDswHxbRINjA-SgfXlHqVUE4xiAA)

	```ts
	interface Animal {
			imageUrl: string;
			species: string;
			images: string[];
			paragraphs: string[];
	}

	// Creates new type with all properties of the `Animal` interface
	// except 'images' and 'paragraphs' properties. We can use this
	// type to render small hover tooltip for a wiki entry list.
	type AnimalShortInfo = Omit<Animal, 'images' | 'paragraphs'>;

	function renderAnimalHoverInfo (animals: AnimalShortInfo[]): HTMLElement {
			const container = document.createElement('div');
			// Internal implementation.
			return container;
	}
	```
	</details>

- [`Uppercase<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype) - Transforms every character in a string into uppercase.
	<details>
	<summary>
		Example
	</summary>

	```ts
	type T = Uppercase<'hello'>;  // 'HELLO'

	type T2 = Uppercase<'foo' | 'bar'>;  // 'FOO' | 'BAR'

	type T3<S extends string> = Uppercase<`aB${S}`>;
	type T4 = T3<'xYz'>;  // 'ABXYZ'

	type T5 = Uppercase<string>;  // string
	type T6 = Uppercase<any>;  // any
	type T7 = Uppercase<never>;  // never
	type T8 = Uppercase<42>;  // Error, type 'number' does not satisfy the constraint 'string'
	```
	</details>

- [`Lowercase<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#lowercasestringtype) - Transforms every character in a string into lowercase.
	<details>
	<summary>
		Example
	</summary>

	```ts
	type T = Lowercase<'HELLO'>;  // 'hello'

	type T2 = Lowercase<'FOO' | 'BAR'>;  // 'foo' | 'bar'

	type T3<S extends string> = Lowercase<`aB${S}`>;
	type T4 = T3<'xYz'>;  // 'abxyz'

	type T5 = Lowercase<string>;  // string
	type T6 = Lowercase<any>;  // any
	type T7 = Lowercase<never>;  // never
	type T8 = Lowercase<42>;  // Error, type 'number' does not satisfy the constraint 'string'
	```
	</details>

- [`Capitalize<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#capitalizestringtype) - Transforms the first character in a string into uppercase.
	<details>
	<summary>
		Example
	</summary>

	```ts
	type T = Capitalize<'hello'>;  // 'Hello'

	type T2 = Capitalize<'foo' | 'bar'>;  // 'Foo' | 'Bar'

	type T3<S extends string> = Capitalize<`aB${S}`>;
	type T4 = T3<'xYz'>;  // 'ABxYz'

	type T5 = Capitalize<string>;  // string
	type T6 = Capitalize<any>;  // any
	type T7 = Capitalize<never>;  // never
	type T8 = Capitalize<42>;  // Error, type 'number' does not satisfy the constraint 'string'
	```
	</details>

- [`Uncapitalize<S extends string>`](https://www.typescriptlang.org/docs/handbook/utility-types.html#uncapitalizestringtype) - Transforms the first character in a string into lowercase.
	<details>
	<summary>
		Example
	</summary>

	```ts
	type T = Uncapitalize<'Hello'>;  // 'hello'

	type T2 = Uncapitalize<'Foo' | 'Bar'>;  // 'foo' | 'bar'

	type T3<S extends string> = Uncapitalize<`AB${S}`>;
	type T4 = T3<'xYz'>;  // 'aBxYz'

	type T5 = Uncapitalize<string>;  // string
	type T6 = Uncapitalize<any>;  // any
	type T7 = Uncapitalize<never>;  // never
	type T8 = Uncapitalize<42>;  // Error, type 'number' does not satisfy the constraint 'string'
	```
	</details>

You can find some examples in the [TypeScript docs](https://www.typescriptlang.org/docs/handbook/utility-types.html).

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Jarek Radosz](https://github.com/CvX)
- [Dimitri Benin](https://github.com/BendingBender)
- [Pelle Wessman](https://github.com/voxpelli)

## License

SPDX-License-Identifier: (MIT OR CC0-1.0)

---

<div align="center">
	<b>
		<a href="https://tidelift.com/subscription/pkg/npm-type-fest?utm_source=npm-type-fest&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
	</b>
	<br>
	<sub>
		Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
	</sub>
</div>
class Node {
	/// value;
	/// next;

	constructor(value) {
		this.value = value;

		// TODO: Remove this when targeting Node.js 12.
		this.next = undefined;
	}
}

class Queue {
	// TODO: Use private class fields when targeting Node.js 12.
	// #_head;
	// #_tail;
	// #_size;

	constructor() {
		this.clear();
	}

	enqueue(value) {
		const node = new Node(value);

		if (this._head) {
			this._tail.next = node;
			this._tail = node;
		} else {
			this._head = node;
			this._tail = node;
		}

		this._size++;
	}

	dequeue() {
		const current = this._head;
		if (!current) {
			return;
		}

		this._head = this._head.next;
		this._size--;
		return current.value;
	}

	clear() {
		this._head = undefined;
		this._tail = undefined;
		this._size = 0;
	}

	get size() {
		return this._size;
	}

	* [Symbol.iterator]() {
		let current = this._head;

		while (current) {
			yield current.value;
			current = current.next;
		}
	}
}

module.exports = Queue;
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
	"name": "yocto-queue",
	"version": "0.1.0",
	"description": "Tiny queue data structure",
	"license": "MIT",
	"repository": "sindresorhus/yocto-queue",
	"funding": "https://github.com/sponsors/sindresorhus",
	"author": {
		"name": "Sindre Sorhus",
		"email": "sindresorhus@gmail.com",
		"url": "https://sindresorhus.com"
	},
	"engines": {
		"node": ">=10"
	},
	"scripts": {
		"test": "xo && ava && tsd"
	},
	"files": [
		"index.js",
		"index.d.ts"
	],
	"keywords": [
		"queue",
		"data",
		"structure",
		"algorithm",
		"queues",
		"queuing",
		"list",
		"array",
		"linkedlist",
		"fifo",
		"enqueue",
		"dequeue",
		"data-structure"
	],
	"devDependencies": {
		"ava": "^2.4.0",
		"tsd": "^0.13.1",
		"xo": "^0.35.0"
	}
}
# yocto-queue [![](https://badgen.net/bundlephobia/minzip/yocto-queue)](https://bundlephobia.com/result?p=yocto-queue)

> Tiny queue data structure

You should use this package instead of an array if you do a lot of `Array#push()` and `Array#shift()` on large arrays, since `Array#shift()` has [linear time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(N)%E2%80%94Linear%20Time) *O(n)* while `Queue#dequeue()` has [constant time complexity](https://medium.com/@ariel.salem1989/an-easy-to-use-guide-to-big-o-time-complexity-5dcf4be8a444#:~:text=O(1)%20%E2%80%94%20Constant%20Time) *O(1)*. That makes a huge difference for large arrays.

> A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is an ordered list of elements where an element is inserted at the end of the queue and is removed from the front of the queue. A queue works based on the first-in, first-out ([FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics))) principle.

## Install

```
$ npm install yocto-queue
```

## Usage

```js
const Queue = require('yocto-queue');

const queue = new Queue();

queue.enqueue('🦄');
queue.enqueue('🌈');

console.log(queue.size);
//=> 2

console.log(...queue);
//=> '🦄 🌈'

console.log(queue.dequeue());
//=> '🦄'

console.log(queue.dequeue());
//=> '🌈'
```

## API

### `queue = new Queue()`

The instance is an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols), which means you can iterate over the queue front to back with a “for…of” loop, or use spreading to convert the queue to an array. Don't do this unless you really need to though, since it's slow.

#### `.enqueue(value)`

Add a value to the queue.

#### `.dequeue()`

Remove the next value in the queue.

Returns the removed value or `undefined` if the queue is empty.

#### `.clear()`

Clear the queue.

#### `.size`

The size of the queue.

## Related

- [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple “Least Recently Used” (LRU) cache
{
  "name": "krunker-civilian-client",
  "version": "0.7.7",
  "description": "Cross-platform Krunker game client",
  "main": "dist/main/index.js",
  "homepage": "https://github.com/bigjakk/Krunker-Civilian-Client",
  "author": "Krunker Civilian Client <krunker@crjlab.net>",
  "license": "GPL-3.0",
  "scripts": {
    "postinstall": "node scripts/download-electron.js",
    "dev": "vite build --mode development --config vite.main.config.ts && vite build --mode development --config vite.preload.config.ts && electron .",
    "build:main": "vite build --config vite.main.config.ts",
    "build:preload": "vite build --config vite.preload.config.ts",
    "build": "npm run build:main && npm run build:preload",
    "start": "npm run build && electron .",
    "download-electron": "node scripts/download-electron.js",
    "dist:win": "npm run build && electron-builder --win",
    "dist:linux": "npm run build && electron-builder --linux",
    "dist:all": "npm run build && electron-builder --win --linux",
    "build:asar": "node scripts/build-asar.js",
    "clean": "rimraf dist out",
    "lint": "eslint src/",
    "prepare": "husky"
  },
  "lint-staged": {
    "src/**/*.ts": "eslint --fix"
  },
  "dependencies": {
    "electron-store": "^8.2.0"
  },
  "devDependencies": {
    "@electron/asar": "^4.2.0",
    "@eslint/js": "^10.0.1",
    "@types/node": "^22.0.0",
    "electron": "npm:electron-nightly@42.0.0-nightly.20260227",
    "electron-builder": "^26.0.0",
    "eslint": "^10.0.2",
    "husky": "^9.1.7",
    "lint-staged": "^16.3.1",
    "rimraf": "^6.0.1",
    "typescript": "^5.7.0",
    "typescript-eslint": "^8.56.1",
    "vite": "^6.0.0"
  }
}
