safe-json-value
Version:
⛑️ JSON serialization should never fail
95 lines (50 loc) • 1.06 kB
JavaScript
import{safeGetChangeProp}from"./get.js";
export const addSize=({type,size,maxSize,changes,path,context})=>{
if(maxSize===SKIP_MAX_SIZE){
return{size,stop:false}
}
const{getSize,getOldValue}=SIZED_TYPES[type];
const newSize=size+getSize(context);
const stop=newSize>maxSize;
if(!stop){
return{size:newSize,stop}
}
changes.push({
path,
oldValue:getOldValue(context),
newValue:undefined,
reason:"unsafeSize"
});
return{size,stop}
};
const SKIP_MAX_SIZE=Number.POSITIVE_INFINITY;
export const DEFAULT_MAX_SIZE=1e7;
const SIZED_TYPES={
value:{
getSize:(value)=>{
if(value===undefined){
return 0
}
return typeof value==="object"&&value!==null?
2:
getJsonLength(value)
},
getOldValue:(value)=>value
},
arrayItem:{
getSize:({empty})=>empty?0:1,
getOldValue:safeGetChangeProp
},
objectProp:{
getSize:({key,empty})=>
typeof key==="symbol"?0:getJsonLength(key)+(empty?1:2),
getOldValue:safeGetChangeProp
}
};
const getJsonLength=(value)=>{
try{
return JSON.stringify(value).length
}catch{
return Number.POSITIVE_INFINITY
}
};