[
  {
    "path": ".gitignore",
    "content": "node_modules\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2018 Mathias Buus\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# jitson\n\nJust-In-Time JSON.parse compiler\n\n```\nnpm install jitson\n```\n\nWorks by schema sampling the incoming data and if the schema is stable, it\nwill compile a fast parser for it using [turbo-json-parse](https://github.com/mafintosh/turbo-json-parse)\n\n## Usage\n\n``` js\nconst jitson = require('jitson')\n\n// make an instance\nconst parse = jitson()\n\nfor (var i = 0; i < 10; i++) {\n  console.log(parse(JSON.stringify({hello: 'world', number: Math.random()})))\n}\n\n// Check if the compiler found a matching schema.\n// If so it is using an optimised parser to parse the JSON\nconsole.log(parse.schema)\n```\n\n## API\n\n#### `const parse = jitson(opts)`\n\nCreate a new JSON parser.\n\nOptions include\n\n```js\n{\n  sampleInterval: 100 // sample the schema everytime we parse 100 objects\n}\n```\n\nIt keeps a small internal cache around of old schemas that is used to produce a better parser.\nIf the cache is empty it will sample right away as well.\n\nAny additional options are forwarded to [turbo-json-parse](https://github.com/mafintosh/turbo-json-parse)\nwhen it triggers a parser compilation.\n\nIt works the best if you try to only pass data to it that has a schema so make\nan instance for each of your http endpoints for example\n\n#### `const object = parse(src)`\n\nSimilar to JSON.parse. Will schema sample the input once in a while\nto check if it has a stable schema. If so it'll optimise the parser.\n\nIf the optimised parser fails it will fallback to JSON.parse and resample more data in future. If the optimised parser keeps failing it'll increase the sampling interval, to not waste too much time sampling and compiling.\n\nIf you are parsing from Node.js buffers make sure to pass that as the `src`\ninstead of `toString()`ing it first as that will produce a faster parser\nwhen compiling.\n\n## License\n\nMIT\n"
  },
  {
    "path": "example.js",
    "content": "const jitson = require('./')\n\n// make an instance\nconst parse = jitson()\n\nfor (var i = 0; i < 10; i++) {\n  console.log(parse(JSON.stringify({ hello: 'world', number: Math.random() })))\n}\n\n// Check if the compiler found a matching schema.\n// If so it is using an optimised parser to parse the JSON\nconsole.log(parse.schema)\n"
  },
  {
    "path": "index.js",
    "content": "const turbo = require('turbo-json-parse')\n\nmodule.exports = jitson\n\nfunction jitson (opts) {\n  if (!opts) opts = {}\n\n  const schemas = []\n  const inputs = []\n  const partial = !!opts.partial\n\n  var sampleInterval = opts.sampleInterval || 100\n  var tick = sampleInterval\n  var compiled = null\n  var failures = 0\n\n  parsePartial.pointer = 0\n\n  const result = partial ? parsePartial : parse\n  result.recompiles = 0\n  result.schema = null\n  result.turbo = null\n  return result\n\n  function sample (src) {\n    const data = JSON.parse(src)\n\n    if (--tick > 0 && inputs.length === 8 && compiled) return data\n    tick = sampleInterval\n\n    if (inputs.length === 8) {\n      inputs.shift()\n      schemas.shift()\n    }\n\n    const sch = getSchema(data)\n    if (!sch) return data\n\n    inputs.push(src)\n    schemas.push(sch)\n\n    const schema = result.schema = joinSchemas(schemas)\n    if (!schema) {\n      if (++failures >= 7) {\n        sampleInterval *= 2\n      }\n      return data\n    }\n\n    failures = 0\n    opts.buffer = inputs.every(isBuffer)\n    opts.defaults = false\n\n    result.recompiles++\n    compiled = result.turbo = turbo(schema, opts)\n    return data\n  }\n\n  function parse (src) {\n    try {\n      if (compiled) return compiled(src, 0)\n    } catch (err) {\n      compiled = result.compiled = result.turbo = null\n    }\n    return sample(src)\n  }\n\n  function parsePartial (src, ptr) {\n    try {\n      if (compiled) {\n        const data = compiled(src, ptr)\n        parse.pointer = compiled.pointer\n        return data\n      }\n    } catch (err) {}\n    throw new Error('not impl')\n  }\n}\n\nfunction isBuffer (buf) {\n  return typeof buf !== 'string'\n}\n\nfunction getSchema (object) {\n  const type = Array.isArray(object) ? 'array' : typeof object\n  switch (type) {\n    case 'number':\n    case 'string':\n    case 'boolean': {\n      return { type }\n    }\n\n    case 'object': {\n      if (!object) return null\n      const res = { type: 'object', ordered: true, properties: {} }\n      for (const key of Object.keys(object)) {\n        const sch = res.properties[key] = getSchema(object[key])\n        if (!sch) return null\n      }\n      return res\n    }\n\n    case 'array': {\n      const res = { type: 'array', items: null }\n      if (object.length) {\n        res.items = getSchema(object[0])\n        if (!res.items) return null\n      }\n      return res\n    }\n  }\n\n  return null\n}\n\nfunction joinSchemas (samples) {\n  if (!samples.length) return null\n  const s = samples[0]\n\n  if (samples.length === 1) return s\n\n  for (const sample of samples) {\n    if (!sample || sample.type !== s.type) return null\n  }\n\n  switch (s.type) {\n    case 'number':\n    case 'string':\n    case 'boolean':\n    case 'integer': {\n      return { type: s.type }\n    }\n\n    case 'object': {\n      const isOrdered = create()\n      const res = { type: 'object', ordered: true, properties: {} }\n      const props = {}\n\n      for (const sample of samples) {\n        if (res.ordered && !isOrdered(Object.keys(sample.properties))) {\n          res.ordered = false\n        }\n        for (const prop of Object.keys(sample.properties)) {\n          if (!props[prop]) props[prop] = []\n          props[prop].push(sample.properties[prop])\n        }\n      }\n      for (const prop of Object.keys(props)) {\n        const val = res.properties[prop] = joinSchemas(props[prop])\n        if (!val) return null\n      }\n\n      return res\n    }\n\n    case 'array': {\n      const items = []\n      for (const sample of samples) {\n        if (sample.items) items.push(sample.items)\n      }\n      const res = { type: 'array', items: joinSchemas(items) }\n      return items.length && !res.items ? null : res\n    }\n  }\n}\n\nfunction upsert (map, key, val) {\n  if (map.has(key)) return map.get(key)\n  map.set(key, val)\n  return val\n}\n\nfunction create () {\n  const lts = new Uint32Array(32)\n  const gts = new Uint32Array(32)\n  const tokens = new Map()\n\n  return isOrdered\n\n  function isOrdered (keys) {\n    const ids = new Uint8Array(keys.length)\n\n    for (var i = 0; i < keys.length; i++) {\n      const id = upsert(tokens, keys[i], tokens.size)\n      if (id >= 32) return false\n      ids[i] = id\n    }\n\n    var l = 0\n    var g = 0\n\n    for (const id of ids) {\n      l |= (1 << id)\n    }\n\n    for (const id of ids) {\n      if (lts[id] & g) return false\n      if (gts[id] & l) return false\n\n      lts[id] |= l\n      gts[id] |= g\n\n      l &= ~(1 << id)\n      g |= (1 << id)\n    }\n\n    return true\n  }\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"jitson\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Just-In-Time JSON.parse compiler\",\n  \"main\": \"index.js\",\n  \"dependencies\": {\n    \"turbo-json-parse\": \"^2.2.1\"\n  },\n  \"devDependencies\": {\n    \"standard\": \"^12.0.0\"\n  },\n  \"scripts\": {\n    \"test\": \"standard\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/mafintosh/jitson.git\"\n  },\n  \"author\": \"Mathias Buus (@mafintosh)\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/mafintosh/jitson/issues\"\n  },\n  \"homepage\": \"https://github.com/mafintosh/jitson\"\n}\n"
  }
]