Repository: mafintosh/jitson
Branch: master
Commit: cd18c20fbe83
Files: 6
Total size: 8.0 KB
Directory structure:
gitextract_x_prs31a/
├── .gitignore
├── LICENSE
├── README.md
├── example.js
├── index.js
└── package.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
node_modules
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2018 Mathias Buus
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.
================================================
FILE: README.md
================================================
# jitson
Just-In-Time JSON.parse compiler
```
npm install jitson
```
Works by schema sampling the incoming data and if the schema is stable, it
will compile a fast parser for it using [turbo-json-parse](https://github.com/mafintosh/turbo-json-parse)
## Usage
``` js
const jitson = require('jitson')
// make an instance
const parse = jitson()
for (var i = 0; i < 10; i++) {
console.log(parse(JSON.stringify({hello: 'world', number: Math.random()})))
}
// Check if the compiler found a matching schema.
// If so it is using an optimised parser to parse the JSON
console.log(parse.schema)
```
## API
#### `const parse = jitson(opts)`
Create a new JSON parser.
Options include
```js
{
sampleInterval: 100 // sample the schema everytime we parse 100 objects
}
```
It keeps a small internal cache around of old schemas that is used to produce a better parser.
If the cache is empty it will sample right away as well.
Any additional options are forwarded to [turbo-json-parse](https://github.com/mafintosh/turbo-json-parse)
when it triggers a parser compilation.
It works the best if you try to only pass data to it that has a schema so make
an instance for each of your http endpoints for example
#### `const object = parse(src)`
Similar to JSON.parse. Will schema sample the input once in a while
to check if it has a stable schema. If so it'll optimise the parser.
If 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.
If you are parsing from Node.js buffers make sure to pass that as the `src`
instead of `toString()`ing it first as that will produce a faster parser
when compiling.
## License
MIT
================================================
FILE: example.js
================================================
const jitson = require('./')
// make an instance
const parse = jitson()
for (var i = 0; i < 10; i++) {
console.log(parse(JSON.stringify({ hello: 'world', number: Math.random() })))
}
// Check if the compiler found a matching schema.
// If so it is using an optimised parser to parse the JSON
console.log(parse.schema)
================================================
FILE: index.js
================================================
const turbo = require('turbo-json-parse')
module.exports = jitson
function jitson (opts) {
if (!opts) opts = {}
const schemas = []
const inputs = []
const partial = !!opts.partial
var sampleInterval = opts.sampleInterval || 100
var tick = sampleInterval
var compiled = null
var failures = 0
parsePartial.pointer = 0
const result = partial ? parsePartial : parse
result.recompiles = 0
result.schema = null
result.turbo = null
return result
function sample (src) {
const data = JSON.parse(src)
if (--tick > 0 && inputs.length === 8 && compiled) return data
tick = sampleInterval
if (inputs.length === 8) {
inputs.shift()
schemas.shift()
}
const sch = getSchema(data)
if (!sch) return data
inputs.push(src)
schemas.push(sch)
const schema = result.schema = joinSchemas(schemas)
if (!schema) {
if (++failures >= 7) {
sampleInterval *= 2
}
return data
}
failures = 0
opts.buffer = inputs.every(isBuffer)
opts.defaults = false
result.recompiles++
compiled = result.turbo = turbo(schema, opts)
return data
}
function parse (src) {
try {
if (compiled) return compiled(src, 0)
} catch (err) {
compiled = result.compiled = result.turbo = null
}
return sample(src)
}
function parsePartial (src, ptr) {
try {
if (compiled) {
const data = compiled(src, ptr)
parse.pointer = compiled.pointer
return data
}
} catch (err) {}
throw new Error('not impl')
}
}
function isBuffer (buf) {
return typeof buf !== 'string'
}
function getSchema (object) {
const type = Array.isArray(object) ? 'array' : typeof object
switch (type) {
case 'number':
case 'string':
case 'boolean': {
return { type }
}
case 'object': {
if (!object) return null
const res = { type: 'object', ordered: true, properties: {} }
for (const key of Object.keys(object)) {
const sch = res.properties[key] = getSchema(object[key])
if (!sch) return null
}
return res
}
case 'array': {
const res = { type: 'array', items: null }
if (object.length) {
res.items = getSchema(object[0])
if (!res.items) return null
}
return res
}
}
return null
}
function joinSchemas (samples) {
if (!samples.length) return null
const s = samples[0]
if (samples.length === 1) return s
for (const sample of samples) {
if (!sample || sample.type !== s.type) return null
}
switch (s.type) {
case 'number':
case 'string':
case 'boolean':
case 'integer': {
return { type: s.type }
}
case 'object': {
const isOrdered = create()
const res = { type: 'object', ordered: true, properties: {} }
const props = {}
for (const sample of samples) {
if (res.ordered && !isOrdered(Object.keys(sample.properties))) {
res.ordered = false
}
for (const prop of Object.keys(sample.properties)) {
if (!props[prop]) props[prop] = []
props[prop].push(sample.properties[prop])
}
}
for (const prop of Object.keys(props)) {
const val = res.properties[prop] = joinSchemas(props[prop])
if (!val) return null
}
return res
}
case 'array': {
const items = []
for (const sample of samples) {
if (sample.items) items.push(sample.items)
}
const res = { type: 'array', items: joinSchemas(items) }
return items.length && !res.items ? null : res
}
}
}
function upsert (map, key, val) {
if (map.has(key)) return map.get(key)
map.set(key, val)
return val
}
function create () {
const lts = new Uint32Array(32)
const gts = new Uint32Array(32)
const tokens = new Map()
return isOrdered
function isOrdered (keys) {
const ids = new Uint8Array(keys.length)
for (var i = 0; i < keys.length; i++) {
const id = upsert(tokens, keys[i], tokens.size)
if (id >= 32) return false
ids[i] = id
}
var l = 0
var g = 0
for (const id of ids) {
l |= (1 << id)
}
for (const id of ids) {
if (lts[id] & g) return false
if (gts[id] & l) return false
lts[id] |= l
gts[id] |= g
l &= ~(1 << id)
g |= (1 << id)
}
return true
}
}
================================================
FILE: package.json
================================================
{
"name": "jitson",
"version": "1.0.0",
"description": "Just-In-Time JSON.parse compiler",
"main": "index.js",
"dependencies": {
"turbo-json-parse": "^2.2.1"
},
"devDependencies": {
"standard": "^12.0.0"
},
"scripts": {
"test": "standard"
},
"repository": {
"type": "git",
"url": "https://github.com/mafintosh/jitson.git"
},
"author": "Mathias Buus (@mafintosh)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mafintosh/jitson/issues"
},
"homepage": "https://github.com/mafintosh/jitson"
}
gitextract_x_prs31a/ ├── .gitignore ├── LICENSE ├── README.md ├── example.js ├── index.js └── package.json
SYMBOL INDEX (6 symbols across 1 files)
FILE: index.js
function jitson (line 5) | function jitson (opts) {
function isBuffer (line 80) | function isBuffer (buf) {
function getSchema (line 84) | function getSchema (object) {
function joinSchemas (line 116) | function joinSchemas (samples) {
function upsert (line 167) | function upsert (map, key, val) {
function create (line 173) | function create () {
Condensed preview — 6 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (9K chars).
[
{
"path": ".gitignore",
"chars": 13,
"preview": "node_modules\n"
},
{
"path": "LICENSE",
"chars": 1079,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2018 Mathias Buus\n\nPermission is hereby granted, free of charge, to any person obta"
},
{
"path": "README.md",
"chars": 1789,
"preview": "# jitson\n\nJust-In-Time JSON.parse compiler\n\n```\nnpm install jitson\n```\n\nWorks by schema sampling the incoming data and i"
},
{
"path": "example.js",
"chars": 323,
"preview": "const jitson = require('./')\n\n// make an instance\nconst parse = jitson()\n\nfor (var i = 0; i < 10; i++) {\n console.log(p"
},
{
"path": "index.js",
"chars": 4421,
"preview": "const turbo = require('turbo-json-parse')\n\nmodule.exports = jitson\n\nfunction jitson (opts) {\n if (!opts) opts = {}\n\n c"
},
{
"path": "package.json",
"chars": 557,
"preview": "{\n \"name\": \"jitson\",\n \"version\": \"1.0.0\",\n \"description\": \"Just-In-Time JSON.parse compiler\",\n \"main\": \"index.js\",\n "
}
]
About this extraction
This page contains the full source code of the mafintosh/jitson GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 6 files (8.0 KB), approximately 2.2k tokens, and a symbol index with 6 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.